mirror of
https://github.com/Tyrrrz/DiscordChatExporter.git
synced 2026-07-07 14:44:39 +02:00
Compare commits
234 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| de773467b6 | |||
| 92766b580b | |||
| abf7498667 | |||
| ae42554621 | |||
| b58e67776c | |||
| 7fc6e0cfe0 | |||
| 35264e8a12 | |||
| 2ab6773c17 | |||
| 650c55bbd1 | |||
| e1726683f8 | |||
| 70a1755c50 | |||
| 524b30b09b | |||
| d39fc212b6 | |||
| 95cd6cb50c | |||
| 79a9ac0462 | |||
| 5b5a53dbf4 | |||
| 2b0fa4213b | |||
| fd9d367bad | |||
| dbc3209160 | |||
| 3bcde0c534 | |||
| 903882e35b | |||
| 3c6d9d74a4 | |||
| 1e53f50ca3 | |||
| cba5a934df | |||
| cd05058cf7 | |||
| e9c3872701 | |||
| 88c4330a66 | |||
| 998bdaf2d4 | |||
| 24a80f915f | |||
| de57cd714d | |||
| f9ab269b29 | |||
| 33feaccee7 | |||
| 4fd6f8272e | |||
| b28f029382 | |||
| 29552be6e5 | |||
| 9491e18e2f | |||
| 4b1c9660be | |||
| 950625e671 | |||
| ce2dedff6b | |||
| baac419538 | |||
| bd40dbde48 | |||
| cbe4bc593c | |||
| cb32cee5f5 | |||
| 82f364a887 | |||
| 152e8c8dcb | |||
| 260139ab25 | |||
| 11e9c0f15c | |||
| ac809d1a3f | |||
| 36fa346299 | |||
| 8c3a5bd096 | |||
| 021682899a | |||
| 0ec6027a93 | |||
| eb49d0bd16 | |||
| e7c2564f6f | |||
| d1b70cf5f6 | |||
| b73d6a78a9 | |||
| b9f04bc4d9 | |||
| d01ed13041 | |||
| ed35a36eaa | |||
| 2ddfb46c31 | |||
| 3c5beeba79 | |||
| ed915443e6 | |||
| f8d55f406c | |||
| 15b605f5a7 | |||
| 511af1e35c | |||
| 2fea455c64 | |||
| c64133f717 | |||
| d18d2e0307 | |||
| 86633b858c | |||
| c390c64316 | |||
| af3a59ce0f | |||
| eb89ea5b40 | |||
| ad3655396f | |||
| 1b8af364d3 | |||
| 58464d8708 | |||
| 026927265a | |||
| 390735032e | |||
| 461d474498 | |||
| 017ed5ae6d | |||
| 6f90c367b9 | |||
| f866c16355 | |||
| 072d4c1fe6 | |||
| 6365e0a080 | |||
| 7b140fd450 | |||
| e237e00600 | |||
| 3aef7faa1e | |||
| ebe4d58a42 | |||
| bed0ade732 | |||
| 06e89538cb | |||
| 7903869f9f | |||
| 32443c5a5b | |||
| d477159907 | |||
| 93578abe24 | |||
| f22b048d32 | |||
| a8031ad3aa | |||
| e49cf997ea | |||
| 8b9afe45b9 | |||
| 77b7977324 | |||
| 915f4c8d9f | |||
| 0872d6d44b | |||
| 3aa90bb27b | |||
| 51acffc92e | |||
| 39a33538fe | |||
| 07ac805677 | |||
| 097a75e326 | |||
| 3d9ee3b339 | |||
| 4ff7990967 | |||
| 730fed075f | |||
| 600c354ab2 | |||
| d8dc12b3f7 | |||
| 33a6d49d76 | |||
| 3861dba60c | |||
| 69acb5bf76 | |||
| 0e67dcbf2e | |||
| 45d2be549d | |||
| 9394824943 | |||
| 43c50324d8 | |||
| a6353de2a7 | |||
| d020652f50 | |||
| 63803f98aa | |||
| 9dda9cfc27 | |||
| 61d0ddeced | |||
| 4c64977b71 | |||
| 8bc5b547ef | |||
| 286981d9f8 | |||
| 5a62ce6af9 | |||
| d72fe594b4 | |||
| 9df98b0405 | |||
| 0d2b9e8bc0 | |||
| 53cebd82eb | |||
| 37fcee2f21 | |||
| 047dccef7f | |||
| cb47902d10 | |||
| dca8b8ceb2 | |||
| a8e7c85b99 | |||
| edd51e0838 | |||
| 5e04accdff | |||
| 547bf0a463 | |||
| 948fab7c86 | |||
| 5038b8541e | |||
| 1da80956dd | |||
| 0763a99765 | |||
| eda5b21684 | |||
| 2c7b054c24 | |||
| 520e023aff | |||
| 949c9d3f1e | |||
| fa825fce47 | |||
| 09acfcff59 | |||
| ddb4856516 | |||
| c4007d4a80 | |||
| 2a432c0ed2 | |||
| c5eeb5f464 | |||
| a6bf546e79 | |||
| 239c47c06e | |||
| 19f678ca01 | |||
| 08442f21b7 | |||
| 921f348769 | |||
| a25e809671 | |||
| fa80c82468 | |||
| 91f4f02a35 | |||
| 6d2880ce26 | |||
| 355b8cb8cf | |||
| 82945ac3cf | |||
| 5009b90a3e | |||
| 1495ed9b90 | |||
| be66c74c08 | |||
| 6f54c09d96 | |||
| 45926b0990 | |||
| 25d29dc079 | |||
| efde9931c9 | |||
| 2c3b461d49 | |||
| b405052fd6 | |||
| da6d903f36 | |||
| e1b1755fba | |||
| 1ff026eba6 | |||
| 1fe4ecb3af | |||
| 47a1518cd9 | |||
| d78c10ebb7 | |||
| 3db29b520c | |||
| 752003abc3 | |||
| e26a0660d1 | |||
| 7dfc3b2723 | |||
| 06c33373de | |||
| 563f5cb67b | |||
| 1f20915b4d | |||
| e58c7aefff | |||
| ac5ccc3fa4 | |||
| 2fc0aa43e8 | |||
| ba66b52fa4 | |||
| ac64d9943a | |||
| 94a85cdb01 | |||
| 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 |
@@ -3,7 +3,7 @@
|
||||
"isRoot": true,
|
||||
"tools": {
|
||||
"xamlstyler.console": {
|
||||
"version": "3.2001.0",
|
||||
"version": "3.2003.9",
|
||||
"commands": [
|
||||
"xstyler"
|
||||
]
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
@@ -0,0 +1,64 @@
|
||||
name: 🐞 Bug report
|
||||
description: Report broken functionality.
|
||||
labels: [bug]
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
🧐 **Guidelines:**
|
||||
|
||||
- Search through [existing issues](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue) first to ensure that this bug has not been reported before.
|
||||
- Write a descriptive title for your issue. Avoid generic or vague titles such as "Something's not working" or "A couple of problems".
|
||||
- Keep your issue focused on one single problem. If you have multiple bug reports, please create separate issues for each of them.
|
||||
- Provide as much context as possible in the details section. Include screenshots, screen recordings, links, references, or anything else you may consider relevant.
|
||||
- If you want to ask a question instead of reporting a bug, please use [discussions](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) instead.
|
||||
|
||||
- type: input
|
||||
attributes:
|
||||
label: Version
|
||||
description: Which version of DiscordChatExporter does this bug affect?
|
||||
placeholder: ver X.Y.Z
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Flavor
|
||||
description: Does this bug affect the GUI version, the CLI version, or both?
|
||||
multiple: true
|
||||
options:
|
||||
- GUI (Graphical User Interface)
|
||||
- CLI (Command Line Interface)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Export format
|
||||
description: Does this bug affect specific export format(s)? If not applicable, leave this field blank.
|
||||
multiple: true
|
||||
options:
|
||||
- HTML
|
||||
- TXT
|
||||
- JSON
|
||||
- CSV
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Details
|
||||
description: Clear and thorough explanation of the bug.
|
||||
placeholder: I was doing X expecting Y to happen, but Z happened instead.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Minimum steps required to reproduce the bug.
|
||||
placeholder: |
|
||||
- Step 1
|
||||
- Step 2
|
||||
- Step 3
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: 📖 Wiki
|
||||
url: https://github.com/Tyrrrz/DiscordChatExporter/wiki
|
||||
about: Find usage guides and frequently asked questions.
|
||||
- name: 🗨 Discussions
|
||||
url: https://github.com/Tyrrrz/DiscordChatExporter/discussions/new
|
||||
about: Ask and answer questions.
|
||||
@@ -0,0 +1,42 @@
|
||||
name: ✨ Feature request
|
||||
description: Request a new feature.
|
||||
labels: [enhancement]
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
🧐 **Guidelines:**
|
||||
|
||||
- Search through [existing issues](https://github.com/Tyrrrz/DiscordChatExporter/issues?q=is%3Aissue) first to ensure that this feature has not been requested before.
|
||||
- Write a descriptive title for your issue. Avoid generic or vague titles such as "Some suggestions" or "Ideas for improvement".
|
||||
- Keep your issue focused on one single problem. If you have multiple feature requests, please create separate issues for each of them.
|
||||
- Provide as much context as possible in the details section. Include screenshots, screen recordings, links, references, or anything else you may consider relevant.
|
||||
- If you want to ask a question instead of requesting a feature, please use [discussions](https://github.com/Tyrrrz/DiscordChatExporter/discussions/new) instead.
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Flavor
|
||||
description: Is this feature request related to specific flavor(s) of DiscordChatExporter? If not applicable, leave this field blank.
|
||||
multiple: true
|
||||
options:
|
||||
- GUI (Graphical User Interface)
|
||||
- CLI (Command Line Interface)
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Export format
|
||||
description: Is this feature request related to specific export format(s)? If not applicable, leave this field blank.
|
||||
multiple: true
|
||||
options:
|
||||
- HTML
|
||||
- TXT
|
||||
- JSON
|
||||
- CSV
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Details
|
||||
description: Clear and thorough explanation of the feature you have in mind.
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,17 @@
|
||||
<!--
|
||||
|
||||
**Important:**
|
||||
|
||||
Please make sure that there is an existing issue that describes the problem solved by your pull request. If there isn't one, consider creating it first.
|
||||
An open issue offers a good place to iron out requirements, discuss possible solutions, and ask questions.
|
||||
|
||||
Remember to also:
|
||||
|
||||
- Keep your pull request focused and as small as possible. If you want to contribute multiple unrelated changes, please create separate pull requests for them.
|
||||
- Follow the coding style and conventions already established by the project. When in doubt about which style to use, ask in the comments to your pull request.
|
||||
- If you want to start a discussion regarding a specific change you've made, add a review comment to your own code. This can be used to highlight something important or to seek further input from others.
|
||||
|
||||
-->
|
||||
|
||||
<!-- Please specify the issue addressed by this pull request -->
|
||||
Closes #ISSUE_NUMBER
|
||||
+52
-47
@@ -3,64 +3,69 @@ name: CD
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
- "*"
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v1
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.3
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v1
|
||||
with:
|
||||
dotnet-version: 3.1.100
|
||||
- name: Install .NET (v3.1)
|
||||
uses: actions/setup-dotnet@v1.7.2
|
||||
with:
|
||||
dotnet-version: 3.1.x
|
||||
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||
- name: Install .NET (v5.0)
|
||||
uses: actions/setup-dotnet@v1.7.2
|
||||
with:
|
||||
dotnet-version: 5.0.x
|
||||
|
||||
- name: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/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: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Pack (GUI)
|
||||
run: Compress-Archive -Path DiscordChatExporter.Gui/bin/Publish/* -DestinationPath DiscordChatExporter.Gui/bin/Publish/Archive.zip -Force
|
||||
shell: pwsh
|
||||
- name: Pack (CLI)
|
||||
run: Compress-Archive -Path DiscordChatExporter.Cli/bin/Publish/* -DestinationPath DiscordChatExporter.Cli/bin/Publish/Archive.zip -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: actions/create-release@v1
|
||||
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: Pack (GUI)
|
||||
run: Compress-Archive -Path DiscordChatExporter.Gui/bin/Publish/* -DestinationPath DiscordChatExporter.Gui/bin/Publish/Archive.zip -Force
|
||||
shell: pwsh
|
||||
|
||||
- name: Upload release asset (CLI)
|
||||
uses: actions/upload-release-asset@v1.0.1
|
||||
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: 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 (GUI)
|
||||
uses: actions/upload-release-asset@v1.0.1
|
||||
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
|
||||
- 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
|
||||
|
||||
+25
-20
@@ -7,28 +7,33 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v1
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2.3.3
|
||||
|
||||
- name: Install .NET Core
|
||||
uses: actions/setup-dotnet@v1
|
||||
with:
|
||||
dotnet-version: 3.1.100
|
||||
- name: Install .NET (v3.1)
|
||||
uses: actions/setup-dotnet@v1.7.2
|
||||
with:
|
||||
dotnet-version: 3.1.x
|
||||
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||
- name: Install .NET (v5.0)
|
||||
uses: actions/setup-dotnet@v1.7.2
|
||||
with:
|
||||
dotnet-version: 5.0.x
|
||||
|
||||
- name: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
- name: Build & publish (CLI)
|
||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Upload build artifacts (CLI)
|
||||
uses: actions/upload-artifact@master
|
||||
with:
|
||||
name: DiscordChatExporter.CLI
|
||||
path: DiscordChatExporter.Cli/bin/Publish/
|
||||
- name: Build & publish (GUI)
|
||||
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
|
||||
|
||||
- name: Upload build artifact (GUI)
|
||||
uses: actions/upload-artifact@master
|
||||
with:
|
||||
name: DiscordChatExporter
|
||||
path: DiscordChatExporter.Gui/bin/Publish/
|
||||
- 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/
|
||||
|
||||
+7
-246
@@ -1,261 +1,22 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
|
||||
# User-specific files
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
.idea/
|
||||
.vs/
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Xx]64/
|
||||
[Xx]86/
|
||||
[Bb]uild/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
|
||||
# Visual Studio 2015 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# DNX
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_i.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# TODO: Comment the next line if you want to checkin your web deploy settings
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
#*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/packages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/packages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/packages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignoreable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
node_modules/
|
||||
orleans.codegen.cs
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# CodeRush
|
||||
.cr/
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
# Coverage
|
||||
*.opencover.xml
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 105 KiB After Width: | Height: | Size: 33 KiB |
+156
-9
@@ -1,8 +1,155 @@
|
||||
### v2.29 (19-Jul-2021)
|
||||
|
||||
- Added support for message filtering, which is accessible as an additional export parameter in the GUI and as the `--filter` option in the CLI. Message filters use a special syntax similar to Discord's search query syntax to allow specifying which messages should be included in the export. For example, you can limit the export to only include messages that contain image attachments (`has:image`) or messages from a certain user (`from:Tyrrrz`) or messages containing certain words (`hello world`), etc. You can also combine filters together (`hi mentions:Tyrrrz`, `from:Tyrrrz | from:96-LB`, `(mentions:Tyrrrz | from:Tyrrrz) has:image`) or negate them (`-has:link`). More thorough documentation coming soon. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- Added support for rendering mentions of voice channels, in addition to text channels.
|
||||
- Added support for rendering unix timestamp markers. Currently, style markers are ignored and timestamps are always rendered with the format configured in settings (or provided via `--date-format` option).
|
||||
- Updated in-app instructions for obtaining a user token. (Thanks [@Yudi](https://github.com/Yudi) and [@virtuallyvlad](https://github.com/virtuallyvlad))
|
||||
- [HTML] Improved visual appearance of the reference symbol (Г-shaped line in replies) to make it more closely resemble Discord's styling.
|
||||
- [HTML] Added more specific fallback text used when rendering referenced messages that contain no text content but have attachments or embeds.
|
||||
- [HTML] Fixed an issue where a broken embed author icon occupied visual space, ruining the embed layout. (Thanks [@Cliff J.](https://github.com/CliffJameston))
|
||||
- [GUI] Improved handling for fatal errors that may occur when attempting to export a channel. These errors are now displayed in a popup, allowing the user to try again instead of having the application crash completely.
|
||||
- [CLI] Fixed an issue where an attempt to export a channel resulted in `NotSupportedException` when the default encoding was set to `UTF8`.
|
||||
- [CLI] Fixed an issue where providing an incorrectly formatted partition limit via `-p|--partition` option resulted in a non-descriptive and unhelpful error.
|
||||
- Improved "Requested resource does not exist" error message by including the ID of the requested resource.
|
||||
|
||||
### v2.28 (19-Jun-2021)
|
||||
|
||||
- [HTML] Added special casing for YouTube video embeds to render them directly using an embedded player. (Thanks [@quentinmay](https://github.com/quentinmay))
|
||||
- [HTML] Added support for rendering standard emoji by code. Such emoji may sometimes be found in messages sent by bots or through webhooks. (Thanks [@CanePlayz](https://github.com/CanePlayz) and [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- [HTML] Changed tooltips on standard emoji to show emoji code instead of their raw string representations. (Thanks [@CanePlayz](https://github.com/CanePlayz) and [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- [HTML] Added tooltips on individual messages to show when those messages were sent.
|
||||
- [HTML] Updated colors and minor styling elements to match Discord's new style direction after rebranding.
|
||||
- [HTML] Updated Twemoji URLs to use SVG image variants for better rendering quality.
|
||||
- [HTML] Changed user avatar URLs to include predetermined size query parameter for better rendering quality.
|
||||
- Changed embed rendering logic to prefer Discord-proxied URLs for external content, in order to avoid unnecessary HTTP requests to third parties.
|
||||
- Fixed an issue where exporting with media sometimes resulted in a crash due to lack of permissions to change file attributes. These errors are now ignored, which means that the creation, write, and access dates of downloaded files may sometimes not match the dates provided by Discord's CDN.
|
||||
- [HTML] Fixed styling issues when rendering embed footers.
|
||||
- [HTML] Fixed an issue where links didn't render properly inside referenced messages.
|
||||
- [HTML] Fixed an issue where standalone emoji were incorrectly enlarged inside referenced messages.
|
||||
- [HTML] Fixed an issue where clicking on a referenced message revealed spoilers inside of it.
|
||||
- [GUI] Fixed an issue where the list of missing components, reported by the prerequisite check at application startup, included Windows updates that were not applicable to the user's system due to the fact that other superseding updates have already been installed. This issue only affected users running DiscordChatExporter on Windows 7.
|
||||
- [GUI] Fixed a few other minor issues related to the prerequisite installation window.
|
||||
|
||||
### v2.27.1 (08-Jun-2021)
|
||||
|
||||
- [GUI] Application will now detect if the required .NET Runtime or any of its prerequisites are missing and prompt the user to download and install them automatically. **Experimental feature, please test it out and report any issues you may find!**
|
||||
- [CLI] Fixed an issue where the application crashed when exporting a channel that had square brackets as part of its name or category name. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
|
||||
### v2.27 (24-Apr-2021)
|
||||
|
||||
- Added partitioning by file size. You can now use values such as `10mb` to indicate a size-based cut off point, in addition to values like `10` to indicate a number of messages. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- [CLI] Improved formatting and progress reporting.
|
||||
- [CLI] Changed `export` command so that it can accept multiple channel IDs passed to `-c|--channel` option. This makes it possible to export multiple channels at once while benefiting from parallelization.
|
||||
- [JSON] Added `color` field to message author. This is a hex string that represents user's color, inherited from their roles. (Thanks [@rtm516](https://github.com/rtm516))
|
||||
- [JSON] Added `categoryId` field to the root. This represents the ID of the category channel that the currently exported channel belongs to. (Thanks [@rtm516](https://github.com/rtm516))
|
||||
- [JSON] Fixed an issue where user discriminator was written without leading zeroes. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- [JSON] Fixed an issue where the application sometimes crashed with an error saying `']' invalid without a matching open`, which was just a validation message that masked the actual error behind the failure. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- Fixed an issue where progress was not reported correctly if the channel didn't have any messages in the specified time range.
|
||||
|
||||
### v2.26.1 (06-Feb-2021)
|
||||
|
||||
- [CLI] Added support for file name templates, which allow you to dynamically generate output file names based on channel and guild metadata. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- Fixed an issue where the application sometimes crashed with `Invalid snowflake` message when exporting chat logs that contained invalid or outdated mentions. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
|
||||
### v2.26 (29-Dec-2020)
|
||||
|
||||
- [HTML] Added support for replies. (Thanks [@Sanqui](https://github.com/Sanqui))
|
||||
- [HTML] Improved styling of non-media attachments (regular files, i.e. not video, audio, or image). (Thanks [@Lucas LaBuff](https://github.com/96-LB))
|
||||
- [HTML] Improved initial export performance.
|
||||
- [JSON] Relaxed escaping rules for unicode characters. (Thanks [@Sanqui](https://github.com/Sanqui))
|
||||
- [JSON] Added support for replies. (Thanks [@Sanqui](https://github.com/Sanqui))
|
||||
- [CLI] Added channel names to errors shown on failures when exporting multiple channels. (Thanks [@Sanqui](https://github.com/Sanqui))
|
||||
- [CLI] Added support for passing message IDs (snowflakes) to `--after` and `--before` options. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- Files downloaded by the "download referenced media" option now have their dates set according to the `Last-Modified` header provided by Discord CDN. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- Fixed an issue where the application sometimes crashed with `NullReferenceException` when retrying a failed HTTP request.
|
||||
- Migrated to Discord API v8.
|
||||
|
||||
### v2.25 (23-Nov-2020)
|
||||
|
||||
- [JSON] Added `mentions` property to the output. This contains users referenced inside the message text, but doesn't include mentions in embeds. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- [HTML] Added better previews for attached video and audio. They are now rendered using a browser native player element. The actual file path can still be retrieved by right clicking and selecting "Copy file path". (Thanks [@sas41](https://github.com/sas41))
|
||||
- [CLI] Fixed an issue where using `--media` option without providing a rooted path via `--output` option triggered an error.
|
||||
- [CLI] Fixed an issue where using `--reuse-media` option without also providing `--media` option was accepted, but didn't actually do anything. Now this produces an error instead. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
|
||||
### v2.24 (24-Oct-2020)
|
||||
|
||||
- [CLI] Updated to [CliFx v1.5](https://github.com/Tyrrrz/CliFx), which brings some UX improvements.
|
||||
- [GUI] Added dark mode, which can be enabled in settings. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- [GUI] Improved the UX in a few minor places.
|
||||
- [JSON] Added `embed.color` property to the output. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- Added additional date formats: `unix` to write dates as a unix timestamp and `unixms` for the milliseconds version. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- Added retry policy for downloading media content. This is mostly a workaround for transient failures that sometimes may occur when downloading assets referenced from embeds. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
- Added an option to reuse already downloaded media to avoid redundant network requests. It can be enabled in settings in GUI, or by passing `--reuse-media` in CLI. To facilitate this feature, the file name strategy has been changed as well -- now instead of relying on the original file name and adding `(n)` to the end in case of duplicates, a URL hash is injected in every file name. This also means that when the "reuse media" option is disabled, existing files inside the media directory may be overwritten. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
|
||||
|
||||
### v2.23 (14-Sep-2020)
|
||||
|
||||
- [CLI] Added a command to export all channels across all servers. Use `exportall` to do it. (Thanks [@wyattscarpenter](https://github.com/wyattscarpenter))
|
||||
- [HTML] Fixed an issue where Whitney fonts were not being loaded properly, causing the browser to fall back to Helvetica.
|
||||
- Fixed an issue where self-contained export crashed occasionally. This usually happened when the server hosting the file did not serve the stream properly. Such files are now ignored after the first failed attempt.
|
||||
|
||||
### v2.22 (12-Aug-2020)
|
||||
|
||||
- [GUI] Improved the channel list by adding collapsible category groups. (Thanks [@CarJem Generations](https://github.com/CarJem))
|
||||
- [GUI] Improved exporting options by adding a set of controls that can be used to limit the date range of the export down to minutes. Previously it was only possible to configure the date range without the time component. (Thanks [@CarJem Generations](https://github.com/CarJem))
|
||||
- [HTML] Fixed an issue where the export didn't reflect changes in nicknames between messages sent by bots. This affected chat logs that contained interactions with the Tupperbox bot. (Thanks [@CarJem Generations](https://github.com/CarJem))
|
||||
- [CLI] Fixed an issue where the application crashed if there were two environment variables defined that had the same name but in different case.
|
||||
|
||||
### v2.21.2 (30-Jul-2020)
|
||||
|
||||
- [GUI] When copy-pasting token, any surrounding spaces are now discarded, in addition to double quotes.
|
||||
- [HTML] Changed underlying templating engine to provide higher performance and better error messages. New templating engine adds a small cold start, but any export after the first should be faster.
|
||||
- Changed naming schema for downloaded media so that it follows `<original filename> (nn)` format rather than `<original filename>-salt`.
|
||||
- [HTML] Fixed an issue where downloaded media was sometimes inaccessible due to reserved characters appearing in the URL.
|
||||
- Fixed an issue where the application crashed when trying to download media with a file name that exceeds system's maximum allowed length.
|
||||
- Fixed an issue where the application crashed when trying to download media with illegal characters in the file name.
|
||||
|
||||
### v2.21.1 (19-Jul-2020)
|
||||
|
||||
- Fixed an issue where the export crashed if an embedded image has been deleted. Such media files are now ignored.
|
||||
- Changed the naming convention for downloaded media files so that the original file names are used when possible.
|
||||
|
||||
### v2.21 (18-Jul-2020)
|
||||
|
||||
- Added a new option that enables self-contained exports for all output formats. You can turn it on in the export setup dialog in GUI or using the `--media` option in CLI. When using this, the application will additionally download any media content directly referenced from the exported file instead of linking back to Discord CDN. The files which are downloaded include: guild icons, user avatars, attachments, embedded images, reaction emoji. Note that only files which are actually referenced by the export are downloaded, which means that, for example, user avatars will not be downloaded when using plain text export format. This option is not meant to enable complete offline viewing for HTML exports, but rather to make it easier to archive media content that may eventually get deleted from Discord servers. Also keep in mind that this option may make the export drastically slower and the total file size larger.
|
||||
- Changed "discordapp.com" to "discord.com" where applicable as Discord is migrating to a new domain. CDN will remain on "cdn.discordapp.com" for the foreseeable future.
|
||||
|
||||
Note that all existing and current HTML exports will likely not render accurately because Discord enabled CORS for their font resources, which prevents them from loading locally. Please refer to [issue #322](https://github.com/Tyrrrz/DiscordChatExporter/issues/322) for discussion on this topic.
|
||||
|
||||
### 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.
|
||||
- [HTML] Fixed an issue where some emoji 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)
|
||||
@@ -15,7 +162,7 @@
|
||||
- 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] Changed emoji parser to be less greedy. As a result it should match fewer character sequences that look like emoji but really aren't, but on the other hand it might miss some actual emoji. This means that some standard emoji (i.e. not custom server emoji) may not look like in Discord. This is a compromise I'm willing to take because detecting emoji 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.
|
||||
|
||||
@@ -56,8 +203,8 @@ Please note that CSV export is most likely not going to receive future updates a
|
||||
### 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.
|
||||
- [HTML] Fixed an issue where some of the emoji were rendered via Twemoji while Discord renders them as plain text.
|
||||
- [HTML] Fixed an issue where emoji weren't jumbo if there were more than one of them.
|
||||
|
||||
### v2.12 (11-Apr-2019)
|
||||
|
||||
@@ -79,15 +226,15 @@ Please note that CSV export is most likely not going to receive future updates a
|
||||
|
||||
### 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 multiple emoji 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] Added support for animated emoji.
|
||||
- [HTML] Standard emoji 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.
|
||||
@@ -147,7 +294,7 @@ Please note that CSV export is most likely not going to receive future updates a
|
||||
- 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 support for jumbo emoji (custom emoji 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.
|
||||
@@ -171,7 +318,7 @@ Please note that CSV export is most likely not going to receive future updates a
|
||||
|
||||
- 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 custom emoji.
|
||||
- Added support for user and role mentions.
|
||||
- Added support for channel mentions.
|
||||
- Fixed text in pre blocks not being wrapped correctly.
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||
<Version>2.17</Version>
|
||||
<Version>2.29</Version>
|
||||
<Company>Tyrrrz</Company>
|
||||
<Copyright>Copyright (c) Alexey Golub</Copyright>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<WarningsAsErrors>nullable</WarningsAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,148 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Exceptions;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Utils.Extensions;
|
||||
using DiscordChatExporter.Core.Discord;
|
||||
using DiscordChatExporter.Core.Discord.Data;
|
||||
using DiscordChatExporter.Core.Exceptions;
|
||||
using DiscordChatExporter.Core.Exporting;
|
||||
using DiscordChatExporter.Core.Exporting.Filtering;
|
||||
using DiscordChatExporter.Core.Exporting.Partitioning;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands.Base
|
||||
{
|
||||
public abstract class ExportCommandBase : TokenCommandBase
|
||||
{
|
||||
[CommandOption("output", 'o', Description = "Output file or directory path.")]
|
||||
public string OutputPath { get; init; } = Directory.GetCurrentDirectory();
|
||||
|
||||
[CommandOption("format", 'f', Description = "Export format.")]
|
||||
public ExportFormat ExportFormat { get; init; } = ExportFormat.HtmlDark;
|
||||
|
||||
[CommandOption("after", Description = "Only include messages sent after this date or message ID.")]
|
||||
public Snowflake? After { get; init; }
|
||||
|
||||
[CommandOption("before", Description = "Only include messages sent before this date or message ID.")]
|
||||
public Snowflake? Before { get; init; }
|
||||
|
||||
[CommandOption("partition", 'p', Description = "Split output into partitions, each limited to this number of messages (e.g. '100') or file size (e.g. '10mb').")]
|
||||
public PartitionLimit PartitionLimit { get; init; } = PartitionLimit.Null;
|
||||
|
||||
[CommandOption("filter", Description = "Only include messages that satisfy this filter (e.g. 'from:foo#1234' or 'has:image').")]
|
||||
public MessageFilter MessageFilter { get; init; } = MessageFilter.Null;
|
||||
|
||||
[CommandOption("parallel", Description = "Limits how many channels can be exported in parallel.")]
|
||||
public int ParallelLimit { get; init; } = 1;
|
||||
|
||||
[CommandOption("media", Description = "Download referenced media content.")]
|
||||
public bool ShouldDownloadMedia { get; init; }
|
||||
|
||||
[CommandOption("reuse-media", Description = "Reuse already existing media content to skip redundant downloads.")]
|
||||
public bool ShouldReuseMedia { get; init; }
|
||||
|
||||
[CommandOption("dateformat", Description = "Format used when writing dates.")]
|
||||
public string DateFormat { get; init; } = "dd-MMM-yy hh:mm tt";
|
||||
|
||||
private ChannelExporter? _channelExporter;
|
||||
protected ChannelExporter Exporter => _channelExporter ??= new ChannelExporter(Discord);
|
||||
|
||||
protected async ValueTask ExportAsync(IConsole console, IReadOnlyList<Channel> channels)
|
||||
{
|
||||
await console.Output.WriteLineAsync($"Exporting {channels.Count} channel(s)...");
|
||||
|
||||
var errors = new ConcurrentDictionary<Channel, string>();
|
||||
|
||||
// Wrap everything in a progress ticker
|
||||
await console.CreateProgressTicker().StartAsync(async progressContext =>
|
||||
{
|
||||
await channels.ParallelForEachAsync(async channel =>
|
||||
{
|
||||
// Export
|
||||
try
|
||||
{
|
||||
await progressContext.StartTaskAsync($"{channel.Category} / {channel.Name}", async progress =>
|
||||
{
|
||||
var guild = await Discord.GetGuildAsync(channel.GuildId);
|
||||
|
||||
var request = new ExportRequest(
|
||||
guild,
|
||||
channel,
|
||||
OutputPath,
|
||||
ExportFormat,
|
||||
After,
|
||||
Before,
|
||||
PartitionLimit,
|
||||
MessageFilter,
|
||||
ShouldDownloadMedia,
|
||||
ShouldReuseMedia,
|
||||
DateFormat
|
||||
);
|
||||
|
||||
await Exporter.ExportChannelAsync(request, progress);
|
||||
});
|
||||
}
|
||||
catch (DiscordChatExporterException ex) when (!ex.IsCritical)
|
||||
{
|
||||
errors[channel] = ex.Message;
|
||||
}
|
||||
}, ParallelLimit.ClampMin(1));
|
||||
});
|
||||
|
||||
// Print result
|
||||
using (console.WithForegroundColor(ConsoleColor.White))
|
||||
{
|
||||
await console.Output.WriteLineAsync(
|
||||
$"Successfully exported {channels.Count - errors.Count} channel(s)."
|
||||
);
|
||||
}
|
||||
|
||||
// Print errors
|
||||
if (errors.Any())
|
||||
{
|
||||
await console.Output.WriteLineAsync();
|
||||
|
||||
using (console.WithForegroundColor(ConsoleColor.Red))
|
||||
{
|
||||
await console.Output.WriteLineAsync(
|
||||
$"Failed to export {errors.Count} channel(s):"
|
||||
);
|
||||
}
|
||||
|
||||
foreach (var (channel, error) in errors)
|
||||
{
|
||||
await console.Output.WriteAsync($"{channel.Category} / {channel.Name}: ");
|
||||
|
||||
using (console.WithForegroundColor(ConsoleColor.Red))
|
||||
await console.Output.WriteLineAsync(error);
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
}
|
||||
|
||||
// Fail the command if ALL channels failed to export.
|
||||
// Having some of the channels fail to export is fine and expected.
|
||||
if (errors.Count >= channels.Count)
|
||||
{
|
||||
throw new CommandException("Export failed.");
|
||||
}
|
||||
}
|
||||
|
||||
public override ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
if (ShouldReuseMedia && !ShouldDownloadMedia)
|
||||
{
|
||||
throw new CommandException("Option --reuse-media cannot be used without --media.");
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Core.Discord;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands.Base
|
||||
{
|
||||
public abstract class TokenCommandBase : ICommand
|
||||
{
|
||||
[CommandOption("token", 't', IsRequired = true, EnvironmentVariable = "DISCORD_TOKEN", Description = "Authentication token.")]
|
||||
public string TokenValue { get; init; } = "";
|
||||
|
||||
[CommandOption("bot", 'b', EnvironmentVariable = "DISCORD_TOKEN_BOT", Description = "Authenticate as a bot.")]
|
||||
public bool IsBotToken { get; init; }
|
||||
|
||||
private AuthToken GetAuthToken() => new(
|
||||
IsBotToken
|
||||
? AuthTokenType.Bot
|
||||
: AuthTokenType.User,
|
||||
TokenValue
|
||||
);
|
||||
|
||||
private DiscordClient? _discordClient;
|
||||
protected DiscordClient Discord => _discordClient ??= new DiscordClient(GetAuthToken());
|
||||
|
||||
public abstract ValueTask ExecuteAsync(IConsole console);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord.Data;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("exportall", Description = "Export all accessible channels.")]
|
||||
public class ExportAllCommand : ExportCommandBase
|
||||
{
|
||||
[CommandOption("include-dm", Description = "Include direct message channels.")]
|
||||
public bool IncludeDirectMessages { get; init; } = true;
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
await base.ExecuteAsync(console);
|
||||
|
||||
// Get channel metadata
|
||||
await console.Output.WriteLineAsync("Fetching channels...");
|
||||
|
||||
var channels = new List<Channel>();
|
||||
|
||||
// Aggregate channels from all guilds
|
||||
await foreach (var guild in Discord.GetUserGuildsAsync())
|
||||
{
|
||||
// Skip DMs if instructed to
|
||||
if (!IncludeDirectMessages && guild.Id == Guild.DirectMessages.Id)
|
||||
continue;
|
||||
|
||||
await foreach (var channel in Discord.GetGuildChannelsAsync(guild.Id))
|
||||
{
|
||||
// Skip non-text channels
|
||||
if (!channel.IsTextChannel)
|
||||
continue;
|
||||
|
||||
channels.Add(channel);
|
||||
}
|
||||
}
|
||||
|
||||
// Export
|
||||
await ExportAsync(console, channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
|
||||
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 ExportChannelCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
|
||||
: base(settingsService, dataService, exportService)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console) => await ExportAsync(console, ChannelId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord;
|
||||
using DiscordChatExporter.Core.Discord.Data;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("export", Description = "Export one or multiple channels.")]
|
||||
public class ExportChannelsCommand : ExportCommandBase
|
||||
{
|
||||
// TODO: change this to plural (breaking change)
|
||||
[CommandOption("channel", 'c', IsRequired = true, Description = "Channel ID(s).")]
|
||||
public IReadOnlyList<Snowflake> ChannelIds { get; init; } = Array.Empty<Snowflake>();
|
||||
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
await base.ExecuteAsync(console);
|
||||
|
||||
// Get channel metadata
|
||||
await console.Output.WriteLineAsync("Fetching channel(s)...");
|
||||
|
||||
var channels = new List<Channel>();
|
||||
|
||||
foreach (var channelId in ChannelIds)
|
||||
{
|
||||
var channel = await Discord.GetChannelAsync(channelId);
|
||||
channels.Add(channel);
|
||||
}
|
||||
|
||||
// Export
|
||||
await ExportAsync(console, channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using CliFx.Utilities;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
public abstract class ExportCommandBase : TokenCommandBase
|
||||
{
|
||||
protected SettingsService SettingsService { get; }
|
||||
|
||||
protected ExportService ExportService { get; }
|
||||
|
||||
[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; }
|
||||
|
||||
[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; }
|
||||
|
||||
protected ExportCommandBase(SettingsService settingsService, DataService dataService, ExportService exportService)
|
||||
: base(dataService)
|
||||
{
|
||||
SettingsService = settingsService;
|
||||
ExportService = exportService;
|
||||
}
|
||||
|
||||
protected async Task ExportAsync(IConsole console, Guild guild, Channel channel)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(DateFormat))
|
||||
SettingsService.DateFormat = DateFormat;
|
||||
|
||||
console.Output.Write($"Exporting channel [{channel.Name}]... ");
|
||||
var progress = console.CreateProgressTicker();
|
||||
|
||||
var outputPath = OutputPath ?? Directory.GetCurrentDirectory();
|
||||
await ExportService.ExportChatLogAsync(GetToken(), guild, channel,
|
||||
outputPath, ExportFormat, PartitionLimit,
|
||||
After, Before, progress);
|
||||
|
||||
console.Output.WriteLine();
|
||||
}
|
||||
|
||||
protected async Task ExportAsync(IConsole console, Channel channel)
|
||||
{
|
||||
var guild = await DataService.GetGuildAsync(GetToken(), channel.GuildId);
|
||||
await ExportAsync(console, guild, channel);
|
||||
}
|
||||
|
||||
protected async Task ExportAsync(IConsole console, string channelId)
|
||||
{
|
||||
var channel = await DataService.GetChannelAsync(GetToken(), channelId);
|
||||
await ExportAsync(console, channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,27 @@
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Models.Exceptions;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Core.Services.Exceptions;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord.Data;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("exportdm", Description = "Export all direct message channels.")]
|
||||
public class ExportDirectMessagesCommand : ExportCommandBase
|
||||
{
|
||||
public ExportDirectMessagesCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
|
||||
: base(settingsService, dataService, exportService)
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
}
|
||||
await base.ExecuteAsync(console);
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console)
|
||||
{
|
||||
// Get channels
|
||||
var channels = await DataService.GetDirectMessageChannelsAsync(GetToken());
|
||||
// Get channel metadata
|
||||
await console.Output.WriteLineAsync("Fetching channels...");
|
||||
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
||||
var textChannels = channels.Where(c => c.IsTextChannel).ToArray();
|
||||
|
||||
// Order channels
|
||||
channels = channels.OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Loop through channels
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ExportAsync(console, channel);
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
console.Error.WriteLine("You don't have access to this channel.");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
console.Error.WriteLine("This channel doesn't exist.");
|
||||
}
|
||||
catch (DomainException ex)
|
||||
{
|
||||
console.Error.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
// Export
|
||||
await ExportAsync(console, textChannels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Models.Exceptions;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using DiscordChatExporter.Core.Services.Exceptions;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
@@ -14,41 +12,19 @@ namespace DiscordChatExporter.Cli.Commands
|
||||
public class ExportGuildCommand : ExportCommandBase
|
||||
{
|
||||
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||
public string GuildId { get; set; }
|
||||
public Snowflake GuildId { get; init; }
|
||||
|
||||
public ExportGuildCommand(SettingsService settingsService, DataService dataService, ExportService exportService)
|
||||
: base(settingsService, dataService, exportService)
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
}
|
||||
await base.ExecuteAsync(console);
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console)
|
||||
{
|
||||
// Get channels
|
||||
var channels = await DataService.GetGuildChannelsAsync(GetToken(), GuildId);
|
||||
// Get channel metadata
|
||||
await console.Output.WriteLineAsync("Fetching channels...");
|
||||
var channels = await Discord.GetGuildChannelsAsync(GuildId);
|
||||
var textChannels = channels.Where(c => c.IsTextChannel).ToArray();
|
||||
|
||||
// Filter and order channels
|
||||
channels = channels.Where(c => c.Type.IsExportable()).OrderBy(c => c.Name).ToArray();
|
||||
|
||||
// Loop through channels
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ExportAsync(console, channel);
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.Forbidden)
|
||||
{
|
||||
console.Error.WriteLine("You don't have access to this channel.");
|
||||
}
|
||||
catch (HttpErrorStatusCodeException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
console.Error.WriteLine("This channel doesn't exist.");
|
||||
}
|
||||
catch (DomainException ex)
|
||||
{
|
||||
console.Error.WriteLine(ex.Message);
|
||||
}
|
||||
}
|
||||
// Export
|
||||
await ExportAsync(console, textChannels);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,45 @@
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("channels", Description = "Get the list of channels in specified guild.")]
|
||||
[Command("channels", Description = "Get the list of channels in a guild.")]
|
||||
public class GetChannelsCommand : TokenCommandBase
|
||||
{
|
||||
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||
public string GuildId { get; set; }
|
||||
public Snowflake GuildId { get; init; }
|
||||
|
||||
public GetChannelsCommand(DataService dataService)
|
||||
: base(dataService)
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
}
|
||||
var channels = await Discord.GetGuildChannelsAsync(GuildId);
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console)
|
||||
{
|
||||
// Get channels
|
||||
var channels = await DataService.GetGuildChannelsAsync(GetToken(), GuildId);
|
||||
var textChannels = channels
|
||||
.Where(c => c.IsTextChannel)
|
||||
.OrderBy(c => c.Category.Position)
|
||||
.ThenBy(c => c.Name)
|
||||
.ToArray();
|
||||
|
||||
// Filter and order channels
|
||||
channels = channels.Where(c => c.Type.IsExportable()).OrderBy(c => c.Name).ToArray();
|
||||
foreach (var channel in textChannels)
|
||||
{
|
||||
// Channel ID
|
||||
await console.Output.WriteAsync(channel.Id.ToString());
|
||||
|
||||
// Print result
|
||||
foreach (var channel in channels)
|
||||
console.Output.WriteLine($"{channel.Id} | {channel.Name}");
|
||||
// Separator
|
||||
using (console.WithForegroundColor(ConsoleColor.DarkGray))
|
||||
await console.Output.WriteAsync(" | ");
|
||||
|
||||
// Channel category / name
|
||||
using (console.WithForegroundColor(ConsoleColor.White))
|
||||
await console.Output.WriteAsync($"{channel.Category} / {channel.Name}");
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,42 @@
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Discord.Data;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("dm", Description = "Get the list of direct message channels.")]
|
||||
public class GetDirectMessageChannelsCommand : TokenCommandBase
|
||||
{
|
||||
public GetDirectMessageChannelsCommand(DataService dataService)
|
||||
: base(dataService)
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
}
|
||||
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console)
|
||||
{
|
||||
// Get channels
|
||||
var channels = await DataService.GetDirectMessageChannelsAsync(GetToken());
|
||||
var textChannels = channels
|
||||
.Where(c => c.IsTextChannel)
|
||||
.OrderBy(c => c.Category.Position)
|
||||
.ThenBy(c => c.Name)
|
||||
.ToArray();
|
||||
|
||||
// Order channels
|
||||
channels = channels.OrderBy(c => c.Name).ToArray();
|
||||
foreach (var channel in textChannels)
|
||||
{
|
||||
// Channel ID
|
||||
await console.Output.WriteAsync(channel.Id.ToString());
|
||||
|
||||
// Print result
|
||||
foreach (var channel in channels)
|
||||
console.Output.WriteLine($"{channel.Id} | {channel.Name}");
|
||||
// Separator
|
||||
using (console.WithForegroundColor(ConsoleColor.DarkGray))
|
||||
await console.Output.WriteAsync(" | ");
|
||||
|
||||
// Channel category / name
|
||||
using (console.WithForegroundColor(ConsoleColor.White))
|
||||
await console.Output.WriteAsync($"{channel.Category} / {channel.Name}");
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,35 @@
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using CliFx.Infrastructure;
|
||||
using DiscordChatExporter.Cli.Commands.Base;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("guilds", Description = "Get the list of accessible guilds.")]
|
||||
public class GetGuildsCommand : TokenCommandBase
|
||||
{
|
||||
public GetGuildsCommand(DataService dataService)
|
||||
: base(dataService)
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
}
|
||||
var guilds = await Discord.GetUserGuildsAsync();
|
||||
|
||||
public override async Task ExecuteAsync(IConsole console)
|
||||
{
|
||||
// Get guilds
|
||||
var guilds = await DataService.GetUserGuildsAsync(GetToken());
|
||||
foreach (var guild in guilds.OrderBy(g => g.Name))
|
||||
{
|
||||
// Guild ID
|
||||
await console.Output.WriteAsync(guild.Id.ToString());
|
||||
|
||||
// Order guilds
|
||||
guilds = guilds.OrderBy(g => g.Name).ToArray();
|
||||
// Separator
|
||||
using (console.WithForegroundColor(ConsoleColor.DarkGray))
|
||||
await console.Output.WriteAsync(" | ");
|
||||
|
||||
// Print result
|
||||
foreach (var guild in guilds)
|
||||
console.Output.WriteLine($"{guild.Id} | {guild.Name}");
|
||||
// Guild name
|
||||
using (console.WithForegroundColor(ConsoleColor.White))
|
||||
await console.Output.WriteAsync(guild.Name);
|
||||
|
||||
await console.Output.WriteLineAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,42 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using CliFx.Infrastructure;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
[Command("guide", Description = "Explains how to obtain token, guild or channel ID.")]
|
||||
public class GuideCommand : ICommand
|
||||
{
|
||||
public Task ExecuteAsync(IConsole console)
|
||||
public ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
console.WithForegroundColor(ConsoleColor.White, () => console.Output.WriteLine("To get user token:"));
|
||||
using (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(" 3. Press Ctrl+Shift+M to toggle device toolbar");
|
||||
console.Output.WriteLine(" 4. Navigate to the Application tab");
|
||||
console.Output.WriteLine(" 5. On the left, expand Local Storage and select https://discord.com");
|
||||
console.Output.WriteLine(" 6. Type \"token\" into the Filter box");
|
||||
console.Output.WriteLine(" 7. If the token key does not appear, press Ctrl+R to reload");
|
||||
console.Output.WriteLine(" 8. Copy the value of the token key");
|
||||
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:"));
|
||||
using (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:"));
|
||||
using (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");
|
||||
@@ -36,7 +44,9 @@ namespace DiscordChatExporter.Cli.Commands
|
||||
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:"));
|
||||
using (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");
|
||||
@@ -45,10 +55,13 @@ namespace DiscordChatExporter.Cli.Commands
|
||||
console.Output.WriteLine(" 6. Copy the first long sequence of numbers inside the URL");
|
||||
console.Output.WriteLine();
|
||||
|
||||
console.Output.WriteLine("If you still have unanswered questions, check out the wiki:");
|
||||
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
|
||||
using (console.WithForegroundColor(ConsoleColor.White))
|
||||
console.Output.WriteLine("For more information, check out the wiki:");
|
||||
|
||||
return Task.CompletedTask;
|
||||
using (console.WithForegroundColor(ConsoleColor.DarkCyan))
|
||||
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using CliFx.Attributes;
|
||||
using CliFx.Services;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Commands
|
||||
{
|
||||
public abstract class TokenCommandBase : ICommand
|
||||
{
|
||||
protected DataService DataService { get; }
|
||||
|
||||
[CommandOption("token", 't', IsRequired = true, Description = "Authorization token.")]
|
||||
public string TokenValue { get; set; }
|
||||
|
||||
[CommandOption("bot", 'b', Description = "Whether this authorization token belongs to a bot.")]
|
||||
public bool IsBotToken { get; set; }
|
||||
|
||||
protected TokenCommandBase(DataService dataService)
|
||||
{
|
||||
DataService = dataService;
|
||||
}
|
||||
|
||||
protected AuthToken GetToken() => new AuthToken(IsBotToken ? AuthTokenType.Bot : AuthTokenType.User, TokenValue);
|
||||
|
||||
public abstract Task ExecuteAsync(IConsole console);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
@@ -7,14 +6,14 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CliFx" Version="0.0.8" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" />
|
||||
<PackageReference Include="CliFx" Version="2.0.6" />
|
||||
<PackageReference Include="Spectre.Console" Version="0.41.0" />
|
||||
<PackageReference Include="Gress" Version="1.2.0" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Models\DiscordChatExporter.Core.Models.csproj" />
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Services\DiscordChatExporter.Core.Services.csproj" />
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core\DiscordChatExporter.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,44 +1,14 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx;
|
||||
using DiscordChatExporter.Cli.Commands;
|
||||
using DiscordChatExporter.Core.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace DiscordChatExporter.Cli
|
||||
{
|
||||
public static class Program
|
||||
{
|
||||
private static IServiceProvider ConfigureServices()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
// Register services
|
||||
services.AddSingleton<DataService>();
|
||||
services.AddSingleton<ExportService>();
|
||||
services.AddSingleton<SettingsService>();
|
||||
|
||||
// Register commands
|
||||
services.AddTransient<ExportChannelCommand>();
|
||||
services.AddTransient<ExportDirectMessagesCommand>();
|
||||
services.AddTransient<ExportGuildCommand>();
|
||||
services.AddTransient<GetChannelsCommand>();
|
||||
services.AddTransient<GetDirectMessageChannelsCommand>();
|
||||
services.AddTransient<GetGuildsCommand>();
|
||||
services.AddTransient<GuideCommand>();
|
||||
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
public static Task<int> Main(string[] args)
|
||||
{
|
||||
var serviceProvider = ConfigureServices();
|
||||
|
||||
return new CliApplicationBuilder()
|
||||
public static async Task<int> Main(string[] args) =>
|
||||
await new CliApplicationBuilder()
|
||||
.AddCommandsFromThisAssembly()
|
||||
.UseCommandFactory(schema => (ICommand) serviceProvider.GetService(schema.Type))
|
||||
.Build()
|
||||
.RunAsync(args);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using CliFx.Infrastructure;
|
||||
using Spectre.Console;
|
||||
|
||||
namespace DiscordChatExporter.Cli.Utils.Extensions
|
||||
{
|
||||
internal static class ConsoleExtensions
|
||||
{
|
||||
public static IAnsiConsole CreateAnsiConsole(this IConsole console) => AnsiConsole.Create(
|
||||
new AnsiConsoleSettings
|
||||
{
|
||||
Ansi = AnsiSupport.Detect,
|
||||
ColorSystem = ColorSystemSupport.Detect,
|
||||
Out = new AnsiConsoleOutput(console.Output)
|
||||
}
|
||||
);
|
||||
|
||||
public static Progress CreateProgressTicker(this IConsole console) => console
|
||||
.CreateAnsiConsole()
|
||||
.Progress()
|
||||
.AutoClear(false)
|
||||
.AutoRefresh(true)
|
||||
.HideCompleted(false)
|
||||
.Columns(
|
||||
new TaskDescriptionColumn {Alignment = Justify.Left},
|
||||
new ProgressBarColumn(),
|
||||
new PercentageColumn()
|
||||
);
|
||||
|
||||
public static async ValueTask StartTaskAsync(
|
||||
this ProgressContext progressContext,
|
||||
string description,
|
||||
Func<ProgressTask, ValueTask> performOperationAsync)
|
||||
{
|
||||
var progressTask = progressContext.AddTask(
|
||||
// Don't recognize random square brackets as style tags
|
||||
Markup.Escape(description),
|
||||
new ProgressTaskSettings {MaxValue = 1}
|
||||
);
|
||||
|
||||
try
|
||||
{
|
||||
await performOperationAsync(progressTask);
|
||||
}
|
||||
finally
|
||||
{
|
||||
progressTask.StopTask();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// ReSharper disable CheckNamespace
|
||||
// TODO: remove after moving to .NET 5
|
||||
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
internal static class IsExternalInit
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown.Ast
|
||||
{
|
||||
public class FormattedNode : Node
|
||||
{
|
||||
public TextFormatting Formatting { get; }
|
||||
|
||||
public IReadOnlyList<Node> Children { get; }
|
||||
|
||||
public FormattedNode(TextFormatting formatting, IReadOnlyList<Node> children)
|
||||
{
|
||||
Formatting = formatting;
|
||||
Children = children;
|
||||
}
|
||||
|
||||
public override string ToString() => $"<{Formatting}> ({Children.Count} direct children)";
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Markdown.Ast
|
||||
{
|
||||
public class MentionNode : Node
|
||||
{
|
||||
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}";
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Markdown.Ast
|
||||
{
|
||||
public enum MentionType
|
||||
{
|
||||
Meta,
|
||||
User,
|
||||
Channel,
|
||||
Role
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Markdown.Ast
|
||||
{
|
||||
public abstract class Node
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Markdown.Internal
|
||||
{
|
||||
internal interface IMatcher<T>
|
||||
{
|
||||
ParsedMatch<T>? Match(StringPart stringPart);
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using DiscordChatExporter.Core.Markdown.Ast;
|
||||
using DiscordChatExporter.Core.Markdown.Internal;
|
||||
|
||||
namespace DiscordChatExporter.Core.Markdown
|
||||
{
|
||||
// The following parsing logic is meant to replicate Discord's markdown grammar as close as possible
|
||||
public static 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<Node> BoldFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> ItalicFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> ItalicBoldFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> ItalicAltFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> UnderlineFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> ItalicUnderlineFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> StrikethroughFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> SpoilerFormattedNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> SingleLineQuoteNodeMatcher = new RegexMatcher<Node>(
|
||||
new Regex("^>\\s(.+)\r?\n?", DefaultRegexOptions),
|
||||
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1]))));
|
||||
|
||||
// Capture any character until the end of the input
|
||||
// Opening 'greater than' characters must be followed by whitespace
|
||||
private static readonly IMatcher<Node> MultiLineQuoteNodeMatcher = new RegexMatcher<Node>(
|
||||
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
|
||||
private static readonly IMatcher<Node> InlineCodeBlockNodeMatcher = new RegexMatcher<Node>(
|
||||
new Regex("`([^`]+)`", DefaultRegexOptions | RegexOptions.Singleline),
|
||||
m => new InlineCodeBlockNode(m.Groups[1].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<Node> MultiLineCodeBlockNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> EveryoneMentionNodeMatcher = new StringMatcher<Node>(
|
||||
"@everyone",
|
||||
p => new MentionNode("everyone", MentionType.Meta));
|
||||
|
||||
// Capture @here
|
||||
private static readonly IMatcher<Node> HereMentionNodeMatcher = new StringMatcher<Node>(
|
||||
"@here",
|
||||
p => new MentionNode("here", MentionType.Meta));
|
||||
|
||||
// Capture <@123456> or <@!123456>
|
||||
private static readonly IMatcher<Node> UserMentionNodeMatcher = new RegexMatcher<Node>(
|
||||
new Regex("<@!?(\\d+)>", DefaultRegexOptions),
|
||||
m => new MentionNode(m.Groups[1].Value, MentionType.User));
|
||||
|
||||
// Capture <#123456>
|
||||
private static readonly IMatcher<Node> ChannelMentionNodeMatcher = new RegexMatcher<Node>(
|
||||
new Regex("<#(\\d+)>", DefaultRegexOptions),
|
||||
m => new MentionNode(m.Groups[1].Value, MentionType.Channel));
|
||||
|
||||
// Capture <@&123456>
|
||||
private static readonly IMatcher<Node> RoleMentionNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> StandardEmojiNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> CustomEmojiNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> TitledLinkNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> AutoLinkNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> HiddenLinkNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> ShrugTextNodeMatcher = new StringMatcher<Node>(
|
||||
@"¯\_(ツ)_/¯",
|
||||
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<Node> IgnoredEmojiTextNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> EscapedSymbolTextNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> EscapedCharacterTextNodeMatcher = new RegexMatcher<Node>(
|
||||
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<Node> AggregateNodeMatcher = new AggregateMatcher<Node>(
|
||||
// Escaped text
|
||||
ShrugTextNodeMatcher,
|
||||
IgnoredEmojiTextNodeMatcher,
|
||||
EscapedSymbolTextNodeMatcher,
|
||||
EscapedCharacterTextNodeMatcher,
|
||||
|
||||
// Formatting
|
||||
ItalicBoldFormattedNodeMatcher,
|
||||
ItalicUnderlineFormattedNodeMatcher,
|
||||
BoldFormattedNodeMatcher,
|
||||
ItalicFormattedNodeMatcher,
|
||||
UnderlineFormattedNodeMatcher,
|
||||
ItalicAltFormattedNodeMatcher,
|
||||
StrikethroughFormattedNodeMatcher,
|
||||
SpoilerFormattedNodeMatcher,
|
||||
MultiLineQuoteNodeMatcher,
|
||||
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<Node> MinimalAggregateNodeMatcher = new AggregateMatcher<Node>(
|
||||
// Mentions
|
||||
EveryoneMentionNodeMatcher,
|
||||
HereMentionNodeMatcher,
|
||||
UserMentionNodeMatcher,
|
||||
ChannelMentionNodeMatcher,
|
||||
RoleMentionNodeMatcher,
|
||||
|
||||
// Emoji
|
||||
CustomEmojiNodeMatcher);
|
||||
|
||||
private static IReadOnlyList<Node> Parse(StringPart stringPart, IMatcher<Node> matcher) =>
|
||||
matcher.MatchAll(stringPart, p => new TextNode(p.ToString())).Select(r => r.Value).ToArray();
|
||||
|
||||
private static IReadOnlyList<Node> Parse(StringPart stringPart) => Parse(stringPart, AggregateNodeMatcher);
|
||||
|
||||
private static IReadOnlyList<Node> ParseMinimal(StringPart stringPart) => Parse(stringPart, MinimalAggregateNodeMatcher);
|
||||
|
||||
public static IReadOnlyList<Node> Parse(string input) => Parse(new StringPart(input));
|
||||
|
||||
public static IReadOnlyList<Node> ParseMinimal(string input) => ParseMinimal(new StringPart(input));
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#attachment-object
|
||||
|
||||
public partial class Attachment : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Url { get; }
|
||||
|
||||
public int? Width { get; }
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
public bool IsImage { get; }
|
||||
|
||||
public FileSize FileSize { get; }
|
||||
|
||||
public Attachment(string id, int? width, int? height, string url, string fileName, FileSize fileSize)
|
||||
{
|
||||
Id = id;
|
||||
Url = url;
|
||||
Width = width;
|
||||
Height = height;
|
||||
FileName = fileName;
|
||||
FileSize = fileSize;
|
||||
|
||||
IsImage = GetIsImage(fileName);
|
||||
}
|
||||
|
||||
public override string ToString() => FileName;
|
||||
}
|
||||
|
||||
public partial class Attachment
|
||||
{
|
||||
private static readonly string[] ImageFileExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
|
||||
|
||||
public static bool GetIsImage(string fileName)
|
||||
{
|
||||
var fileExtension = Path.GetExtension(fileName);
|
||||
return ImageFileExtensions.Contains(fileExtension, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
public class AuthToken
|
||||
{
|
||||
public AuthTokenType Type { get; }
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
public AuthToken(AuthTokenType type, string value)
|
||||
{
|
||||
Type = type;
|
||||
Value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#channel-object
|
||||
|
||||
public partial class Channel : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string? ParentId { get; }
|
||||
|
||||
public string GuildId { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string? Topic { get; }
|
||||
|
||||
public ChannelType Type { get; }
|
||||
|
||||
public Channel(string id, string? parentId, string guildId, string name, string? topic, ChannelType type)
|
||||
{
|
||||
Id = id;
|
||||
ParentId = parentId;
|
||||
GuildId = guildId;
|
||||
Name = name;
|
||||
Topic = topic;
|
||||
Type = type;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Channel
|
||||
{
|
||||
public static Channel CreateDeletedChannel(string id) =>
|
||||
new Channel(id, null, "unknown-guild", "deleted-channel", null, ChannelType.GuildTextChat);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,48 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object
|
||||
|
||||
public 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>";
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-author-structure
|
||||
|
||||
public 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>";
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-field-structure
|
||||
|
||||
public 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}";
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-footer-structure
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#embed-object-embed-image-structure
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/emoji#emoji-object
|
||||
|
||||
public partial class Emoji
|
||||
{
|
||||
public string? Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public bool IsAnimated { get; }
|
||||
|
||||
public string ImageUrl { get; }
|
||||
|
||||
public Emoji(string? id, string name, bool isAnimated)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IsAnimated = isAnimated;
|
||||
|
||||
ImageUrl = GetImageUrl(id, name, isAnimated);
|
||||
}
|
||||
}
|
||||
|
||||
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 unicode emoji
|
||||
var emojiRunes = GetRunes(name).ToArray();
|
||||
if (emojiRunes.Any())
|
||||
{
|
||||
// Get corresponding Twemoji image
|
||||
var twemojiName = GetTwemojiName(emojiRunes);
|
||||
return $"https://twemoji.maxcdn.com/2/72x72/{twemojiName}.png";
|
||||
}
|
||||
|
||||
// Fallback in case of failure
|
||||
return name;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models.Exceptions
|
||||
{
|
||||
public class DomainException : Exception
|
||||
{
|
||||
public DomainException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
public enum ExportFormat
|
||||
{
|
||||
PlainText,
|
||||
HtmlDark,
|
||||
HtmlLight,
|
||||
Csv
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
public static bool IsExportable(this ChannelType channelType) =>
|
||||
channelType == ChannelType.GuildTextChat ||
|
||||
channelType == ChannelType.DirectTextChat ||
|
||||
channelType == ChannelType.DirectGroupTextChat ||
|
||||
channelType == ChannelType.GuildNews ||
|
||||
channelType == ChannelType.GuildStore;
|
||||
|
||||
public static string GetFileExtension(this ExportFormat format) =>
|
||||
format switch
|
||||
{
|
||||
ExportFormat.PlainText => "txt",
|
||||
ExportFormat.HtmlDark => "html",
|
||||
ExportFormat.HtmlLight => "html",
|
||||
ExportFormat.Csv => "csv",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format))
|
||||
};
|
||||
|
||||
public static string GetDisplayName(this ExportFormat format) =>
|
||||
format switch
|
||||
{
|
||||
ExportFormat.PlainText => "Plain Text",
|
||||
ExportFormat.HtmlDark => "HTML (Dark)",
|
||||
ExportFormat.HtmlLight => "HTML (Light)",
|
||||
ExportFormat.Csv => "Comma Separated Values (CSV)",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format))
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// Loosely based on https://github.com/omar/ByteSize (MIT license)
|
||||
|
||||
public struct FileSize
|
||||
{
|
||||
public const long BytesInKiloByte = 1024;
|
||||
public const long BytesInMegaByte = 1024 * BytesInKiloByte;
|
||||
public const long BytesInGigaByte = 1024 * BytesInMegaByte;
|
||||
public const long BytesInTeraByte = 1024 * BytesInGigaByte;
|
||||
public const long BytesInPetaByte = 1024 * BytesInTeraByte;
|
||||
|
||||
public const string ByteSymbol = "B";
|
||||
public const string KiloByteSymbol = "KB";
|
||||
public const string MegaByteSymbol = "MB";
|
||||
public const string GigaByteSymbol = "GB";
|
||||
public const string TeraByteSymbol = "TB";
|
||||
public const string PetaByteSymbol = "PB";
|
||||
|
||||
public double Bytes { get; }
|
||||
public double KiloBytes => Bytes / BytesInKiloByte;
|
||||
public double MegaBytes => Bytes / BytesInMegaByte;
|
||||
public double GigaBytes => Bytes / BytesInGigaByte;
|
||||
public double TeraBytes => Bytes / BytesInTeraByte;
|
||||
public double PetaBytes => Bytes / BytesInPetaByte;
|
||||
|
||||
public string LargestWholeNumberSymbol
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Math.Abs(PetaBytes) >= 1)
|
||||
return PetaByteSymbol;
|
||||
|
||||
if (Math.Abs(TeraBytes) >= 1)
|
||||
return TeraByteSymbol;
|
||||
|
||||
if (Math.Abs(GigaBytes) >= 1)
|
||||
return GigaByteSymbol;
|
||||
|
||||
if (Math.Abs(MegaBytes) >= 1)
|
||||
return MegaByteSymbol;
|
||||
|
||||
if (Math.Abs(KiloBytes) >= 1)
|
||||
return KiloByteSymbol;
|
||||
|
||||
return ByteSymbol;
|
||||
}
|
||||
}
|
||||
|
||||
public double LargestWholeNumberValue
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Math.Abs(PetaBytes) >= 1)
|
||||
return PetaBytes;
|
||||
|
||||
if (Math.Abs(TeraBytes) >= 1)
|
||||
return TeraBytes;
|
||||
|
||||
if (Math.Abs(GigaBytes) >= 1)
|
||||
return GigaBytes;
|
||||
|
||||
if (Math.Abs(MegaBytes) >= 1)
|
||||
return MegaBytes;
|
||||
|
||||
if (Math.Abs(KiloBytes) >= 1)
|
||||
return KiloBytes;
|
||||
|
||||
return Bytes;
|
||||
}
|
||||
}
|
||||
|
||||
public FileSize(double bytes)
|
||||
{
|
||||
Bytes = bytes;
|
||||
}
|
||||
|
||||
public override string ToString() => $"{LargestWholeNumberValue:0.##} {LargestWholeNumberSymbol}";
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.string.IsNullOrWhiteSpace(com/developers/docs/resources/guild#guild-object
|
||||
|
||||
public partial class Guild : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string? IconHash { get; }
|
||||
|
||||
public string IconUrl { get; }
|
||||
|
||||
public Guild(string id, string name, string? iconHash)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
IconHash = iconHash;
|
||||
|
||||
IconUrl = GetIconUrl(id, iconHash);
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Guild
|
||||
{
|
||||
public static string GetIconUrl(string id, string? iconHash)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(iconHash)
|
||||
? $"https://cdn.discordapp.com/icons/{id}/{iconHash}.png"
|
||||
: "https://cdn.discordapp.com/embed/avatars/0.png";
|
||||
}
|
||||
|
||||
public static Guild DirectMessages { get; } = new Guild("@me", "Direct Messages", null);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
public interface IHasId
|
||||
{
|
||||
string Id { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#message-object
|
||||
|
||||
public class Message : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string ChannelId { 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, string channelId, 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;
|
||||
ChannelId = channelId;
|
||||
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 ?? "<message without content>";
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// Used for grouping contiguous messages in HTML export
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#message-object-message-types
|
||||
|
||||
public enum MessageType
|
||||
{
|
||||
Default,
|
||||
RecipientAdd,
|
||||
RecipientRemove,
|
||||
Call,
|
||||
ChannelNameChange,
|
||||
ChannelIconChange,
|
||||
ChannelPinnedMessage,
|
||||
GuildMemberJoin
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#reaction-object
|
||||
|
||||
public class Reaction
|
||||
{
|
||||
public int Count { get; }
|
||||
|
||||
public Emoji Emoji { get; }
|
||||
|
||||
public Reaction(int count, Emoji emoji)
|
||||
{
|
||||
Count = count;
|
||||
Emoji = emoji;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/topics/permissions#role-object
|
||||
|
||||
public partial class Role : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public Role(string id, string name)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Role
|
||||
{
|
||||
public static Role CreateDeletedRole(string id) => new Role(id, "deleted-role");
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
{
|
||||
// https://discordapp.com/developers/docs/topics/permissions#role-object
|
||||
|
||||
public partial class User : IHasId
|
||||
{
|
||||
public string Id { get; }
|
||||
|
||||
public int Discriminator { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public string FullName { get; }
|
||||
|
||||
public string? AvatarHash { get; }
|
||||
|
||||
public string AvatarUrl { get; }
|
||||
|
||||
public bool IsBot { get; }
|
||||
|
||||
public User(string id, int discriminator, string name, string? avatarHash, bool isBot)
|
||||
{
|
||||
Id = id;
|
||||
Discriminator = discriminator;
|
||||
Name = name;
|
||||
AvatarHash = avatarHash;
|
||||
IsBot = isBot;
|
||||
|
||||
FullName = GetFullName(name, discriminator);
|
||||
AvatarUrl = GetAvatarUrl(id, discriminator, avatarHash);
|
||||
}
|
||||
|
||||
public override string ToString() => FullName;
|
||||
}
|
||||
|
||||
public partial class User
|
||||
{
|
||||
public static string GetFullName(string name, int discriminator) => $"{name}#{discriminator:0000}";
|
||||
|
||||
public 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 CreateUnknownUser(string id) => new User(id, 0, "Unknown", null, false);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Resources\HtmlCore.css" />
|
||||
<EmbeddedResource Include="Resources\HtmlDark.css" />
|
||||
<EmbeddedResource Include="Resources\HtmlLight.css" />
|
||||
<EmbeddedResource Include="Resources\HtmlLayoutTemplate.html" />
|
||||
<EmbeddedResource Include="Resources\HtmlMessageGroupTemplate.html" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Scriban" Version="2.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Markdown\DiscordChatExporter.Core.Markdown.csproj" />
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Models\DiscordChatExporter.Core.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,25 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Rendering.Logic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Formatters
|
||||
{
|
||||
public class CsvMessageWriter : MessageWriterBase
|
||||
{
|
||||
public CsvMessageWriter(TextWriter writer, RenderContext context)
|
||||
: base(writer, context)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task WritePreambleAsync()
|
||||
{
|
||||
await Writer.WriteLineAsync(CsvRenderingLogic.FormatHeader(Context));
|
||||
}
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
await Writer.WriteLineAsync(CsvRenderingLogic.FormatMessage(Context, message));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Rendering.Logic;
|
||||
using Scriban;
|
||||
using Scriban.Runtime;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Formatters
|
||||
{
|
||||
public partial class HtmlMessageWriter : MessageWriterBase
|
||||
{
|
||||
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(TextWriter writer, RenderContext context, string themeName)
|
||||
: base(writer, context)
|
||||
{
|
||||
_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 => SharedRenderingLogic.FormatDate(d, Context.DateFormat)));
|
||||
|
||||
scriptObject.Import("FormatMarkdown",
|
||||
new Func<string, string>(m => HtmlRenderingLogic.FormatMarkdown(Context, m)));
|
||||
|
||||
// Push model
|
||||
templateContext.PushGlobal(scriptObject);
|
||||
|
||||
// Push output
|
||||
templateContext.PushOutput(new TextWriterOutput(Writer));
|
||||
|
||||
return templateContext;
|
||||
}
|
||||
|
||||
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() || HtmlRenderingLogic.CanBeGrouped(_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 partial class HtmlMessageWriter
|
||||
{
|
||||
private static readonly Assembly ResourcesAssembly = typeof(HtmlRenderingLogic).Assembly;
|
||||
private static readonly string ResourcesNamespace = $"{ResourcesAssembly.GetName().Name}.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% ~}}");
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Formatters
|
||||
{
|
||||
public abstract class MessageWriterBase : IAsyncDisposable
|
||||
{
|
||||
protected TextWriter Writer { get; }
|
||||
|
||||
protected RenderContext Context { get; }
|
||||
|
||||
protected MessageWriterBase(TextWriter writer, RenderContext context)
|
||||
{
|
||||
Writer = writer;
|
||||
Context = context;
|
||||
}
|
||||
|
||||
public virtual Task WritePreambleAsync() => Task.CompletedTask;
|
||||
|
||||
public abstract Task WriteMessageAsync(Message message);
|
||||
|
||||
public virtual Task WritePostambleAsync() => Task.CompletedTask;
|
||||
|
||||
public async ValueTask DisposeAsync() => await Writer.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Rendering.Logic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Formatters
|
||||
{
|
||||
public class PlainTextMessageWriter : MessageWriterBase
|
||||
{
|
||||
private long _messageCount;
|
||||
|
||||
public PlainTextMessageWriter(TextWriter writer, RenderContext context)
|
||||
: base(writer, context)
|
||||
{
|
||||
}
|
||||
|
||||
public override async Task WritePreambleAsync()
|
||||
{
|
||||
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatPreamble(Context));
|
||||
}
|
||||
|
||||
public override async Task WriteMessageAsync(Message message)
|
||||
{
|
||||
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatMessage(Context, message));
|
||||
await Writer.WriteLineAsync();
|
||||
|
||||
_messageCount++;
|
||||
}
|
||||
|
||||
public override async Task WritePostambleAsync()
|
||||
{
|
||||
await Writer.WriteLineAsync();
|
||||
await Writer.WriteLineAsync(PlainTextRenderingLogic.FormatPostamble(_messageCount));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System.Text;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Internal
|
||||
{
|
||||
internal static class Extensions
|
||||
{
|
||||
public static StringBuilder AppendLineIfNotEmpty(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
using static DiscordChatExporter.Core.Rendering.Logic.SharedRenderingLogic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Logic
|
||||
{
|
||||
public static class CsvRenderingLogic
|
||||
{
|
||||
// Header is always the same
|
||||
public static string FormatHeader(RenderContext context) => "AuthorID,Author,Date,Content,Attachments,Reactions";
|
||||
|
||||
private static string EncodeValue(string value)
|
||||
{
|
||||
value = value.Replace("\"", "\"\"");
|
||||
return $"\"{value}\"";
|
||||
}
|
||||
|
||||
public static string FormatMarkdown(RenderContext context, string markdown) =>
|
||||
PlainTextRenderingLogic.FormatMarkdown(context, markdown);
|
||||
|
||||
public static string FormatMessage(RenderContext context, Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.Append(EncodeValue(message.Author.Id)).Append(',')
|
||||
.Append(EncodeValue(message.Author.FullName)).Append(',')
|
||||
.Append(EncodeValue(FormatDate(message.Timestamp, context.DateFormat))).Append(',')
|
||||
.Append(EncodeValue(FormatMarkdown(context, message.Content ?? ""))).Append(',')
|
||||
.Append(EncodeValue(message.Attachments.Select(a => a.Url).JoinToString(","))).Append(',')
|
||||
.Append(EncodeValue(message.Reactions.Select(r => $"{r.Emoji.Name} ({r.Count})").JoinToString(",")));
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using DiscordChatExporter.Core.Markdown;
|
||||
using DiscordChatExporter.Core.Markdown.Ast;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Logic
|
||||
{
|
||||
internal static class HtmlRenderingLogic
|
||||
{
|
||||
public static bool CanBeGrouped(Message message1, Message message2)
|
||||
{
|
||||
if (message1.Author.Id != message2.Author.Id)
|
||||
return false;
|
||||
|
||||
if ((message2.Timestamp - message1.Timestamp).Duration().TotalMinutes > 7)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string HtmlEncode(string s) => WebUtility.HtmlEncode(s);
|
||||
|
||||
private static string FormatMarkdownNode(RenderContext context, Node node, bool isJumbo)
|
||||
{
|
||||
// Text node
|
||||
if (node is TextNode textNode)
|
||||
{
|
||||
// Return HTML-encoded text
|
||||
return HtmlEncode(textNode.Text);
|
||||
}
|
||||
|
||||
// Formatted node
|
||||
if (node is FormattedNode formattedNode)
|
||||
{
|
||||
// Recursively get inner html
|
||||
var innerHtml = FormatMarkdownNodes(context, formattedNode.Children, false);
|
||||
|
||||
// Bold
|
||||
if (formattedNode.Formatting == TextFormatting.Bold)
|
||||
return $"<strong>{innerHtml}</strong>";
|
||||
|
||||
// Italic
|
||||
if (formattedNode.Formatting == TextFormatting.Italic)
|
||||
return $"<em>{innerHtml}</em>";
|
||||
|
||||
// Underline
|
||||
if (formattedNode.Formatting == TextFormatting.Underline)
|
||||
return $"<u>{innerHtml}</u>";
|
||||
|
||||
// Strikethrough
|
||||
if (formattedNode.Formatting == TextFormatting.Strikethrough)
|
||||
return $"<s>{innerHtml}</s>";
|
||||
|
||||
// Spoiler
|
||||
if (formattedNode.Formatting == TextFormatting.Spoiler)
|
||||
return $"<span class=\"spoiler\">{innerHtml}</span>";
|
||||
|
||||
// Quote
|
||||
if (formattedNode.Formatting == TextFormatting.Quote)
|
||||
return $"<div class=\"quote\">{innerHtml}</div>";
|
||||
}
|
||||
|
||||
// Inline code block node
|
||||
if (node is InlineCodeBlockNode inlineCodeBlockNode)
|
||||
{
|
||||
return $"<span class=\"pre pre--inline\">{HtmlEncode(inlineCodeBlockNode.Code)}</span>";
|
||||
}
|
||||
|
||||
// Multi-line code block node
|
||||
if (node is MultiLineCodeBlockNode multilineCodeBlockNode)
|
||||
{
|
||||
// Set CSS class for syntax highlighting
|
||||
var highlightCssClass = !string.IsNullOrWhiteSpace(multilineCodeBlockNode.Language)
|
||||
? $"language-{multilineCodeBlockNode.Language}"
|
||||
: "nohighlight";
|
||||
|
||||
return $"<div class=\"pre pre--multiline {highlightCssClass}\">{HtmlEncode(multilineCodeBlockNode.Code)}</div>";
|
||||
}
|
||||
|
||||
// Mention node
|
||||
if (node is MentionNode mentionNode)
|
||||
{
|
||||
// Meta mention node
|
||||
if (mentionNode.Type == MentionType.Meta)
|
||||
{
|
||||
return $"<span class=\"mention\">@{HtmlEncode(mentionNode.Id)}</span>";
|
||||
}
|
||||
|
||||
// User mention node
|
||||
if (mentionNode.Type == MentionType.User)
|
||||
{
|
||||
var user = context.MentionableUsers.FirstOrDefault(u => u.Id == mentionNode.Id) ??
|
||||
User.CreateUnknownUser(mentionNode.Id);
|
||||
|
||||
return $"<span class=\"mention\" title=\"{HtmlEncode(user.FullName)}\">@{HtmlEncode(user.Name)}</span>";
|
||||
}
|
||||
|
||||
// Channel mention node
|
||||
if (mentionNode.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = context.MentionableChannels.FirstOrDefault(c => c.Id == mentionNode.Id) ??
|
||||
Channel.CreateDeletedChannel(mentionNode.Id);
|
||||
|
||||
return $"<span class=\"mention\">#{HtmlEncode(channel.Name)}</span>";
|
||||
}
|
||||
|
||||
// Role mention node
|
||||
if (mentionNode.Type == MentionType.Role)
|
||||
{
|
||||
var role = context.MentionableRoles.FirstOrDefault(r => r.Id == mentionNode.Id) ??
|
||||
Role.CreateDeletedRole(mentionNode.Id);
|
||||
|
||||
return $"<span class=\"mention\">@{HtmlEncode(role.Name)}</span>";
|
||||
}
|
||||
}
|
||||
|
||||
// Emoji node
|
||||
if (node is EmojiNode emojiNode)
|
||||
{
|
||||
// Get emoji image URL
|
||||
var emojiImageUrl = Emoji.GetImageUrl(emojiNode.Id, emojiNode.Name, emojiNode.IsAnimated);
|
||||
|
||||
// Make emoji large if it's jumbo
|
||||
var jumboableCssClass = isJumbo ? "emoji--large" : null;
|
||||
|
||||
return $"<img class=\"emoji {jumboableCssClass}\" alt=\"{emojiNode.Name}\" title=\"{emojiNode.Name}\" src=\"{emojiImageUrl}\" />";
|
||||
}
|
||||
|
||||
// Link node
|
||||
if (node is LinkNode linkNode)
|
||||
{
|
||||
// Extract message ID if the link points to a Discord message
|
||||
var linkedMessageId = Regex.Match(linkNode.Url, "^https?://discordapp.com/channels/.*?/(\\d+)/?$").Groups[1].Value;
|
||||
|
||||
return string.IsNullOrWhiteSpace(linkedMessageId)
|
||||
? $"<a href=\"{Uri.EscapeUriString(linkNode.Url)}\">{HtmlEncode(linkNode.Title)}</a>"
|
||||
: $"<a href=\"{Uri.EscapeUriString(linkNode.Url)}\" onclick=\"scrollToMessage(event, '{linkedMessageId}')\">{HtmlEncode(linkNode.Title)}</a>";
|
||||
}
|
||||
|
||||
// Throw on unexpected nodes
|
||||
throw new InvalidOperationException($"Unexpected node [{node.GetType()}].");
|
||||
}
|
||||
|
||||
private static string FormatMarkdownNodes(RenderContext context, IReadOnlyList<Node> nodes, bool isTopLevel)
|
||||
{
|
||||
// Emojis are jumbo if all top-level nodes are emoji nodes or whitespace text nodes
|
||||
var isJumbo = isTopLevel && nodes.All(n => n is EmojiNode || n is TextNode textNode && string.IsNullOrWhiteSpace(textNode.Text));
|
||||
|
||||
return nodes.Select(n => FormatMarkdownNode(context, n, isJumbo)).JoinToString("");
|
||||
}
|
||||
|
||||
public static string FormatMarkdown(RenderContext context, string markdown) =>
|
||||
FormatMarkdownNodes(context, MarkdownParser.Parse(markdown), true);
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Core.Markdown;
|
||||
using DiscordChatExporter.Core.Markdown.Ast;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Rendering.Internal;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
using static DiscordChatExporter.Core.Rendering.Logic.SharedRenderingLogic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Logic
|
||||
{
|
||||
public static class PlainTextRenderingLogic
|
||||
{
|
||||
public static string FormatPreamble(RenderContext context)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
buffer.AppendLine($"Guild: {context.Guild.Name}");
|
||||
buffer.AppendLine($"Channel: {context.Channel.Name}");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(context.Channel.Topic))
|
||||
buffer.AppendLine($"Topic: {context.Channel.Topic}");
|
||||
|
||||
if (context.After != null)
|
||||
buffer.AppendLine($"After: {FormatDate(context.After.Value, context.DateFormat)}");
|
||||
|
||||
if (context.Before != null)
|
||||
buffer.AppendLine($"Before: {FormatDate(context.Before.Value, context.DateFormat)}");
|
||||
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
public static string FormatPostamble(long messageCount)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
buffer.AppendLine($"Exported {messageCount:N0} message(s)");
|
||||
buffer.Append('=', 62).AppendLine();
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
private static string FormatMarkdownNode(RenderContext context, Node node)
|
||||
{
|
||||
// Text node
|
||||
if (node is TextNode textNode)
|
||||
{
|
||||
return textNode.Text;
|
||||
}
|
||||
|
||||
// Mention node
|
||||
if (node is MentionNode mentionNode)
|
||||
{
|
||||
// Meta mention node
|
||||
if (mentionNode.Type == MentionType.Meta)
|
||||
{
|
||||
return $"@{mentionNode.Id}";
|
||||
}
|
||||
|
||||
// User mention node
|
||||
if (mentionNode.Type == MentionType.User)
|
||||
{
|
||||
var user = context.MentionableUsers.FirstOrDefault(u => u.Id == mentionNode.Id) ??
|
||||
User.CreateUnknownUser(mentionNode.Id);
|
||||
|
||||
return $"@{user.Name}";
|
||||
}
|
||||
|
||||
// Channel mention node
|
||||
if (mentionNode.Type == MentionType.Channel)
|
||||
{
|
||||
var channel = context.MentionableChannels.FirstOrDefault(c => c.Id == mentionNode.Id) ??
|
||||
Channel.CreateDeletedChannel(mentionNode.Id);
|
||||
|
||||
return $"#{channel.Name}";
|
||||
}
|
||||
|
||||
// Role mention node
|
||||
if (mentionNode.Type == MentionType.Role)
|
||||
{
|
||||
var role = context.MentionableRoles.FirstOrDefault(r => r.Id == mentionNode.Id) ??
|
||||
Role.CreateDeletedRole(mentionNode.Id);
|
||||
|
||||
return $"@{role.Name}";
|
||||
}
|
||||
}
|
||||
|
||||
// Emoji node
|
||||
if (node is EmojiNode emojiNode)
|
||||
{
|
||||
return emojiNode.IsCustomEmoji ? $":{emojiNode.Name}:" : emojiNode.Name;
|
||||
}
|
||||
|
||||
// Throw on unexpected nodes
|
||||
throw new InvalidOperationException($"Unexpected node [{node.GetType()}].");
|
||||
}
|
||||
|
||||
public static string FormatMarkdown(RenderContext context, string markdown) =>
|
||||
MarkdownParser.ParseMinimal(markdown).Select(n => FormatMarkdownNode(context, n)).JoinToString("");
|
||||
|
||||
public static string FormatMessageHeader(RenderContext context, Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
// Timestamp & author
|
||||
buffer
|
||||
.Append($"[{FormatDate(message.Timestamp, context.DateFormat)}]")
|
||||
.Append(' ')
|
||||
.Append($"{message.Author.FullName}");
|
||||
|
||||
// Whether the message is pinned
|
||||
if (message.IsPinned)
|
||||
{
|
||||
buffer.Append(' ').Append("(pinned)");
|
||||
}
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
public static string FormatMessageContent(RenderContext context, Message message)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message.Content))
|
||||
return "";
|
||||
|
||||
return FormatMarkdown(context, message.Content);
|
||||
}
|
||||
|
||||
public static 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();
|
||||
}
|
||||
|
||||
public static string FormatEmbeds(RenderContext context, IReadOnlyList<Embed> embeds)
|
||||
{
|
||||
if (!embeds.Any())
|
||||
return "";
|
||||
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
foreach (var embed in embeds)
|
||||
{
|
||||
buffer.AppendLine("{Embed}");
|
||||
|
||||
// Author name
|
||||
if (!string.IsNullOrWhiteSpace(embed.Author?.Name))
|
||||
buffer.AppendLine(embed.Author.Name);
|
||||
|
||||
// URL
|
||||
if (!string.IsNullOrWhiteSpace(embed.Url))
|
||||
buffer.AppendLine(embed.Url);
|
||||
|
||||
// Title
|
||||
if (!string.IsNullOrWhiteSpace(embed.Title))
|
||||
buffer.AppendLine(FormatMarkdown(context, embed.Title));
|
||||
|
||||
// Description
|
||||
if (!string.IsNullOrWhiteSpace(embed.Description))
|
||||
buffer.AppendLine(FormatMarkdown(context, embed.Description));
|
||||
|
||||
// Fields
|
||||
foreach (var field in embed.Fields)
|
||||
{
|
||||
// Name
|
||||
if (!string.IsNullOrWhiteSpace(field.Name))
|
||||
buffer.AppendLine(field.Name);
|
||||
|
||||
// Value
|
||||
if (!string.IsNullOrWhiteSpace(field.Value))
|
||||
buffer.AppendLine(field.Value);
|
||||
}
|
||||
|
||||
// Thumbnail URL
|
||||
if (!string.IsNullOrWhiteSpace(embed.Thumbnail?.Url))
|
||||
buffer.AppendLine(embed.Thumbnail?.Url);
|
||||
|
||||
// Image URL
|
||||
if (!string.IsNullOrWhiteSpace(embed.Image?.Url))
|
||||
buffer.AppendLine(embed.Image?.Url);
|
||||
|
||||
// Footer text
|
||||
if (!string.IsNullOrWhiteSpace(embed.Footer?.Text))
|
||||
buffer.AppendLine(embed.Footer?.Text);
|
||||
|
||||
buffer.AppendLine();
|
||||
}
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
|
||||
public static 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();
|
||||
}
|
||||
|
||||
public static string FormatMessage(RenderContext context, Message message)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
buffer
|
||||
.AppendLine(FormatMessageHeader(context, message))
|
||||
.AppendLineIfNotEmpty(FormatMessageContent(context, message))
|
||||
.AppendLine()
|
||||
.AppendLineIfNotEmpty(FormatAttachments(message.Attachments))
|
||||
.AppendLineIfNotEmpty(FormatEmbeds(context, message.Embeds))
|
||||
.AppendLineIfNotEmpty(FormatReactions(message.Reactions));
|
||||
|
||||
return buffer.Trim().ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering.Logic
|
||||
{
|
||||
public static class SharedRenderingLogic
|
||||
{
|
||||
public static string FormatDate(DateTimeOffset date, string dateFormat) =>
|
||||
date.ToLocalTime().ToString(dateFormat, CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Rendering.Formatters;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering
|
||||
{
|
||||
public partial class MessageRenderer : IAsyncDisposable
|
||||
{
|
||||
private readonly RenderOptions _options;
|
||||
private readonly RenderContext _context;
|
||||
|
||||
private long _renderedMessageCount;
|
||||
private int _partitionIndex;
|
||||
private MessageWriterBase? _writer;
|
||||
|
||||
public MessageRenderer(RenderOptions options, RenderContext context)
|
||||
{
|
||||
_options = options;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
private async Task InitializeWriterAsync()
|
||||
{
|
||||
// Get partition file path
|
||||
var filePath = GetPartitionFilePath(_options.BaseFilePath, _partitionIndex);
|
||||
|
||||
// Create output directory
|
||||
var dirPath = Path.GetDirectoryName(_options.BaseFilePath);
|
||||
if (!string.IsNullOrWhiteSpace(dirPath))
|
||||
Directory.CreateDirectory(dirPath);
|
||||
|
||||
// Create writer
|
||||
_writer = CreateMessageWriter(filePath, _options.Format, _context);
|
||||
|
||||
// Write preamble
|
||||
await _writer.WritePreambleAsync();
|
||||
}
|
||||
|
||||
private async Task ResetWriterAsync()
|
||||
{
|
||||
if (_writer != null)
|
||||
{
|
||||
// Write postamble
|
||||
await _writer.WritePostambleAsync();
|
||||
|
||||
// Flush
|
||||
await _writer.DisposeAsync();
|
||||
_writer = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task RenderMessageAsync(Message message)
|
||||
{
|
||||
// Ensure underlying writer is initialized
|
||||
if (_writer == null)
|
||||
await InitializeWriterAsync();
|
||||
|
||||
// Render the actual message
|
||||
await _writer!.WriteMessageAsync(message);
|
||||
|
||||
// Increment count
|
||||
_renderedMessageCount++;
|
||||
|
||||
// Shift partition if necessary
|
||||
if (_options.PartitionLimit != null &&
|
||||
_options.PartitionLimit != 0 &&
|
||||
_renderedMessageCount % _options.PartitionLimit == 0)
|
||||
{
|
||||
await ResetWriterAsync();
|
||||
_partitionIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync() => await ResetWriterAsync();
|
||||
}
|
||||
|
||||
public partial class MessageRenderer
|
||||
{
|
||||
private static string GetPartitionFilePath(string baseFilePath, int partitionIndex)
|
||||
{
|
||||
// First partition - no changes
|
||||
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 MessageWriterBase CreateMessageWriter(string filePath, ExportFormat format, RenderContext context)
|
||||
{
|
||||
// Create inner writer (it will get disposed by the wrapper)
|
||||
var writer = File.CreateText(filePath);
|
||||
|
||||
// Create formatter
|
||||
if (format == ExportFormat.PlainText)
|
||||
return new PlainTextMessageWriter(writer, context);
|
||||
|
||||
if (format == ExportFormat.Csv)
|
||||
return new CsvMessageWriter(writer, context);
|
||||
|
||||
if (format == ExportFormat.HtmlDark)
|
||||
return new HtmlMessageWriter(writer, context, "Dark");
|
||||
|
||||
if (format == ExportFormat.HtmlLight)
|
||||
return new HtmlMessageWriter(writer, context, "Light");
|
||||
|
||||
throw new InvalidOperationException($"Unknown export format [{format}].");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering
|
||||
{
|
||||
public class RenderContext
|
||||
{
|
||||
public Guild Guild { get; }
|
||||
|
||||
public Channel Channel { get; }
|
||||
|
||||
public DateTimeOffset? After { get; }
|
||||
|
||||
public DateTimeOffset? Before { get; }
|
||||
|
||||
public string DateFormat { get; }
|
||||
|
||||
public IReadOnlyCollection<User> MentionableUsers { get; }
|
||||
|
||||
public IReadOnlyCollection<Channel> MentionableChannels { get; }
|
||||
|
||||
public IReadOnlyCollection<Role> MentionableRoles { get; }
|
||||
|
||||
public RenderContext(Guild guild, Channel channel, DateTimeOffset? after, DateTimeOffset? before, string dateFormat,
|
||||
IReadOnlyCollection<User> mentionableUsers, IReadOnlyCollection<Channel> mentionableChannels, IReadOnlyCollection<Role> mentionableRoles)
|
||||
{
|
||||
Guild = guild;
|
||||
Channel = channel;
|
||||
After = after;
|
||||
Before = before;
|
||||
DateFormat = dateFormat;
|
||||
MentionableUsers = mentionableUsers;
|
||||
MentionableChannels = mentionableChannels;
|
||||
MentionableRoles = mentionableRoles;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Rendering
|
||||
{
|
||||
public class RenderOptions
|
||||
{
|
||||
public string BaseFilePath { get; }
|
||||
|
||||
public ExportFormat Format { get; }
|
||||
|
||||
public int? PartitionLimit { get; }
|
||||
|
||||
public RenderOptions(string baseFilePath, ExportFormat format, int? partitionLimit)
|
||||
{
|
||||
BaseFilePath = baseFilePath;
|
||||
Format = format;
|
||||
PartitionLimit = partitionLimit;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,362 +0,0 @@
|
||||
/* 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 {
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.3;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.quote {
|
||||
margin: 0.5em 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 {
|
||||
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-thumbnail {
|
||||
margin-top: 0.3em;
|
||||
max-width: 50%;
|
||||
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;
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
/* General */
|
||||
|
||||
body {
|
||||
background-color: #36393e;
|
||||
color: #dcddde;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #0096cf;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.quote {
|
||||
border-color: #4f545c;
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #2f3136 !important;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
border-color: #282b30 !important;
|
||||
color: #b9bbbe !important;
|
||||
}
|
||||
|
||||
.mention {
|
||||
color: #7289da;
|
||||
}
|
||||
|
||||
/* === 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;
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
<!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);
|
||||
}
|
||||
}
|
||||
</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.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>
|
||||
@@ -1,121 +0,0 @@
|
||||
/* General */
|
||||
|
||||
body {
|
||||
background-color: #ffffff;
|
||||
color: #23262a;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #00b0f4;
|
||||
}
|
||||
|
||||
.spoiler {
|
||||
background-color: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.quote {
|
||||
border-color: #c7ccd1;
|
||||
}
|
||||
|
||||
.pre {
|
||||
background-color: #f9f9f9 !important;
|
||||
}
|
||||
|
||||
.pre--multiline {
|
||||
border-color: #f3f3f3 !important;
|
||||
color: #657b83 !important;
|
||||
}
|
||||
|
||||
.mention {
|
||||
background-color: #f1f3fb;
|
||||
color: #7289da;
|
||||
}
|
||||
|
||||
/* 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;
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
<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 ~}}
|
||||
<span class="chatlog__author-name" title="{{ MessageGroup.Author.FullName | html.escape }}" data-user-id="{{ MessageGroup.Author.Id | html.escape }}">{{ 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">
|
||||
<span class="markdown">{{ message.Content | FormatMarkdown }}</span>
|
||||
|
||||
{{~ # Edited timestamp ~}}
|
||||
{{~ if message.EditedTimestamp ~}}
|
||||
<span class="chatlog__edited-timestamp" title="{{ message.EditedTimestamp | FormatDate | html.escape }}">(edited)</span>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Attachments ~}}
|
||||
{{~ for attachment in message.Attachments ~}}
|
||||
<div class="chatlog__attachment">
|
||||
<a href="{{ attachment.Url }}">
|
||||
{{ # Image }}
|
||||
{{~ if attachment.IsImage ~}}
|
||||
<img class="chatlog__attachment-thumbnail" src="{{ attachment.Url }}" alt="Attachment" />
|
||||
{{~ # Non-image ~}}
|
||||
{{~ else ~}}
|
||||
Attachment: {{ attachment.FileName }} ({{ attachment.FileSize }})
|
||||
{{~ end ~}}
|
||||
</a>
|
||||
</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 }}"><span class="markdown">{{ embed.Title | FormatMarkdown }}</span></a>
|
||||
{{~ else ~}}
|
||||
<span class="markdown">{{ embed.Title | FormatMarkdown }}</span>
|
||||
{{~ end ~}}
|
||||
</div>
|
||||
{{~ end ~}}
|
||||
|
||||
{{~ # Description ~}}
|
||||
{{~ if embed.Description ~}}
|
||||
<div class="chatlog__embed-description"><span class="markdown">{{ embed.Description | FormatMarkdown }}</span></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"><span class="markdown">{{ field.Name | FormatMarkdown }}</span></div>
|
||||
{{~ end ~}}
|
||||
{{~ if field.Value ~}}
|
||||
<div class="chatlog__embed-field-value"><span class="markdown">{{ field.Value | FormatMarkdown }}</span></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>
|
||||
@@ -1,216 +0,0 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services.Internal;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public partial class DataService
|
||||
{
|
||||
private User ParseUser(JToken json)
|
||||
{
|
||||
var id = json["id"]!.Value<string>();
|
||||
var discriminator = json["discriminator"]!.Value<int>();
|
||||
var name = json["username"]!.Value<string>();
|
||||
var avatarHash = json["avatar"]!.Value<string>();
|
||||
var isBot = json["bot"]?.Value<bool>() ?? false;
|
||||
|
||||
return new User(id, discriminator, name, avatarHash, isBot);
|
||||
}
|
||||
|
||||
private Guild ParseGuild(JToken json)
|
||||
{
|
||||
var id = json["id"]!.Value<string>();
|
||||
var name = json["name"]!.Value<string>();
|
||||
var iconHash = json["icon"]!.Value<string>();
|
||||
|
||||
return new Guild(id, name, iconHash);
|
||||
}
|
||||
|
||||
private Channel ParseChannel(JToken json)
|
||||
{
|
||||
// Get basic data
|
||||
var id = json["id"]!.Value<string>();
|
||||
var parentId = json["parent_id"]?.Value<string>();
|
||||
var type = (ChannelType) json["type"]!.Value<int>();
|
||||
var topic = json["topic"]?.Value<string>();
|
||||
|
||||
// Try to extract guild ID
|
||||
var guildId = json["guild_id"]?.Value<string>();
|
||||
|
||||
// If the guild ID is blank, it's direct messages
|
||||
if (string.IsNullOrWhiteSpace(guildId))
|
||||
guildId = Guild.DirectMessages.Id;
|
||||
|
||||
// Try to extract name
|
||||
var name = json["name"]?.Value<string>();
|
||||
|
||||
// If the name is blank, it's direct messages
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
name = json["recipients"]?.Select(ParseUser).Select(u => u.Name).JoinToString(", ");
|
||||
|
||||
// If the name is still blank for some reason, fallback to ID
|
||||
// (blind fix to https://github.com/Tyrrrz/DiscordChatExporter/issues/227)
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
name = id;
|
||||
|
||||
return new Channel(id, parentId, guildId, name, topic, type);
|
||||
}
|
||||
|
||||
private Role ParseRole(JToken json)
|
||||
{
|
||||
var id = json["id"]!.Value<string>();
|
||||
var name = json["name"]!.Value<string>();
|
||||
|
||||
return new Role(id, name);
|
||||
}
|
||||
|
||||
private Attachment ParseAttachment(JToken json)
|
||||
{
|
||||
var id = json["id"]!.Value<string>();
|
||||
var url = json["url"]!.Value<string>();
|
||||
var width = json["width"]?.Value<int>();
|
||||
var height = json["height"]?.Value<int>();
|
||||
var fileName = json["filename"]!.Value<string>();
|
||||
var fileSizeBytes = json["size"]!.Value<long>();
|
||||
|
||||
var fileSize = new FileSize(fileSizeBytes);
|
||||
|
||||
return new Attachment(id, width, height, url, fileName, fileSize);
|
||||
}
|
||||
|
||||
private EmbedAuthor ParseEmbedAuthor(JToken json)
|
||||
{
|
||||
var name = json["name"]?.Value<string>();
|
||||
var url = json["url"]?.Value<string>();
|
||||
var iconUrl = json["icon_url"]?.Value<string>();
|
||||
|
||||
return new EmbedAuthor(name, url, iconUrl);
|
||||
}
|
||||
|
||||
private EmbedField ParseEmbedField(JToken json)
|
||||
{
|
||||
var name = json["name"]!.Value<string>();
|
||||
var value = json["value"]!.Value<string>();
|
||||
var isInline = json["inline"]?.Value<bool>() ?? false;
|
||||
|
||||
return new EmbedField(name, value, isInline);
|
||||
}
|
||||
|
||||
private EmbedImage ParseEmbedImage(JToken json)
|
||||
{
|
||||
var url = json["url"]?.Value<string>();
|
||||
var width = json["width"]?.Value<int>();
|
||||
var height = json["height"]?.Value<int>();
|
||||
|
||||
return new EmbedImage(url, width, height);
|
||||
}
|
||||
|
||||
private EmbedFooter ParseEmbedFooter(JToken json)
|
||||
{
|
||||
var text = json["text"]!.Value<string>();
|
||||
var iconUrl = json["icon_url"]?.Value<string>();
|
||||
|
||||
return new EmbedFooter(text, iconUrl);
|
||||
}
|
||||
|
||||
private Embed ParseEmbed(JToken json)
|
||||
{
|
||||
// Get basic data
|
||||
var title = json["title"]?.Value<string>();
|
||||
var description = json["description"]?.Value<string>();
|
||||
var url = json["url"]?.Value<string>();
|
||||
var timestamp = json["timestamp"]?.Value<DateTime>().ToDateTimeOffset();
|
||||
|
||||
// Get color
|
||||
var color = json["color"] != null
|
||||
? Color.FromArgb(json["color"]!.Value<int>()).ResetAlpha()
|
||||
: default(Color?);
|
||||
|
||||
// Get author
|
||||
var author = json["author"] != null ? ParseEmbedAuthor(json["author"]!) : null;
|
||||
|
||||
// Get fields
|
||||
var fields = (json["fields"] ?? Enumerable.Empty<JToken>()).Select(ParseEmbedField).ToArray();
|
||||
|
||||
// Get thumbnail
|
||||
var thumbnail = json["thumbnail"] != null ? ParseEmbedImage(json["thumbnail"]!) : null;
|
||||
|
||||
// Get image
|
||||
var image = json["image"] != null ? ParseEmbedImage(json["image"]!) : null;
|
||||
|
||||
// Get footer
|
||||
var footer = json["footer"] != null ? ParseEmbedFooter(json["footer"]!) : null;
|
||||
|
||||
return new Embed(title, url, timestamp, color, author, description, fields, thumbnail, image, footer);
|
||||
}
|
||||
|
||||
private Emoji ParseEmoji(JToken json)
|
||||
{
|
||||
var id = json["id"]?.Value<string>();
|
||||
var name = json["name"]!.Value<string>();
|
||||
var isAnimated = json["animated"]?.Value<bool>() ?? false;
|
||||
|
||||
return new Emoji(id, name, isAnimated);
|
||||
}
|
||||
|
||||
private Reaction ParseReaction(JToken json)
|
||||
{
|
||||
var count = json["count"]!.Value<int>();
|
||||
var emoji = ParseEmoji(json["emoji"]!);
|
||||
|
||||
return new Reaction(count, emoji);
|
||||
}
|
||||
|
||||
private Message ParseMessage(JToken json)
|
||||
{
|
||||
// Get basic data
|
||||
var id = json["id"]!.Value<string>();
|
||||
var channelId = json["channel_id"]!.Value<string>();
|
||||
var timestamp = json["timestamp"]!.Value<DateTime>().ToDateTimeOffset();
|
||||
var editedTimestamp = json["edited_timestamp"]?.Value<DateTime?>()?.ToDateTimeOffset();
|
||||
var content = json["content"]!.Value<string>();
|
||||
var type = (MessageType) json["type"]!.Value<int>();
|
||||
|
||||
// Workarounds for non-default types
|
||||
if (type == MessageType.RecipientAdd)
|
||||
content = "Added a recipient.";
|
||||
else if (type == MessageType.RecipientRemove)
|
||||
content = "Removed a recipient.";
|
||||
else if (type == MessageType.Call)
|
||||
content = "Started a call.";
|
||||
else if (type == MessageType.ChannelNameChange)
|
||||
content = "Changed the channel name.";
|
||||
else if (type == MessageType.ChannelIconChange)
|
||||
content = "Changed the channel icon.";
|
||||
else if (type == MessageType.ChannelPinnedMessage)
|
||||
content = "Pinned a message.";
|
||||
else if (type == MessageType.GuildMemberJoin)
|
||||
content = "Joined the server.";
|
||||
|
||||
// Get author
|
||||
var author = ParseUser(json["author"]!);
|
||||
|
||||
// Get attachments
|
||||
var attachments = (json["attachments"] ?? Enumerable.Empty<JToken>()).Select(ParseAttachment).ToArray();
|
||||
|
||||
// Get embeds
|
||||
var embeds = (json["embeds"] ?? Enumerable.Empty<JToken>()).Select(ParseEmbed).ToArray();
|
||||
|
||||
// Get reactions
|
||||
var reactions = (json["reactions"] ?? Enumerable.Empty<JToken>()).Select(ParseReaction).ToArray();
|
||||
|
||||
// Get mentions
|
||||
var mentionedUsers = (json["mentions"] ?? Enumerable.Empty<JToken>()).Select(ParseUser).ToArray();
|
||||
|
||||
// Get whether this message is pinned
|
||||
var isPinned = json["pinned"]!.Value<bool>();
|
||||
|
||||
return new Message(id, channelId, type, author, timestamp, editedTimestamp, isPinned, content, attachments, embeds,
|
||||
reactions, mentionedUsers);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Services.Exceptions;
|
||||
using DiscordChatExporter.Core.Services.Internal;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Polly;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public partial class DataService : IDisposable
|
||||
{
|
||||
private readonly HttpClient _httpClient = new HttpClient();
|
||||
private readonly IAsyncPolicy<HttpResponseMessage> _httpPolicy;
|
||||
|
||||
public DataService()
|
||||
{
|
||||
_httpClient.BaseAddress = new Uri("https://discordapp.com/api/v6");
|
||||
|
||||
// Discord seems to always respond 429 on our 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.
|
||||
_httpPolicy = 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);
|
||||
}
|
||||
|
||||
private async Task<JToken> GetApiResponseAsync(AuthToken token, string route)
|
||||
{
|
||||
using var response = await _httpPolicy.ExecuteAsync(async () =>
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, route);
|
||||
|
||||
request.Headers.Authorization = token.Type == AuthTokenType.Bot
|
||||
? new AuthenticationHeaderValue("Bot", token.Value)
|
||||
: new AuthenticationHeaderValue(token.Value);
|
||||
|
||||
return await _httpClient.SendAsync(request);
|
||||
});
|
||||
|
||||
// We throw our own exception here because default one doesn't have status code
|
||||
if (!response.IsSuccessStatusCode)
|
||||
throw new HttpErrorStatusCodeException(response.StatusCode, response.ReasonPhrase);
|
||||
|
||||
var jsonRaw = await response.Content.ReadAsStringAsync();
|
||||
return JToken.Parse(jsonRaw);
|
||||
}
|
||||
|
||||
public async Task<Guild> GetGuildAsync(AuthToken token, string guildId)
|
||||
{
|
||||
// Special case for direct messages pseudo-guild
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
return Guild.DirectMessages;
|
||||
|
||||
var response = await GetApiResponseAsync(token, $"guilds/{guildId}");
|
||||
var guild = ParseGuild(response);
|
||||
|
||||
return guild;
|
||||
}
|
||||
|
||||
public async Task<Channel> GetChannelAsync(AuthToken token, string channelId)
|
||||
{
|
||||
var response = await GetApiResponseAsync(token, $"channels/{channelId}");
|
||||
var channel = ParseChannel(response);
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Guild> GetUserGuildsAsync(AuthToken token)
|
||||
{
|
||||
var afterId = "";
|
||||
|
||||
while (true)
|
||||
{
|
||||
var route = "users/@me/guilds?limit=100";
|
||||
if (!string.IsNullOrWhiteSpace(afterId))
|
||||
route += $"&after={afterId}";
|
||||
|
||||
var response = await GetApiResponseAsync(token, route);
|
||||
|
||||
if (!response.HasValues)
|
||||
yield break;
|
||||
|
||||
foreach (var guild in response.Select(ParseGuild))
|
||||
{
|
||||
yield return guild;
|
||||
afterId = guild.Id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Channel>> GetDirectMessageChannelsAsync(AuthToken token)
|
||||
{
|
||||
var response = await GetApiResponseAsync(token, "users/@me/channels");
|
||||
var channels = response.Select(ParseChannel).ToArray();
|
||||
|
||||
return channels;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Channel>> GetGuildChannelsAsync(AuthToken token, string guildId)
|
||||
{
|
||||
// Special case for direct messages pseudo-guild
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
return Array.Empty<Channel>();
|
||||
|
||||
var response = await GetApiResponseAsync(token, $"guilds/{guildId}/channels");
|
||||
var channels = response.Select(ParseChannel).ToArray();
|
||||
|
||||
return channels;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Role>> GetGuildRolesAsync(AuthToken token, string guildId)
|
||||
{
|
||||
// Special case for direct messages pseudo-guild
|
||||
if (guildId == Guild.DirectMessages.Id)
|
||||
return Array.Empty<Role>();
|
||||
|
||||
var response = await GetApiResponseAsync(token, $"guilds/{guildId}/roles");
|
||||
var roles = response.Select(ParseRole).ToArray();
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
private async Task<Message> GetLastMessageAsync(AuthToken token, string channelId, DateTimeOffset? before = null)
|
||||
{
|
||||
var route = $"channels/{channelId}/messages?limit=1";
|
||||
if (before != null)
|
||||
route += $"&before={before.Value.ToSnowflake()}";
|
||||
|
||||
var response = await GetApiResponseAsync(token, route);
|
||||
|
||||
return response.Select(ParseMessage).FirstOrDefault();
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<Message> GetMessagesAsync(AuthToken token, string channelId,
|
||||
DateTimeOffset? after = null, DateTimeOffset? before = null, IProgress<double>? progress = null)
|
||||
{
|
||||
// Get the last message
|
||||
var lastMessage = await GetLastMessageAsync(token, channelId, before);
|
||||
|
||||
// If the last message doesn't exist or it's outside of range - return
|
||||
if (lastMessage == null || lastMessage.Timestamp < after)
|
||||
{
|
||||
progress?.Report(1);
|
||||
yield break;
|
||||
}
|
||||
|
||||
// Get other messages
|
||||
var firstMessage = default(Message);
|
||||
var afterId = after?.ToSnowflake() ?? "0";
|
||||
while (true)
|
||||
{
|
||||
// Get message batch
|
||||
var route = $"channels/{channelId}/messages?limit=100&after={afterId}";
|
||||
var response = await GetApiResponseAsync(token, route);
|
||||
|
||||
// Parse
|
||||
var messages = response
|
||||
.Select(ParseMessage)
|
||||
.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())
|
||||
break;
|
||||
|
||||
// Trim messages to range (until last message)
|
||||
var messagesInRange = messages
|
||||
.TakeWhile(m => m.Id != lastMessage.Id && m.Timestamp < lastMessage.Timestamp)
|
||||
.ToArray();
|
||||
|
||||
// Yield messages
|
||||
foreach (var message in messagesInRange)
|
||||
{
|
||||
// Set first message if it's not set
|
||||
firstMessage ??= message;
|
||||
|
||||
// Report progress (based on the time range of parsed messages compared to total)
|
||||
progress?.Report((message.Timestamp - firstMessage.Timestamp).TotalSeconds /
|
||||
(lastMessage.Timestamp - firstMessage.Timestamp).TotalSeconds);
|
||||
|
||||
yield return message;
|
||||
afterId = message.Id;
|
||||
}
|
||||
|
||||
// Break if messages were trimmed (which means the last message was encountered)
|
||||
if (messagesInRange.Length != messages.Length)
|
||||
break;
|
||||
}
|
||||
|
||||
// Yield last message
|
||||
yield return lastMessage;
|
||||
progress?.Report(1);
|
||||
}
|
||||
|
||||
public void Dispose() => _httpClient.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Import Project="../DiscordChatExporter.props" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
<PackageReference Include="Onova" Version="2.5.2" />
|
||||
<PackageReference Include="Polly" Version="7.2.0" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
<PackageReference Include="Tyrrrz.Settings" Version="1.3.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Models\DiscordChatExporter.Core.Models.csproj" />
|
||||
<ProjectReference Include="..\DiscordChatExporter.Core.Rendering\DiscordChatExporter.Core.Rendering.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,19 +0,0 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services.Exceptions
|
||||
{
|
||||
public class HttpErrorStatusCodeException : Exception
|
||||
{
|
||||
public HttpStatusCode StatusCode { get; }
|
||||
|
||||
public string ReasonPhrase { get; }
|
||||
|
||||
public HttpErrorStatusCodeException(HttpStatusCode statusCode, string reasonPhrase)
|
||||
: base($"Error HTTP status code: {statusCode} - {reasonPhrase}")
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
ReasonPhrase = reasonPhrase;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
using DiscordChatExporter.Core.Models.Exceptions;
|
||||
using DiscordChatExporter.Core.Rendering;
|
||||
using DiscordChatExporter.Core.Services.Logic;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public partial class ExportService
|
||||
{
|
||||
private readonly SettingsService _settingsService;
|
||||
private readonly DataService _dataService;
|
||||
|
||||
public ExportService(SettingsService settingsService, DataService dataService)
|
||||
{
|
||||
_settingsService = settingsService;
|
||||
_dataService = dataService;
|
||||
}
|
||||
|
||||
public async Task ExportChatLogAsync(AuthToken token, Guild guild, Channel channel,
|
||||
string outputPath, ExportFormat format, int? partitionLimit,
|
||||
DateTimeOffset? after = null, DateTimeOffset? before = null, IProgress<double>? progress = null)
|
||||
{
|
||||
// Get base file path from output path
|
||||
var baseFilePath = GetFilePathFromOutputPath(outputPath, format, guild, channel, after, before);
|
||||
|
||||
// Create options
|
||||
var options = new RenderOptions(baseFilePath, format, partitionLimit);
|
||||
|
||||
// Create context
|
||||
var mentionableUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
|
||||
var mentionableChannels = await _dataService.GetGuildChannelsAsync(token, guild.Id);
|
||||
var mentionableRoles = await _dataService.GetGuildRolesAsync(token, guild.Id);
|
||||
|
||||
var context = new RenderContext
|
||||
(
|
||||
guild, channel, after, before, _settingsService.DateFormat,
|
||||
mentionableUsers, mentionableChannels, mentionableRoles
|
||||
);
|
||||
|
||||
// Create renderer
|
||||
await using var renderer = new MessageRenderer(options, context);
|
||||
|
||||
// Render messages
|
||||
var renderedAnything = false;
|
||||
await foreach (var message in _dataService.GetMessagesAsync(token, channel.Id, after, before, progress))
|
||||
{
|
||||
// Add encountered users to the list of mentionable users
|
||||
mentionableUsers.Add(message.Author);
|
||||
mentionableUsers.AddRange(message.MentionedUsers);
|
||||
|
||||
// Render message
|
||||
await renderer.RenderMessageAsync(message);
|
||||
renderedAnything = true;
|
||||
}
|
||||
|
||||
// Throw if no messages were rendered
|
||||
if (!renderedAnything)
|
||||
throw new DomainException($"Channel [{channel.Name}] contains no messages for specified period");
|
||||
}
|
||||
}
|
||||
|
||||
public partial class ExportService
|
||||
{
|
||||
private static string GetFilePathFromOutputPath(string outputPath, ExportFormat format, Guild guild, Channel channel,
|
||||
DateTimeOffset? after, DateTimeOffset? before)
|
||||
{
|
||||
// Output is a directory
|
||||
if (Directory.Exists(outputPath) || string.IsNullOrWhiteSpace(Path.GetExtension(outputPath)))
|
||||
{
|
||||
var fileName = ExportLogic.GetDefaultExportFileName(format, guild, channel, after, before);
|
||||
return Path.Combine(outputPath, fileName);
|
||||
}
|
||||
|
||||
// Output is a file
|
||||
return outputPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services.Internal
|
||||
{
|
||||
internal static class Extensions
|
||||
{
|
||||
public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime) => new DateTimeOffset(dateTime);
|
||||
|
||||
public static string ToSnowflake(this DateTimeOffset dateTime)
|
||||
{
|
||||
var value = ((ulong) dateTime.ToUnixTimeMilliseconds() - 1420070400000UL) << 22;
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
public static Color ResetAlpha(this Color color) => Color.FromArgb(1, color);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using DiscordChatExporter.Core.Models;
|
||||
|
||||
namespace DiscordChatExporter.Core.Services.Logic
|
||||
{
|
||||
public static class ExportLogic
|
||||
{
|
||||
public static string GetDefaultExportFileName(ExportFormat format,
|
||||
Guild guild, Channel channel,
|
||||
DateTimeOffset? after = null, DateTimeOffset? before = null)
|
||||
{
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
// Append guild and channel names
|
||||
buffer.Append($"{guild.Name} - {channel.Name} [{channel.Id}]");
|
||||
|
||||
// Append 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(")");
|
||||
}
|
||||
|
||||
// Append extension
|
||||
buffer.Append($".{format.GetFileExtension()}");
|
||||
|
||||
// Replace invalid chars
|
||||
foreach (var invalidChar in Path.GetInvalidFileNameChars())
|
||||
buffer.Replace(invalidChar, '_');
|
||||
|
||||
return buffer.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord
|
||||
{
|
||||
public class AuthToken
|
||||
{
|
||||
public AuthTokenType Type { get; }
|
||||
|
||||
public string Value { get; }
|
||||
|
||||
public AuthToken(AuthTokenType type, string value)
|
||||
{
|
||||
Type = type;
|
||||
Value = value;
|
||||
}
|
||||
|
||||
public AuthenticationHeaderValue GetAuthenticationHeader() => Type switch
|
||||
{
|
||||
AuthTokenType.Bot => new AuthenticationHeaderValue("Bot", Value),
|
||||
_ => new AuthenticationHeaderValue(Value)
|
||||
};
|
||||
|
||||
public override string ToString() => Value;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
namespace DiscordChatExporter.Core.Discord
|
||||
{
|
||||
public enum AuthTokenType
|
||||
{
|
||||
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.com/developers/docs/resources/channel#attachment-object
|
||||
public partial class Attachment : IHasId
|
||||
{
|
||||
public Snowflake Id { get; }
|
||||
|
||||
public string Url { get; }
|
||||
|
||||
public string FileName { get; }
|
||||
|
||||
public string FileExtension => Path.GetExtension(FileName);
|
||||
|
||||
public int? Width { get; }
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public bool IsImage => ImageFileExtensions.Contains(FileExtension);
|
||||
|
||||
public bool IsVideo => VideoFileExtensions.Contains(FileExtension);
|
||||
|
||||
public bool IsAudio => AudioFileExtensions.Contains(FileExtension);
|
||||
|
||||
public bool IsSpoiler => FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
|
||||
|
||||
public FileSize FileSize { get; }
|
||||
|
||||
public Attachment(
|
||||
Snowflake 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 HashSet<string> ImageFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
|
||||
|
||||
private static readonly HashSet<string> VideoFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{".mp4", ".webm"};
|
||||
|
||||
private static readonly HashSet<string> AudioFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{".mp3", ".wav", ".ogg", ".flac", ".m4a"};
|
||||
|
||||
public static Attachment Parse(JsonElement json)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||
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,99 @@
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using JsonExtensions.Reading;
|
||||
using Tyrrrz.Extensions;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.com/developers/docs/resources/channel#channel-object
|
||||
public partial class Channel : IHasId
|
||||
{
|
||||
public Snowflake Id { get; }
|
||||
|
||||
public ChannelType Type { get; }
|
||||
|
||||
public bool IsTextChannel => Type is
|
||||
ChannelType.GuildTextChat or
|
||||
ChannelType.DirectTextChat or
|
||||
ChannelType.DirectGroupTextChat or
|
||||
ChannelType.GuildNews or
|
||||
ChannelType.GuildStore;
|
||||
|
||||
public bool IsVoiceChannel => !IsTextChannel;
|
||||
|
||||
public Snowflake GuildId { get; }
|
||||
|
||||
public ChannelCategory Category { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public int? Position { get; }
|
||||
|
||||
public string? Topic { get; }
|
||||
|
||||
public Channel(
|
||||
Snowflake id,
|
||||
ChannelType type,
|
||||
Snowflake guildId,
|
||||
ChannelCategory category,
|
||||
string name,
|
||||
int? position,
|
||||
string? topic)
|
||||
{
|
||||
Id = id;
|
||||
Type = type;
|
||||
GuildId = guildId;
|
||||
Category = category;
|
||||
Name = name;
|
||||
Position = position;
|
||||
Topic = topic;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class Channel
|
||||
{
|
||||
private static ChannelCategory GetFallbackCategory(ChannelType channelType) => new(
|
||||
Snowflake.Zero,
|
||||
channelType switch
|
||||
{
|
||||
ChannelType.GuildTextChat => "Text",
|
||||
ChannelType.DirectTextChat => "Private",
|
||||
ChannelType.DirectGroupTextChat => "Group",
|
||||
ChannelType.GuildNews => "News",
|
||||
ChannelType.GuildStore => "Store",
|
||||
_ => "Default"
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
public static Channel Parse(JsonElement json, ChannelCategory? category = null, int? position = null)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||
var guildId = json.GetPropertyOrNull("guild_id")?.GetString().Pipe(Snowflake.Parse);
|
||||
var topic = json.GetPropertyOrNull("topic")?.GetString();
|
||||
var type = (ChannelType) json.GetProperty("type").GetInt32();
|
||||
|
||||
var name =
|
||||
// Guild channel
|
||||
json.GetPropertyOrNull("name")?.GetString() ??
|
||||
// DM channel
|
||||
json.GetPropertyOrNull("recipients")?.EnumerateArray().Select(User.Parse).Select(u => u.Name).JoinToString(", ") ??
|
||||
// Fallback
|
||||
id.ToString();
|
||||
|
||||
return new Channel(
|
||||
id,
|
||||
type,
|
||||
guildId ?? Guild.DirectMessages.Id,
|
||||
category ?? GetFallbackCategory(type),
|
||||
name,
|
||||
position ?? json.GetPropertyOrNull("position")?.GetInt32(),
|
||||
topic
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
public partial class ChannelCategory : IHasId
|
||||
{
|
||||
public Snowflake Id { get; }
|
||||
|
||||
public string Name { get; }
|
||||
|
||||
public int? Position { get; }
|
||||
|
||||
public ChannelCategory(Snowflake id, string name, int? position)
|
||||
{
|
||||
Id = id;
|
||||
Name = name;
|
||||
Position = position;
|
||||
}
|
||||
|
||||
public override string ToString() => Name;
|
||||
}
|
||||
|
||||
public partial class ChannelCategory
|
||||
{
|
||||
public static ChannelCategory Parse(JsonElement json, int? position = null)
|
||||
{
|
||||
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||
|
||||
var name =
|
||||
json.GetPropertyOrNull("name")?.GetString() ??
|
||||
id.ToString();
|
||||
|
||||
return new ChannelCategory(
|
||||
id,
|
||||
name,
|
||||
position ?? json.GetPropertyOrNull("position")?.GetInt32()
|
||||
);
|
||||
}
|
||||
|
||||
public static ChannelCategory Empty { get; } = new(Snowflake.Zero, "<unknown category>", 0);
|
||||
}
|
||||
}
|
||||
+3
-4
@@ -1,11 +1,10 @@
|
||||
namespace DiscordChatExporter.Core.Models
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discordapp.com/developers/docs/resources/channel#channel-object-channel-types
|
||||
// https://discord.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,
|
||||
GuildTextChat = 0,
|
||||
DirectTextChat,
|
||||
GuildVoiceChat,
|
||||
DirectGroupTextChat,
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data.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 FileSize(long bytes) => TotalBytes = bytes;
|
||||
|
||||
private double GetLargestWholeNumberValue()
|
||||
{
|
||||
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(TotalGigaBytes) >= 1)
|
||||
return "GB";
|
||||
|
||||
if (Math.Abs(TotalMegaBytes) >= 1)
|
||||
return "MB";
|
||||
|
||||
if (Math.Abs(TotalKiloBytes) >= 1)
|
||||
return "KB";
|
||||
|
||||
return "bytes";
|
||||
}
|
||||
|
||||
public override string ToString() => $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}";
|
||||
}
|
||||
|
||||
public partial struct FileSize
|
||||
{
|
||||
public static FileSize FromBytes(long bytes) => new(bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace DiscordChatExporter.Core.Discord.Data.Common
|
||||
{
|
||||
public interface IHasId
|
||||
{
|
||||
Snowflake Id { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data.Common
|
||||
{
|
||||
public partial class IdBasedEqualityComparer : IEqualityComparer<IHasId>
|
||||
{
|
||||
public bool Equals(IHasId? x, IHasId? y) => x?.Id == y?.Id;
|
||||
|
||||
public int GetHashCode(IHasId obj) => obj.Id.GetHashCode();
|
||||
}
|
||||
|
||||
public partial class IdBasedEqualityComparer
|
||||
{
|
||||
public static IdBasedEqualityComparer Instance { get; } = new();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.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 YouTubeVideoEmbedProjection? TryGetYouTubeVideo() => YouTubeVideoEmbedProjection.TryResolve(this);
|
||||
|
||||
public override string ToString() => Title ?? "<untitled embed>";
|
||||
}
|
||||
|
||||
public partial class Embed
|
||||
{
|
||||
public static Embed Parse(JsonElement json)
|
||||
{
|
||||
var title = json.GetPropertyOrNull("title")?.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 description = json.GetPropertyOrNull("description")?.GetString();
|
||||
|
||||
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,40 @@
|
||||
using System.Text.Json;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.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 string? IconProxyUrl { get; }
|
||||
|
||||
public EmbedAuthor(string? name, string? url, string? iconUrl, string? iconProxyUrl)
|
||||
{
|
||||
Name = name;
|
||||
Url = url;
|
||||
IconUrl = iconUrl;
|
||||
IconProxyUrl = iconProxyUrl;
|
||||
}
|
||||
|
||||
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();
|
||||
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetString();
|
||||
|
||||
return new EmbedAuthor(name, url, iconUrl, iconProxyUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.Text.Json;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.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,36 @@
|
||||
using System.Text.Json;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure
|
||||
public partial class EmbedFooter
|
||||
{
|
||||
public string Text { get; }
|
||||
|
||||
public string? IconUrl { get; }
|
||||
|
||||
public string? IconProxyUrl { get; }
|
||||
|
||||
public EmbedFooter(string text, string? iconUrl, string? iconProxyUrl)
|
||||
{
|
||||
Text = text;
|
||||
IconUrl = iconUrl;
|
||||
IconProxyUrl = iconProxyUrl;
|
||||
}
|
||||
|
||||
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();
|
||||
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetString();
|
||||
|
||||
return new EmbedFooter(text, iconUrl, iconProxyUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Text.Json;
|
||||
using JsonExtensions.Reading;
|
||||
|
||||
namespace DiscordChatExporter.Core.Discord.Data
|
||||
{
|
||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
|
||||
public partial class EmbedImage
|
||||
{
|
||||
public string? Url { get; }
|
||||
|
||||
public string? ProxyUrl { get; }
|
||||
|
||||
public int? Width { get; }
|
||||
|
||||
public int? Height { get; }
|
||||
|
||||
public EmbedImage(string? url, string? proxyUrl, int? width, int? height)
|
||||
{
|
||||
Url = url;
|
||||
ProxyUrl = proxyUrl;
|
||||
Height = height;
|
||||
Width = width;
|
||||
}
|
||||
}
|
||||
|
||||
public partial class EmbedImage
|
||||
{
|
||||
public static EmbedImage Parse(JsonElement json)
|
||||
{
|
||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||
var proxyUrl = json.GetPropertyOrNull("proxy_url")?.GetString();
|
||||
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
||||
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
||||
|
||||
return new EmbedImage(url, proxyUrl, width, height);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user