mirror of
https://github.com/Tyrrrz/DiscordChatExporter.git
synced 2026-07-07 06:39:33 +02:00
Compare commits
368 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a1d34e8fb6 | |||
| 4a35a7b530 | |||
| 247f3a9c5b | |||
| be73f0b92c | |||
| d03be8b1dd | |||
| 9d0d7cd5dd | |||
| b2a48d338a | |||
| 88a4fa792b | |||
| dc79813ad7 | |||
| 6a430cdc76 | |||
| 2a02894d64 | |||
| 8685a3d7e3 | |||
| 130c0b6fe2 | |||
| f153aad3f1 | |||
| 6f1c944cb3 | |||
| de9e7caaeb | |||
| 9711a8cca4 | |||
| 4ab6607e78 | |||
| d74e6453f6 | |||
| ca7fc4d8d1 | |||
| 81ed85a3e0 | |||
| 18979c6a38 | |||
| 5bce4b52ff | |||
| dac7c664d9 | |||
| 6a8579787d | |||
| dbf15c7bee | |||
| a41a4ca8a7 | |||
| c098f4b137 | |||
| ff15257d23 | |||
| 79e43c4144 | |||
| 7bb8038ce9 | |||
| ee27167998 | |||
| 9f4277ae84 | |||
| 70a1c9db8c | |||
| 378f0a20db | |||
| a24fe3906c | |||
| eececb6701 | |||
| d3adf19500 | |||
| a01835efb6 | |||
| 1d39fe9c53 | |||
| 9f6090b3af | |||
| 9fa40dca00 | |||
| 8a4f306012 | |||
| 37be80e9e1 | |||
| 1475ffaf0e | |||
| aa50dd6dc7 | |||
| 539f57f455 | |||
| e1f83997aa | |||
| 26d713a17c | |||
| 5c2e725739 | |||
| bf56902134 | |||
| b4df267372 | |||
| 4ebc681327 | |||
| 5cb6adf19e | |||
| cec8409ac4 | |||
| 3af9421304 | |||
| cc6f930dc6 | |||
| e6aac3cdb9 | |||
| 8f1aec241b | |||
| 41c828eb3e | |||
| 964317dac0 | |||
| 2a223599f9 | |||
| fc38afe6a0 | |||
| 23512dae64 | |||
| 8382ca725d | |||
| 457e14d0b6 | |||
| b830014a46 | |||
| 35e1114318 | |||
| 610bf4baa3 | |||
| d84222ea09 | |||
| cc1bb924e7 | |||
| 0d2ae8b5db | |||
| 632b9f953b | |||
| 9a52c6a6f6 | |||
| fc8c1c5914 | |||
| 279a6aee84 | |||
| 73ab983056 | |||
| e5a2852165 | |||
| 1bf9d9e2e2 | |||
| 9299b95250 | |||
| 5e0a2c6761 | |||
| ccbd11e526 | |||
| 2c36f6a826 | |||
| d6980cef8d | |||
| fa4bb3b693 | |||
| 05c551f80c | |||
| 69cfe1845b | |||
| 3a0d351143 | |||
| f04719c4bd | |||
| d88cd9b228 | |||
| cd042e5368 | |||
| 533671c59f | |||
| 29c35f6754 | |||
| 7b32101517 | |||
| 9bb88128b0 | |||
| 12a5091d73 | |||
| 82af36c90d | |||
| a2beb9836b | |||
| 60f46bad29 | |||
| 2cdb230b1e | |||
| 9241b7d2d1 | |||
| 40f54d9a98 | |||
| f2faf823b9 | |||
| 5b9eaa57f5 | |||
| 58ba99e0c6 | |||
| 117d1b7e4a | |||
| 835910ee22 | |||
| 5630020d88 | |||
| 71e6a8de7a | |||
| 592b8b6294 | |||
| e6edcd27a4 | |||
| 557b5be844 | |||
| 02fe2a46e8 | |||
| 76c7f9b419 | |||
| 9a383d2bd4 | |||
| 2ed374ee5c | |||
| 0ced31ca4a | |||
| 3bb5638b56 | |||
| 3b5d752c95 | |||
| 2b1f599cbe | |||
| 7cb1c21897 | |||
| 37bcea86e3 | |||
| 559ef71d2f | |||
| ab0ce478db | |||
| afb9f52221 | |||
| d65ca409b1 | |||
| 7784383ea7 | |||
| 26322da800 | |||
| 1325edb135 | |||
| dec2c26d83 | |||
| 82b0b8cb0a | |||
| a7da90943f | |||
| 1edeaf9d3a | |||
| 9c043376f9 | |||
| 77366cc9b4 | |||
| ffdca7b799 | |||
| 30cba7959f | |||
| 7951703cf2 | |||
| 795dfbb213 | |||
| 6d9bc3625f | |||
| 4bfb2ec7fd | |||
| 359278afec | |||
| 19f58f2c8c | |||
| 640b1f5866 | |||
| d13d04e75b | |||
| 6bf0ce3790 | |||
| aef8a1f6d2 | |||
| a63bf95212 | |||
| af9855fc15 | |||
| 4113101c0c | |||
| cac48b3541 | |||
| 0a60dea5c1 | |||
| 889446fff7 | |||
| 6d1cfef729 | |||
| 77bf32aa5a | |||
| ac2b450892 | |||
| 4046fd0ad9 | |||
| 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 | |||
| b518fb2f59 | |||
| 94165dcd8d | |||
| d6507598fa | |||
| a0359b1e43 | |||
| aa53cecd4e | |||
| 4144911208 | |||
| d28e81f8dc | |||
| 761cb032d7 | |||
| 47f0561c71 | |||
| 23116b776b | |||
| ba27a9f909 | |||
| 52684c264f | |||
| bcad5b4ed1 | |||
| 95a4217ab3 | |||
| 4e8fb80ac5 | |||
| 7ae560dde0 | |||
| 97a36028b9 | |||
| f0d99676a3 | |||
| 8e38adae7e | |||
| d95bc37592 | |||
| 3f6354053c | |||
| a9bab60ba6 | |||
| 614bd8590d | |||
| bd9dc6455f | |||
| 0faa427970 | |||
| dd9da4831e | |||
| 0d816cee5d | |||
| f63ea41188 | |||
| 3572a21aad | |||
| 37ee0b8be3 | |||
| ed146bac22 | |||
| b9c449709f | |||
| 25207c5093 | |||
| 4fbec95208 | |||
| 0a48da4c56 | |||
| 3f5f62585c | |||
| 49f39c7097 | |||
| e3eac10fb8 | |||
| 23f9331e4e | |||
| 69088b83eb | |||
| 7ecf90d1cb | |||
| f0cd2dce1b | |||
| e8436faf66 | |||
| 61dce7c1a8 | |||
| 6fee160bc7 | |||
| 8678043f0d | |||
| e4f0b8193f | |||
| df811d0b1a | |||
| 08da5d685b | |||
| c2cebe99e3 | |||
| 481991bd00 | |||
| d958f613a3 | |||
| 3b7da21c24 | |||
| 1d0a13c613 | |||
| 67036f59ce | |||
| 517542730a | |||
| 19dc2334e2 | |||
| 4e1f783145 | |||
| ff6ef480ab | |||
| e1e8c73613 | |||
| e0284e281c | |||
| 435510baf9 | |||
| cc2583f96b | |||
| de763f8aaa | |||
| 7b67cbc385 | |||
| 7ffb799136 | |||
| 5a84fb25e6 | |||
| 9988300942 | |||
| 4540134a98 | |||
| 656e5a5b0d | |||
| 63e3ba8891 | |||
| d7572d9fd3 | |||
| 63c835df88 | |||
| 7bfd645e8e | |||
| 4e5d3cb4ed | |||
| cff976e2e4 | |||
| 0c69fd6e45 | |||
| 909a58b641 | |||
| 2db4ad46cc | |||
| ffa1023c50 | |||
| f7ef3bbb44 | |||
| bb2b04d2e5 | |||
| 1f36fb608a | |||
| b6e93e5770 | |||
| 8515efe11b | |||
| 7da82f9ef4 | |||
| 6ccba43807 | |||
| 2ce9e2c77e | |||
| a6a54d688f | |||
| e0d2f9c1ba | |||
| 01f8cf0e32 | |||
| ebab80fda1 | |||
| c432a75f62 | |||
| be4989ea34 | |||
| f8dae72411 | |||
| ab46361489 | |||
| 4a986fe5df | |||
| e3d2afac87 | |||
| 0cfcaca6b2 | |||
| 107c9de265 | |||
| 5d6edfd937 | |||
| 60a5a69aa4 | |||
| cc565598d3 | |||
| 6a7000cbc9 | |||
| 6706ff95f1 | |||
| ecc95c9c7f | |||
| d4f2049db6 | |||
| 4d5118de76 | |||
| 171718989a | |||
| 75e8d59cc3 | |||
| 1d7264a71b | |||
| 2c0a63352c | |||
| 42d4d64695 | |||
| 6968f987ce | |||
| 5ecbfd50b8 | |||
| e59a1ea8b4 | |||
| 540ce7f3c3 | |||
| a0d261f966 | |||
| 10446064d5 | |||
| 6709821324 | |||
| 705e60c76d | |||
| 8ac8c16db3 | |||
| 1850caba71 | |||
| 6ccaf3f106 | |||
| d7345e91d3 | |||
| e5e9d4c9ff | |||
| b280f8b736 | |||
| ca452d2421 | |||
| 9e7d4033e0 | |||
| 263a606bff | |||
| 1e853f11b0 | |||
| 77d0956f5d | |||
| d251e8ecf6 | |||
| 01f0e6952d | |||
| 28a67ab60d | |||
| 42bb4e72d2 | |||
| a79d72f975 | |||
| b110413c08 | |||
| a556926fe6 | |||
| 5a57b4a6b1 |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": 1,
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"xamlstyler.console": {
|
||||
"version": "3.2003.9",
|
||||
"commands": [
|
||||
"xstyler"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
github: Tyrrrz
|
||||
patreon: Tyrrrz
|
||||
custom: ['buymeacoffee.com/Tyrrrz', 'tyrrrz.me/donate']
|
||||
@@ -0,0 +1,66 @@
|
||||
name: CD
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v1.4.0
|
||||
with:
|
||||
dotnet-version: 3.1.100
|
||||
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Pack (CLI)
|
||||
run: Compress-Archive -Path DiscordChatExporter.Cli/bin/Publish/* -DestinationPath DiscordChatExporter.Cli/bin/Publish/Archive.zip -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Pack (GUI)
|
||||
run: Compress-Archive -Path DiscordChatExporter.Gui/bin/Publish/* -DestinationPath DiscordChatExporter.Gui/bin/Publish/Archive.zip -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1.0.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ github.ref }}
|
||||
release_name: ${{ github.ref }}
|
||||
body: |
|
||||
[Changelog](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/Changelog.md)
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Upload release asset (CLI)
|
||||
uses: actions/upload-release-asset@v1.0.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: DiscordChatExporter.Cli/bin/Publish/Archive.zip
|
||||
asset_name: DiscordChatExporter.CLI.zip
|
||||
asset_content_type: application/zip
|
||||
|
||||
- name: Upload release asset (GUI)
|
||||
uses: actions/upload-release-asset@v1.0.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
upload_url: ${{ steps.create_release.outputs.upload_url }}
|
||||
asset_path: DiscordChatExporter.Gui/bin/Publish/Archive.zip
|
||||
asset_name: DiscordChatExporter.zip
|
||||
asset_content_type: application/zip
|
||||
@@ -0,0 +1,34 @@
|
||||
name: CI
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v1.4.0
|
||||
with:
|
||||
dotnet-version: 3.1.100
|
||||
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Upload build artifacts (CLI)
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: DiscordChatExporter.CLI
|
||||
path: DiscordChatExporter.Cli/bin/Publish/
|
||||
|
||||
- name: Upload build artifact (GUI)
|
||||
uses: actions/upload-artifact@v1
|
||||
with:
|
||||
name: DiscordChatExporter
|
||||
path: DiscordChatExporter.Gui/bin/Publish/
|
||||
+1
-4
@@ -258,7 +258,4 @@ paket-files/
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Ammy auto-generated XAML
|
||||
*.g.xaml
|
||||
*.pyc
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 105 KiB |
+208
@@ -0,0 +1,208 @@
|
||||
### v2.20 (27-Apr-2020)
|
||||
|
||||
- [CLI] Added environment variables as fallback for `--token` and `--bot` options. They are `DISCORD_TOKEN` and `DISCORD_TOKEN_BOT` respectively.
|
||||
- [GUI] Fixed a crash that occurred if the application was closed in the middle of an auto-update.
|
||||
- [GUI] Added a link to project's wiki in the usage guide.
|
||||
- [HTML] Added full spoiler support for text and images. To spoil the hidden content you now need to click on it, similarly to how it works in Discord. (Thanks [@FM-96](https://github.com/FM-96))
|
||||
- [HTML] Updated grammar for consecutive single-line quotes. Previously they appeared separately, now they're grouped together as if it was one multi-line quote instead.
|
||||
- [HTML] Fixed an issue where messages sent by the same bot but with different usernames were grouped together when they shouldn't be.
|
||||
- [HTML] Updated grammar for single-line code blocks to accept double backticks as synonymous with single backticks. This change makes code blocks appear the same, whether they were inserted manually or using Discord's buggy markdown preview mode.
|
||||
- [HTML] Fixed styling inconsistencies and other minor issues.
|
||||
- [TXT/JSON] Fixed an issue where markdown was not parsed correctly in embed fields.
|
||||
- [HTML] Changed markdown formatting in embeds so it follows the same set of rules as in Discord.
|
||||
- Added channel category to the default file name used when exporting chat logs.
|
||||
- [HTML/TXT/JSON] Added channel category to exported metadata.
|
||||
- [CLI] Updated commands to also show channel category as well as channel name wherever relevant.
|
||||
- Starting with this release, Docker images will have new tags: `stable` for latest stable release and `2.20` for a specific version.
|
||||
|
||||
### v2.19 (26-Mar-2020)
|
||||
|
||||
- Added parallel exporting. This option allows you to export multiple channels faster by doing it in parallel. You can configure the parallel limit in settings (GUI) or with the `--parallel` option (CLI). Default value is `1`, which means there is no parallelization. Warning: be careful when using this option, as this will result in higher volume of concurrent HTTP requests sent to Discord, which might get you flagged. Use at your own risk.
|
||||
- [HTML] Added support for user colors. User names are now appropriately colored according to the assigned guild roles.
|
||||
- [HTML] Added support for nicknames. User names are replaced with nicknames where it's applicable. It's still possible to see the full user name by hovering your mouse over the nickname.
|
||||
- [HTML] Improved styling for mentions to bring it more in line with how it looks in Discord.
|
||||
|
||||
### v2.18 (04-Feb-2020)
|
||||
|
||||
- Added JSON export format. It's a structured data format which is easy to parse. If you're using DiscordChatExporter to export chat logs for further ingestion by another tool, this is most likely the format you will want to use.
|
||||
- [GUI] You can now quickly jump to a specific channel in a list. For example, if you want to jump to a channel named "General", you can simply press the 'g' key in the channel list view. You can also press 'g', 'e' and 'n' in quick succession which will jump to the next channel that starts with "gen". This mechanic is consistent with other Windows applications.
|
||||
- [CLI] Improved help text screen.
|
||||
|
||||
### v2.17 (12-Jan-2020)
|
||||
|
||||
- Fixed an issue where an empty file was produced when exporting a channel with no messages (for specified period). With the new behavior, no file will be created and instead a message will be shown to the user informing of the failure.
|
||||
- [HTML/TXT] Added message count to the bottom of the file. This number shows how many messages were exported as part of the current file. Prior to 2.16 this number was present along with the rest of the metadata at the top, then removed due to changes in the exporter, and now brought back at the end of the file instead.
|
||||
- [HTML] Fixed an issue where some emojis were not properly rendered.
|
||||
- [GUI] Added a setting that lets you configure whether to remember the last used token. Previously it was the default behavior, but now you can disable it if you don't want the token persisted on your system.
|
||||
|
||||
### v2.16 (08-Dec-2019)
|
||||
|
||||
- Migrated from .NET Framework to .NET Core. To run this and future versions of DiscordChatExporter you will need [.NET Core runtime for desktop apps](https://dotnet.microsoft.com/download/dotnet-core/3.1/runtime) (for GUI/CLI version on Windows) or [.NET Core base runtime](https://dotnet.microsoft.com/download/dotnet-core/3.1) (for CLI version on Windows, Linux or macOS).
|
||||
- Reworked the exporter engine to render output using streaming data source. This means that only a very small portion of messages are cached in memory when exporting. In other words, you are only limited by storage space and not how much RAM you have, so you can now export terabytes of chat logs without hitting out of memory exceptions. I still recommend using partitions if you're exporting very large chat logs (250k+ messages) to HTML, unless you want your computer to catch fire when you try to open the export in browser.
|
||||
- Changed how partitioned files are named, due to the fact that total number of partitions is no longer known ahead of time.
|
||||
- Added a warning about automating user accounts to the usage guide in both GUI and CLI versions.
|
||||
- Added support for announcement (news) channels. You will now be able to see them in the list and export them.
|
||||
- Fixed various issues that resulted in exceptions during export process.
|
||||
- [HTML/TXT] Removed message count from the metadata. Due to the fact that the messages are exported as they are streamed, total number of messages is not known ahead of time.
|
||||
- [HTML] Changed default color of the embed color pill to match the theme.
|
||||
- [HTML] Changed emoji parser to be less greedy. As a result it should match fewer character sequences that look like emojis but really aren't, but on the other hand it might miss some actual emojis. This means that some standard emojis (i.e. not custom server emojis) may not look like in Discord. This is a compromise I'm willing to take because detecting emojis in text is really hard to get right and not worth it at all.
|
||||
- [HTML] Some other minor styling adjustments.
|
||||
- [CSV] Replaced semicolons (;) with (,) as separators.
|
||||
|
||||
Please note that CSV export is most likely not going to receive future updates and will remain only as an option for those who wish to use it for text analysis. In other words, it won't contain any of the rich media features like embeds. If you're currently using CSV as a structured output to feed into your program, JSON output will replace that in the future.
|
||||
|
||||
### v2.15 (15-Sep-2019)
|
||||
|
||||
- Improved markdown parser and made it even faster for non-HTML formats.
|
||||
- [HTML] Added support for block quotes.
|
||||
- [HTML] Links pointing to a Discord message will now navigate to the linked message inside exported chat log if it's there.
|
||||
- [HTML] Updated light theme to match how it looks in Discord after recent changes.
|
||||
- [HTML] Added indication for when a message is pinned. Pinned messages now have a tinted background.
|
||||
- [HTML] Fixed an issue where multiline code blocks sometimes had incorrect formatting applied to them.
|
||||
- [TXT] Added indication for when a message is pinned. Pinned messages now have `(pinned)` next to timestamp and author.
|
||||
- [CSV] Added message author's user ID to output.
|
||||
- [GUI] Streamlined auto-update process a bit.
|
||||
- [GUI] Added some tooltips.
|
||||
|
||||
### v2.14 (15-Jun-2019)
|
||||
|
||||
- [TXT] Added support for embeds.
|
||||
- [TXT] Added support for reactions.
|
||||
- [CSV] Added support for reactions.
|
||||
- [TXT] Changed how attachments are rendered.
|
||||
|
||||
### v2.13.1 (06-Jun-2019)
|
||||
|
||||
- Fixed an issue where the app sometimes crashed when exporting due to `System.InvalidCastException`.
|
||||
- [HTML] Added `data-user-id` attribute to `span.chatlog__author-name`. The value of this attribute is author's Discord user ID.
|
||||
|
||||
### v2.13 (15-May-2019)
|
||||
|
||||
- Updated usage instructions.
|
||||
- [HTML] Added BOT tags to messages posted by bots.
|
||||
- [GUI] UI will now be disabled when exporting.
|
||||
- [GUI] Notification informing that the export has completed will now appear after all exports have completed, instead of each of them separately.
|
||||
|
||||
### v2.12.1 (12-Apr-2019)
|
||||
|
||||
- [GUI] Fixed an issue where the app crashed when trying to export multiple channels.
|
||||
- [HTML] Fixed an issue where some of the emojis were rendered via Twemoji while Discord renders them as plain text.
|
||||
- [HTML] Fixed an issue where emojis weren't jumbo if there were more than one of them.
|
||||
|
||||
### v2.12 (11-Apr-2019)
|
||||
|
||||
- Improved markdown parsing performance which speeds up the final stage of exporting by around 4.5 times.
|
||||
- Improved performance when exporting as PlainText or CSV.
|
||||
- [GUI] Fixed an issue where the app would freeze up and report as "not responding" during the final stage of exporting.
|
||||
- [CLI] Fixed an issue where it would say "Completed" after exporting a chat log, even if the process failed.
|
||||
|
||||
### v2.11 (14-Mar-2019)
|
||||
|
||||
- [HTML] Added syntax highlighting for multiline code blocks via Highlight.js.
|
||||
- Added retry policy for all 5xx status codes to prevent random crashes.
|
||||
|
||||
### 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).
|
||||
- Exported file will no longer open automatically on completion.
|
||||
- Reduced amount of memory used during exporting.
|
||||
- Disabled message grouping in PlainText export.
|
||||
- Improved encoding of newlines in CSV export.
|
||||
- Improved error messages in the GUI app during crashes.
|
||||
|
||||
### v2.7 (14-Sep-2018)
|
||||
|
||||
- Updated instructions on how to obtain the user token.
|
||||
- Expanded CLI with new commands: `channels` (get a list of channels in a guild), `dm` (get a list of DM channels), `guilds` (get a list of guilds), on top of `export` (export chatlog).
|
||||
- Improved help text and error messages in CLI.
|
||||
- In CLI, the file name will be automatically generated if the provided output file path is a directory.
|
||||
|
||||
### v2.6 (25-Jul-2018)
|
||||
|
||||
- Added support for bot tokens as an alternative to user tokens. For GUI, use the button in the top-left to switch between user and bot token. For CLI, pass the `--bot` switch to indicate that the given token is a bot token.
|
||||
- Added support for animated avatars.
|
||||
|
||||
### v2.5.1 (01-Jul-2018)
|
||||
|
||||
- Fixed a bug that would prevent timestamps from rendering properly in CSV and PlainText exports.
|
||||
- Fixed incorrect layout in CSV export.
|
||||
- Improved readability of PlainText export.
|
||||
|
||||
### v2.5 (28-Jun-2018)
|
||||
|
||||
- Added support for embeds and webhooks (HTML only).
|
||||
- Implemented progress reporting when downloading messages.
|
||||
- Added support for reactions (HTML only).
|
||||
- Selected date range is now shown in the export (HTML and PlainText).
|
||||
- Added placeholders for guild icons to display while the icons are loading.
|
||||
- Added support for jumbo emojis (custom emojis only).
|
||||
- Added basic retry policy for 429 error responses.
|
||||
- Added validation for from/to dates in the UI which prevents choosing invalid date ranges.
|
||||
- Added an error message when trying to export a deleted channel.
|
||||
|
||||
### v2.4.1 (15-Apr-2018)
|
||||
|
||||
- Added CSV export format.
|
||||
- Channels are now ordered by name in the UI.
|
||||
- Exported file is now always opened upon completion.
|
||||
|
||||
### v2.4 (08-Apr-2018)
|
||||
|
||||
- Added channel topic to output.
|
||||
- Added a command line interface alternative to the current graphical user interface.
|
||||
- Implemented application auto-update (can be disabled in settings).
|
||||
- Improved some GUI elements and replaced some dialogs with notifications.
|
||||
- Fixed a lot of issues with the markdown processor.
|
||||
- Fixed DM group chats that have a custom name being shown as blank in the list.
|
||||
|
||||
### v2.3 (27-Oct-2017)
|
||||
|
||||
- Improved message date filtering, it's now marginally faster.
|
||||
- Fixed underscores not recognized as italics in markdown.
|
||||
- Added support for custom emojis.
|
||||
- Added support for user and role mentions.
|
||||
- Added support for channel mentions.
|
||||
- Fixed text in pre blocks not being wrapped correctly.
|
||||
- Added workaround for non-default message types.
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Utilities;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands.Base
|
||||
{
|
||||
public abstract class ExportCommandBase : TokenCommandBase
|
||||
{
|
||||
[CommandOption("format", 'f', Description = "Output file format.")]
|
||||
public ExportFormat ExportFormat { get; set; } = ExportFormat.HtmlDark;
|
||||
|
||||
[CommandOption("output", 'o', Description = "Output file or directory path.")]
|
||||
public string OutputPath { get; set; } = Directory.GetCurrentDirectory();
|
||||
|
||||
[CommandOption("after", Description = "Limit to messages sent after this date.")]
|
||||
public DateTimeOffset? After { get; set; }
|
||||
|
||||
[CommandOption("before", Description = "Limit to messages sent before this date.")]
|
||||
public DateTimeOffset? Before { get; set; }
|
||||
|
||||
[CommandOption("partition", 'p', Description = "Split output into partitions limited to this number of messages.")]
|
||||
public int? PartitionLimit { get; set; }
|
||||
|
||||
[CommandOption("dateformat", Description = "Date format used in output.")]
|
||||
public string DateFormat { get; set; } = "dd-MMM-yy hh:mm tt";
|
||||
|
||||
protected ChannelExporter GetChannelExporter() => new ChannelExporter(GetDiscordClient());
|
||||
|
||||
protected async ValueTask ExportAsync(IConsole console, Guild guild, Channel channel)
|
||||
{
|
||||
console.Output.Write($"Exporting channel '{channel.Category} / {channel.Name}'... ");
|
||||
var progress = console.CreateProgressTicker();
|
||||
|
||||
await GetChannelExporter().ExportAsync(guild, channel,
|
||||
OutputPath, ExportFormat, DateFormat, PartitionLimit,
|
||||
After, Before, progress);
|
||||
|
||||
console.Output.WriteLine();
|
||||
console.Output.WriteLine("Done.");
|
||||
}
|
||||
|
||||
protected async ValueTask ExportAsync(IConsole console, Channel channel)
|
||||
{
|
||||
var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId);
|
||||
await ExportAsync(console, guild, channel);
|
||||
}
|
||||
|
||||
protected async ValueTask ExportAsync(IConsole console, string channelId)
|
||||
{
|
||||
var channel = await GetDiscordClient().GetChannelAsync(channelId);
|
||||
await ExportAsync(console, channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Utilities;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exceptions;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
using Gress;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands.Base
|
||||
{
|
||||
public abstract class ExportMultipleCommandBase : ExportCommandBase
|
||||
{
|
||||
[CommandOption("parallel", Description = "Export this number of separate channels in parallel.")]
|
||||
public int ParallelLimit { get; set; } = 1;
|
||||
|
||||
protected async ValueTask ExportMultipleAsync(IConsole console, IReadOnlyList<Channel> channels)
|
||||
{
|
||||
// This uses a separate route from ExportCommandBase because the progress ticker is not thread-safe
|
||||
// Ugly code ahead. Will need to refactor.
|
||||
|
||||
console.Output.Write($"Exporting {channels.Count} channels... ");
|
||||
var progress = console.CreateProgressTicker();
|
||||
|
||||
var operations = progress.Wrap().CreateOperations(channels.Count);
|
||||
|
||||
var errors = new List<string>();
|
||||
|
||||
var successfulExportCount = 0;
|
||||
await channels.Zip(operations).ParallelForEachAsync(async tuple =>
|
||||
{
|
||||
var (channel, operation) = tuple;
|
||||
|
||||
try
|
||||
{
|
||||
var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId);
|
||||
|
||||
await GetChannelExporter().ExportAsync(guild, channel,
|
||||
OutputPath, ExportFormat, DateFormat, PartitionLimit,
|
||||
After, Before, operation);
|
||||
|
||||
Interlocked.Increment(ref successfulExportCount);
|
||||
}
|
||||
catch (DiscordChatExporterException ex) when (!ex.IsCritical)
|
||||
{
|
||||
errors.Add(ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
operation.Dispose();
|
||||
}
|
||||
}, ParallelLimit.ClampMin(1));
|
||||
|
||||
console.Output.WriteLine();
|
||||
|
||||
foreach (var error in errors)
|
||||
console.Error.WriteLine(error);
|
||||
|
||||
console.Output.WriteLine($"Successfully exported {successfulExportCount} channel(s).");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Domain.Discord;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands.Base
|
||||
{
|
||||
public abstract class TokenCommandBase : ICommand
|
||||
{
|
||||
[CommandOption("token", 't', IsRequired = true, EnvironmentVariableName = "DISCORD_TOKEN",
|
||||
Description = "Authorization token.")]
|
||||
public string TokenValue { get; set; } = "";
|
||||
|
||||
[CommandOption("bot", 'b', EnvironmentVariableName = "DISCORD_TOKEN_BOT",
|
||||
Description = "Whether this authorization token belongs to a bot.")]
|
||||
public bool IsBotToken { get; set; }
|
||||
|
||||
protected AuthToken GetAuthToken() => new AuthToken(IsBotToken ? AuthTokenType.Bot : AuthTokenType.User, TokenValue);
|
||||
|
||||
protected DiscordClient GetDiscordClient() => new DiscordClient(GetAuthToken());
|
||||
|
||||
public abstract ValueTask ExecuteAsync(IConsole console);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("export", Description = "Export a channel.")]
|
||||
public class ExportChannelCommand : ExportCommandBase
|
||||
{
|
||||
[CommandOption("channel", 'c', IsRequired = true, Description = "Channel ID.")]
|
||||
public string ChannelId { get; set; } = "";
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console) => await ExportAsync(console, ChannelId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("exportdm", Description = "Export all direct message channels.")]
|
||||
public class ExportDirectMessagesCommand : ExportMultipleCommandBase
|
||||
{
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var dmChannels = await GetDiscordClient().GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
||||
await ExportMultipleAsync(console, dmChannels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("exportguild", Description = "Export all channels within specified guild.")]
|
||||
public class ExportGuildCommand : ExportMultipleCommandBase
|
||||
{
|
||||
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||
public string GuildId { get; set; } = "";
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var guildChannels = await GetDiscordClient().GetGuildChannelsAsync(GuildId);
|
||||
await ExportMultipleAsync(console, guildChannels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("channels", Description = "Get the list of channels in specified guild.")]
|
||||
public class GetChannelsCommand : TokenCommandBase
|
||||
{
|
||||
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||
public string GuildId { get; set; } = "";
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var guildChannels = await GetDiscordClient().GetGuildChannelsAsync(GuildId);
|
||||
|
||||
foreach (var channel in guildChannels.OrderBy(c => c.Category).ThenBy(c => c.Name))
|
||||
console.Output.WriteLine($"{channel.Id} | {channel.Category} / {channel.Name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("dm", Description = "Get the list of direct message channels.")]
|
||||
public class GetDirectMessageChannelsCommand : TokenCommandBase
|
||||
{
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var dmChannels = await GetDiscordClient().GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
||||
|
||||
foreach (var channel in dmChannels.OrderBy(c => c.Category).ThenBy(c => c.Name))
|
||||
console.Output.WriteLine($"{channel.Id} | {channel.Category} / {channel.Name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("guilds", Description = "Get the list of accessible guilds.")]
|
||||
public class GetGuildsCommand : TokenCommandBase
|
||||
{
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
var guilds = await GetDiscordClient().GetUserGuildsAsync();
|
||||
|
||||
foreach (var guild in guilds.OrderBy(g => g.Name))
|
||||
console.Output.WriteLine($"{guild.Id} | {guild.Name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("guide", Description = "Explains how to obtain token, guild or channel ID.")]
|
||||
public class GuideCommand : ICommand
|
||||
{
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get user token:"));
|
||||
console.Output.WriteLine(" 1. Open Discord");
|
||||
console.Output.WriteLine(" 2. Press Ctrl+Shift+I to show developer tools");
|
||||
console.Output.WriteLine(" 3. Navigate to the Application tab");
|
||||
console.Output.WriteLine(" 4. Select \"Local Storage\" > \"https://discordapp.com\" on the left");
|
||||
console.Output.WriteLine(" 5. Press Ctrl+R to reload");
|
||||
console.Output.WriteLine(" 6. Find \"token\" at the bottom and copy the value");
|
||||
console.Output.WriteLine(" * Automating user accounts is technically against TOS, use at your own risk.");
|
||||
console.Output.WriteLine();
|
||||
|
||||
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get bot token:"));
|
||||
console.Output.WriteLine(" 1. Go to Discord developer portal");
|
||||
console.Output.WriteLine(" 2. Open your application's settings");
|
||||
console.Output.WriteLine(" 3. Navigate to the Bot section on the left");
|
||||
console.Output.WriteLine(" 4. Under Token click Copy");
|
||||
console.Output.WriteLine();
|
||||
|
||||
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get guild ID or guild channel ID:"));
|
||||
console.Output.WriteLine(" 1. Open Discord");
|
||||
console.Output.WriteLine(" 2. Open Settings");
|
||||
console.Output.WriteLine(" 3. Go to Appearance section");
|
||||
console.Output.WriteLine(" 4. Enable Developer Mode");
|
||||
console.Output.WriteLine(" 5. Right click on the desired guild or channel and click Copy ID");
|
||||
console.Output.WriteLine();
|
||||
|
||||
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get direct message channel ID:"));
|
||||
console.Output.WriteLine(" 1. Open Discord");
|
||||
console.Output.WriteLine(" 2. Open the desired direct message channel");
|
||||
console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
|
||||
console.Output.WriteLine(" 4. Navigate to the Console tab");
|
||||
console.Output.WriteLine(" 5. Type \"window.location.href\" and press Enter");
|
||||
console.Output.WriteLine(" 6. Copy the first long sequence of numbers inside the URL");
|
||||
console.Output.WriteLine();
|
||||
|
||||
console.Output.WriteLine("For more information, check out the wiki:");
|
||||
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ApplicationIcon>..\favicon.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CliFx" Version="1.1.0" />
|
||||
<PackageReference Include="Gress" Version="1.2.0" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Domain\DiscordChatExporter.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
|
||||
namespace DiscordChatExporter.Cli
|
||||
{
|
||||
public static class Program
|
||||
{
|
||||
public static async Task<int> Main(string[] args) =>
|
||||
await new CliApplicationBuilder()
|
||||
.AddCommandsFromThisAssembly()
|
||||
.Build()
|
||||
.RunAsync(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord
|
||||
{
|
||||
public enum AuthTokenType { User, Bot }
|
||||
|
||||
public class AuthToken
|
||||
{
|
||||
public AuthTokenType Type { get; }
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
public AuthToken(AuthTokenType type, string value)
|
||||
{
|
||||
Type = type;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public AuthenticationHeaderValue GetAuthorizationHeader() => Type == AuthTokenType.User
|
||||
? new AuthenticationHeaderValue(Value)
|
||||
: new AuthenticationHeaderValue("Bot", Value);
|
||||
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exceptions;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using Polly;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord
|
||||
{
|
||||
public partial class DiscordClient
|
||||
{
|
||||
private readonly AuthToken _token;
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly IAsyncPolicy<HttpResponseMessage> _httpRequestPolicy;
|
||||
|
||||
private readonly Uri _baseUri = new Uri("https://discordapp.com/api/v6/", UriKind.Absolute);
|
||||
|
||||
public DiscordClient(AuthToken token, HttpClient httpClient)
|
||||
{
|
||||
_token = token;
|
||||
_httpClient = httpClient;
|
||||
|
||||
// Discord seems to always respond with 429 on the first request with unreasonable wait time (10+ minutes).
|
||||
// For that reason the policy will start respecting their retry-after header only after Nth failed response.
|
||||
_httpRequestPolicy = Policy
|
||||
.HandleResult<HttpResponseMessage>(m => m.StatusCode == HttpStatusCode.TooManyRequests)
|
||||
.OrResult(m => m.StatusCode >= HttpStatusCode.InternalServerError)
|
||||
.WaitAndRetryAsync(6,
|
||||
(i, result, ctx) =>
|
||||
{
|
||||
if (i <= 3)
|
||||
return TimeSpan.FromSeconds(2 * i);
|
||||
|
||||
if (i <= 5)
|
||||
return TimeSpan.FromSeconds(5 * i);
|
||||
|
||||
return result.Result.Headers.RetryAfter.Delta ?? TimeSpan.FromSeconds(10 * i);
|
||||
},
|
||||
(response, timespan, retryCount, context) => Task.CompletedTask);
|
||||
}
|
||||
|
||||
public DiscordClient(AuthToken token)
|
||||
: this(token, LazyHttpClient.Value)
|
||||
{
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> GetResponseAsync(string url)
|
||||
{
|
||||
return await _httpRequestPolicy.ExecuteAsync(async () =>
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
|
||||
request.Headers.Authorization = _token.GetAuthorizationHeader();
|
||||
|
||||
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<JsonElement> GetJsonResponseAsync(string url)
|
||||
{
|
||||
using var response = await GetResponseAsync(url);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw response.StatusCode switch
|
||||
{
|
||||
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(),
|
||||
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(),
|
||||
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(),
|
||||
_ => DiscordChatExporterException.FailedHttpRequest(response)
|
||||
};
|
||||
}
|
||||
|
||||
return await response.Content.ReadAsJsonAsync();
|
||||
}
|
||||
|
||||
private async Task<JsonElement?> TryGetJsonResponseAsync(string url)
|
||||
{
|
||||
using var response = await GetResponseAsync(url);
|
||||
|
||||
return response.IsSuccessStatusCode
|
||||
? await response.Content.ReadAsJsonAsync()
|
||||
: (JsonElement?) null;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Guild> GetUserGuildsAsync()
|
||||
{
|
||||
yield return Guild.DirectMessages;
|
||||
|
||||
var afterId = "";
|
||||
while (true)
|
||||
{
|
||||
var url = new UrlBuilder()
|
||||
.SetPath("users/@me/guilds")
|
||||
.SetQueryParameter("limit", "100")
|
||||
.SetQueryParameterIfNotNullOrWhiteSpace("after", afterId)
|
||||
.Build();
|
||||
|
||||
var response = await GetJsonResponseAsync(url);
|
||||
|
||||
var isEmpty = true;
|
||||
foreach (var guildJson in response.EnumerateArray())
|
||||
{
|
||||
var guild = Guild.Parse(guildJson);
|
||||
yield return guild;
|
||||
|
||||
afterId = guild.Id;
|
||||
isEmpty = false;
|
||||
}
|
||||
|
||||
if (isEmpty)
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Guild> GetGuildAsync(string guildId)
|
||||
{
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
return Guild.DirectMessages;
|
||||
|
||||
var response = await GetJsonResponseAsync($"guilds/{guildId}");
|
||||
return Guild.Parse(response);
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Channel> GetGuildChannelsAsync(string guildId)
|
||||
{
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
{
|
||||
var response = await GetJsonResponseAsync("users/@me/channels");
|
||||
foreach (var channelJson in response.EnumerateArray())
|
||||
yield return Channel.Parse(channelJson);
|
||||
}
|
||||
else
|
||||
{
|
||||
var response = await GetJsonResponseAsync($"guilds/{guildId}/channels");
|
||||
|
||||
var categories = response
|
||||
.EnumerateArray()
|
||||
.ToDictionary(
|
||||
j => j.GetProperty("id").GetString(),
|
||||
j => j.GetProperty("name").GetString()
|
||||
);
|
||||
|
||||
foreach (var channelJson in response.EnumerateArray())
|
||||
{
|
||||
var parentId = channelJson.GetPropertyOrNull("parent_id")?.GetString();
|
||||
var category = !string.IsNullOrWhiteSpace(parentId)
|
||||
? categories.GetValueOrDefault(parentId)
|
||||
: null;
|
||||
|
||||
var channel = Channel.Parse(channelJson, category);
|
||||
|
||||
// Skip non-text channels
|
||||
if (!channel.IsTextChannel)
|
||||
continue;
|
||||
|
||||
yield return channel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Role> GetGuildRolesAsync(string guildId)
|
||||
{
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
yield break;
|
||||
|
||||
var response = await GetJsonResponseAsync($"guilds/{guildId}/roles");
|
||||
|
||||
foreach (var roleJson in response.EnumerateArray())
|
||||
yield return Role.Parse(roleJson);
|
||||
}
|
||||
|
||||
public async Task<Member?> TryGetGuildMemberAsync(string guildId, User user)
|
||||
{
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
return Member.CreateForUser(user);
|
||||
|
||||
var response = await TryGetJsonResponseAsync($"guilds/{guildId}/members/{user.Id}");
|
||||
return response?.Pipe(Member.Parse);
|
||||
}
|
||||
|
||||
private async Task<string> GetChannelCategoryAsync(string channelParentId)
|
||||
{
|
||||
var response = await GetJsonResponseAsync($"channels/{channelParentId}");
|
||||
return response.GetProperty("name").GetString();
|
||||
}
|
||||
|
||||
public async Task<Channel> GetChannelAsync(string channelId)
|
||||
{
|
||||
var response = await GetJsonResponseAsync($"channels/{channelId}");
|
||||
|
||||
var parentId = response.GetPropertyOrNull("parent_id")?.GetString();
|
||||
var category = !string.IsNullOrWhiteSpace(parentId)
|
||||
? await GetChannelCategoryAsync(parentId)
|
||||
: null;
|
||||
|
||||
return Channel.Parse(response, category);
|
||||
}
|
||||
|
||||
private async Task<Message?> TryGetLastMessageAsync(string channelId, DateTimeOffset? before = null)
|
||||
{
|
||||
var url = new UrlBuilder()
|
||||
.SetPath($"channels/{channelId}/messages")
|
||||
.SetQueryParameter("limit", "1")
|
||||
.SetQueryParameterIfNotNullOrWhiteSpace("before", before?.ToSnowflake())
|
||||
.Build();
|
||||
|
||||
var response = await GetJsonResponseAsync(url);
|
||||
return response.EnumerateArray().Select(Message.Parse).LastOrDefault();
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Message> GetMessagesAsync(
|
||||
string channelId,
|
||||
DateTimeOffset? after = null,
|
||||
DateTimeOffset? before = null,
|
||||
IProgress<double>? progress = null)
|
||||
{
|
||||
// Get the last message in the specified range
|
||||
var lastMessage = await TryGetLastMessageAsync(channelId, before);
|
||||
if (lastMessage == null || lastMessage.Timestamp < after)
|
||||
yield break;
|
||||
|
||||
var firstMessage = default(Message);
|
||||
var afterId = after?.ToSnowflake() ?? "0";
|
||||
|
||||
while (true)
|
||||
{
|
||||
var url = new UrlBuilder()
|
||||
.SetPath($"channels/{channelId}/messages")
|
||||
.SetQueryParameter("limit", "100")
|
||||
.SetQueryParameter("after", afterId)
|
||||
.Build();
|
||||
|
||||
var response = await GetJsonResponseAsync(url);
|
||||
|
||||
var messages = response
|
||||
.EnumerateArray()
|
||||
.Select(Message.Parse)
|
||||
.Reverse() // reverse because messages appear newest first
|
||||
.ToArray();
|
||||
|
||||
// Break if there are no messages (can happen if messages are deleted during execution)
|
||||
if (!messages.Any())
|
||||
yield break;
|
||||
|
||||
foreach (var message in messages)
|
||||
{
|
||||
firstMessage ??= message;
|
||||
|
||||
// Ensure messages are in range (take into account that last message could have been deleted)
|
||||
if (message.Timestamp > lastMessage.Timestamp)
|
||||
yield break;
|
||||
|
||||
// Report progress based on the duration of parsed messages divided by total
|
||||
progress?.Report(
|
||||
(message.Timestamp - firstMessage.Timestamp) /
|
||||
(lastMessage.Timestamp - firstMessage.Timestamp)
|
||||
);
|
||||
|
||||
yield return message;
|
||||
afterId = message.Id;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public partial class DiscordClient
|
||||
{
|
||||
private static readonly Lazy<HttpClient> LazyHttpClient = new Lazy<HttpClient>(() =>
|
||||
{
|
||||
var handler = new HttpClientHandler();
|
||||
|
||||
if (handler.SupportsAutomaticDecompression)
|
||||
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||
|
||||
handler.UseCookies = false;
|
||||
|
||||
return new HttpClient(handler, true);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#attachment-object
|
||||
public partial class Attachment : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Url { get; }
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
public int? Width { get; }
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public bool IsImage =>
|
||||
ImageFileExtensions.Contains(Path.GetExtension(FileName), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public bool IsSpoiler =>
|
||||
IsImage && FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
|
||||
|
||||
public FileSize FileSize { get; }
|
||||
|
||||
public Attachment(string id, string url, string fileName, int? width, int? height, FileSize fileSize)
|
||||
{
|
||||
Id = id;
|
||||
Url = url;
|
||||
FileName = fileName;
|
||||
Width = width;
|
||||
Height = height;
|
||||
FileSize = fileSize;
|
||||
}
|
||||
|
||||
public override string ToString() => FileName;
|
||||
}
|
||||
|
||||
public partial class Attachment
|
||||
{
|
||||
private static readonly string[] ImageFileExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
|
||||
|
||||
public static Attachment Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var url = json.GetProperty("url").GetString();
|
||||
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
||||
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
||||
var fileName = json.GetProperty("filename").GetString();
|
||||
var fileSize = json.GetProperty("size").GetInt64().Pipe(FileSize.FromBytes);
|
||||
|
||||
return new Attachment(id, url, fileName, width, height, fileSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#channel-object-channel-types
|
||||
// Order of enum fields needs to match the order in the docs.
|
||||
public enum ChannelType
|
||||
{
|
||||
GuildTextChat,
|
||||
DirectTextChat,
|
||||
GuildVoiceChat,
|
||||
DirectGroupTextChat,
|
||||
GuildCategory,
|
||||
GuildNews,
|
||||
GuildStore
|
||||
}
|
||||
|
||||
// https://discordapp.com/developers/docs/resources/channel#channel-object
|
||||
public partial class Channel : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public ChannelType Type { get; }
|
||||
|
||||
public bool IsTextChannel =>
|
||||
Type == ChannelType.GuildTextChat ||
|
||||
Type == ChannelType.DirectTextChat ||
|
||||
Type == ChannelType.DirectGroupTextChat ||
|
||||
Type == ChannelType.GuildNews ||
|
||||
Type == ChannelType.GuildStore;
|
||||
|
||||
public string GuildId { get; }
|
||||
|
||||
public string Category { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string? Topic { get; }
|
||||
|
||||
public Channel(string id, ChannelType type, string guildId, string category, string name, string? topic)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
GuildId = guildId;
|
||||
Category = category;
|
||||
Name = name;
|
||||
Topic = topic;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Channel
|
||||
{
|
||||
private static string GetDefaultCategory(ChannelType channelType) => channelType switch
|
||||
{
|
||||
ChannelType.GuildTextChat => "Text",
|
||||
ChannelType.DirectTextChat => "Private",
|
||||
ChannelType.DirectGroupTextChat => "Group",
|
||||
ChannelType.GuildNews => "News",
|
||||
ChannelType.GuildStore => "Store",
|
||||
_ => "Default"
|
||||
};
|
||||
|
||||
public static Channel Parse(JsonElement json, string? category = null)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var guildId = json.GetPropertyOrNull("guild_id")?.GetString();
|
||||
var topic = json.GetPropertyOrNull("topic")?.GetString();
|
||||
|
||||
var type = (ChannelType) json.GetProperty("type").GetInt32();
|
||||
|
||||
var name =
|
||||
json.GetPropertyOrNull("name")?.GetString() ??
|
||||
json.GetPropertyOrNull("recipients")?.EnumerateArray().Select(User.Parse).Select(u => u.Name).JoinToString(", ") ??
|
||||
id;
|
||||
|
||||
return new Channel(
|
||||
id,
|
||||
type,
|
||||
guildId ?? Guild.DirectMessages.Id,
|
||||
category ?? GetDefaultCategory(type),
|
||||
name,
|
||||
topic);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models.Common
|
||||
{
|
||||
// Loosely based on https://github.com/omar/ByteSize (MIT license)
|
||||
public readonly partial struct FileSize
|
||||
{
|
||||
public long TotalBytes { get; }
|
||||
|
||||
public double TotalKiloBytes => TotalBytes / 1024.0;
|
||||
public double TotalMegaBytes => TotalKiloBytes / 1024.0;
|
||||
public double TotalGigaBytes => TotalMegaBytes / 1024.0;
|
||||
public double TotalTeraBytes => TotalGigaBytes / 1024.0;
|
||||
public double TotalPetaBytes => TotalTeraBytes / 1024.0;
|
||||
|
||||
public FileSize(long bytes) => TotalBytes = bytes;
|
||||
|
||||
private double GetLargestWholeNumberValue()
|
||||
{
|
||||
if (Math.Abs(TotalPetaBytes) >= 1)
|
||||
return TotalPetaBytes;
|
||||
|
||||
if (Math.Abs(TotalTeraBytes) >= 1)
|
||||
return TotalTeraBytes;
|
||||
|
||||
if (Math.Abs(TotalGigaBytes) >= 1)
|
||||
return TotalGigaBytes;
|
||||
|
||||
if (Math.Abs(TotalMegaBytes) >= 1)
|
||||
return TotalMegaBytes;
|
||||
|
||||
if (Math.Abs(TotalKiloBytes) >= 1)
|
||||
return TotalKiloBytes;
|
||||
|
||||
return TotalBytes;
|
||||
}
|
||||
|
||||
private string GetLargestWholeNumberSymbol()
|
||||
{
|
||||
if (Math.Abs(TotalPetaBytes) >= 1)
|
||||
return "PB";
|
||||
|
||||
if (Math.Abs(TotalTeraBytes) >= 1)
|
||||
return "TB";
|
||||
|
||||
if (Math.Abs(TotalGigaBytes) >= 1)
|
||||
return "GB";
|
||||
|
||||
if (Math.Abs(TotalMegaBytes) >= 1)
|
||||
return "MB";
|
||||
|
||||
if (Math.Abs(TotalKiloBytes) >= 1)
|
||||
return "KB";
|
||||
|
||||
return "B";
|
||||
}
|
||||
|
||||
public override string ToString() => $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}";
|
||||
}
|
||||
|
||||
public partial struct FileSize
|
||||
{
|
||||
public static FileSize FromBytes(long bytes) => new FileSize(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace DiscordChatExporter.Domain.Discord.Models.Common
|
||||
{
|
||||
public interface IHasId
|
||||
{
|
||||
string Id { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models.Common
|
||||
{
|
||||
public partial class IdBasedEqualityComparer : IEqualityComparer<IHasId>
|
||||
{
|
||||
public bool Equals(IHasId? x, IHasId? y) => StringComparer.Ordinal.Equals(x?.Id, y?.Id);
|
||||
|
||||
public int GetHashCode(IHasId obj) => StringComparer.Ordinal.GetHashCode(obj.Id);
|
||||
}
|
||||
|
||||
public partial class IdBasedEqualityComparer
|
||||
{
|
||||
public static IdBasedEqualityComparer Instance { get; } = new IdBasedEqualityComparer();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object
|
||||
public partial class Embed
|
||||
{
|
||||
public string? Title { get; }
|
||||
|
||||
public string? Url { get; }
|
||||
|
||||
public DateTimeOffset? Timestamp { get; }
|
||||
|
||||
public Color? Color { get; }
|
||||
|
||||
public EmbedAuthor? Author { get; }
|
||||
|
||||
public string? Description { get; }
|
||||
|
||||
public IReadOnlyList<EmbedField> Fields { get; }
|
||||
|
||||
public EmbedImage? Thumbnail { get; }
|
||||
|
||||
public EmbedImage? Image { get; }
|
||||
|
||||
public EmbedFooter? Footer { get; }
|
||||
|
||||
public Embed(
|
||||
string? title,
|
||||
string? url,
|
||||
DateTimeOffset? timestamp,
|
||||
Color? color,
|
||||
EmbedAuthor? author,
|
||||
string? description,
|
||||
IReadOnlyList<EmbedField> fields,
|
||||
EmbedImage? thumbnail,
|
||||
EmbedImage? image,
|
||||
EmbedFooter? footer)
|
||||
{
|
||||
Title = title;
|
||||
Url = url;
|
||||
Timestamp = timestamp;
|
||||
Color = color;
|
||||
Author = author;
|
||||
Description = description;
|
||||
Fields = fields;
|
||||
Thumbnail = thumbnail;
|
||||
Image = image;
|
||||
Footer = footer;
|
||||
}
|
||||
|
||||
public override string ToString() => Title ?? "<untitled embed>";
|
||||
}
|
||||
|
||||
public partial class Embed
|
||||
{
|
||||
public static Embed Parse(JsonElement json)
|
||||
{
|
||||
var title = json.GetPropertyOrNull("title")?.GetString();
|
||||
var description = json.GetPropertyOrNull("description")?.GetString();
|
||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffset();
|
||||
var color = json.GetPropertyOrNull("color")?.GetInt32().Pipe(System.Drawing.Color.FromArgb).ResetAlpha();
|
||||
|
||||
var author = json.GetPropertyOrNull("author")?.Pipe(EmbedAuthor.Parse);
|
||||
var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse);
|
||||
var image = json.GetPropertyOrNull("image")?.Pipe(EmbedImage.Parse);
|
||||
var footer = json.GetPropertyOrNull("footer")?.Pipe(EmbedFooter.Parse);
|
||||
|
||||
var fields =
|
||||
json.GetPropertyOrNull("fields")?.EnumerateArray().Select(EmbedField.Parse).ToArray() ??
|
||||
Array.Empty<EmbedField>();
|
||||
|
||||
return new Embed(
|
||||
title,
|
||||
url,
|
||||
timestamp,
|
||||
color,
|
||||
author,
|
||||
description,
|
||||
fields,
|
||||
thumbnail,
|
||||
image,
|
||||
footer
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-author-structure
|
||||
public partial class EmbedAuthor
|
||||
{
|
||||
public string? Name { get; }
|
||||
|
||||
public string? Url { get; }
|
||||
|
||||
public string? IconUrl { get; }
|
||||
|
||||
public EmbedAuthor(string? name, string? url, string? iconUrl)
|
||||
{
|
||||
Name = name;
|
||||
Url = url;
|
||||
IconUrl = iconUrl;
|
||||
}
|
||||
|
||||
public override string ToString() => Name ?? "<unnamed author>";
|
||||
}
|
||||
|
||||
public partial class EmbedAuthor
|
||||
{
|
||||
public static EmbedAuthor Parse(JsonElement json)
|
||||
{
|
||||
var name = json.GetPropertyOrNull("name")?.GetString();
|
||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
||||
|
||||
return new EmbedAuthor(name, url, iconUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-field-structure
|
||||
public partial class EmbedField
|
||||
{
|
||||
public string Name { get; }
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
public bool IsInline { get; }
|
||||
|
||||
public EmbedField(string name, string value, bool isInline)
|
||||
{
|
||||
Name = name;
|
||||
Value = value;
|
||||
IsInline = isInline;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{Name} | {Value}";
|
||||
}
|
||||
|
||||
public partial class EmbedField
|
||||
{
|
||||
public static EmbedField Parse(JsonElement json)
|
||||
{
|
||||
var name = json.GetProperty("name").GetString();
|
||||
var value = json.GetProperty("value").GetString();
|
||||
var isInline = json.GetPropertyOrNull("inline")?.GetBoolean() ?? false;
|
||||
|
||||
return new EmbedField(name, value, isInline);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-footer-structure
|
||||
public partial class EmbedFooter
|
||||
{
|
||||
public string Text { get; }
|
||||
|
||||
public string? IconUrl { get; }
|
||||
|
||||
public EmbedFooter(string text, string? iconUrl)
|
||||
{
|
||||
Text = text;
|
||||
IconUrl = iconUrl;
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
}
|
||||
|
||||
public partial class EmbedFooter
|
||||
{
|
||||
public static EmbedFooter Parse(JsonElement json)
|
||||
{
|
||||
var text = json.GetProperty("text").GetString();
|
||||
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
||||
|
||||
return new EmbedFooter(text, iconUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-image-structure
|
||||
public partial class EmbedImage
|
||||
{
|
||||
public string? Url { get; }
|
||||
|
||||
public int? Width { get; }
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public EmbedImage(string? url, int? width, int? height)
|
||||
{
|
||||
Url = url;
|
||||
Height = height;
|
||||
Width = width;
|
||||
}
|
||||
}
|
||||
|
||||
public partial class EmbedImage
|
||||
{
|
||||
public static EmbedImage Parse(JsonElement json)
|
||||
{
|
||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
||||
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
||||
|
||||
return new EmbedImage(url, width, height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.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; }
|
||||
|
||||
public Emoji(string? id, string name, bool isAnimated)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IsAnimated = isAnimated;
|
||||
|
||||
ImageUrl = GetImageUrl(id, name, isAnimated);
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Emoji
|
||||
{
|
||||
private static IEnumerable<Rune> GetRunes(string emoji)
|
||||
{
|
||||
var lastIndex = 0;
|
||||
while (lastIndex < emoji.Length && Rune.TryGetRuneAt(emoji, lastIndex, out var rune))
|
||||
{
|
||||
// Skip variant selector rune
|
||||
if (rune.Value != 0xfe0f)
|
||||
yield return rune;
|
||||
|
||||
lastIndex += rune.Utf16SequenceLength;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetTwemojiName(IEnumerable<Rune> runes) =>
|
||||
runes.Select(r => r.Value.ToString("x")).JoinToString("-");
|
||||
|
||||
public static string GetImageUrl(string? id, string name, bool isAnimated)
|
||||
{
|
||||
// Custom emoji
|
||||
if (!string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
// Animated
|
||||
if (isAnimated)
|
||||
return $"https://cdn.discordapp.com/emojis/{id}.gif";
|
||||
|
||||
// Non-animated
|
||||
return $"https://cdn.discordapp.com/emojis/{id}.png";
|
||||
}
|
||||
|
||||
// Standard emoji
|
||||
var emojiRunes = GetRunes(name).ToArray();
|
||||
var twemojiName = GetTwemojiName(emojiRunes);
|
||||
return $"https://twemoji.maxcdn.com/2/72x72/{twemojiName}.png";
|
||||
}
|
||||
|
||||
public static Emoji Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetPropertyOrNull("id")?.GetString();
|
||||
var name = json.GetProperty("name").GetString();
|
||||
var isAnimated = json.GetPropertyOrNull("animated")?.GetBoolean() ?? false;
|
||||
|
||||
return new Emoji(id, name, isAnimated);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/guild#guild-object
|
||||
public partial class Guild : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string IconUrl { get; }
|
||||
|
||||
public Guild(string id, string name, string? iconHash)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
|
||||
IconUrl = GetIconUrl(id, iconHash);
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Guild
|
||||
{
|
||||
public static Guild DirectMessages { get; } =
|
||||
new Guild("@me", "Direct Messages", null);
|
||||
|
||||
private static string GetIconUrl(string id, string? iconHash) =>
|
||||
!string.IsNullOrWhiteSpace(iconHash)
|
||||
? $"https://cdn.discordapp.com/icons/{id}/{iconHash}.png"
|
||||
: "https://cdn.discordapp.com/embed/avatars/0.png";
|
||||
|
||||
public static Guild Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var name = json.GetProperty("name").GetString();
|
||||
var iconHash = json.GetProperty("icon").GetString();
|
||||
|
||||
return new Guild(id, name, iconHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/guild#guild-member-object
|
||||
public partial class Member : IHasId
|
||||
{
|
||||
public string Id => User.Id;
|
||||
|
||||
public User User { get; }
|
||||
|
||||
public string Nick { get; }
|
||||
|
||||
public IReadOnlyList<string> RoleIds { get; }
|
||||
|
||||
public Member(User user, string? nick, IReadOnlyList<string> roleIds)
|
||||
{
|
||||
User = user;
|
||||
Nick = nick ?? user.Name;
|
||||
RoleIds = roleIds;
|
||||
}
|
||||
|
||||
public override string ToString() => Nick;
|
||||
}
|
||||
|
||||
public partial class Member
|
||||
{
|
||||
public static Member CreateForUser(User user) =>
|
||||
new Member(user, null, Array.Empty<string>());
|
||||
|
||||
public static Member Parse(JsonElement json)
|
||||
{
|
||||
var user = json.GetProperty("user").Pipe(User.Parse);
|
||||
var nick = json.GetPropertyOrNull("nick")?.GetString();
|
||||
|
||||
var roleIds =
|
||||
json.GetPropertyOrNull("roles")?.EnumerateArray().Select(j => j.GetString()).ToArray() ??
|
||||
Array.Empty<string>();
|
||||
|
||||
return new Member(
|
||||
user,
|
||||
nick,
|
||||
roleIds
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#message-object-message-types
|
||||
public enum MessageType
|
||||
{
|
||||
Default,
|
||||
RecipientAdd,
|
||||
RecipientRemove,
|
||||
Call,
|
||||
ChannelNameChange,
|
||||
ChannelIconChange,
|
||||
ChannelPinnedMessage,
|
||||
GuildMemberJoin
|
||||
}
|
||||
|
||||
// https://discordapp.com/developers/docs/resources/channel#message-object
|
||||
public partial class Message : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public MessageType Type { get; }
|
||||
|
||||
public User Author { get; }
|
||||
|
||||
public DateTimeOffset Timestamp { get; }
|
||||
|
||||
public DateTimeOffset? EditedTimestamp { get; }
|
||||
|
||||
public bool IsPinned { get; }
|
||||
|
||||
public string Content { get; }
|
||||
|
||||
public IReadOnlyList<Attachment> Attachments { get; }
|
||||
|
||||
public IReadOnlyList<Embed> Embeds { get; }
|
||||
|
||||
public IReadOnlyList<Reaction> Reactions { get; }
|
||||
|
||||
public IReadOnlyList<User> MentionedUsers { get; }
|
||||
|
||||
public Message(
|
||||
string id,
|
||||
MessageType type,
|
||||
User author,
|
||||
DateTimeOffset timestamp,
|
||||
DateTimeOffset? editedTimestamp,
|
||||
bool isPinned,
|
||||
string content,
|
||||
IReadOnlyList<Attachment> attachments,
|
||||
IReadOnlyList<Embed> embeds,
|
||||
IReadOnlyList<Reaction> reactions,
|
||||
IReadOnlyList<User> mentionedUsers)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
Author = author;
|
||||
Timestamp = timestamp;
|
||||
EditedTimestamp = editedTimestamp;
|
||||
IsPinned = isPinned;
|
||||
Content = content;
|
||||
Attachments = attachments;
|
||||
Embeds = embeds;
|
||||
Reactions = reactions;
|
||||
MentionedUsers = mentionedUsers;
|
||||
}
|
||||
|
||||
public override string ToString() =>
|
||||
Content ?? (Embeds.Any()
|
||||
? "<embed>"
|
||||
: "<no content>");
|
||||
}
|
||||
|
||||
public partial class Message
|
||||
{
|
||||
public static Message Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var author = json.GetProperty("author").Pipe(User.Parse);
|
||||
var timestamp = json.GetProperty("timestamp").GetDateTimeOffset();
|
||||
var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffset();
|
||||
var type = (MessageType) json.GetProperty("type").GetInt32();
|
||||
var isPinned = json.GetPropertyOrNull("pinned")?.GetBoolean() ?? false;
|
||||
|
||||
var content = type switch
|
||||
{
|
||||
MessageType.RecipientAdd => "Added a recipient.",
|
||||
MessageType.RecipientRemove => "Removed a recipient.",
|
||||
MessageType.Call => "Started a call.",
|
||||
MessageType.ChannelNameChange => "Changed the channel name.",
|
||||
MessageType.ChannelIconChange => "Changed the channel icon.",
|
||||
MessageType.ChannelPinnedMessage => "Pinned a message.",
|
||||
MessageType.GuildMemberJoin => "Joined the server.",
|
||||
_ => json.GetPropertyOrNull("content")?.GetString() ?? ""
|
||||
};
|
||||
|
||||
var attachments =
|
||||
json.GetPropertyOrNull("attachments")?.EnumerateArray().Select(Attachment.Parse).ToArray() ??
|
||||
Array.Empty<Attachment>();
|
||||
|
||||
var embeds =
|
||||
json.GetPropertyOrNull("embeds")?.EnumerateArray().Select(Embed.Parse).ToArray() ??
|
||||
Array.Empty<Embed>();
|
||||
|
||||
var reactions =
|
||||
json.GetPropertyOrNull("reactions")?.EnumerateArray().Select(Reaction.Parse).ToArray() ??
|
||||
Array.Empty<Reaction>();
|
||||
|
||||
var mentionedUsers =
|
||||
json.GetPropertyOrNull("mentions")?.EnumerateArray().Select(User.Parse).ToArray() ??
|
||||
Array.Empty<User>();
|
||||
|
||||
return new Message(
|
||||
id,
|
||||
type,
|
||||
author,
|
||||
timestamp,
|
||||
editedTimestamp,
|
||||
isPinned,
|
||||
content,
|
||||
attachments,
|
||||
embeds,
|
||||
reactions,
|
||||
mentionedUsers
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#reaction-object
|
||||
public partial class Reaction
|
||||
{
|
||||
public Emoji Emoji { get; }
|
||||
|
||||
public int Count { get; }
|
||||
|
||||
public Reaction(Emoji emoji, int count)
|
||||
{
|
||||
Emoji = emoji;
|
||||
Count = count;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{Emoji} ({Count})";
|
||||
}
|
||||
|
||||
public partial class Reaction
|
||||
{
|
||||
public static Reaction Parse(JsonElement json)
|
||||
{
|
||||
var count = json.GetProperty("count").GetInt32();
|
||||
var emoji = json.GetProperty("emoji").Pipe(Emoji.Parse);
|
||||
|
||||
return new Reaction(emoji, count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Drawing;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/topics/permissions#role-object
|
||||
public partial class Role
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public int Position { get; }
|
||||
|
||||
public Color? Color { get; }
|
||||
|
||||
public Role(string id, string name, int position, Color? color)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
Position = position;
|
||||
Color = color;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Role
|
||||
{
|
||||
public static Role Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var name = json.GetProperty("name").GetString();
|
||||
var position = json.GetProperty("position").GetInt32();
|
||||
|
||||
var color = json.GetPropertyOrNull("color")?
|
||||
.GetInt32()
|
||||
.Pipe(System.Drawing.Color.FromArgb)
|
||||
.ResetAlpha()
|
||||
.NullIf(c => c.ToRgb() <= 0);
|
||||
|
||||
return new Role(id, name, position, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/user#user-object
|
||||
public partial class User : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public bool IsBot { get; }
|
||||
|
||||
public int Discriminator { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string FullName => $"{Name}#{Discriminator:0000}";
|
||||
|
||||
public string AvatarUrl { get; }
|
||||
|
||||
public User(string id, bool isBot, int discriminator, string name, string? avatarHash)
|
||||
{
|
||||
Id = id;
|
||||
IsBot = isBot;
|
||||
Discriminator = discriminator;
|
||||
Name = name;
|
||||
|
||||
AvatarUrl = GetAvatarUrl(id, discriminator, avatarHash);
|
||||
}
|
||||
|
||||
public override string ToString() => FullName;
|
||||
}
|
||||
|
||||
public partial class User
|
||||
{
|
||||
private static string GetAvatarUrl(string id, int discriminator, string? avatarHash)
|
||||
{
|
||||
// Custom avatar
|
||||
if (!string.IsNullOrWhiteSpace(avatarHash))
|
||||
{
|
||||
// Animated
|
||||
if (avatarHash.StartsWith("a_", StringComparison.Ordinal))
|
||||
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.gif";
|
||||
|
||||
// Non-animated
|
||||
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.png";
|
||||
}
|
||||
|
||||
// Default avatar
|
||||
return $"https://cdn.discordapp.com/embed/avatars/{discriminator % 5}.png";
|
||||
}
|
||||
|
||||
public static User Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString();
|
||||
var discriminator = json.GetProperty("discriminator").GetString().Pipe(int.Parse);
|
||||
var name = json.GetProperty("username").GetString();
|
||||
var avatarHash = json.GetProperty("avatar").GetString();
|
||||
var isBot = json.GetPropertyOrNull("bot")?.GetBoolean() ?? false;
|
||||
|
||||
return new User(id, isBot, discriminator, name, avatarHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Discord
|
||||
{
|
||||
internal class UrlBuilder
|
||||
{
|
||||
private string _path = "";
|
||||
|
||||
private readonly Dictionary<string, string?> _queryParameters =
|
||||
new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public UrlBuilder SetPath(string path)
|
||||
{
|
||||
_path = path;
|
||||
return this;
|
||||
}
|
||||
|
||||
public UrlBuilder SetQueryParameter(string key, string? value)
|
||||
{
|
||||
var keyEncoded = WebUtility.UrlEncode(key);
|
||||
var valueEncoded = WebUtility.UrlEncode(value);
|
||||
_queryParameters[keyEncoded] = valueEncoded;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public UrlBuilder SetQueryParameterIfNotNullOrWhiteSpace(string key, string? value) =>
|
||||
!string.IsNullOrWhiteSpace(value)
|
||||
? SetQueryParameter(key, value)
|
||||
: this;
|
||||
|
||||
public string Build()
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer.Append(_path);
|
||||
|
||||
if (_queryParameters.Any())
|
||||
buffer.Append('?').AppendJoin('&', _queryParameters.Select(kvp => $"{kvp.Key}={kvp.Value}"));
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Polly" Version="7.2.0" />
|
||||
<PackageReference Include="Scriban" Version="2.1.2" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Exporting\Resources\HtmlCore.css" />
|
||||
<EmbeddedResource Include="Exporting\Resources\HtmlDark.css" />
|
||||
<EmbeddedResource Include="Exporting\Resources\HtmlLayoutTemplate.html" />
|
||||
<EmbeddedResource Include="Exporting\Resources\HtmlLight.css" />
|
||||
<EmbeddedResource Include="Exporting\Resources\HtmlMessageGroupTemplate.html" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exceptions
|
||||
{
|
||||
public partial class DiscordChatExporterException : Exception
|
||||
{
|
||||
public bool IsCritical { get; }
|
||||
|
||||
public DiscordChatExporterException(string message, bool isCritical = false)
|
||||
: base(message)
|
||||
{
|
||||
IsCritical = isCritical;
|
||||
}
|
||||
}
|
||||
|
||||
public partial class DiscordChatExporterException
|
||||
{
|
||||
internal static DiscordChatExporterException FailedHttpRequest(HttpResponseMessage response)
|
||||
{
|
||||
var message = $@"
|
||||
Failed to perform an HTTP request.
|
||||
|
||||
{response.RequestMessage}
|
||||
|
||||
{response}";
|
||||
|
||||
return new DiscordChatExporterException(message.Trim(), true);
|
||||
}
|
||||
|
||||
internal static DiscordChatExporterException Unauthorized()
|
||||
{
|
||||
const string message = "Authentication token is invalid.";
|
||||
return new DiscordChatExporterException(message);
|
||||
}
|
||||
|
||||
internal static DiscordChatExporterException Forbidden()
|
||||
{
|
||||
const string message = "Access is forbidden.";
|
||||
return new DiscordChatExporterException(message);
|
||||
}
|
||||
|
||||
internal static DiscordChatExporterException NotFound()
|
||||
{
|
||||
const string message = "Not found.";
|
||||
return new DiscordChatExporterException(message);
|
||||
}
|
||||
|
||||
internal static DiscordChatExporterException ChannelEmpty(string channel)
|
||||
{
|
||||
var message = $"Channel '{channel}' contains no messages for the specified period.";
|
||||
return new DiscordChatExporterException(message);
|
||||
}
|
||||
|
||||
internal static DiscordChatExporterException ChannelEmpty(Channel channel) =>
|
||||
ChannelEmpty(channel.Name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
||||
using DiscordChatExporter.Domain.Exceptions;
|
||||
using DiscordChatExporter.Domain.Utilities;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
public partial class ChannelExporter
|
||||
{
|
||||
private readonly DiscordClient _discord;
|
||||
|
||||
public ChannelExporter(DiscordClient discord) => _discord = discord;
|
||||
|
||||
public ChannelExporter(AuthToken token) : this(new DiscordClient(token)) {}
|
||||
|
||||
public async Task ExportAsync(
|
||||
Guild guild,
|
||||
Channel channel,
|
||||
string outputPath,
|
||||
ExportFormat format,
|
||||
string dateFormat,
|
||||
int? partitionLimit,
|
||||
DateTimeOffset? after = null,
|
||||
DateTimeOffset? before = null,
|
||||
IProgress<double>? progress = null)
|
||||
{
|
||||
var baseFilePath = GetFilePathFromOutputPath(guild, channel, outputPath, format, after, before);
|
||||
|
||||
// Options
|
||||
var options = new ExportOptions(baseFilePath, format, partitionLimit);
|
||||
|
||||
// Context
|
||||
var contextMembers = new HashSet<Member>(IdBasedEqualityComparer.Instance);
|
||||
var contextChannels = await _discord.GetGuildChannelsAsync(guild.Id);
|
||||
var contextRoles = await _discord.GetGuildRolesAsync(guild.Id);
|
||||
|
||||
var context = new ExportContext(
|
||||
guild, channel, after, before, dateFormat,
|
||||
contextMembers, contextChannels, contextRoles
|
||||
);
|
||||
|
||||
await using var messageExporter = new MessageExporter(options, context);
|
||||
|
||||
var exportedAnything = false;
|
||||
var encounteredUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
|
||||
await foreach (var message in _discord.GetMessagesAsync(channel.Id, after, before, progress))
|
||||
{
|
||||
// Resolve members for referenced users
|
||||
foreach (var referencedUser in message.MentionedUsers.Prepend(message.Author))
|
||||
{
|
||||
if (encounteredUsers.Add(referencedUser))
|
||||
{
|
||||
var member =
|
||||
await _discord.TryGetGuildMemberAsync(guild.Id, referencedUser) ??
|
||||
Member.CreateForUser(referencedUser);
|
||||
|
||||
contextMembers.Add(member);
|
||||
}
|
||||
}
|
||||
|
||||
// Export message
|
||||
await messageExporter.ExportMessageAsync(message);
|
||||
exportedAnything = true;
|
||||
}
|
||||
|
||||
// Throw if no messages were exported
|
||||
if (!exportedAnything)
|
||||
throw DiscordChatExporterException.ChannelEmpty(channel);
|
||||
}
|
||||
}
|
||||
|
||||
public partial class ChannelExporter
|
||||
{
|
||||
public static string GetDefaultExportFileName(
|
||||
Guild guild,
|
||||
Channel channel,
|
||||
ExportFormat format,
|
||||
DateTimeOffset? after = null,
|
||||
DateTimeOffset? before = null)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
// Guild and channel names
|
||||
buffer.Append($"{guild.Name} - {channel.Category} - {channel.Name} [{channel.Id}]");
|
||||
|
||||
// Date range
|
||||
if (after != null || before != null)
|
||||
{
|
||||
buffer.Append(" (");
|
||||
|
||||
// Both 'after' and 'before' are set
|
||||
if (after != null && before != null)
|
||||
{
|
||||
buffer.Append($"{after:yyyy-MM-dd} to {before:yyyy-MM-dd}");
|
||||
}
|
||||
// Only 'after' is set
|
||||
else if (after != null)
|
||||
{
|
||||
buffer.Append($"after {after:yyyy-MM-dd}");
|
||||
}
|
||||
// Only 'before' is set
|
||||
else
|
||||
{
|
||||
buffer.Append($"before {before:yyyy-MM-dd}");
|
||||
}
|
||||
|
||||
buffer.Append(")");
|
||||
}
|
||||
|
||||
// File extension
|
||||
buffer.Append($".{format.GetFileExtension()}");
|
||||
|
||||
// Replace invalid chars
|
||||
foreach (var invalidChar in Path.GetInvalidFileNameChars())
|
||||
buffer.Replace(invalidChar, '_');
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private static string GetFilePathFromOutputPath(
|
||||
Guild guild,
|
||||
Channel channel,
|
||||
string outputPath,
|
||||
ExportFormat format,
|
||||
DateTimeOffset? after = null,
|
||||
DateTimeOffset? before = null)
|
||||
{
|
||||
// Output is a directory
|
||||
if (Directory.Exists(outputPath) || string.IsNullOrWhiteSpace(Path.GetExtension(outputPath)))
|
||||
{
|
||||
var fileName = GetDefaultExportFileName(guild, channel, format, after, before);
|
||||
return Path.Combine(outputPath, fileName);
|
||||
}
|
||||
|
||||
// Output is a file
|
||||
return outputPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
public class ExportContext
|
||||
{
|
||||
public Guild Guild { get; }
|
||||
|
||||
public Channel Channel { get; }
|
||||
|
||||
public DateTimeOffset? After { get; }
|
||||
|
||||
public DateTimeOffset? Before { get; }
|
||||
|
||||
public string DateFormat { get; }
|
||||
|
||||
public IReadOnlyCollection<Member> Members { get; }
|
||||
|
||||
public IReadOnlyCollection<Channel> Channels { get; }
|
||||
|
||||
public IReadOnlyCollection<Role> Roles { get; }
|
||||
|
||||
public ExportContext(
|
||||
Guild guild,
|
||||
Channel channel,
|
||||
DateTimeOffset? after,
|
||||
DateTimeOffset? before,
|
||||
string dateFormat,
|
||||
IReadOnlyCollection<Member> members,
|
||||
IReadOnlyCollection<Channel> channels,
|
||||
IReadOnlyCollection<Role> roles)
|
||||
{
|
||||
Guild = guild;
|
||||
Channel = channel;
|
||||
After = after;
|
||||
Before = before;
|
||||
DateFormat = dateFormat;
|
||||
Members = members;
|
||||
Channels = channels;
|
||||
Roles = roles;
|
||||
}
|
||||
|
||||
public Member? TryGetMentionedMember(string id) =>
|
||||
Members.FirstOrDefault(m => m.Id == id);
|
||||
|
||||
public Channel? TryGetMentionedChannel(string id) =>
|
||||
Channels.FirstOrDefault(c => c.Id == id);
|
||||
|
||||
public Role? TryGetMentionedRole(string id) =>
|
||||
Roles.FirstOrDefault(r => r.Id == id);
|
||||
|
||||
public Member? TryGetUserMember(User user) => Members
|
||||
.FirstOrDefault(m => m.Id == user.Id);
|
||||
|
||||
public Color? TryGetUserColor(User user)
|
||||
{
|
||||
var member = TryGetUserMember(user);
|
||||
var roles = member?.RoleIds.Join(Roles, i => i, r => r.Id, (_, role) => role);
|
||||
|
||||
return roles?
|
||||
.OrderByDescending(r => r.Position)
|
||||
.Select(r => r.Color)
|
||||
.FirstOrDefault(c => c != null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
public enum ExportFormat
|
||||
{
|
||||
PlainText,
|
||||
HtmlDark,
|
||||
HtmlLight,
|
||||
Csv,
|
||||
Json
|
||||
}
|
||||
|
||||
public static class ExportFormatExtensions
|
||||
{
|
||||
public static string GetFileExtension(this ExportFormat format) => format switch
|
||||
{
|
||||
ExportFormat.PlainText => "txt",
|
||||
ExportFormat.HtmlDark => "html",
|
||||
ExportFormat.HtmlLight => "html",
|
||||
ExportFormat.Csv => "csv",
|
||||
ExportFormat.Json => "json",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format))
|
||||
};
|
||||
|
||||
public static string GetDisplayName(this ExportFormat format) => format switch
|
||||
{
|
||||
ExportFormat.PlainText => "TXT",
|
||||
ExportFormat.HtmlDark => "HTML (Dark)",
|
||||
ExportFormat.HtmlLight => "HTML (Light)",
|
||||
ExportFormat.Csv => "CSV",
|
||||
ExportFormat.Json => "JSON",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
public class ExportOptions
|
||||
{
|
||||
public string BaseFilePath { get; }
|
||||
|
||||
public ExportFormat Format { get; }
|
||||
|
||||
public int? PartitionLimit { get; }
|
||||
|
||||
public ExportOptions(string baseFilePath, ExportFormat format, int? partitionLimit)
|
||||
{
|
||||
BaseFilePath = baseFilePath;
|
||||
Format = format;
|
||||
PartitionLimit = partitionLimit;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting.Writers;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
internal partial class MessageExporter : IAsyncDisposable
|
||||
{
|
||||
private readonly ExportOptions _options;
|
||||
private readonly ExportContext _context;
|
||||
|
||||
private long _renderedMessageCount;
|
||||
private int _partitionIndex;
|
||||
private MessageWriter? _writer;
|
||||
|
||||
public MessageExporter(ExportOptions options, ExportContext context)
|
||||
{
|
||||
_options = options;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
private bool IsPartitionLimitReached() =>
|
||||
_renderedMessageCount > 0 &&
|
||||
_options.PartitionLimit != null &&
|
||||
_options.PartitionLimit != 0 &&
|
||||
_renderedMessageCount % _options.PartitionLimit == 0;
|
||||
|
||||
private async Task ResetWriterAsync()
|
||||
{
|
||||
if (_writer != null)
|
||||
{
|
||||
await _writer.WritePostambleAsync();
|
||||
await _writer.DisposeAsync();
|
||||
_writer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<MessageWriter> GetWriterAsync()
|
||||
{
|
||||
// Ensure partition limit has not been exceeded
|
||||
if (IsPartitionLimitReached())
|
||||
{
|
||||
await ResetWriterAsync();
|
||||
_partitionIndex++;
|
||||
}
|
||||
|
||||
// Writer is still valid - return
|
||||
if (_writer != null)
|
||||
return _writer;
|
||||
|
||||
var filePath = GetPartitionFilePath(_options.BaseFilePath, _partitionIndex);
|
||||
|
||||
var dirPath = Path.GetDirectoryName(_options.BaseFilePath);
|
||||
if (!string.IsNullOrWhiteSpace(dirPath))
|
||||
Directory.CreateDirectory(dirPath);
|
||||
|
||||
var writer = CreateMessageWriter(filePath, _options.Format, _context);
|
||||
await writer.WritePreambleAsync();
|
||||
|
||||
return _writer = writer;
|
||||
}
|
||||
|
||||
public async Task ExportMessageAsync(Message message)
|
||||
{
|
||||
var writer = await GetWriterAsync();
|
||||
await writer.WriteMessageAsync(message);
|
||||
_renderedMessageCount++;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync() => await ResetWriterAsync();
|
||||
}
|
||||
|
||||
internal partial class MessageExporter
|
||||
{
|
||||
private static string GetPartitionFilePath(string baseFilePath, int partitionIndex)
|
||||
{
|
||||
// First partition - don't change file name
|
||||
if (partitionIndex <= 0)
|
||||
return baseFilePath;
|
||||
|
||||
// Inject partition index into file name
|
||||
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(baseFilePath);
|
||||
var fileExt = Path.GetExtension(baseFilePath);
|
||||
var fileName = $"{fileNameWithoutExt} [part {partitionIndex + 1}]{fileExt}";
|
||||
|
||||
// Generate new path
|
||||
var dirPath = Path.GetDirectoryName(baseFilePath);
|
||||
if (!string.IsNullOrWhiteSpace(dirPath))
|
||||
return Path.Combine(dirPath, fileName);
|
||||
|
||||
return fileName;
|
||||
}
|
||||
|
||||
private static MessageWriter CreateMessageWriter(string filePath, ExportFormat format, ExportContext context)
|
||||
{
|
||||
// Stream will be disposed by the underlying writer
|
||||
var stream = File.Create(filePath);
|
||||
|
||||
return format switch
|
||||
{
|
||||
ExportFormat.PlainText => new PlainTextMessageWriter(stream, context),
|
||||
ExportFormat.Csv => new CsvMessageWriter(stream, context),
|
||||
ExportFormat.HtmlDark => new HtmlMessageWriter(stream, context, "Dark"),
|
||||
ExportFormat.HtmlLight => new HtmlMessageWriter(stream, context, "Light"),
|
||||
ExportFormat.Json => new JsonMessageWriter(stream, context),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format), $"Unknown export format '{format}'.")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting
|
||||
{
|
||||
// Used for grouping contiguous messages in HTML export
|
||||
internal partial class MessageGroup
|
||||
{
|
||||
public User Author { get; }
|
||||
|
||||
public DateTimeOffset Timestamp { get; }
|
||||
|
||||
public IReadOnlyList<Message> Messages { get; }
|
||||
|
||||
public MessageGroup(User author, DateTimeOffset timestamp, IReadOnlyList<Message> messages)
|
||||
{
|
||||
Author = author;
|
||||
Timestamp = timestamp;
|
||||
Messages = messages;
|
||||
}
|
||||
}
|
||||
|
||||
internal partial class MessageGroup
|
||||
{
|
||||
public static bool CanGroup(Message message1, Message message2) =>
|
||||
string.Equals(message1.Author.Id, message2.Author.Id, StringComparison.Ordinal) &&
|
||||
string.Equals(message1.Author.FullName, message2.Author.FullName, StringComparison.Ordinal) &&
|
||||
(message2.Timestamp - message1.Timestamp).Duration().TotalMinutes <= 7;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
/* General */
|
||||
|
||||
@font-face {
|
||||
font-family: Whitney;
|
||||
src: url(https://discordapp.com/assets/6c6374bad0b0b6d204d8d6dc4a18d820.woff);
|
||||
font-weight: 300;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: Whitney;
|
||||
src: url(https://discordapp.com/assets/e8acd7d9bf6207f99350ca9f9e23b168.woff);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: Whitney;
|
||||
src: url(https://discordapp.com/assets/3bdef1251a424500c1b3a78dea9b7e57.woff);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: Whitney;
|
||||
src: url(https://discordapp.com/assets/be0060dafb7a0e31d2a1ca17c0708636.woff);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: Whitney;
|
||||
src: url(https://discordapp.com/assets/8e12fb4f14d9c4592eb8ec9f22337b04.woff);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Whitney", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
img {
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.markdown {
|
||||
max-width: 100%;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.3;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
width: fit-content;
|
||||
}
|
||||
|
||||
.spoiler--hidden {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.spoiler-text {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-text {
|
||||
color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-text::selection {
|
||||
color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
.spoiler-image {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-image {
|
||||
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-image img {
|
||||
filter: blur(44px);
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-image:after {
|
||||
content: "SPOILER";
|
||||
color: #dcddde;
|
||||
background-color: rgba(0, 0, 0, 0.6);
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
font-weight: 600;
|
||||
padding: 0.5em 0.7em;
|
||||
border-radius: 20px;
|
||||
letter-spacing: 0.05em;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.spoiler--hidden:hover .spoiler-image:after {
|
||||
color: #fff;
|
||||
background-color: rgba(0, 0, 0, 0.9);
|
||||
}
|
||||
|
||||
.quote {
|
||||
margin: 0.1em 0;
|
||||
padding-left: 0.6em;
|
||||
border-left: 4px solid;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.pre {
|
||||
font-family: "Consolas", "Courier New", Courier, monospace;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
margin-top: 0.25em;
|
||||
padding: 0.5em;
|
||||
border: 2px solid;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.pre--inline {
|
||||
padding: 2px;
|
||||
border-radius: 3px;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.mention {
|
||||
border-radius: 3px;
|
||||
padding: 0 2px;
|
||||
color: #7289da;
|
||||
background: rgba(114, 137, 218, .1);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.emoji {
|
||||
width: 1.25em;
|
||||
height: 1.25em;
|
||||
margin: 0 0.06em;
|
||||
vertical-align: -0.4em;
|
||||
}
|
||||
|
||||
.emoji--small {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
}
|
||||
|
||||
.emoji--large {
|
||||
width: 2.8em;
|
||||
height: 2.8em;
|
||||
}
|
||||
|
||||
/* Preamble */
|
||||
|
||||
.preamble {
|
||||
display: grid;
|
||||
margin: 0 0.3em 0.6em 0.3em;
|
||||
max-width: 100%;
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
|
||||
.preamble__guild-icon-container {
|
||||
grid-column: 1;
|
||||
}
|
||||
|
||||
.preamble__guild-icon {
|
||||
max-width: 88px;
|
||||
max-height: 88px;
|
||||
}
|
||||
|
||||
.preamble__entries-container {
|
||||
grid-column: 2;
|
||||
margin-left: 0.6em;
|
||||
}
|
||||
|
||||
.preamble__entry {
|
||||
font-size: 1.4em;
|
||||
}
|
||||
|
||||
.preamble__entry--small {
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
/* Chatlog */
|
||||
|
||||
.chatlog {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.chatlog__message-group {
|
||||
display: grid;
|
||||
margin: 0 0.6em;
|
||||
padding: 0.9em 0;
|
||||
border-top: 1px solid;
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
|
||||
.chatlog__author-avatar-container {
|
||||
grid-column: 1;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.chatlog__author-avatar {
|
||||
border-radius: 50%;
|
||||
height: 40px;
|
||||
width: 40px;
|
||||
}
|
||||
|
||||
.chatlog__messages {
|
||||
grid-column: 2;
|
||||
margin-left: 1.2em;
|
||||
min-width: 50%;
|
||||
}
|
||||
|
||||
.chatlog__author-name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.chatlog__timestamp {
|
||||
margin-left: 0.3em;
|
||||
font-size: 0.75em;
|
||||
}
|
||||
|
||||
.chatlog__message {
|
||||
padding: 0.1em 0.3em;
|
||||
margin: 0 -0.3em;
|
||||
background-color: transparent;
|
||||
transition: background-color 1s ease;
|
||||
}
|
||||
|
||||
.chatlog__content {
|
||||
font-size: 0.95em;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.chatlog__edited-timestamp {
|
||||
margin-left: 0.15em;
|
||||
font-size: 0.8em;
|
||||
}
|
||||
|
||||
.chatlog__attachment {
|
||||
margin-top: 0.3em;
|
||||
}
|
||||
|
||||
.chatlog__attachment-thumbnail {
|
||||
vertical-align: top;
|
||||
max-width: 45vw;
|
||||
max-height: 500px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__embed {
|
||||
display: flex;
|
||||
margin-top: 0.3em;
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
.chatlog__embed-color-pill {
|
||||
flex-shrink: 0;
|
||||
width: 0.25em;
|
||||
border-top-left-radius: 3px;
|
||||
border-bottom-left-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__embed-content-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.5em 0.6em;
|
||||
border: 1px solid;
|
||||
border-top-right-radius: 3px;
|
||||
border-bottom-right-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__embed-content {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.chatlog__embed-text {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.chatlog__embed-author {
|
||||
display: flex;
|
||||
margin-bottom: 0.3em;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.chatlog__embed-author-icon {
|
||||
margin-right: 0.5em;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name {
|
||||
font-size: 0.875em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chatlog__embed-title {
|
||||
margin-bottom: 0.2em;
|
||||
font-size: 0.875em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chatlog__embed-description {
|
||||
font-weight: 500;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.chatlog__embed-fields {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.chatlog__embed-field {
|
||||
flex: 0;
|
||||
min-width: 100%;
|
||||
max-width: 506px;
|
||||
padding-top: 0.6em;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
.chatlog__embed-field--inline {
|
||||
flex: 1;
|
||||
flex-basis: auto;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.chatlog__embed-field-name {
|
||||
margin-bottom: 0.2em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.chatlog__embed-field-value {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.chatlog__embed-thumbnail {
|
||||
flex: 0;
|
||||
margin-left: 1.2em;
|
||||
max-width: 80px;
|
||||
max-height: 80px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__embed-image-container {
|
||||
margin-top: 0.6em;
|
||||
}
|
||||
|
||||
.chatlog__embed-image {
|
||||
max-width: 500px;
|
||||
max-height: 400px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__embed-footer {
|
||||
margin-top: 0.6em;
|
||||
}
|
||||
|
||||
.chatlog__embed-footer-icon {
|
||||
margin-right: 0.2em;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.chatlog__embed-footer-text {
|
||||
font-size: 0.75em;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.chatlog__reactions {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 0.35em 0.1em 0.1em 0.1em;
|
||||
padding: 0.2em 0.35em;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
min-width: 9px;
|
||||
margin-left: 0.35em;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
.chatlog__bot-tag {
|
||||
position: relative;
|
||||
top: -.2em;
|
||||
margin-left: 0.3em;
|
||||
padding: 0.05em 0.3em;
|
||||
border-radius: 3px;
|
||||
vertical-align: middle;
|
||||
line-height: 1.3;
|
||||
background: #7289da;
|
||||
color: #ffffff;
|
||||
font-size: 0.625em;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Postamble */
|
||||
|
||||
.postamble {
|
||||
margin: 1.4em 0.3em 0.6em 0.3em;
|
||||
padding: 1em;
|
||||
border-top: 1px solid;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/* General */
|
||||
|
||||
body {
|
||||
background-color: #36393e;
|
||||
color: #dcddde;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #0096cf;
|
||||
}
|
||||
|
||||
.spoiler-text {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-text {
|
||||
background-color: #202225;
|
||||
}
|
||||
|
||||
.spoiler--hidden:hover .spoiler-text {
|
||||
background-color: rgba(32, 34, 37, 0.8);
|
||||
}
|
||||
|
||||
.quote {
|
||||
border-color: #4f545c;
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #2f3136 !important;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
border-color: #282b30 !important;
|
||||
color: #b9bbbe !important;
|
||||
}
|
||||
|
||||
/* === Preamble === */
|
||||
|
||||
.preamble__entry {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
/* Chatlog */
|
||||
|
||||
.chatlog__message-group {
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.chatlog__author-name {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.chatlog__timestamp {
|
||||
color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.chatlog__message--highlighted {
|
||||
background-color: rgba(114, 137, 218, 0.2) !important;
|
||||
}
|
||||
|
||||
.chatlog__message--pinned {
|
||||
background-color: rgba(249, 168, 37, 0.05);
|
||||
}
|
||||
|
||||
.chatlog__edited-timestamp {
|
||||
color: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.chatlog__embed-color-pill--default {
|
||||
background-color: rgba(79, 84, 92, 1);
|
||||
}
|
||||
|
||||
.chatlog__embed-content-container {
|
||||
background-color: rgba(46, 48, 54, 0.3);
|
||||
border-color: rgba(46, 48, 54, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name-link {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.chatlog__embed-title {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.chatlog__embed-description {
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-field-name {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.chatlog__embed-field-value {
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__embed-footer {
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
background-color: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
/* Postamble */
|
||||
|
||||
.postamble {
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.postamble__entry {
|
||||
color: #ffffff;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
{{~ # Metadata ~}}
|
||||
<title>{{ Context.Guild.Name | html.escape }} - {{ Context.Channel.Name | html.escape }}</title>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width">
|
||||
|
||||
{{~ # Styles ~}}
|
||||
<style>
|
||||
{{ CoreStyleSheet }}
|
||||
</style>
|
||||
<style>
|
||||
{{ ThemeStyleSheet }}
|
||||
</style>
|
||||
|
||||
{{~ # Syntax highlighting ~}}
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/{{HighlightJsStyleName}}.min.css">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('.pre--multiline').forEach(block => hljs.highlightBlock(block));
|
||||
});
|
||||
</script>
|
||||
|
||||
{{~ # Local scripts ~}}
|
||||
<script>
|
||||
function scrollToMessage(event, id) {
|
||||
var element = document.getElementById('message-' + id);
|
||||
|
||||
if (element) {
|
||||
event.preventDefault();
|
||||
|
||||
element.classList.add('chatlog__message--highlighted');
|
||||
|
||||
window.scrollTo({
|
||||
top: element.getBoundingClientRect().top - document.body.getBoundingClientRect().top - (window.innerHeight / 2),
|
||||
behavior: 'smooth'
|
||||
});
|
||||
|
||||
window.setTimeout(function() {
|
||||
element.classList.remove('chatlog__message--highlighted');
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function showSpoiler(event, element) {
|
||||
if (element && element.classList.contains('spoiler--hidden')) {
|
||||
event.preventDefault();
|
||||
element.classList.remove('spoiler--hidden');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
{{~ # Preamble ~}}
|
||||
<div class="preamble">
|
||||
<div class="preamble__guild-icon-container">
|
||||
<img class="preamble__guild-icon" src="{{ Context.Guild.IconUrl }}" alt="Guild icon">
|
||||
</div>
|
||||
<div class="preamble__entries-container">
|
||||
<div class="preamble__entry">{{ Context.Guild.Name | html.escape }}</div>
|
||||
<div class="preamble__entry">{{ Context.Channel.Category | html.escape }} / {{ Context.Channel.Name | html.escape }}</div>
|
||||
|
||||
{{~ if Context.Channel.Topic ~}}
|
||||
<div class="preamble__entry preamble__entry--small">{{ Context.Channel.Topic | html.escape }}</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ if Context.After || Context.Before ~}}
|
||||
<div class="preamble__entry preamble__entry--small">
|
||||
{{~ if Context.After && Context.Before ~}}
|
||||
Between {{ Context.After | FormatDate | html.escape }} and {{ Context.Before | FormatDate | html.escape }}
|
||||
{{~ else if Context.After ~}}
|
||||
After {{ Context.After | FormatDate | html.escape }}
|
||||
{{~ else if Context.Before ~}}
|
||||
Before {{ Context.Before | FormatDate | html.escape }}
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{~ # Log ~}}
|
||||
<div class="chatlog">
|
||||
{{~ %SPLIT% ~}}
|
||||
</div>
|
||||
|
||||
{{~ # Postamble ~}}
|
||||
<div class="postamble">
|
||||
<div class="postamble__entry">Exported {{ MessageCount | object.format "N0" }} message(s)</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,124 @@
|
||||
/* General */
|
||||
|
||||
body {
|
||||
background-color: #ffffff;
|
||||
color: #23262a;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #00b0f4;
|
||||
}
|
||||
|
||||
.spoiler-text {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.spoiler--hidden .spoiler-text {
|
||||
background-color: #b9bbbe;
|
||||
}
|
||||
|
||||
.spoiler--hidden:hover .spoiler-text {
|
||||
background-color: rgba(185, 187, 190, 0.8);
|
||||
}
|
||||
|
||||
.quote {
|
||||
border-color: #c7ccd1;
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #f9f9f9 !important;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
border-color: #f3f3f3 !important;
|
||||
color: #657b83 !important;
|
||||
}
|
||||
|
||||
/* Preamble */
|
||||
|
||||
.preamble__entry {
|
||||
color: #2f3136;
|
||||
}
|
||||
|
||||
/* Chatlog */
|
||||
|
||||
.chatlog__message-group {
|
||||
border-color: #eceeef;
|
||||
}
|
||||
|
||||
.chatlog__author-name {
|
||||
font-weight: 600;
|
||||
color: #2f3136;
|
||||
}
|
||||
|
||||
.chatlog__timestamp {
|
||||
color: #747f8d;
|
||||
}
|
||||
|
||||
.chatlog__message--highlighted {
|
||||
background-color: rgba(114, 137, 218, 0.2) !important;
|
||||
}
|
||||
|
||||
.chatlog__message--pinned {
|
||||
background-color: rgba(249, 168, 37, 0.05);
|
||||
}
|
||||
|
||||
.chatlog__edited-timestamp {
|
||||
color: #747f8d;
|
||||
}
|
||||
|
||||
.chatlog__embed-color-pill--default {
|
||||
background-color: rgba(227, 229, 232, 1);
|
||||
}
|
||||
|
||||
.chatlog__embed-content-container {
|
||||
background-color: rgba(249, 249, 249, 0.3);
|
||||
border-color: rgba(204, 204, 204, 0.3);
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name {
|
||||
color: #4f545c;
|
||||
}
|
||||
|
||||
.chatlog__embed-author-name-link {
|
||||
color: #4f545c;
|
||||
}
|
||||
|
||||
.chatlog__embed-title {
|
||||
color: #4f545c;
|
||||
}
|
||||
|
||||
.chatlog__embed-description {
|
||||
color: #737f8d;
|
||||
}
|
||||
|
||||
.chatlog__embed-field-name {
|
||||
color: #36393e;
|
||||
}
|
||||
|
||||
.chatlog__embed-field-value {
|
||||
color: #737f8d;
|
||||
}
|
||||
|
||||
.chatlog__embed-footer {
|
||||
color: rgba(79, 83, 91, 0.6);
|
||||
}
|
||||
|
||||
.chatlog__reaction {
|
||||
background-color: rgba(79, 84, 92, 0.06);
|
||||
}
|
||||
|
||||
.chatlog__reaction-count {
|
||||
color: #747f8d;
|
||||
}
|
||||
|
||||
/* Postamble */
|
||||
|
||||
.postamble {
|
||||
border-color: #eceeef;
|
||||
}
|
||||
|
||||
.postamble__entry {
|
||||
color: #2f3136;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<div class="chatlog__message-group">
|
||||
{{~ # Avatar ~}}
|
||||
<div class="chatlog__author-avatar-container">
|
||||
<img class="chatlog__author-avatar" src="{{ MessageGroup.Author.AvatarUrl }}" alt="Avatar">
|
||||
</div>
|
||||
<div class="chatlog__messages">
|
||||
{{~ # Author name and timestamp ~}}
|
||||
{{~ userColor = TryGetUserColor MessageGroup.Author | FormatColorRgb ~}}
|
||||
<span class="chatlog__author-name" title="{{ MessageGroup.Author.FullName | html.escape }}" data-user-id="{{ MessageGroup.Author.Id | html.escape }}" {{ if userColor }} style="color: {{ userColor }}" {{ end }}>{{ (TryGetUserNick MessageGroup.Author ?? MessageGroup.Author.Name) | html.escape }}</span>
|
||||
|
||||
{{~ # Bot tag ~}}
|
||||
{{~ if MessageGroup.Author.IsBot ~}}
|
||||
<span class="chatlog__bot-tag">BOT</span>
|
||||
{{~ end ~}}
|
||||
|
||||
<span class="chatlog__timestamp">{{ MessageGroup.Timestamp | FormatDate | html.escape }}</span>
|
||||
|
||||
{{~ # Messages ~}}
|
||||
{{~ for message in MessageGroup.Messages ~}}
|
||||
<div class="chatlog__message {{ if message.IsPinned }}chatlog__message--pinned{{ end }}" data-message-id="{{ message.Id }}" id="message-{{ message.Id }}">
|
||||
{{~ # Content ~}}
|
||||
{{~ if message.Content ~}}
|
||||
<div class="chatlog__content">
|
||||
<div class="markdown">
|
||||
{{- message.Content | FormatMarkdown -}}
|
||||
|
||||
{{- # Edited timestamp -}}
|
||||
{{- if message.EditedTimestamp -}}
|
||||
{{-}}<span class="chatlog__edited-timestamp" title="{{ message.EditedTimestamp | FormatDate | html.escape }}">(edited)</span>{{-}}
|
||||
{{- end -}}
|
||||
</div>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Attachments ~}}
|
||||
{{~ for attachment in message.Attachments ~}}
|
||||
<div class="chatlog__attachment">
|
||||
{{ # Spoiler image }}
|
||||
{{~ if attachment.IsSpoiler ~}}
|
||||
<div class="spoiler spoiler--hidden" onclick="showSpoiler(event, this)">
|
||||
<div class="spoiler-image">
|
||||
<a href="{{ attachment.Url }}">
|
||||
<img class="chatlog__attachment-thumbnail" src="{{ attachment.Url }}" alt="Attachment">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{{~ else ~}}
|
||||
<a href="{{ attachment.Url }}">
|
||||
{{ # Non-spoiler image }}
|
||||
{{~ if attachment.IsImage ~}}
|
||||
<img class="chatlog__attachment-thumbnail" src="{{ attachment.Url }}" alt="Attachment">
|
||||
{{~ # Non-image ~}}
|
||||
{{~ else ~}}
|
||||
Attachment: {{ attachment.FileName }} ({{ attachment.FileSize }})
|
||||
{{~ end ~}}
|
||||
</a>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Embeds ~}}
|
||||
{{~ for embed in message.Embeds ~}}
|
||||
<div class="chatlog__embed">
|
||||
{{~ if embed.Color ~}}
|
||||
<div class="chatlog__embed-color-pill" style="background-color: rgba({{ embed.Color.R }},{{ embed.Color.G }},{{ embed.Color.B }},{{ embed.Color.A }})"></div>
|
||||
{{~ else ~}}
|
||||
<div class="chatlog__embed-color-pill chatlog__embed-color-pill--default"></div>
|
||||
{{~ end ~}}
|
||||
<div class="chatlog__embed-content-container">
|
||||
<div class="chatlog__embed-content">
|
||||
<div class="chatlog__embed-text">
|
||||
{{~ # Author ~}}
|
||||
{{~ if embed.Author ~}}
|
||||
<div class="chatlog__embed-author">
|
||||
{{~ if embed.Author.IconUrl ~}}
|
||||
<img class="chatlog__embed-author-icon" src="{{ embed.Author.IconUrl }}" alt="Author icon">
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ if embed.Author.Name ~}}
|
||||
<span class="chatlog__embed-author-name">
|
||||
{{~ if embed.Author.Url ~}}
|
||||
<a class="chatlog__embed-author-name-link" href="{{ embed.Author.Url }}">{{ embed.Author.Name | html.escape }}</a>
|
||||
{{~ else ~}}
|
||||
{{ embed.Author.Name | html.escape }}
|
||||
{{~ end ~}}
|
||||
</span>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Title ~}}
|
||||
{{~ if embed.Title ~}}
|
||||
<div class="chatlog__embed-title">
|
||||
{{~ if embed.Url ~}}
|
||||
<a class="chatlog__embed-title-link" href="{{ embed.Url }}"><div class="markdown">{{ embed.Title | FormatEmbedMarkdown }}</div></a>
|
||||
{{~ else ~}}
|
||||
<div class="markdown">{{ embed.Title | FormatEmbedMarkdown }}</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Description ~}}
|
||||
{{~ if embed.Description ~}}
|
||||
<div class="chatlog__embed-description"><div class="markdown">{{ embed.Description | FormatEmbedMarkdown }}</div></div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Fields ~}}
|
||||
{{~ if embed.Fields | array.size > 0 ~}}
|
||||
<div class="chatlog__embed-fields">
|
||||
{{~ 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"><div class="markdown">{{ field.Name | FormatEmbedMarkdown }}</div></div>
|
||||
{{~ end ~}}
|
||||
{{~ if field.Value ~}}
|
||||
<div class="chatlog__embed-field-value"><div class="markdown">{{ field.Value | FormatEmbedMarkdown }}</div></div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
|
||||
{{~ # Thumbnail ~}}
|
||||
{{~ if embed.Thumbnail ~}}
|
||||
<div class="chatlog__embed-thumbnail-container">
|
||||
<a class="chatlog__embed-thumbnail-link" href="{{ embed.Thumbnail.Url }}">
|
||||
<img class="chatlog__embed-thumbnail" src="{{ embed.Thumbnail.Url }}" alt="Thumbnail">
|
||||
</a>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
|
||||
{{~ # Image ~}}
|
||||
{{~ if embed.Image ~}}
|
||||
<div class="chatlog__embed-image-container">
|
||||
<a class="chatlog__embed-image-link" href="{{ embed.Image.Url }}">
|
||||
<img class="chatlog__embed-image" src="{{ embed.Image.Url }}" alt="Image">
|
||||
</a>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Footer ~}}
|
||||
{{~ if embed.Footer || embed.Timestamp ~}}
|
||||
<div class="chatlog__embed-footer">
|
||||
{{~ if embed.Footer ~}}
|
||||
{{~ if embed.Footer.Text && embed.Footer.IconUrl ~}}
|
||||
<img class="chatlog__embed-footer-icon" src="{{ embed.Footer.IconUrl }}" alt="Footer icon">
|
||||
{{~ end ~}}
|
||||
{{~ end ~}}
|
||||
|
||||
<span class="chatlog__embed-footer-text">
|
||||
{{~ if embed.Footer ~}}
|
||||
{{~ if embed.Footer.Text ~}}
|
||||
{{ embed.Footer.Text | html.escape }}
|
||||
{{ if embed.Timestamp }} • {{ end }}
|
||||
{{~ end ~}}
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ if embed.Timestamp ~}}
|
||||
{{ embed.Timestamp | FormatDate | html.escape }}
|
||||
{{~ end ~}}
|
||||
</span>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Reactions ~}}
|
||||
{{~ if message.Reactions | array.size > 0 ~}}
|
||||
<div class="chatlog__reactions">
|
||||
{{~ for reaction in message.Reactions ~}}
|
||||
<div class="chatlog__reaction">
|
||||
<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 ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,58 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
||||
{
|
||||
internal partial class CsvMessageWriter : MessageWriter
|
||||
{
|
||||
private readonly TextWriter _writer;
|
||||
|
||||
public CsvMessageWriter(Stream stream, ExportContext context)
|
||||
: base(stream, context)
|
||||
{
|
||||
_writer = new StreamWriter(stream);
|
||||
}
|
||||
|
||||
private string FormatMarkdown(string? markdown) =>
|
||||
PlainTextMarkdownVisitor.Format(Context, markdown ?? "");
|
||||
|
||||
public override async Task WritePreambleAsync() =>
|
||||
await _writer.WriteLineAsync("AuthorID,Author,Date,Content,Attachments,Reactions");
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.Append(CsvEncode(message.Author.Id)).Append(',')
|
||||
.Append(CsvEncode(message.Author.FullName)).Append(',')
|
||||
.Append(CsvEncode(message.Timestamp.ToLocalString(Context.DateFormat))).Append(',')
|
||||
.Append(CsvEncode(FormatMarkdown(message.Content))).Append(',')
|
||||
.Append(CsvEncode(message.Attachments.Select(a => a.Url).JoinToString(","))).Append(',')
|
||||
.Append(CsvEncode(message.Reactions.Select(r => $"{r.Emoji.Name} ({r.Count})").JoinToString(",")));
|
||||
|
||||
await _writer.WriteLineAsync(buffer.ToString());
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _writer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
internal partial class CsvMessageWriter
|
||||
{
|
||||
private static string CsvEncode(string value)
|
||||
{
|
||||
value = value.Replace("\"", "\"\"");
|
||||
return $"\"{value}\"";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using Scriban;
|
||||
using Scriban.Runtime;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
||||
{
|
||||
internal partial class HtmlMessageWriter : MessageWriter
|
||||
{
|
||||
private readonly TextWriter _writer;
|
||||
private readonly string _themeName;
|
||||
private readonly List<Message> _messageGroupBuffer = new List<Message>();
|
||||
|
||||
private readonly Template _preambleTemplate;
|
||||
private readonly Template _messageGroupTemplate;
|
||||
private readonly Template _postambleTemplate;
|
||||
|
||||
private long _messageCount;
|
||||
|
||||
public HtmlMessageWriter(Stream stream, ExportContext context, string themeName)
|
||||
: base(stream, context)
|
||||
{
|
||||
_writer = new StreamWriter(stream);
|
||||
_themeName = themeName;
|
||||
|
||||
_preambleTemplate = Template.Parse(GetPreambleTemplateCode());
|
||||
_messageGroupTemplate = Template.Parse(GetMessageGroupTemplateCode());
|
||||
_postambleTemplate = Template.Parse(GetPostambleTemplateCode());
|
||||
}
|
||||
|
||||
private MessageGroup GetCurrentMessageGroup()
|
||||
{
|
||||
var firstMessage = _messageGroupBuffer.First();
|
||||
return new MessageGroup(firstMessage.Author, firstMessage.Timestamp, _messageGroupBuffer);
|
||||
}
|
||||
|
||||
private TemplateContext CreateTemplateContext(IReadOnlyDictionary<string, object>? constants = null)
|
||||
{
|
||||
// Template context
|
||||
var templateContext = new TemplateContext
|
||||
{
|
||||
MemberRenamer = m => m.Name,
|
||||
MemberFilter = m => true,
|
||||
LoopLimit = int.MaxValue,
|
||||
StrictVariables = true
|
||||
};
|
||||
|
||||
// Model
|
||||
var scriptObject = new ScriptObject();
|
||||
|
||||
// Constants
|
||||
scriptObject.SetValue("Context", Context, true);
|
||||
scriptObject.SetValue("CoreStyleSheet", GetCoreStyleSheetCode(), true);
|
||||
scriptObject.SetValue("ThemeStyleSheet", GetThemeStyleSheetCode(_themeName), true);
|
||||
scriptObject.SetValue("HighlightJsStyleName", $"solarized-{_themeName.ToLowerInvariant()}", true);
|
||||
|
||||
// Additional constants
|
||||
if (constants != null)
|
||||
{
|
||||
foreach (var (member, value) in constants)
|
||||
scriptObject.SetValue(member, value, true);
|
||||
}
|
||||
|
||||
// Functions
|
||||
scriptObject.Import("FormatDate",
|
||||
new Func<DateTimeOffset, string>(d => d.ToLocalString(Context.DateFormat)));
|
||||
|
||||
scriptObject.Import("FormatColorRgb",
|
||||
new Func<Color?, string?>(c => c != null ? $"rgb({c?.R}, {c?.G}, {c?.B})" : null));
|
||||
|
||||
scriptObject.Import("TryGetUserColor",
|
||||
new Func<User, Color?>(Context.TryGetUserColor));
|
||||
|
||||
scriptObject.Import("TryGetUserNick",
|
||||
new Func<User, string?>(u => Context.TryGetUserMember(u)?.Nick));
|
||||
|
||||
scriptObject.Import("FormatMarkdown",
|
||||
new Func<string?, string>(m => FormatMarkdown(m)));
|
||||
|
||||
scriptObject.Import("FormatEmbedMarkdown",
|
||||
new Func<string?, string>(m => FormatMarkdown(m, false)));
|
||||
|
||||
// Push model
|
||||
templateContext.PushGlobal(scriptObject);
|
||||
|
||||
// Push output
|
||||
templateContext.PushOutput(new TextWriterOutput(_writer));
|
||||
|
||||
return templateContext;
|
||||
}
|
||||
|
||||
private string FormatMarkdown(string? markdown, bool isJumboAllowed = true) =>
|
||||
HtmlMarkdownVisitor.Format(Context, markdown ?? "", isJumboAllowed);
|
||||
|
||||
private async Task RenderCurrentMessageGroupAsync()
|
||||
{
|
||||
var templateContext = CreateTemplateContext(new Dictionary<string, object>
|
||||
{
|
||||
["MessageGroup"] = GetCurrentMessageGroup()
|
||||
});
|
||||
|
||||
await templateContext.EvaluateAsync(_messageGroupTemplate.Page);
|
||||
}
|
||||
|
||||
public override async Task WritePreambleAsync()
|
||||
{
|
||||
var templateContext = CreateTemplateContext();
|
||||
await templateContext.EvaluateAsync(_preambleTemplate.Page);
|
||||
}
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
// If message group is empty or the given message can be grouped, buffer the given message
|
||||
if (!_messageGroupBuffer.Any() || MessageGroup.CanGroup(_messageGroupBuffer.Last(), message))
|
||||
{
|
||||
_messageGroupBuffer.Add(message);
|
||||
}
|
||||
// Otherwise, flush the group and render messages
|
||||
else
|
||||
{
|
||||
await RenderCurrentMessageGroupAsync();
|
||||
|
||||
_messageGroupBuffer.Clear();
|
||||
_messageGroupBuffer.Add(message);
|
||||
}
|
||||
|
||||
// Increment message count
|
||||
_messageCount++;
|
||||
}
|
||||
|
||||
public override async Task WritePostambleAsync()
|
||||
{
|
||||
// Flush current message group
|
||||
if (_messageGroupBuffer.Any())
|
||||
await RenderCurrentMessageGroupAsync();
|
||||
|
||||
var templateContext = CreateTemplateContext(new Dictionary<string, object>
|
||||
{
|
||||
["MessageCount"] = _messageCount
|
||||
});
|
||||
|
||||
await templateContext.EvaluateAsync(_postambleTemplate.Page);
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _writer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
internal partial class HtmlMessageWriter
|
||||
{
|
||||
private static readonly Assembly ResourcesAssembly = typeof(HtmlMessageWriter).Assembly;
|
||||
private static readonly string ResourcesNamespace = $"{ResourcesAssembly.GetName().Name}.Exporting.Resources";
|
||||
|
||||
private static string GetCoreStyleSheetCode() =>
|
||||
ResourcesAssembly
|
||||
.GetManifestResourceString($"{ResourcesNamespace}.HtmlCore.css");
|
||||
|
||||
private static string GetThemeStyleSheetCode(string themeName) =>
|
||||
ResourcesAssembly
|
||||
.GetManifestResourceString($"{ResourcesNamespace}.Html{themeName}.css");
|
||||
|
||||
private static string GetPreambleTemplateCode() =>
|
||||
ResourcesAssembly
|
||||
.GetManifestResourceString($"{ResourcesNamespace}.HtmlLayoutTemplate.html")
|
||||
.SubstringUntil("{{~ %SPLIT% ~}}");
|
||||
|
||||
private static string GetMessageGroupTemplateCode() =>
|
||||
ResourcesAssembly
|
||||
.GetManifestResourceString($"{ResourcesNamespace}.HtmlMessageGroupTemplate.html");
|
||||
|
||||
private static string GetPostambleTemplateCode() =>
|
||||
ResourcesAssembly
|
||||
.GetManifestResourceString($"{ResourcesNamespace}.HtmlLayoutTemplate.html")
|
||||
.SubstringAfter("{{~ %SPLIT% ~}}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
||||
{
|
||||
internal class JsonMessageWriter : MessageWriter
|
||||
{
|
||||
private readonly Utf8JsonWriter _writer;
|
||||
|
||||
private long _messageCount;
|
||||
|
||||
public JsonMessageWriter(Stream stream, ExportContext context)
|
||||
: base(stream, context)
|
||||
{
|
||||
_writer = new Utf8JsonWriter(stream, new JsonWriterOptions
|
||||
{
|
||||
Indented = true
|
||||
});
|
||||
}
|
||||
|
||||
private string FormatMarkdown(string? markdown) =>
|
||||
PlainTextMarkdownVisitor.Format(Context, markdown ?? "");
|
||||
|
||||
private void WriteAttachment(Attachment attachment)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
|
||||
_writer.WriteString("id", attachment.Id);
|
||||
_writer.WriteString("url", attachment.Url);
|
||||
_writer.WriteString("fileName", attachment.FileName);
|
||||
_writer.WriteNumber("fileSizeBytes", attachment.FileSize.TotalBytes);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbedAuthor(EmbedAuthor embedAuthor)
|
||||
{
|
||||
_writer.WriteStartObject("author");
|
||||
|
||||
_writer.WriteString("name", embedAuthor.Name);
|
||||
_writer.WriteString("url", embedAuthor.Url);
|
||||
_writer.WriteString("iconUrl", embedAuthor.IconUrl);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbedThumbnail(EmbedImage embedThumbnail)
|
||||
{
|
||||
_writer.WriteStartObject("thumbnail");
|
||||
|
||||
_writer.WriteString("url", embedThumbnail.Url);
|
||||
_writer.WriteNumber("width", embedThumbnail.Width);
|
||||
_writer.WriteNumber("height", embedThumbnail.Height);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbedImage(EmbedImage embedImage)
|
||||
{
|
||||
_writer.WriteStartObject("image");
|
||||
|
||||
_writer.WriteString("url", embedImage.Url);
|
||||
_writer.WriteNumber("width", embedImage.Width);
|
||||
_writer.WriteNumber("height", embedImage.Height);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbedFooter(EmbedFooter embedFooter)
|
||||
{
|
||||
_writer.WriteStartObject("footer");
|
||||
|
||||
_writer.WriteString("text", embedFooter.Text);
|
||||
_writer.WriteString("iconUrl", embedFooter.IconUrl);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbedField(EmbedField embedField)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
|
||||
_writer.WriteString("name", FormatMarkdown(embedField.Name));
|
||||
_writer.WriteString("value", FormatMarkdown(embedField.Value));
|
||||
_writer.WriteBoolean("isInline", embedField.IsInline);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteEmbed(Embed embed)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
|
||||
_writer.WriteString("title", FormatMarkdown(embed.Title));
|
||||
_writer.WriteString("url", embed.Url);
|
||||
_writer.WriteString("timestamp", embed.Timestamp);
|
||||
_writer.WriteString("description", FormatMarkdown(embed.Description));
|
||||
|
||||
if (embed.Author != null)
|
||||
WriteEmbedAuthor(embed.Author);
|
||||
|
||||
if (embed.Thumbnail != null)
|
||||
WriteEmbedThumbnail(embed.Thumbnail);
|
||||
|
||||
if (embed.Image != null)
|
||||
WriteEmbedImage(embed.Image);
|
||||
|
||||
if (embed.Footer != null)
|
||||
WriteEmbedFooter(embed.Footer);
|
||||
|
||||
// Fields
|
||||
_writer.WriteStartArray("fields");
|
||||
|
||||
foreach (var field in embed.Fields)
|
||||
WriteEmbedField(field);
|
||||
|
||||
_writer.WriteEndArray();
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private void WriteReaction(Reaction reaction)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
|
||||
// Emoji
|
||||
_writer.WriteStartObject("emoji");
|
||||
_writer.WriteString("id", reaction.Emoji.Id);
|
||||
_writer.WriteString("name", reaction.Emoji.Name);
|
||||
_writer.WriteBoolean("isAnimated", reaction.Emoji.IsAnimated);
|
||||
_writer.WriteString("imageUrl", reaction.Emoji.ImageUrl);
|
||||
_writer.WriteEndObject();
|
||||
|
||||
_writer.WriteNumber("count", reaction.Count);
|
||||
|
||||
_writer.WriteEndObject();
|
||||
}
|
||||
|
||||
public override async Task WritePreambleAsync()
|
||||
{
|
||||
// Root object (start)
|
||||
_writer.WriteStartObject();
|
||||
|
||||
// Guild
|
||||
_writer.WriteStartObject("guild");
|
||||
_writer.WriteString("id", Context.Guild.Id);
|
||||
_writer.WriteString("name", Context.Guild.Name);
|
||||
_writer.WriteString("iconUrl", Context.Guild.IconUrl);
|
||||
_writer.WriteEndObject();
|
||||
|
||||
// Channel
|
||||
_writer.WriteStartObject("channel");
|
||||
_writer.WriteString("id", Context.Channel.Id);
|
||||
_writer.WriteString("type", Context.Channel.Type.ToString());
|
||||
_writer.WriteString("category", Context.Channel.Category);
|
||||
_writer.WriteString("name", Context.Channel.Name);
|
||||
_writer.WriteString("topic", Context.Channel.Topic);
|
||||
_writer.WriteEndObject();
|
||||
|
||||
// Date range
|
||||
_writer.WriteStartObject("dateRange");
|
||||
_writer.WriteString("after", Context.After);
|
||||
_writer.WriteString("before", Context.Before);
|
||||
_writer.WriteEndObject();
|
||||
|
||||
// Message array (start)
|
||||
_writer.WriteStartArray("messages");
|
||||
|
||||
await _writer.FlushAsync();
|
||||
}
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
_writer.WriteStartObject();
|
||||
|
||||
// Metadata
|
||||
_writer.WriteString("id", message.Id);
|
||||
_writer.WriteString("type", message.Type.ToString());
|
||||
_writer.WriteString("timestamp", message.Timestamp);
|
||||
_writer.WriteString("timestampEdited", message.EditedTimestamp);
|
||||
_writer.WriteBoolean("isPinned", message.IsPinned);
|
||||
|
||||
// Content
|
||||
_writer.WriteString("content", FormatMarkdown(message.Content));
|
||||
|
||||
// Author
|
||||
_writer.WriteStartObject("author");
|
||||
_writer.WriteString("id", message.Author.Id);
|
||||
_writer.WriteString("name", message.Author.Name);
|
||||
_writer.WriteString("discriminator", $"{message.Author.Discriminator:0000}");
|
||||
_writer.WriteBoolean("isBot", message.Author.IsBot);
|
||||
_writer.WriteString("avatarUrl", message.Author.AvatarUrl);
|
||||
_writer.WriteEndObject();
|
||||
|
||||
// Attachments
|
||||
_writer.WriteStartArray("attachments");
|
||||
|
||||
foreach (var attachment in message.Attachments)
|
||||
WriteAttachment(attachment);
|
||||
|
||||
_writer.WriteEndArray();
|
||||
|
||||
// Embeds
|
||||
_writer.WriteStartArray("embeds");
|
||||
|
||||
foreach (var embed in message.Embeds)
|
||||
WriteEmbed(embed);
|
||||
|
||||
_writer.WriteEndArray();
|
||||
|
||||
// Reactions
|
||||
_writer.WriteStartArray("reactions");
|
||||
|
||||
foreach (var reaction in message.Reactions)
|
||||
WriteReaction(reaction);
|
||||
|
||||
_writer.WriteEndArray();
|
||||
|
||||
_writer.WriteEndObject();
|
||||
|
||||
// Flush every 100 messages
|
||||
if (_messageCount++ % 100 == 0)
|
||||
await _writer.FlushAsync();
|
||||
}
|
||||
|
||||
public override async Task WritePostambleAsync()
|
||||
{
|
||||
// Message array (end)
|
||||
_writer.WriteEndArray();
|
||||
|
||||
_writer.WriteNumber("messageCount", _messageCount);
|
||||
|
||||
// Root object (end)
|
||||
_writer.WriteEndObject();
|
||||
|
||||
await _writer.FlushAsync();
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _writer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
using DiscordChatExporter.Domain.Markdown;
|
||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
||||
{
|
||||
internal partial class HtmlMarkdownVisitor : MarkdownVisitor
|
||||
{
|
||||
private readonly ExportContext _context;
|
||||
private readonly StringBuilder _buffer;
|
||||
private readonly bool _isJumbo;
|
||||
|
||||
public HtmlMarkdownVisitor(ExportContext context, StringBuilder buffer, bool isJumbo)
|
||||
{
|
||||
_context = context;
|
||||
_buffer = buffer;
|
||||
_isJumbo = isJumbo;
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitText(TextNode text)
|
||||
{
|
||||
_buffer.Append(HtmlEncode(text.Text));
|
||||
return base.VisitText(text);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitFormatted(FormattedNode formatted)
|
||||
{
|
||||
var (tagOpen, tagClose) = formatted.Formatting switch
|
||||
{
|
||||
TextFormatting.Bold => ("<strong>", "</strong>"),
|
||||
TextFormatting.Italic => ("<em>", "</em>"),
|
||||
TextFormatting.Underline => ("<u>", "</u>"),
|
||||
TextFormatting.Strikethrough => ("<s>", "</s>"),
|
||||
TextFormatting.Spoiler => (
|
||||
"<span class=\"spoiler spoiler--hidden\" onclick=\"showSpoiler(event, this)\"><span class=\"spoiler-text\">", "</span></span>"),
|
||||
TextFormatting.Quote => ("<div class=\"quote\">", "</div>"),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(formatted.Formatting))
|
||||
};
|
||||
|
||||
_buffer.Append(tagOpen);
|
||||
var result = base.VisitFormatted(formatted);
|
||||
_buffer.Append(tagClose);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitInlineCodeBlock(InlineCodeBlockNode inlineCodeBlock)
|
||||
{
|
||||
_buffer
|
||||
.Append("<span class=\"pre pre--inline\">")
|
||||
.Append(HtmlEncode(inlineCodeBlock.Code))
|
||||
.Append("</span>");
|
||||
|
||||
return base.VisitInlineCodeBlock(inlineCodeBlock);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitMultiLineCodeBlock(MultiLineCodeBlockNode multiLineCodeBlock)
|
||||
{
|
||||
var highlightCssClass = !string.IsNullOrWhiteSpace(multiLineCodeBlock.Language)
|
||||
? $"language-{multiLineCodeBlock.Language}"
|
||||
: "nohighlight";
|
||||
|
||||
_buffer
|
||||
.Append($"<div class=\"pre pre--multiline {highlightCssClass}\">")
|
||||
.Append(HtmlEncode(multiLineCodeBlock.Code))
|
||||
.Append("</div>");
|
||||
|
||||
return base.VisitMultiLineCodeBlock(multiLineCodeBlock);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitMention(MentionNode mention)
|
||||
{
|
||||
if (mention.Type == MentionType.Meta)
|
||||
{
|
||||
_buffer
|
||||
.Append("<span class=\"mention\">")
|
||||
.Append("@").Append(HtmlEncode(mention.Id))
|
||||
.Append("</span>");
|
||||
}
|
||||
else if (mention.Type == MentionType.User)
|
||||
{
|
||||
var member = _context.TryGetMentionedMember(mention.Id);
|
||||
var fullName = member?.User.FullName ?? "Unknown";
|
||||
var nick = member?.Nick ?? "Unknown";
|
||||
|
||||
_buffer
|
||||
.Append($"<span class=\"mention\" title=\"{HtmlEncode(fullName)}\">")
|
||||
.Append("@").Append(HtmlEncode(nick))
|
||||
.Append("</span>");
|
||||
}
|
||||
else if (mention.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = _context.TryGetMentionedChannel(mention.Id);
|
||||
var name = channel?.Name ?? "deleted-channel";
|
||||
|
||||
_buffer
|
||||
.Append("<span class=\"mention\">")
|
||||
.Append("#").Append(HtmlEncode(name))
|
||||
.Append("</span>");
|
||||
}
|
||||
else if (mention.Type == MentionType.Role)
|
||||
{
|
||||
var role = _context.TryGetMentionedRole(mention.Id);
|
||||
var name = role?.Name ?? "deleted-role";
|
||||
var color = role?.Color;
|
||||
|
||||
var style = color != null
|
||||
? $"color: rgb({color?.R}, {color?.G}, {color?.B}); background-color: rgba({color?.R}, {color?.G}, {color?.B}, 0.1);"
|
||||
: "";
|
||||
|
||||
_buffer
|
||||
.Append($"<span class=\"mention\" style=\"{style}\">")
|
||||
.Append("@").Append(HtmlEncode(name))
|
||||
.Append("</span>");
|
||||
}
|
||||
|
||||
return base.VisitMention(mention);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitEmoji(EmojiNode emoji)
|
||||
{
|
||||
var emojiImageUrl = Emoji.GetImageUrl(emoji.Id, emoji.Name, emoji.IsAnimated);
|
||||
var jumboClass = _isJumbo ? "emoji--large" : "";
|
||||
|
||||
_buffer
|
||||
.Append($"<img class=\"emoji {jumboClass}\" alt=\"{emoji.Name}\" title=\"{emoji.Name}\" src=\"{emojiImageUrl}\">");
|
||||
|
||||
return base.VisitEmoji(emoji);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitLink(LinkNode link)
|
||||
{
|
||||
// Extract message ID if the link points to a Discord message
|
||||
var linkedMessageId = Regex.Match(link.Url, "^https?://discordapp.com/channels/.*?/(\\d+)/?$").Groups[1].Value;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(linkedMessageId))
|
||||
{
|
||||
_buffer
|
||||
.Append($"<a href=\"{Uri.EscapeUriString(link.Url)}\" onclick=\"scrollToMessage(event, '{linkedMessageId}')\">")
|
||||
.Append(HtmlEncode(link.Title))
|
||||
.Append("</a>");
|
||||
}
|
||||
else
|
||||
{
|
||||
_buffer
|
||||
.Append($"<a href=\"{Uri.EscapeUriString(link.Url)}\">")
|
||||
.Append(HtmlEncode(link.Title))
|
||||
.Append("</a>");
|
||||
}
|
||||
|
||||
return base.VisitLink(link);
|
||||
}
|
||||
}
|
||||
|
||||
internal partial class HtmlMarkdownVisitor
|
||||
{
|
||||
private static string HtmlEncode(string text) => WebUtility.HtmlEncode(text);
|
||||
|
||||
public static string Format(ExportContext context, string markdown, bool isJumboAllowed = true)
|
||||
{
|
||||
var nodes = MarkdownParser.Parse(markdown);
|
||||
|
||||
var isJumbo =
|
||||
isJumboAllowed &&
|
||||
nodes.All(n => n is EmojiNode || n is TextNode textNode && string.IsNullOrWhiteSpace(textNode.Text));
|
||||
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
new HtmlMarkdownVisitor(context, buffer, isJumbo).Visit(nodes);
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Domain.Markdown;
|
||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
||||
{
|
||||
internal partial class PlainTextMarkdownVisitor : MarkdownVisitor
|
||||
{
|
||||
private readonly ExportContext _context;
|
||||
private readonly StringBuilder _buffer;
|
||||
|
||||
public PlainTextMarkdownVisitor(ExportContext context, StringBuilder buffer)
|
||||
{
|
||||
_context = context;
|
||||
_buffer = buffer;
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitText(TextNode text)
|
||||
{
|
||||
_buffer.Append(text.Text);
|
||||
return base.VisitText(text);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitMention(MentionNode mention)
|
||||
{
|
||||
if (mention.Type == MentionType.Meta)
|
||||
{
|
||||
_buffer.Append($"@{mention.Id}");
|
||||
}
|
||||
else if (mention.Type == MentionType.User)
|
||||
{
|
||||
var member = _context.TryGetMentionedMember(mention.Id);
|
||||
var name = member?.User.Name ?? "Unknown";
|
||||
|
||||
_buffer.Append($"@{name}");
|
||||
}
|
||||
else if (mention.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = _context.TryGetMentionedChannel(mention.Id);
|
||||
var name = channel?.Name ?? "deleted-channel";
|
||||
|
||||
_buffer.Append($"#{name}");
|
||||
}
|
||||
else if (mention.Type == MentionType.Role)
|
||||
{
|
||||
var role = _context.TryGetMentionedRole(mention.Id);
|
||||
var name = role?.Name ?? "deleted-role";
|
||||
|
||||
_buffer.Append($"@{name}");
|
||||
}
|
||||
|
||||
return base.VisitMention(mention);
|
||||
}
|
||||
|
||||
public override MarkdownNode VisitEmoji(EmojiNode emoji)
|
||||
{
|
||||
_buffer.Append(
|
||||
emoji.IsCustomEmoji
|
||||
? $":{emoji.Name}:"
|
||||
: emoji.Name
|
||||
);
|
||||
|
||||
return base.VisitEmoji(emoji);
|
||||
}
|
||||
}
|
||||
|
||||
internal partial class PlainTextMarkdownVisitor
|
||||
{
|
||||
public static string Format(ExportContext context, string markdown)
|
||||
{
|
||||
var nodes = MarkdownParser.ParseMinimal(markdown);
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
new PlainTextMarkdownVisitor(context, buffer).Visit(nodes);
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
||||
{
|
||||
internal abstract class MessageWriter : IAsyncDisposable
|
||||
{
|
||||
protected Stream Stream { get; }
|
||||
|
||||
protected ExportContext Context { get; }
|
||||
|
||||
protected MessageWriter(Stream stream, ExportContext context)
|
||||
{
|
||||
Stream = stream;
|
||||
Context = context;
|
||||
}
|
||||
|
||||
public virtual Task WritePreambleAsync() => Task.CompletedTask;
|
||||
|
||||
public abstract Task WriteMessageAsync(Message message);
|
||||
|
||||
public virtual Task WritePostambleAsync() => Task.CompletedTask;
|
||||
|
||||
public virtual async ValueTask DisposeAsync() => await Stream.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
||||
using DiscordChatExporter.Domain.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
||||
{
|
||||
internal class PlainTextMessageWriter : MessageWriter
|
||||
{
|
||||
private readonly TextWriter _writer;
|
||||
|
||||
private long _messageCount;
|
||||
|
||||
public PlainTextMessageWriter(Stream stream, ExportContext context)
|
||||
: base(stream, context)
|
||||
{
|
||||
_writer = new StreamWriter(stream);
|
||||
}
|
||||
|
||||
private string FormatMarkdown(string? markdown) =>
|
||||
PlainTextMarkdownVisitor.Format(Context, markdown ?? "");
|
||||
|
||||
private string FormatMessageHeader(Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
// Timestamp & author
|
||||
buffer
|
||||
.Append($"[{message.Timestamp.ToLocalString(Context.DateFormat)}]")
|
||||
.Append(' ')
|
||||
.Append($"{message.Author.FullName}");
|
||||
|
||||
// Whether the message is pinned
|
||||
if (message.IsPinned)
|
||||
buffer.Append(' ').Append("(pinned)");
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatAttachments(IReadOnlyList<Attachment> attachments)
|
||||
{
|
||||
if (!attachments.Any())
|
||||
return "";
|
||||
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.AppendLine("{Attachments}")
|
||||
.AppendJoin(Environment.NewLine, attachments.Select(a => a.Url))
|
||||
.AppendLine();
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatEmbeds(IReadOnlyList<Embed> embeds)
|
||||
{
|
||||
if (!embeds.Any())
|
||||
return "";
|
||||
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
foreach (var embed in embeds)
|
||||
{
|
||||
buffer
|
||||
.AppendLine("{Embed}")
|
||||
.AppendLineIfNotNullOrWhiteSpace(embed.Author?.Name)
|
||||
.AppendLineIfNotNullOrWhiteSpace(embed.Url)
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatMarkdown(embed.Title))
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatMarkdown(embed.Description));
|
||||
|
||||
foreach (var field in embed.Fields)
|
||||
{
|
||||
buffer
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatMarkdown(field.Name))
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatMarkdown(field.Value));
|
||||
}
|
||||
|
||||
buffer
|
||||
.AppendLineIfNotNullOrWhiteSpace(embed.Thumbnail?.Url)
|
||||
.AppendLineIfNotNullOrWhiteSpace(embed.Image?.Url)
|
||||
.AppendLineIfNotNullOrWhiteSpace(embed.Footer?.Text)
|
||||
.AppendLine();
|
||||
}
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatReactions(IReadOnlyList<Reaction> reactions)
|
||||
{
|
||||
if (!reactions.Any())
|
||||
return "";
|
||||
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer.AppendLine("{Reactions}");
|
||||
|
||||
foreach (var reaction in reactions)
|
||||
{
|
||||
buffer.Append(reaction.Emoji.Name);
|
||||
|
||||
if (reaction.Count > 1)
|
||||
buffer.Append($" ({reaction.Count})");
|
||||
|
||||
buffer.Append(" ");
|
||||
}
|
||||
|
||||
buffer.AppendLine();
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private string FormatMessage(Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.AppendLine(FormatMessageHeader(message))
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatMarkdown(message.Content))
|
||||
.AppendLine()
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatAttachments(message.Attachments))
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatEmbeds(message.Embeds))
|
||||
.AppendLineIfNotNullOrWhiteSpace(FormatReactions(message.Reactions));
|
||||
|
||||
return buffer.Trim().ToString();
|
||||
}
|
||||
|
||||
public override async Task WritePreambleAsync()
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
buffer.AppendLine($"Guild: {Context.Guild.Name}");
|
||||
buffer.AppendLine($"Channel: {Context.Channel.Category} / {Context.Channel.Name}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Context.Channel.Topic))
|
||||
buffer.AppendLine($"Topic: {Context.Channel.Topic}");
|
||||
|
||||
if (Context.After != null)
|
||||
buffer.AppendLine($"After: {Context.After.Value.ToLocalString(Context.DateFormat)}");
|
||||
|
||||
if (Context.Before != null)
|
||||
buffer.AppendLine($"Before: {Context.Before.Value.ToLocalString(Context.DateFormat)}");
|
||||
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
|
||||
await _writer.WriteLineAsync(buffer.ToString());
|
||||
}
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
await _writer.WriteLineAsync(FormatMessage(message));
|
||||
await _writer.WriteLineAsync();
|
||||
|
||||
_messageCount++;
|
||||
}
|
||||
|
||||
public override async Task WritePostambleAsync()
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.Append('=', 62).AppendLine()
|
||||
.AppendLine($"Exported {_messageCount:N0} message(s)")
|
||||
.Append('=', 62).AppendLine()
|
||||
.AppendLine();
|
||||
|
||||
await _writer.WriteLineAsync(buffer.ToString());
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _writer.DisposeAsync();
|
||||
await base.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Drawing;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class ColorExtensions
|
||||
{
|
||||
public static Color WithAlpha(this Color color, int alpha) => Color.FromArgb(alpha, color);
|
||||
|
||||
public static Color ResetAlpha(this Color color) => color.WithAlpha(255);
|
||||
|
||||
public static int ToRgb(this Color color) => color.ToArgb() & 0xffffff;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class DateExtensions
|
||||
{
|
||||
public static string ToSnowflake(this DateTimeOffset dateTime)
|
||||
{
|
||||
var value = ((ulong) dateTime.ToUnixTimeMilliseconds() - 1420070400000UL) << 22;
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
public static string ToLocalString(this DateTimeOffset dateTime, string format) =>
|
||||
dateTime.ToLocalTime().ToString(format, CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class GenericExtensions
|
||||
{
|
||||
public static TOut Pipe<TIn, TOut>(this TIn input, Func<TIn, TOut> transform) => transform(input);
|
||||
|
||||
public static T? NullIf<T>(this T value, Func<T, bool> predicate) where T : struct =>
|
||||
!predicate(value)
|
||||
? value
|
||||
: (T?) null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class HttpClientExtensions
|
||||
{
|
||||
public static async Task<JsonElement> ReadAsJsonAsync(this HttpContent content)
|
||||
{
|
||||
await using var stream = await content.ReadAsStreamAsync();
|
||||
using var doc = await JsonDocument.ParseAsync(stream);
|
||||
|
||||
return doc.RootElement.Clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class JsonElementExtensions
|
||||
{
|
||||
public static JsonElement? GetPropertyOrNull(this JsonElement element, string propertyName) =>
|
||||
element.TryGetProperty(propertyName, out var result) && result.ValueKind != JsonValueKind.Null
|
||||
? result
|
||||
: (JsonElement?) null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Text;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class StringExtensions
|
||||
{
|
||||
public static StringBuilder AppendLineIfNotNullOrWhiteSpace(this StringBuilder builder, string? value) =>
|
||||
!string.IsNullOrWhiteSpace(value) ? builder.AppendLine(value) : builder;
|
||||
|
||||
public static StringBuilder Trim(this StringBuilder builder)
|
||||
{
|
||||
while (builder.Length > 0 && char.IsWhiteSpace(builder[0]))
|
||||
builder.Remove(0, 1);
|
||||
|
||||
while (builder.Length > 0 && char.IsWhiteSpace(builder[^1]))
|
||||
builder.Remove(builder.Length - 1, 1);
|
||||
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Internal
|
||||
{
|
||||
internal static class Utf8JsonWriterExtensions
|
||||
{
|
||||
public static void WriteString(this Utf8JsonWriter writer, string propertyName, DateTimeOffset? value)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
|
||||
if (value != null)
|
||||
writer.WriteStringValue(value.Value);
|
||||
else
|
||||
writer.WriteNullValue();
|
||||
}
|
||||
|
||||
public static void WriteNumber(this Utf8JsonWriter writer, string propertyName, int? value)
|
||||
{
|
||||
writer.WritePropertyName(propertyName);
|
||||
|
||||
if (value != null)
|
||||
writer.WriteNumberValue(value.Value);
|
||||
else
|
||||
writer.WriteNullValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal class EmojiNode : MarkdownNode
|
||||
{
|
||||
public string? Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public bool IsAnimated { get; }
|
||||
|
||||
public bool IsCustomEmoji => !string.IsNullOrWhiteSpace(Id);
|
||||
|
||||
public EmojiNode(string? id, string name, bool isAnimated)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IsAnimated = isAnimated;
|
||||
}
|
||||
|
||||
public EmojiNode(string name)
|
||||
: this(null, name, false)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Emoji> {Name}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal enum TextFormatting
|
||||
{
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
Strikethrough,
|
||||
Spoiler,
|
||||
Quote
|
||||
}
|
||||
|
||||
internal class FormattedNode : MarkdownNode
|
||||
{
|
||||
public TextFormatting Formatting { get; }
|
||||
|
||||
public IReadOnlyList<MarkdownNode> Children { get; }
|
||||
|
||||
public FormattedNode(TextFormatting formatting, IReadOnlyList<MarkdownNode> children)
|
||||
{
|
||||
Formatting = formatting;
|
||||
Children = children;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Formatting}> (+{Children.Count})";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal class InlineCodeBlockNode : MarkdownNode
|
||||
{
|
||||
public string Code { get; }
|
||||
|
||||
public InlineCodeBlockNode(string code)
|
||||
{
|
||||
Code = code;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Code> {Code}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal class LinkNode : MarkdownNode
|
||||
{
|
||||
public string Url { get; }
|
||||
|
||||
public string Title { get; }
|
||||
|
||||
public LinkNode(string url, string title)
|
||||
{
|
||||
Url = url;
|
||||
Title = title;
|
||||
}
|
||||
|
||||
public LinkNode(string url)
|
||||
: this(url, url)
|
||||
{
|
||||
}
|
||||
|
||||
public override string ToString() => $"<Link> {Title}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal abstract class MarkdownNode
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal enum MentionType
|
||||
{
|
||||
Meta,
|
||||
User,
|
||||
Channel,
|
||||
Role
|
||||
}
|
||||
|
||||
internal class MentionNode : MarkdownNode
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public MentionType Type { get; }
|
||||
|
||||
public MentionNode(string id, MentionType type)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Type} mention> {Id}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal class MultiLineCodeBlockNode : MarkdownNode
|
||||
{
|
||||
public string Language { get; }
|
||||
|
||||
public string Code { get; }
|
||||
|
||||
public MultiLineCodeBlockNode(string language, string code)
|
||||
{
|
||||
Language = language;
|
||||
Code = code;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Language}> {Code}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
||||
{
|
||||
internal class TextNode : MarkdownNode
|
||||
{
|
||||
public string Text { get; }
|
||||
|
||||
public TextNode(string text)
|
||||
{
|
||||
Text = text;
|
||||
}
|
||||
|
||||
public override string ToString() => Text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
||||
using DiscordChatExporter.Domain.Markdown.Matching;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown
|
||||
{
|
||||
// The following parsing logic is meant to replicate Discord's markdown grammar as close as possible
|
||||
internal static partial class MarkdownParser
|
||||
{
|
||||
private const RegexOptions DefaultRegexOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline;
|
||||
|
||||
/* Formatting */
|
||||
|
||||
// Capture any character until the earliest double asterisk not followed by an asterisk
|
||||
private static readonly IMatcher<MarkdownNode> BoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Bold, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the earliest single asterisk not preceded or followed by an asterisk
|
||||
// Opening asterisk must not be followed by whitespace
|
||||
// Closing asterisk must not be preceded by whitespace
|
||||
private static readonly IMatcher<MarkdownNode> ItalicFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the earliest triple asterisk not followed by an asterisk
|
||||
private static readonly IMatcher<MarkdownNode> ItalicBoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\*(\\*\\*.+?\\*\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]), BoldFormattedNodeMatcher)));
|
||||
|
||||
// Capture any character except underscore until an underscore
|
||||
// Closing underscore must not be followed by a word character
|
||||
private static readonly IMatcher<MarkdownNode> ItalicAltFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("_([^_]+)_(?!\\w)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the earliest double underscore not followed by an underscore
|
||||
private static readonly IMatcher<MarkdownNode> UnderlineFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("__(.+?)__(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Underline, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the earliest triple underscore not followed by an underscore
|
||||
private static readonly IMatcher<MarkdownNode> ItalicUnderlineFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("_(__.+?__)_(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]), UnderlineFormattedNodeMatcher)));
|
||||
|
||||
// Capture any character until the earliest double tilde
|
||||
private static readonly IMatcher<MarkdownNode> StrikethroughFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("~~(.+?)~~", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Strikethrough, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the earliest double pipe
|
||||
private static readonly IMatcher<MarkdownNode> SpoilerFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\|\\|(.+?)\\|\\|", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Spoiler, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the end of the line
|
||||
// Opening 'greater than' character must be followed by whitespace
|
||||
private static readonly IMatcher<MarkdownNode> SingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("^>\\s(.+\n?)", DefaultRegexOptions),
|
||||
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Repeatedly capture any character until the end of the line
|
||||
// This one is tricky as it ends up producing multiple separate captures which need to be joined
|
||||
private static readonly IMatcher<MarkdownNode> RepeatedSingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("(?:^>\\s(.+\n?)){2,}", DefaultRegexOptions),
|
||||
(p, m) =>
|
||||
{
|
||||
var content = string.Concat(m.Groups[1].Captures.Select(c => c.Value));
|
||||
return new FormattedNode(TextFormatting.Quote, Parse(content));
|
||||
});
|
||||
|
||||
// Capture any character until the end of the input
|
||||
// Opening 'greater than' characters must be followed by whitespace
|
||||
private static readonly IMatcher<MarkdownNode> MultiLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("^>>>\\s(.+)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
/* Code blocks */
|
||||
|
||||
// Capture any character except backtick until a backtick
|
||||
// Blank lines at the beginning and end of content are trimmed
|
||||
// There can be either one or two backticks, but equal number on both sides
|
||||
private static readonly IMatcher<MarkdownNode> InlineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("(`{1,2})([^`]+)\\1", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
m => new InlineCodeBlockNode(m.Groups[2].Value.Trim('\r', '\n')));
|
||||
|
||||
// Capture language identifier and then any character until the earliest triple backtick
|
||||
// Language identifier is one word immediately after opening backticks, followed immediately by newline
|
||||
// Blank lines at the beginning and end of content are trimmed
|
||||
private static readonly IMatcher<MarkdownNode> MultiLineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("```(?:(\\w*)\\n)?(.+?)```", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
m => new MultiLineCodeBlockNode(m.Groups[1].Value, m.Groups[2].Value.Trim('\r', '\n')));
|
||||
|
||||
/* Mentions */
|
||||
|
||||
// Capture @everyone
|
||||
private static readonly IMatcher<MarkdownNode> EveryoneMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||
"@everyone",
|
||||
p => new MentionNode("everyone", MentionType.Meta));
|
||||
|
||||
// Capture @here
|
||||
private static readonly IMatcher<MarkdownNode> HereMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||
"@here",
|
||||
p => new MentionNode("here", MentionType.Meta));
|
||||
|
||||
// Capture <@123456> or <@!123456>
|
||||
private static readonly IMatcher<MarkdownNode> UserMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("<@!?(\\d+)>", DefaultRegexOptions),
|
||||
m => new MentionNode(m.Groups[1].Value, MentionType.User));
|
||||
|
||||
// Capture <#123456>
|
||||
private static readonly IMatcher<MarkdownNode> ChannelMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("<#(\\d+)>", DefaultRegexOptions),
|
||||
m => new MentionNode(m.Groups[1].Value, MentionType.Channel));
|
||||
|
||||
// Capture <@&123456>
|
||||
private static readonly IMatcher<MarkdownNode> RoleMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("<@&(\\d+)>", DefaultRegexOptions),
|
||||
m => new MentionNode(m.Groups[1].Value, MentionType.Role));
|
||||
|
||||
/* Emojis */
|
||||
|
||||
// Capture any country flag emoji (two regional indicator surrogate pairs)
|
||||
// ... or "miscellaneous symbol" character
|
||||
// ... or surrogate pair
|
||||
// ... or digit followed by enclosing mark
|
||||
// (this does not match all emojis in Discord but it's reasonably accurate enough)
|
||||
private static readonly IMatcher<MarkdownNode> StandardEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("((?:[\\uD83C][\\uDDE6-\\uDDFF]){2}|[\\u2600-\\u26FF]|\\p{Cs}{2}|\\d\\p{Me})", DefaultRegexOptions),
|
||||
m => new EmojiNode(m.Groups[1].Value));
|
||||
|
||||
// Capture <:lul:123456> or <a:lul:123456>
|
||||
private static readonly IMatcher<MarkdownNode> CustomEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("<(a)?:(.+?):(\\d+?)>", DefaultRegexOptions),
|
||||
m => new EmojiNode(m.Groups[3].Value, m.Groups[2].Value, !string.IsNullOrWhiteSpace(m.Groups[1].Value)));
|
||||
|
||||
/* Links */
|
||||
|
||||
// Capture [title](link)
|
||||
private static readonly IMatcher<MarkdownNode> TitledLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\[(.+?)\\]\\((.+?)\\)", DefaultRegexOptions),
|
||||
m => new LinkNode(m.Groups[2].Value, m.Groups[1].Value));
|
||||
|
||||
// Capture any non-whitespace character after http:// or https:// until the last punctuation character or whitespace
|
||||
private static readonly IMatcher<MarkdownNode> AutoLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("(https?://\\S*[^\\.,:;\"\'\\s])", DefaultRegexOptions),
|
||||
m => new LinkNode(m.Groups[1].Value));
|
||||
|
||||
// Same as auto link but also surrounded by angular brackets
|
||||
private static readonly IMatcher<MarkdownNode> HiddenLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("<(https?://\\S*[^\\.,:;\"\'\\s])>", DefaultRegexOptions),
|
||||
m => new LinkNode(m.Groups[1].Value));
|
||||
|
||||
/* Text */
|
||||
|
||||
// Capture the shrug emoticon
|
||||
// This escapes it from matching for formatting
|
||||
private static readonly IMatcher<MarkdownNode> ShrugTextNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||
@"¯\_(ツ)_/¯",
|
||||
p => new TextNode(p.ToString()));
|
||||
|
||||
// Capture some specific emojis that don't get rendered
|
||||
// This escapes it from matching for emoji
|
||||
private static readonly IMatcher<MarkdownNode> IgnoredEmojiTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("(\\u26A7|\\u2640|\\u2642|\\u2695|\\u267E|\\u00A9|\\u00AE|\\u2122)", DefaultRegexOptions),
|
||||
m => new TextNode(m.Groups[1].Value));
|
||||
|
||||
// Capture any "symbol/other" character or surrogate pair preceded by a backslash
|
||||
// This escapes it from matching for emoji
|
||||
private static readonly IMatcher<MarkdownNode> EscapedSymbolTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\\\(\\p{So}|\\p{Cs}{2})", DefaultRegexOptions),
|
||||
m => new TextNode(m.Groups[1].Value));
|
||||
|
||||
// Capture any non-whitespace, non latin alphanumeric character preceded by a backslash
|
||||
// This escapes it from matching for formatting or other tokens
|
||||
private static readonly IMatcher<MarkdownNode> EscapedCharacterTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||
new Regex("\\\\([^a-zA-Z0-9\\s])", DefaultRegexOptions),
|
||||
m => new TextNode(m.Groups[1].Value));
|
||||
|
||||
// Combine all matchers into one
|
||||
// Matchers that have similar patterns are ordered from most specific to least specific
|
||||
private static readonly IMatcher<MarkdownNode> AggregateNodeMatcher = new AggregateMatcher<MarkdownNode>(
|
||||
// Escaped text
|
||||
ShrugTextNodeMatcher,
|
||||
IgnoredEmojiTextNodeMatcher,
|
||||
EscapedSymbolTextNodeMatcher,
|
||||
EscapedCharacterTextNodeMatcher,
|
||||
|
||||
// Formatting
|
||||
ItalicBoldFormattedNodeMatcher,
|
||||
ItalicUnderlineFormattedNodeMatcher,
|
||||
BoldFormattedNodeMatcher,
|
||||
ItalicFormattedNodeMatcher,
|
||||
UnderlineFormattedNodeMatcher,
|
||||
ItalicAltFormattedNodeMatcher,
|
||||
StrikethroughFormattedNodeMatcher,
|
||||
SpoilerFormattedNodeMatcher,
|
||||
MultiLineQuoteNodeMatcher,
|
||||
RepeatedSingleLineQuoteNodeMatcher,
|
||||
SingleLineQuoteNodeMatcher,
|
||||
|
||||
// Code blocks
|
||||
MultiLineCodeBlockNodeMatcher,
|
||||
InlineCodeBlockNodeMatcher,
|
||||
|
||||
// Mentions
|
||||
EveryoneMentionNodeMatcher,
|
||||
HereMentionNodeMatcher,
|
||||
UserMentionNodeMatcher,
|
||||
ChannelMentionNodeMatcher,
|
||||
RoleMentionNodeMatcher,
|
||||
|
||||
// Links
|
||||
TitledLinkNodeMatcher,
|
||||
AutoLinkNodeMatcher,
|
||||
HiddenLinkNodeMatcher,
|
||||
|
||||
// Emoji
|
||||
StandardEmojiNodeMatcher,
|
||||
CustomEmojiNodeMatcher
|
||||
);
|
||||
|
||||
// Minimal set of matchers for non-multimedia formats (e.g. plain text)
|
||||
private static readonly IMatcher<MarkdownNode> MinimalAggregateNodeMatcher = new AggregateMatcher<MarkdownNode>(
|
||||
// Mentions
|
||||
EveryoneMentionNodeMatcher,
|
||||
HereMentionNodeMatcher,
|
||||
UserMentionNodeMatcher,
|
||||
ChannelMentionNodeMatcher,
|
||||
RoleMentionNodeMatcher,
|
||||
|
||||
// Emoji
|
||||
CustomEmojiNodeMatcher
|
||||
);
|
||||
|
||||
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart, IMatcher<MarkdownNode> matcher) =>
|
||||
matcher
|
||||
.MatchAll(stringPart, p => new TextNode(p.ToString()))
|
||||
.Select(r => r.Value)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
internal static partial class MarkdownParser
|
||||
{
|
||||
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart) => Parse(stringPart, AggregateNodeMatcher);
|
||||
|
||||
private static IReadOnlyList<MarkdownNode> ParseMinimal(StringPart stringPart) => Parse(stringPart, MinimalAggregateNodeMatcher);
|
||||
|
||||
public static IReadOnlyList<MarkdownNode> Parse(string input) => Parse(new StringPart(input));
|
||||
|
||||
public static IReadOnlyList<MarkdownNode> ParseMinimal(string input) => ParseMinimal(new StringPart(input));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown
|
||||
{
|
||||
internal abstract class MarkdownVisitor
|
||||
{
|
||||
public virtual MarkdownNode VisitText(TextNode text) => text;
|
||||
|
||||
public virtual MarkdownNode VisitFormatted(FormattedNode formatted)
|
||||
{
|
||||
Visit(formatted.Children);
|
||||
return formatted;
|
||||
}
|
||||
|
||||
public virtual MarkdownNode VisitInlineCodeBlock(InlineCodeBlockNode inlineCodeBlock) => inlineCodeBlock;
|
||||
|
||||
public virtual MarkdownNode VisitMultiLineCodeBlock(MultiLineCodeBlockNode multiLineCodeBlock) => multiLineCodeBlock;
|
||||
|
||||
public virtual MarkdownNode VisitLink(LinkNode link) => link;
|
||||
|
||||
public virtual MarkdownNode VisitEmoji(EmojiNode emoji) => emoji;
|
||||
|
||||
public virtual MarkdownNode VisitMention(MentionNode mention) => mention;
|
||||
|
||||
public MarkdownNode Visit(MarkdownNode node) => node switch
|
||||
{
|
||||
TextNode text => VisitText(text),
|
||||
FormattedNode formatted => VisitFormatted(formatted),
|
||||
InlineCodeBlockNode inlineCodeBlock => VisitInlineCodeBlock(inlineCodeBlock),
|
||||
MultiLineCodeBlockNode multiLineCodeBlock => VisitMultiLineCodeBlock(multiLineCodeBlock),
|
||||
LinkNode link => VisitLink(link),
|
||||
EmojiNode emoji => VisitEmoji(emoji),
|
||||
MentionNode mention => VisitMention(mention),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||
};
|
||||
|
||||
public void Visit(IEnumerable<MarkdownNode> nodes)
|
||||
{
|
||||
foreach (var node in nodes)
|
||||
Visit(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal class AggregateMatcher<T> : IMatcher<T>
|
||||
{
|
||||
private readonly IReadOnlyList<IMatcher<T>> _matchers;
|
||||
|
||||
public AggregateMatcher(IReadOnlyList<IMatcher<T>> matchers)
|
||||
{
|
||||
_matchers = matchers;
|
||||
}
|
||||
|
||||
public AggregateMatcher(params IMatcher<T>[] matchers)
|
||||
: this((IReadOnlyList<IMatcher<T>>) matchers)
|
||||
{
|
||||
}
|
||||
|
||||
public ParsedMatch<T>? TryMatch(StringPart stringPart)
|
||||
{
|
||||
ParsedMatch<T>? earliestMatch = null;
|
||||
|
||||
// Try to match the input with each matcher and get the match with the lowest start index
|
||||
foreach (var matcher in _matchers)
|
||||
{
|
||||
// Try to match
|
||||
var match = matcher.TryMatch(stringPart);
|
||||
|
||||
// If there's no match - continue
|
||||
if (match == null)
|
||||
continue;
|
||||
|
||||
// If this match is earlier than previous earliest - replace
|
||||
if (earliestMatch == null || match.StringPart.StartIndex < earliestMatch.StringPart.StartIndex)
|
||||
earliestMatch = match;
|
||||
|
||||
// If the earliest match starts at the very beginning - break,
|
||||
// because it's impossible to find a match earlier than that
|
||||
if (earliestMatch.StringPart.StartIndex == stringPart.StartIndex)
|
||||
break;
|
||||
}
|
||||
|
||||
return earliestMatch;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal interface IMatcher<T>
|
||||
{
|
||||
ParsedMatch<T>? TryMatch(StringPart stringPart);
|
||||
}
|
||||
|
||||
internal static class MatcherExtensions
|
||||
{
|
||||
public static IEnumerable<ParsedMatch<T>> MatchAll<T>(this IMatcher<T> matcher,
|
||||
StringPart stringPart, Func<StringPart, T> transformFallback)
|
||||
{
|
||||
// Loop through segments divided by individual matches
|
||||
var currentIndex = stringPart.StartIndex;
|
||||
while (currentIndex < stringPart.EndIndex)
|
||||
{
|
||||
// Find a match within this segment
|
||||
var match = matcher.TryMatch(stringPart.Slice(currentIndex, stringPart.EndIndex - currentIndex));
|
||||
|
||||
// If there's no match - break
|
||||
if (match == null)
|
||||
break;
|
||||
|
||||
// If this match doesn't start immediately at current index - transform and yield fallback first
|
||||
if (match.StringPart.StartIndex > currentIndex)
|
||||
{
|
||||
var fallbackPart = stringPart.Slice(currentIndex, match.StringPart.StartIndex - currentIndex);
|
||||
yield return new ParsedMatch<T>(fallbackPart, transformFallback(fallbackPart));
|
||||
}
|
||||
|
||||
// Yield match
|
||||
yield return match;
|
||||
|
||||
// Shift current index to the end of the match
|
||||
currentIndex = match.StringPart.StartIndex + match.StringPart.Length;
|
||||
}
|
||||
|
||||
// If EOL wasn't reached - transform and yield remaining part as fallback
|
||||
if (currentIndex < stringPart.EndIndex)
|
||||
{
|
||||
var fallbackPart = stringPart.Slice(currentIndex);
|
||||
yield return new ParsedMatch<T>(fallbackPart, transformFallback(fallbackPart));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal class ParsedMatch<T>
|
||||
{
|
||||
public StringPart StringPart { get; }
|
||||
|
||||
public T Value { get; }
|
||||
|
||||
public ParsedMatch(StringPart stringPart, T value)
|
||||
{
|
||||
StringPart = stringPart;
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal class RegexMatcher<T> : IMatcher<T>
|
||||
{
|
||||
private readonly Regex _regex;
|
||||
private readonly Func<StringPart, Match, T> _transform;
|
||||
|
||||
public RegexMatcher(Regex regex, Func<StringPart, Match, T> transform)
|
||||
{
|
||||
_regex = regex;
|
||||
_transform = transform;
|
||||
}
|
||||
|
||||
public RegexMatcher(Regex regex, Func<Match, T> transform)
|
||||
: this(regex, (p, m) => transform(m))
|
||||
{
|
||||
}
|
||||
|
||||
public ParsedMatch<T>? TryMatch(StringPart stringPart)
|
||||
{
|
||||
var match = _regex.Match(stringPart.Target, stringPart.StartIndex, stringPart.Length);
|
||||
if (!match.Success)
|
||||
return null;
|
||||
|
||||
// Overload regex.Match(string, int, int) doesn't take the whole string into account,
|
||||
// it effectively functions as a match check on a substring.
|
||||
// Which is super weird because regex.Match(string, int) takes the whole input in context.
|
||||
// So in order to properly account for ^/$ regex tokens, we need to make sure that
|
||||
// the expression also matches on the bigger part of the input.
|
||||
if (!_regex.IsMatch(stringPart.Target.Substring(0, stringPart.EndIndex), stringPart.StartIndex))
|
||||
return null;
|
||||
|
||||
var stringPartMatch = stringPart.Slice(match.Index, match.Length);
|
||||
return new ParsedMatch<T>(stringPartMatch, _transform(stringPartMatch, match));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal class StringMatcher<T> : IMatcher<T>
|
||||
{
|
||||
private readonly string _needle;
|
||||
private readonly StringComparison _comparison;
|
||||
private readonly Func<StringPart, T> _transform;
|
||||
|
||||
public StringMatcher(string needle, StringComparison comparison, Func<StringPart, T> transform)
|
||||
{
|
||||
_needle = needle;
|
||||
_comparison = comparison;
|
||||
_transform = transform;
|
||||
}
|
||||
|
||||
public StringMatcher(string needle, Func<StringPart, T> transform)
|
||||
: this(needle, StringComparison.Ordinal, transform)
|
||||
{
|
||||
}
|
||||
|
||||
public ParsedMatch<T>? TryMatch(StringPart stringPart)
|
||||
{
|
||||
var index = stringPart.Target.IndexOf(_needle, stringPart.StartIndex, stringPart.Length, _comparison);
|
||||
|
||||
if (index >= 0)
|
||||
{
|
||||
var stringPartMatch = stringPart.Slice(index, _needle.Length);
|
||||
return new ParsedMatch<T>(stringPartMatch, _transform(stringPartMatch));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
||||
{
|
||||
internal readonly struct StringPart
|
||||
{
|
||||
public string Target { get; }
|
||||
|
||||
public int StartIndex { get; }
|
||||
|
||||
public int Length { get; }
|
||||
|
||||
public int EndIndex { get; }
|
||||
|
||||
public StringPart(string target, int startIndex, int length)
|
||||
{
|
||||
Target = target;
|
||||
StartIndex = startIndex;
|
||||
Length = length;
|
||||
EndIndex = startIndex + length;
|
||||
}
|
||||
|
||||
public StringPart(string target)
|
||||
: this(target, 0, target.Length)
|
||||
{
|
||||
}
|
||||
|
||||
public StringPart Slice(int newStartIndex, int newLength) => new StringPart(Target, newStartIndex, newLength);
|
||||
|
||||
public StringPart Slice(int newStartIndex) => Slice(newStartIndex, EndIndex - newStartIndex);
|
||||
|
||||
public StringPart Slice(Capture capture) => Slice(capture.Index, capture.Length);
|
||||
|
||||
public override string ToString() => Target.Substring(StartIndex, Length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DiscordChatExporter.Domain.Utilities
|
||||
{
|
||||
public static class AsyncExtensions
|
||||
{
|
||||
private static async ValueTask<IReadOnlyList<T>> AggregateAsync<T>(this IAsyncEnumerable<T> asyncEnumerable)
|
||||
{
|
||||
var list = new List<T>();
|
||||
|
||||
await foreach (var i in asyncEnumerable)
|
||||
list.Add(i);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public static ValueTaskAwaiter<IReadOnlyList<T>> GetAwaiter<T>(this IAsyncEnumerable<T> asyncEnumerable) =>
|
||||
asyncEnumerable.AggregateAsync().GetAwaiter();
|
||||
|
||||
public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> handleAsync, int degreeOfParallelism)
|
||||
{
|
||||
using var semaphore = new SemaphoreSlim(degreeOfParallelism);
|
||||
|
||||
await Task.WhenAll(source.Select(async item =>
|
||||
{
|
||||
// ReSharper disable once AccessToDisposedClosure
|
||||
await semaphore.WaitAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await handleAsync(item);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ReSharper disable once AccessToDisposedClosure
|
||||
semaphore.Release();
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<Application
|
||||
x:Class="DiscordChatExporter.Gui.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:DiscordChatExporter.Gui"
|
||||
xmlns:s="https://github.com/canton7/Stylet">
|
||||
<Application.Resources>
|
||||
<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.MergedDictionaries>
|
||||
|
||||
<!-- Colors -->
|
||||
<Color x:Key="PrimaryColor">#343838</Color>
|
||||
<Color x:Key="PrimaryLightColor">#5E6262</Color>
|
||||
<Color x:Key="PrimaryDarkColor">#0D1212</Color>
|
||||
<Color x:Key="AccentColor">#F9A825</Color>
|
||||
<Color x:Key="AccentDarkColor">#C17900</Color>
|
||||
<Color x:Key="TextColor">#000000</Color>
|
||||
<Color x:Key="InverseTextColor">#FFFFFF</Color>
|
||||
|
||||
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="{DynamicResource PrimaryLightColor}" />
|
||||
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="{DynamicResource PrimaryColor}" />
|
||||
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="{DynamicResource PrimaryDarkColor}" />
|
||||
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="{DynamicResource AccentColor}" />
|
||||
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="{DynamicResource TextColor}" />
|
||||
|
||||
<SolidColorBrush
|
||||
x:Key="PrimaryTextBrush"
|
||||
Opacity="0.87"
|
||||
Color="{DynamicResource TextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="SecondaryTextBrush"
|
||||
Opacity="0.64"
|
||||
Color="{DynamicResource TextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="DimTextBrush"
|
||||
Opacity="0.45"
|
||||
Color="{DynamicResource TextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="PrimaryInverseTextBrush"
|
||||
Opacity="1"
|
||||
Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="SecondaryInverseTextBrush"
|
||||
Opacity="0.7"
|
||||
Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="DimInverseTextBrush"
|
||||
Opacity="0.52"
|
||||
Color="{DynamicResource InverseTextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="AccentTextBrush"
|
||||
Opacity="1"
|
||||
Color="{DynamicResource AccentColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="AccentDarkTextBrush"
|
||||
Opacity="1"
|
||||
Color="{DynamicResource AccentDarkColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="DividerBrush"
|
||||
Opacity="0.12"
|
||||
Color="{DynamicResource TextColor}" />
|
||||
<SolidColorBrush
|
||||
x:Key="InverseDividerBrush"
|
||||
Opacity="0.12"
|
||||
Color="{DynamicResource InverseTextColor}" />
|
||||
|
||||
<!-- Styles -->
|
||||
<Style x:Key="MaterialDesignRoot" TargetType="{x:Type Control}">
|
||||
<Setter Property="FontFamily" Value="{DynamicResource MaterialDesignFont}" />
|
||||
<Setter Property="RenderOptions.BitmapScalingMode" Value="HighQuality" />
|
||||
<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 MaterialDesignScrollBarMinimal}" TargetType="{x:Type ScrollBar}" />
|
||||
|
||||
<Style BasedOn="{StaticResource MaterialDesignLinearProgressBar}" TargetType="{x:Type ProgressBar}">
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource SecondaryAccentBrush}" />
|
||||
<Setter Property="Height" Value="2" />
|
||||
<Setter Property="Maximum" Value="1" />
|
||||
<Setter Property="Minimum" Value="0" />
|
||||
</Style>
|
||||
|
||||
<Style BasedOn="{StaticResource MaterialDesignTextBox}" TargetType="{x:Type TextBox}">
|
||||
<Setter Property="Foreground" Value="{DynamicResource PrimaryTextBrush}" />
|
||||
</Style>
|
||||
|
||||
<Style BasedOn="{StaticResource MaterialDesignComboBox}" TargetType="{x:Type ComboBox}">
|
||||
<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}"
|
||||
TargetType="{x:Type ToggleButton}">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource PrimaryHueMidBrush}" />
|
||||
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource MaterialDesignFlatButtonClick}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignFlatButtonClick}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</s:ApplicationLoader>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace DiscordChatExporter.Gui
|
||||
{
|
||||
public partial class App
|
||||
{
|
||||
private static readonly Assembly Assembly = typeof(App).Assembly;
|
||||
|
||||
public static string Name => Assembly.GetName().Name!;
|
||||
|
||||
public static Version Version => Assembly.GetName().Version!;
|
||||
|
||||
public static string VersionString => Version.ToString(3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Behaviors
|
||||
{
|
||||
public class ChannelMultiSelectionListBoxBehavior : MultiSelectionListBoxBehavior<Channel>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using Microsoft.Xaml.Behaviors;
|
||||
|
||||
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,36 @@
|
||||
using DiscordChatExporter.Gui.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
using Stylet;
|
||||
using StyletIoC;
|
||||
|
||||
#if !DEBUG
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
#endif
|
||||
|
||||
namespace DiscordChatExporter.Gui
|
||||
{
|
||||
public class Bootstrapper : Bootstrapper<RootViewModel>
|
||||
{
|
||||
protected override void ConfigureIoC(IStyletIoCBuilder builder)
|
||||
{
|
||||
base.ConfigureIoC(builder);
|
||||
|
||||
// Bind settings as singleton
|
||||
builder.Bind<SettingsService>().ToSelf().InSingletonScope();
|
||||
|
||||
// Bind view model factory
|
||||
builder.Bind<IViewModelFactory>().ToAbstractFactory();
|
||||
}
|
||||
|
||||
#if !DEBUG
|
||||
protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
base.OnUnhandledException(e);
|
||||
|
||||
MessageBox.Show(e.Exception.ToString(), "Error occured", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Converters
|
||||
{
|
||||
[ValueConversion(typeof(DateTimeOffset?), typeof(DateTime?))]
|
||||
public class DateTimeOffsetToDateTimeConverter : IValueConverter
|
||||
{
|
||||
public static DateTimeOffsetToDateTimeConverter Instance { get; } = new DateTimeOffsetToDateTimeConverter();
|
||||
|
||||
public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is DateTimeOffset dateTimeOffsetValue)
|
||||
return dateTimeOffsetValue.DateTime;
|
||||
|
||||
return default(DateTime?);
|
||||
}
|
||||
|
||||
public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is DateTime dateTimeValue)
|
||||
return new DateTimeOffset(dateTimeValue);
|
||||
|
||||
return default(DateTimeOffset?);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
using DiscordChatExporter.Domain.Exporting;
|
||||
|
||||
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)
|
||||
{
|
||||
if (value is ExportFormat exportFormatValue)
|
||||
return exportFormatValue.GetDisplayName();
|
||||
|
||||
return default(string);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Converters
|
||||
{
|
||||
[ValueConversion(typeof(bool), typeof(bool))]
|
||||
public class InverseBoolConverter : IValueConverter
|
||||
{
|
||||
public static InverseBoolConverter Instance { get; } = new InverseBoolConverter();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
return !boolValue;
|
||||
|
||||
return default(bool);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
return !boolValue;
|
||||
|
||||
return default(bool);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AssemblyName>DiscordChatExporter</AssemblyName>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ApplicationIcon>../favicon.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="../favicon.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Gress" Version="1.2.0" />
|
||||
<PackageReference Include="MaterialDesignColors" Version="1.2.2" />
|
||||
<PackageReference Include="MaterialDesignThemes" Version="3.0.1" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.19" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="1.1.0" />
|
||||
<PackageReference Include="Onova" Version="2.6.0" />
|
||||
<PackageReference Include="Stylet" Version="1.3.1" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
<PackageReference Include="Tyrrrz.Settings" Version="1.3.4" />
|
||||
<PackageReference Include="PropertyChanged.Fody" Version="3.2.8" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Domain\DiscordChatExporter.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="Format XAML" AfterTargets="BeforeBuild">
|
||||
<Exec Command="dotnet tool restore" />
|
||||
<Exec Command="dotnet xstyler -r -d ." />
|
||||
</Target>
|
||||
|
||||
</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,64 @@
|
||||
<?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 rebuilt. -->
|
||||
<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:attribute name="SuppressWarnings" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings from this weaver.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="SuppressOnPropertyNameChangedWarning" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings about mismatched On_PropertyName_Changed methods.</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 (PEVerify) on the target assembly after all weavers have been executed.</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:attribute name="GenerateXsd" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Internal
|
||||
{
|
||||
internal static class ProcessEx
|
||||
{
|
||||
public static void StartShellExecute(string path)
|
||||
{
|
||||
var startInfo = new ProcessStartInfo(path)
|
||||
{
|
||||
UseShellExecute = true
|
||||
};
|
||||
|
||||
using (Process.Start(startInfo))
|
||||
{ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using DiscordChatExporter.Domain.Discord;
|
||||
using DiscordChatExporter.Domain.Exporting;
|
||||
using Tyrrrz.Settings;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Services
|
||||
{
|
||||
public class SettingsService : SettingsManager
|
||||
{
|
||||
public string DateFormat { get; set; } = "dd-MMM-yy hh:mm tt";
|
||||
|
||||
public bool IsAutoUpdateEnabled { get; set; } = true;
|
||||
|
||||
public bool IsTokenPersisted { get; set; } = true;
|
||||
|
||||
public int ParallelLimit { get; set; } = 1;
|
||||
|
||||
public AuthToken? LastToken { get; set; }
|
||||
|
||||
public ExportFormat LastExportFormat { get; set; } = ExportFormat.HtmlDark;
|
||||
|
||||
public int? LastPartitionLimit { get; set; }
|
||||
|
||||
public SettingsService()
|
||||
{
|
||||
Configuration.StorageSpace = StorageSpace.Instance;
|
||||
Configuration.SubDirectoryPath = "";
|
||||
Configuration.FileName = "Settings.dat";
|
||||
}
|
||||
|
||||
public bool ShouldSerializeLastToken() => IsTokenPersisted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Onova;
|
||||
using Onova.Exceptions;
|
||||
using Onova.Services;
|
||||
|
||||
namespace DiscordChatExporter.Gui.Services
|
||||
{
|
||||
public class UpdateService : IDisposable
|
||||
{
|
||||
private readonly IUpdateManager _updateManager = new UpdateManager(
|
||||
new GithubPackageResolver("Tyrrrz", "DiscordChatExporter", "DiscordChatExporter.zip"),
|
||||
new ZipPackageExtractor());
|
||||
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
private Version? _updateVersion;
|
||||
private bool _updatePrepared;
|
||||
private bool _updaterLaunched;
|
||||
|
||||
public UpdateService(SettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
|
||||
public async Task<Version?> CheckForUpdatesAsync()
|
||||
{
|
||||
if (!_settingsService.IsAutoUpdateEnabled)
|
||||
return null;
|
||||
|
||||
var check = await _updateManager.CheckForUpdatesAsync();
|
||||
return check.CanUpdate ? check.LastVersion : null;
|
||||
}
|
||||
|
||||
public async Task PrepareUpdateAsync(Version version)
|
||||
{
|
||||
if (!_settingsService.IsAutoUpdateEnabled)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
await _updateManager.PrepareUpdateAsync(_updateVersion = version);
|
||||
_updatePrepared = true;
|
||||
}
|
||||
catch (UpdaterAlreadyLaunchedException)
|
||||
{
|
||||
// Ignore race conditions
|
||||
}
|
||||
catch (LockFileNotAcquiredException)
|
||||
{
|
||||
// Ignore race conditions
|
||||
}
|
||||
}
|
||||
|
||||
public void FinalizeUpdate(bool needRestart)
|
||||
{
|
||||
if (!_settingsService.IsAutoUpdateEnabled)
|
||||
return;
|
||||
|
||||
if (_updateVersion == null || !_updatePrepared || _updaterLaunched)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
_updateManager.LaunchUpdater(_updateVersion, needRestart);
|
||||
_updaterLaunched = true;
|
||||
}
|
||||
catch (UpdaterAlreadyLaunchedException)
|
||||
{
|
||||
// Ignore race conditions
|
||||
}
|
||||
catch (LockFileNotAcquiredException)
|
||||
{
|
||||
// Ignore race conditions
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _updateManager.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Domain.Discord.Models;
|
||||
using DiscordChatExporter.Domain.Exporting;
|
||||
using DiscordChatExporter.Gui.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Dialogs
|
||||
{
|
||||
public class ExportSetupViewModel : DialogScreen
|
||||
{
|
||||
private readonly DialogManager _dialogManager;
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
public Guild? Guild { get; set; }
|
||||
|
||||
public IReadOnlyList<Channel>? Channels { get; set; }
|
||||
|
||||
public bool IsSingleChannel => Channels == null || Channels.Count == 1;
|
||||
|
||||
public string? OutputPath { get; set; }
|
||||
|
||||
public IReadOnlyList<ExportFormat> AvailableFormats =>
|
||||
Enum.GetValues(typeof(ExportFormat)).Cast<ExportFormat>().ToArray();
|
||||
|
||||
public ExportFormat SelectedFormat { get; set; }
|
||||
|
||||
public DateTimeOffset? After { get; set; }
|
||||
|
||||
public DateTimeOffset? Before { get; set; }
|
||||
|
||||
public int? PartitionLimit { get; set; }
|
||||
|
||||
public ExportSetupViewModel(DialogManager dialogManager, SettingsService settingsService)
|
||||
{
|
||||
_dialogManager = dialogManager;
|
||||
_settingsService = settingsService;
|
||||
|
||||
// Persist preferences
|
||||
SelectedFormat = _settingsService.LastExportFormat;
|
||||
PartitionLimit = _settingsService.LastPartitionLimit;
|
||||
}
|
||||
|
||||
public void Confirm()
|
||||
{
|
||||
// Persist preferences
|
||||
_settingsService.LastExportFormat = SelectedFormat;
|
||||
_settingsService.LastPartitionLimit = PartitionLimit;
|
||||
|
||||
// Clamp 'after' and 'before' values
|
||||
if (After > Before)
|
||||
After = Before;
|
||||
if (Before < After)
|
||||
Before = After;
|
||||
|
||||
// If single channel - prompt file path
|
||||
if (IsSingleChannel)
|
||||
{
|
||||
// Get single channel
|
||||
var channel = Channels.Single();
|
||||
|
||||
// Generate default file name
|
||||
var defaultFileName = ChannelExporter.GetDefaultExportFileName(Guild!, channel, SelectedFormat, After, Before);
|
||||
|
||||
// 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 (string.IsNullOrWhiteSpace(OutputPath))
|
||||
return;
|
||||
|
||||
// Close dialog
|
||||
Close(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using DiscordChatExporter.Gui.Services;
|
||||
using DiscordChatExporter.Gui.ViewModels.Framework;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Gui.ViewModels.Dialogs
|
||||
{
|
||||
public class SettingsViewModel : DialogScreen
|
||||
{
|
||||
private readonly SettingsService _settingsService;
|
||||
|
||||
public string DateFormat
|
||||
{
|
||||
get => _settingsService.DateFormat;
|
||||
set => _settingsService.DateFormat = value;
|
||||
}
|
||||
|
||||
public bool IsAutoUpdateEnabled
|
||||
{
|
||||
get => _settingsService.IsAutoUpdateEnabled;
|
||||
set => _settingsService.IsAutoUpdateEnabled = value;
|
||||
}
|
||||
|
||||
public bool IsTokenPersisted
|
||||
{
|
||||
get => _settingsService.IsTokenPersisted;
|
||||
set => _settingsService.IsTokenPersisted = value;
|
||||
}
|
||||
|
||||
public int ParallelLimit
|
||||
{
|
||||
get => _settingsService.ParallelLimit;
|
||||
set => _settingsService.ParallelLimit = value.Clamp(1, 10);
|
||||
}
|
||||
|
||||
public SettingsViewModel(SettingsService settingsService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user