mirror of
https://github.com/Tyrrrz/DiscordChatExporter.git
synced 2026-07-07 14:44:39 +02:00
Compare commits
127 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 |
@@ -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
|
||||||
@@ -13,10 +13,15 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2.3.3
|
uses: actions/checkout@v2.3.3
|
||||||
|
|
||||||
- name: Install .NET
|
- name: Install .NET (v3.1)
|
||||||
uses: actions/setup-dotnet@v1.7.2
|
uses: actions/setup-dotnet@v1.7.2
|
||||||
with:
|
with:
|
||||||
dotnet-version: 3.1.100
|
dotnet-version: 3.1.x
|
||||||
|
|
||||||
|
- name: Install .NET (v5.0)
|
||||||
|
uses: actions/setup-dotnet@v1.7.2
|
||||||
|
with:
|
||||||
|
dotnet-version: 5.0.x
|
||||||
|
|
||||||
- name: Build & publish (CLI)
|
- name: Build & publish (CLI)
|
||||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||||
|
|||||||
@@ -10,10 +10,15 @@ jobs:
|
|||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v2.3.3
|
uses: actions/checkout@v2.3.3
|
||||||
|
|
||||||
- name: Install .NET
|
- name: Install .NET (v3.1)
|
||||||
uses: actions/setup-dotnet@v1.7.2
|
uses: actions/setup-dotnet@v1.7.2
|
||||||
with:
|
with:
|
||||||
dotnet-version: 3.1.100
|
dotnet-version: 3.1.x
|
||||||
|
|
||||||
|
- name: Install .NET (v5.0)
|
||||||
|
uses: actions/setup-dotnet@v1.7.2
|
||||||
|
with:
|
||||||
|
dotnet-version: 5.0.x
|
||||||
|
|
||||||
- name: Build & publish (CLI)
|
- name: Build & publish (CLI)
|
||||||
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
|
||||||
|
|||||||
+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
|
# User-specific files
|
||||||
*.suo
|
*.suo
|
||||||
*.user
|
*.user
|
||||||
*.userosscache
|
*.userosscache
|
||||||
*.sln.docstates
|
*.sln.docstates
|
||||||
|
.idea/
|
||||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
.vs/
|
||||||
*.userprefs
|
|
||||||
|
|
||||||
# Build results
|
# Build results
|
||||||
[Dd]ebug/
|
[Dd]ebug/
|
||||||
[Dd]ebugPublic/
|
[Dd]ebugPublic/
|
||||||
[Rr]elease/
|
[Rr]elease/
|
||||||
[Rr]eleases/
|
[Rr]eleases/
|
||||||
x64/
|
[Xx]64/
|
||||||
x86/
|
[Xx]86/
|
||||||
|
[Bb]uild/
|
||||||
bld/
|
bld/
|
||||||
[Bb]in/
|
[Bb]in/
|
||||||
[Oo]bj/
|
[Oo]bj/
|
||||||
[Ll]og/
|
|
||||||
|
|
||||||
# Visual Studio 2015 cache/options directory
|
# Coverage
|
||||||
.vs/
|
*.opencover.xml
|
||||||
# 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
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 33 KiB |
+76
-10
@@ -1,3 +1,69 @@
|
|||||||
|
### 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)
|
### 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))
|
- [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))
|
||||||
@@ -44,7 +110,7 @@
|
|||||||
|
|
||||||
### v2.21 (18-Jul-2020)
|
### 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 emojis. 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.
|
- 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.
|
- 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.
|
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.
|
||||||
@@ -83,7 +149,7 @@ Note that all existing and current HTML exports will likely not render accuratel
|
|||||||
|
|
||||||
- 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.
|
- 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/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.
|
- [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)
|
### v2.16 (08-Dec-2019)
|
||||||
@@ -96,7 +162,7 @@ Note that all existing and current HTML exports will likely not render accuratel
|
|||||||
- Fixed various issues that resulted in exceptions during export process.
|
- 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/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 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.
|
- [HTML] Some other minor styling adjustments.
|
||||||
- [CSV] Replaced semicolons (;) with (,) as separators.
|
- [CSV] Replaced semicolons (;) with (,) as separators.
|
||||||
|
|
||||||
@@ -137,8 +203,8 @@ Please note that CSV export is most likely not going to receive future updates a
|
|||||||
### v2.12.1 (12-Apr-2019)
|
### v2.12.1 (12-Apr-2019)
|
||||||
|
|
||||||
- [GUI] Fixed an issue where the app crashed when trying to export multiple channels.
|
- [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 some of the emoji 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 emoji weren't jumbo if there were more than one of them.
|
||||||
|
|
||||||
### v2.12 (11-Apr-2019)
|
### v2.12 (11-Apr-2019)
|
||||||
|
|
||||||
@@ -160,15 +226,15 @@ Please note that CSV export is most likely not going to receive future updates a
|
|||||||
|
|
||||||
### v2.10.1 (06-Mar-2019)
|
### 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] 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.
|
- [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)
|
### v2.10 (03-Mar-2019)
|
||||||
|
|
||||||
- [HTML] Reworked the entire markdown parsing engine which fixes numerous rendering inconsistencies (over 15 issues fixed).
|
- [HTML] Reworked the entire markdown parsing engine which fixes numerous rendering inconsistencies (over 15 issues fixed).
|
||||||
- [HTML] Added support for animated emojis.
|
- [HTML] Added support for animated emoji.
|
||||||
- [HTML] Standard emojis are now rendered using Twemoji, the same image set that Discord uses.
|
- [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] Fixed an issue where video attachments would render incorrectly.
|
||||||
- [HTML] Minor fixes in styling.
|
- [HTML] Minor fixes in styling.
|
||||||
- [GUI] Aggregated export progress is now shown in the taskbar.
|
- [GUI] Aggregated export progress is now shown in the taskbar.
|
||||||
@@ -228,7 +294,7 @@ Please note that CSV export is most likely not going to receive future updates a
|
|||||||
- Added support for reactions (HTML only).
|
- Added support for reactions (HTML only).
|
||||||
- Selected date range is now shown in the export (HTML and PlainText).
|
- 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 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 basic retry policy for 429 error responses.
|
||||||
- Added validation for from/to dates in the UI which prevents choosing invalid date ranges.
|
- 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.
|
- Added an error message when trying to export a deleted channel.
|
||||||
@@ -252,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.
|
- Improved message date filtering, it's now marginally faster.
|
||||||
- Fixed underscores not recognized as italics in markdown.
|
- 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 user and role mentions.
|
||||||
- Added support for channel mentions.
|
- Added support for channel mentions.
|
||||||
- Fixed text in pre blocks not being wrapped correctly.
|
- Fixed text in pre blocks not being wrapped correctly.
|
||||||
|
|||||||
@@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>netcoreapp3.1</TargetFramework>
|
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||||
<Version>2.25</Version>
|
<Version>2.29</Version>
|
||||||
<Company>Tyrrrz</Company>
|
<Company>Tyrrrz</Company>
|
||||||
<Copyright>Copyright (c) Alexey Golub</Copyright>
|
<Copyright>Copyright (c) Alexey Golub</Copyright>
|
||||||
<LangVersion>latest</LangVersion>
|
<LangVersion>preview</LangVersion>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<WarningsAsErrors>nullable</WarningsAsErrors>
|
<WarningsAsErrors>nullable</WarningsAsErrors>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
@@ -1,94 +1,145 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
using CliFx.Exceptions;
|
using CliFx.Exceptions;
|
||||||
using CliFx.Utilities;
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Cli.Utils.Extensions;
|
||||||
using DiscordChatExporter.Domain.Exporting;
|
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
|
namespace DiscordChatExporter.Cli.Commands.Base
|
||||||
{
|
{
|
||||||
public abstract class ExportCommandBase : TokenCommandBase
|
public abstract class ExportCommandBase : TokenCommandBase
|
||||||
{
|
{
|
||||||
[CommandOption("output", 'o',
|
[CommandOption("output", 'o', Description = "Output file or directory path.")]
|
||||||
Description = "Output file or directory path.")]
|
public string OutputPath { get; init; } = Directory.GetCurrentDirectory();
|
||||||
public string OutputPath { get; set; } = Directory.GetCurrentDirectory();
|
|
||||||
|
|
||||||
[CommandOption("format", 'f',
|
[CommandOption("format", 'f', Description = "Export format.")]
|
||||||
Description = "Export format.")]
|
public ExportFormat ExportFormat { get; init; } = ExportFormat.HtmlDark;
|
||||||
public ExportFormat ExportFormat { get; set; } = ExportFormat.HtmlDark;
|
|
||||||
|
|
||||||
[CommandOption("after",
|
[CommandOption("after", Description = "Only include messages sent after this date or message ID.")]
|
||||||
Description = "Only include messages sent after this date.")]
|
public Snowflake? After { get; init; }
|
||||||
public DateTimeOffset? After { get; set; }
|
|
||||||
|
|
||||||
[CommandOption("before",
|
[CommandOption("before", Description = "Only include messages sent before this date or message ID.")]
|
||||||
Description = "Only include messages sent before this date.")]
|
public Snowflake? Before { get; init; }
|
||||||
public DateTimeOffset? Before { get; set; }
|
|
||||||
|
|
||||||
[CommandOption("partition", 'p',
|
[CommandOption("partition", 'p', Description = "Split output into partitions, each limited to this number of messages (e.g. '100') or file size (e.g. '10mb').")]
|
||||||
Description = "Split output into partitions limited to this number of messages.")]
|
public PartitionLimit PartitionLimit { get; init; } = PartitionLimit.Null;
|
||||||
public int? PartitionLimit { get; set; }
|
|
||||||
|
|
||||||
[CommandOption("media",
|
[CommandOption("filter", Description = "Only include messages that satisfy this filter (e.g. 'from:foo#1234' or 'has:image').")]
|
||||||
Description = "Download referenced media content.")]
|
public MessageFilter MessageFilter { get; init; } = MessageFilter.Null;
|
||||||
public bool ShouldDownloadMedia { get; set; }
|
|
||||||
|
|
||||||
[CommandOption("reuse-media",
|
[CommandOption("parallel", Description = "Limits how many channels can be exported in parallel.")]
|
||||||
Description = "Reuse already existing media content to skip redundant downloads.")]
|
public int ParallelLimit { get; init; } = 1;
|
||||||
public bool ShouldReuseMedia { get; set; }
|
|
||||||
|
|
||||||
[CommandOption("dateformat",
|
[CommandOption("media", Description = "Download referenced media content.")]
|
||||||
Description = "Format used when writing dates.")]
|
public bool ShouldDownloadMedia { get; init; }
|
||||||
public string DateFormat { get; set; } = "dd-MMM-yy hh:mm tt";
|
|
||||||
|
|
||||||
protected ChannelExporter GetChannelExporter() => new ChannelExporter(GetDiscordClient());
|
[CommandOption("reuse-media", Description = "Reuse already existing media content to skip redundant downloads.")]
|
||||||
|
public bool ShouldReuseMedia { get; init; }
|
||||||
|
|
||||||
protected async ValueTask ExportAsync(IConsole console, Guild guild, Channel channel)
|
[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)
|
||||||
{
|
{
|
||||||
console.Output.Write($"Exporting channel '{channel.Category} / {channel.Name}'... ");
|
await console.Output.WriteLineAsync($"Exporting {channels.Count} channel(s)...");
|
||||||
var progress = console.CreateProgressTicker();
|
|
||||||
|
|
||||||
var request = new ExportRequest(
|
var errors = new ConcurrentDictionary<Channel, string>();
|
||||||
guild,
|
|
||||||
channel,
|
|
||||||
OutputPath,
|
|
||||||
ExportFormat,
|
|
||||||
After,
|
|
||||||
Before,
|
|
||||||
PartitionLimit,
|
|
||||||
ShouldDownloadMedia,
|
|
||||||
ShouldReuseMedia,
|
|
||||||
DateFormat
|
|
||||||
);
|
|
||||||
|
|
||||||
await GetChannelExporter().ExportChannelAsync(request, progress);
|
// 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);
|
||||||
|
|
||||||
console.Output.WriteLine();
|
var request = new ExportRequest(
|
||||||
console.Output.WriteLine("Done.");
|
guild,
|
||||||
}
|
channel,
|
||||||
|
OutputPath,
|
||||||
|
ExportFormat,
|
||||||
|
After,
|
||||||
|
Before,
|
||||||
|
PartitionLimit,
|
||||||
|
MessageFilter,
|
||||||
|
ShouldDownloadMedia,
|
||||||
|
ShouldReuseMedia,
|
||||||
|
DateFormat
|
||||||
|
);
|
||||||
|
|
||||||
protected async ValueTask ExportAsync(IConsole console, Channel channel)
|
await Exporter.ExportChannelAsync(request, progress);
|
||||||
{
|
});
|
||||||
var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId);
|
}
|
||||||
await ExportAsync(console, guild, channel);
|
catch (DiscordChatExporterException ex) when (!ex.IsCritical)
|
||||||
}
|
{
|
||||||
|
errors[channel] = ex.Message;
|
||||||
|
}
|
||||||
|
}, ParallelLimit.ClampMin(1));
|
||||||
|
});
|
||||||
|
|
||||||
protected async ValueTask ExportAsync(IConsole console, string channelId)
|
// Print result
|
||||||
{
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
var channel = await GetDiscordClient().GetChannelAsync(channelId);
|
{
|
||||||
await ExportAsync(console, channel);
|
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)
|
public override ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
if (ShouldReuseMedia && !ShouldDownloadMedia)
|
if (ShouldReuseMedia && !ShouldDownloadMedia)
|
||||||
{
|
{
|
||||||
throw new CommandException(
|
throw new CommandException("Option --reuse-media cannot be used without --media.");
|
||||||
"The --reuse-media option cannot be used without the --media option."
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return default;
|
return default;
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
|
||||||
using CliFx.Utilities;
|
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
|
||||||
using DiscordChatExporter.Domain.Exceptions;
|
|
||||||
using DiscordChatExporter.Domain.Exporting;
|
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
|
||||||
using Gress;
|
|
||||||
using Tyrrrz.Extensions;
|
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands.Base
|
|
||||||
{
|
|
||||||
public abstract class ExportMultipleCommandBase : ExportCommandBase
|
|
||||||
{
|
|
||||||
[CommandOption("parallel",
|
|
||||||
Description = "Limits how many channels can be exported in parallel.")]
|
|
||||||
public int ParallelLimit { get; set; } = 1;
|
|
||||||
|
|
||||||
protected async ValueTask ExportMultipleAsync(IConsole console, IReadOnlyList<Channel> channels)
|
|
||||||
{
|
|
||||||
// This uses a different route from ExportCommandBase.ExportAsync() because it runs
|
|
||||||
// in parallel and needs another way to report progress to console.
|
|
||||||
|
|
||||||
console.Output.Write($"Exporting {channels.Count} channels... ");
|
|
||||||
var progress = console.CreateProgressTicker();
|
|
||||||
|
|
||||||
var operations = progress.Wrap().CreateOperations(channels.Count);
|
|
||||||
|
|
||||||
var successfulExportCount = 0;
|
|
||||||
var errors = new ConcurrentBag<string>();
|
|
||||||
|
|
||||||
await channels.Zip(operations).ParallelForEachAsync(async tuple =>
|
|
||||||
{
|
|
||||||
var (channel, operation) = tuple;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var guild = await GetDiscordClient().GetGuildAsync(channel.GuildId);
|
|
||||||
|
|
||||||
var request = new ExportRequest(
|
|
||||||
guild,
|
|
||||||
channel,
|
|
||||||
OutputPath,
|
|
||||||
ExportFormat,
|
|
||||||
After,
|
|
||||||
Before,
|
|
||||||
PartitionLimit,
|
|
||||||
ShouldDownloadMedia,
|
|
||||||
ShouldReuseMedia,
|
|
||||||
DateFormat
|
|
||||||
);
|
|
||||||
|
|
||||||
await GetChannelExporter().ExportChannelAsync(request, operation);
|
|
||||||
|
|
||||||
Interlocked.Increment(ref successfulExportCount);
|
|
||||||
}
|
|
||||||
catch (DiscordChatExporterException ex) when (!ex.IsCritical)
|
|
||||||
{
|
|
||||||
errors.Add(ex.Message);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
operation.Dispose();
|
|
||||||
}
|
|
||||||
}, ParallelLimit.ClampMin(1));
|
|
||||||
|
|
||||||
console.Output.WriteLine();
|
|
||||||
|
|
||||||
foreach (var error in errors)
|
|
||||||
console.Error.WriteLine(error);
|
|
||||||
|
|
||||||
console.Output.WriteLine($"Successfully exported {successfulExportCount} channel(s).");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +1,28 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
using CliFx;
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
using DiscordChatExporter.Domain.Discord;
|
using CliFx.Infrastructure;
|
||||||
|
using DiscordChatExporter.Core.Discord;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands.Base
|
namespace DiscordChatExporter.Cli.Commands.Base
|
||||||
{
|
{
|
||||||
public abstract class TokenCommandBase : ICommand
|
public abstract class TokenCommandBase : ICommand
|
||||||
{
|
{
|
||||||
[CommandOption("token", 't', IsRequired = true,
|
[CommandOption("token", 't', IsRequired = true, EnvironmentVariable = "DISCORD_TOKEN", Description = "Authentication token.")]
|
||||||
EnvironmentVariableName = "DISCORD_TOKEN",
|
public string TokenValue { get; init; } = "";
|
||||||
Description = "Authorization token.")]
|
|
||||||
public string TokenValue { get; set; } = "";
|
|
||||||
|
|
||||||
[CommandOption("bot", 'b',
|
[CommandOption("bot", 'b', EnvironmentVariable = "DISCORD_TOKEN_BOT", Description = "Authenticate as a bot.")]
|
||||||
EnvironmentVariableName = "DISCORD_TOKEN_BOT",
|
public bool IsBotToken { get; init; }
|
||||||
Description = "Authorize as a bot.")]
|
|
||||||
public bool IsBotToken { get; set; }
|
|
||||||
|
|
||||||
protected AuthToken GetAuthToken() => new AuthToken(
|
private AuthToken GetAuthToken() => new(
|
||||||
IsBotToken
|
IsBotToken
|
||||||
? AuthTokenType.Bot
|
? AuthTokenType.Bot
|
||||||
: AuthTokenType.User,
|
: AuthTokenType.User,
|
||||||
TokenValue
|
TokenValue
|
||||||
);
|
);
|
||||||
|
|
||||||
protected DiscordClient GetDiscordClient() => new DiscordClient(GetAuthToken());
|
private DiscordClient? _discordClient;
|
||||||
|
protected DiscordClient Discord => _discordClient ??= new DiscordClient(GetAuthToken());
|
||||||
|
|
||||||
public abstract ValueTask ExecuteAsync(IConsole console);
|
public abstract ValueTask ExecuteAsync(IConsole console);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,46 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
[Command("exportall", Description = "Export all accessible channels.")]
|
[Command("exportall", Description = "Export all accessible channels.")]
|
||||||
public class ExportAllCommand : ExportMultipleCommandBase
|
public class ExportAllCommand : ExportCommandBase
|
||||||
{
|
{
|
||||||
[CommandOption("include-dm",
|
[CommandOption("include-dm", Description = "Include direct message channels.")]
|
||||||
Description = "Include direct message channels.")]
|
public bool IncludeDirectMessages { get; init; } = true;
|
||||||
public bool IncludeDirectMessages { get; set; } = true;
|
|
||||||
|
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
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>();
|
var channels = new List<Channel>();
|
||||||
|
|
||||||
// Aggregate channels from all guilds
|
// Aggregate channels from all guilds
|
||||||
await foreach (var guild in GetDiscordClient().GetUserGuildsAsync())
|
await foreach (var guild in Discord.GetUserGuildsAsync())
|
||||||
{
|
{
|
||||||
// Skip DMs if instructed to
|
// Skip DMs if instructed to
|
||||||
if (!IncludeDirectMessages && guild.Id == Guild.DirectMessages.Id)
|
if (!IncludeDirectMessages && guild.Id == Guild.DirectMessages.Id)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
await foreach (var channel in GetDiscordClient().GetGuildChannelsAsync(guild.Id))
|
await foreach (var channel in Discord.GetGuildChannelsAsync(guild.Id))
|
||||||
{
|
{
|
||||||
|
// Skip non-text channels
|
||||||
|
if (!channel.IsTextChannel)
|
||||||
|
continue;
|
||||||
|
|
||||||
channels.Add(channel);
|
channels.Add(channel);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await ExportMultipleAsync(console, channels);
|
// Export
|
||||||
|
await ExportAsync(console, channels);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
using System.Threading.Tasks;
|
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
|
||||||
{
|
|
||||||
[Command("export", Description = "Export a channel.")]
|
|
||||||
public class ExportChannelCommand : ExportCommandBase
|
|
||||||
{
|
|
||||||
[CommandOption("channel", 'c', IsRequired = true,
|
|
||||||
Description = "Channel ID.")]
|
|
||||||
public string ChannelId { get; set; } = "";
|
|
||||||
|
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
|
||||||
{
|
|
||||||
await base.ExecuteAsync(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,19 +1,27 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Linq;
|
||||||
using CliFx;
|
using System.Threading.Tasks;
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
[Command("exportdm", Description = "Export all direct message channels.")]
|
[Command("exportdm", Description = "Export all direct message channels.")]
|
||||||
public class ExportDirectMessagesCommand : ExportMultipleCommandBase
|
public class ExportDirectMessagesCommand : ExportCommandBase
|
||||||
{
|
{
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
public override async ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
var channels = await GetDiscordClient().GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
await base.ExecuteAsync(console);
|
||||||
await ExportMultipleAsync(console, channels);
|
|
||||||
|
// 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();
|
||||||
|
|
||||||
|
// Export
|
||||||
|
await ExportAsync(console, textChannels);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,22 +1,30 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Linq;
|
||||||
using CliFx;
|
using System.Threading.Tasks;
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Discord;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
[Command("exportguild", Description = "Export all channels within specified guild.")]
|
[Command("exportguild", Description = "Export all channels within specified guild.")]
|
||||||
public class ExportGuildCommand : ExportMultipleCommandBase
|
public class ExportGuildCommand : ExportCommandBase
|
||||||
{
|
{
|
||||||
[CommandOption("guild", 'g', IsRequired = true,
|
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||||
Description = "Guild ID.")]
|
public Snowflake GuildId { get; init; }
|
||||||
public string GuildId { get; set; } = "";
|
|
||||||
|
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
public override async ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
var channels = await GetDiscordClient().GetGuildChannelsAsync(GuildId);
|
await base.ExecuteAsync(console);
|
||||||
await ExportMultipleAsync(console, channels);
|
|
||||||
|
// Get channel metadata
|
||||||
|
await console.Output.WriteLineAsync("Fetching channels...");
|
||||||
|
var channels = await Discord.GetGuildChannelsAsync(GuildId);
|
||||||
|
var textChannels = channels.Where(c => c.IsTextChannel).ToArray();
|
||||||
|
|
||||||
|
// Export
|
||||||
|
await ExportAsync(console, textChannels);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,25 +1,45 @@
|
|||||||
using System.Linq;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Discord;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
[Command("channels", Description = "Get the list of channels in a guild.")]
|
[Command("channels", Description = "Get the list of channels in a guild.")]
|
||||||
public class GetChannelsCommand : TokenCommandBase
|
public class GetChannelsCommand : TokenCommandBase
|
||||||
{
|
{
|
||||||
[CommandOption("guild", 'g', IsRequired = true,
|
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
|
||||||
Description = "Guild ID.")]
|
public Snowflake GuildId { get; init; }
|
||||||
public string GuildId { get; set; } = "";
|
|
||||||
|
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
public override async ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
var channels = await GetDiscordClient().GetGuildChannelsAsync(GuildId);
|
var channels = await Discord.GetGuildChannelsAsync(GuildId);
|
||||||
|
|
||||||
foreach (var channel in channels.OrderBy(c => c.Category).ThenBy(c => c.Name))
|
var textChannels = channels
|
||||||
console.Output.WriteLine($"{channel.Id} | {channel.Category} / {channel.Name}");
|
.Where(c => c.IsTextChannel)
|
||||||
|
.OrderBy(c => c.Category.Position)
|
||||||
|
.ThenBy(c => c.Name)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
foreach (var channel in textChannels)
|
||||||
|
{
|
||||||
|
// Channel ID
|
||||||
|
await console.Output.WriteAsync(channel.Id.ToString());
|
||||||
|
|
||||||
|
// 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,10 +1,11 @@
|
|||||||
using System.Linq;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
@@ -13,10 +14,29 @@ namespace DiscordChatExporter.Cli.Commands
|
|||||||
{
|
{
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
public override async ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
var channels = await GetDiscordClient().GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id);
|
||||||
|
|
||||||
foreach (var channel in channels.OrderBy(c => c.Category).ThenBy(c => c.Name))
|
var textChannels = channels
|
||||||
console.Output.WriteLine($"{channel.Id} | {channel.Category} / {channel.Name}");
|
.Where(c => c.IsTextChannel)
|
||||||
|
.OrderBy(c => c.Category.Position)
|
||||||
|
.ThenBy(c => c.Name)
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
foreach (var channel in textChannels)
|
||||||
|
{
|
||||||
|
// Channel ID
|
||||||
|
await console.Output.WriteAsync(channel.Id.ToString());
|
||||||
|
|
||||||
|
// 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,9 +1,10 @@
|
|||||||
using System.Linq;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
using DiscordChatExporter.Cli.Commands.Base;
|
using DiscordChatExporter.Cli.Commands.Base;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
@@ -12,10 +13,23 @@ namespace DiscordChatExporter.Cli.Commands
|
|||||||
{
|
{
|
||||||
public override async ValueTask ExecuteAsync(IConsole console)
|
public override async ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
var guilds = await GetDiscordClient().GetUserGuildsAsync();
|
var guilds = await Discord.GetUserGuildsAsync();
|
||||||
|
|
||||||
foreach (var guild in guilds.OrderBy(g => g.Name))
|
foreach (var guild in guilds.OrderBy(g => g.Name))
|
||||||
console.Output.WriteLine($"{guild.Id} | {guild.Name}");
|
{
|
||||||
|
// Guild ID
|
||||||
|
await console.Output.WriteAsync(guild.Id.ToString());
|
||||||
|
|
||||||
|
// Separator
|
||||||
|
using (console.WithForegroundColor(ConsoleColor.DarkGray))
|
||||||
|
await console.Output.WriteAsync(" | ");
|
||||||
|
|
||||||
|
// Guild name
|
||||||
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
|
await console.Output.WriteAsync(guild.Name);
|
||||||
|
|
||||||
|
await console.Output.WriteLineAsync();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using CliFx;
|
using CliFx;
|
||||||
using CliFx.Attributes;
|
using CliFx.Attributes;
|
||||||
|
using CliFx.Infrastructure;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Cli.Commands
|
namespace DiscordChatExporter.Cli.Commands
|
||||||
{
|
{
|
||||||
@@ -10,30 +11,32 @@ namespace DiscordChatExporter.Cli.Commands
|
|||||||
{
|
{
|
||||||
public ValueTask ExecuteAsync(IConsole console)
|
public ValueTask ExecuteAsync(IConsole console)
|
||||||
{
|
{
|
||||||
console.WithForegroundColor(ConsoleColor.White, () =>
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
console.Output.WriteLine("To get user token:")
|
console.Output.WriteLine("To get user token:");
|
||||||
);
|
|
||||||
console.Output.WriteLine(" 1. Open Discord");
|
console.Output.WriteLine(" 1. Open Discord");
|
||||||
console.Output.WriteLine(" 2. Press Ctrl+Shift+I to show developer tools");
|
console.Output.WriteLine(" 2. Press Ctrl+Shift+I to show developer tools");
|
||||||
console.Output.WriteLine(" 3. Navigate to the Application tab");
|
console.Output.WriteLine(" 3. Press Ctrl+Shift+M to toggle device toolbar");
|
||||||
console.Output.WriteLine(" 4. Select \"Local Storage\" > \"https://discord.com\" on the left");
|
console.Output.WriteLine(" 4. Navigate to the Application tab");
|
||||||
console.Output.WriteLine(" 5. Press Ctrl+R to reload");
|
console.Output.WriteLine(" 5. On the left, expand Local Storage and select https://discord.com");
|
||||||
console.Output.WriteLine(" 6. Find \"token\" at the bottom and copy the value");
|
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(" * Automating user accounts is technically against TOS, use at your own risk.");
|
||||||
console.Output.WriteLine();
|
console.Output.WriteLine();
|
||||||
|
|
||||||
console.WithForegroundColor(ConsoleColor.White, () =>
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
console.Output.WriteLine("To get bot token:")
|
console.Output.WriteLine("To get bot token:");
|
||||||
);
|
|
||||||
console.Output.WriteLine(" 1. Go to Discord developer portal");
|
console.Output.WriteLine(" 1. Go to Discord developer portal");
|
||||||
console.Output.WriteLine(" 2. Open your application's settings");
|
console.Output.WriteLine(" 2. Open your application's settings");
|
||||||
console.Output.WriteLine(" 3. Navigate to the Bot section on the left");
|
console.Output.WriteLine(" 3. Navigate to the Bot section on the left");
|
||||||
console.Output.WriteLine(" 4. Under Token click Copy");
|
console.Output.WriteLine(" 4. Under Token click Copy");
|
||||||
console.Output.WriteLine();
|
console.Output.WriteLine();
|
||||||
|
|
||||||
console.WithForegroundColor(ConsoleColor.White, () =>
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
console.Output.WriteLine("To get guild ID or guild channel ID:")
|
console.Output.WriteLine("To get guild ID or guild channel ID:");
|
||||||
);
|
|
||||||
console.Output.WriteLine(" 1. Open Discord");
|
console.Output.WriteLine(" 1. Open Discord");
|
||||||
console.Output.WriteLine(" 2. Open Settings");
|
console.Output.WriteLine(" 2. Open Settings");
|
||||||
console.Output.WriteLine(" 3. Go to Appearance section");
|
console.Output.WriteLine(" 3. Go to Appearance section");
|
||||||
@@ -41,9 +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(" 5. Right click on the desired guild or channel and click Copy ID");
|
||||||
console.Output.WriteLine();
|
console.Output.WriteLine();
|
||||||
|
|
||||||
console.WithForegroundColor(ConsoleColor.White, () =>
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
console.Output.WriteLine("To get direct message channel ID:")
|
console.Output.WriteLine("To get direct message channel ID:");
|
||||||
);
|
|
||||||
console.Output.WriteLine(" 1. Open Discord");
|
console.Output.WriteLine(" 1. Open Discord");
|
||||||
console.Output.WriteLine(" 2. Open the desired direct message channel");
|
console.Output.WriteLine(" 2. Open the desired direct message channel");
|
||||||
console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
|
console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
|
||||||
@@ -52,12 +55,11 @@ namespace DiscordChatExporter.Cli.Commands
|
|||||||
console.Output.WriteLine(" 6. Copy the first long sequence of numbers inside the URL");
|
console.Output.WriteLine(" 6. Copy the first long sequence of numbers inside the URL");
|
||||||
console.Output.WriteLine();
|
console.Output.WriteLine();
|
||||||
|
|
||||||
console.WithForegroundColor(ConsoleColor.White,
|
using (console.WithForegroundColor(ConsoleColor.White))
|
||||||
() => console.Output.WriteLine("For more information, check out the wiki:")
|
console.Output.WriteLine("For more information, check out the wiki:");
|
||||||
);
|
|
||||||
console.WithForegroundColor(ConsoleColor.Blue,
|
using (console.WithForegroundColor(ConsoleColor.DarkCyan))
|
||||||
() => console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki")
|
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
|
||||||
);
|
|
||||||
|
|
||||||
return default;
|
return default;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
<Import Project="../DiscordChatExporter.props" />
|
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
@@ -7,13 +6,14 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="CliFx" Version="1.5.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="Gress" Version="1.2.0" />
|
||||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\DiscordChatExporter.Domain\DiscordChatExporter.Domain.csproj" />
|
<ProjectReference Include="..\DiscordChatExporter.Core\DiscordChatExporter.Core.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -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
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-4
@@ -1,9 +1,7 @@
|
|||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord
|
namespace DiscordChatExporter.Core.Discord
|
||||||
{
|
{
|
||||||
public enum AuthTokenType { User, Bot }
|
|
||||||
|
|
||||||
public class AuthToken
|
public class AuthToken
|
||||||
{
|
{
|
||||||
public AuthTokenType Type { get; }
|
public AuthTokenType Type { get; }
|
||||||
@@ -16,7 +14,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
Value = value;
|
Value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public AuthenticationHeaderValue GetAuthorizationHeader() => Type switch
|
public AuthenticationHeaderValue GetAuthenticationHeader() => Type switch
|
||||||
{
|
{
|
||||||
AuthTokenType.Bot => new AuthenticationHeaderValue("Bot", Value),
|
AuthTokenType.Bot => new AuthenticationHeaderValue("Bot", Value),
|
||||||
_ => new AuthenticationHeaderValue(Value)
|
_ => new AuthenticationHeaderValue(Value)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Discord
|
||||||
|
{
|
||||||
|
public enum AuthTokenType
|
||||||
|
{
|
||||||
|
User,
|
||||||
|
Bot
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-20
@@ -2,36 +2,44 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#attachment-object
|
// https://discord.com/developers/docs/resources/channel#attachment-object
|
||||||
public partial class Attachment : IHasId
|
public partial class Attachment : IHasId
|
||||||
{
|
{
|
||||||
public string Id { get; }
|
public Snowflake Id { get; }
|
||||||
|
|
||||||
public string Url { get; }
|
public string Url { get; }
|
||||||
|
|
||||||
public string FileName { get; }
|
public string FileName { get; }
|
||||||
|
|
||||||
|
public string FileExtension => Path.GetExtension(FileName);
|
||||||
|
|
||||||
public int? Width { get; }
|
public int? Width { get; }
|
||||||
|
|
||||||
public int? Height { get; }
|
public int? Height { get; }
|
||||||
|
|
||||||
public bool IsImage => ImageFileExtensions.Contains(Path.GetExtension(FileName));
|
public bool IsImage => ImageFileExtensions.Contains(FileExtension);
|
||||||
|
|
||||||
public bool IsVideo => VideoFileExtensions.Contains(Path.GetExtension(FileName));
|
public bool IsVideo => VideoFileExtensions.Contains(FileExtension);
|
||||||
|
|
||||||
public bool IsAudio => AudioFileExtensions.Contains(Path.GetExtension(FileName));
|
public bool IsAudio => AudioFileExtensions.Contains(FileExtension);
|
||||||
|
|
||||||
public bool IsSpoiler =>
|
public bool IsSpoiler => FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
|
||||||
(IsImage || IsVideo || IsAudio) && FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
|
|
||||||
|
|
||||||
public FileSize FileSize { get; }
|
public FileSize FileSize { get; }
|
||||||
|
|
||||||
public Attachment(string id, string url, string fileName, int? width, int? height, FileSize fileSize)
|
public Attachment(
|
||||||
|
Snowflake id,
|
||||||
|
string url,
|
||||||
|
string fileName,
|
||||||
|
int? width,
|
||||||
|
int? height,
|
||||||
|
FileSize fileSize)
|
||||||
{
|
{
|
||||||
Id = id;
|
Id = id;
|
||||||
Url = url;
|
Url = url;
|
||||||
@@ -46,21 +54,18 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public partial class Attachment
|
public partial class Attachment
|
||||||
{
|
{
|
||||||
private static readonly HashSet<string> ImageFileExtensions =
|
private static readonly HashSet<string> ImageFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||||
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
{".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
|
||||||
{".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};
|
|
||||||
|
|
||||||
private static readonly HashSet<string> VideoFileExtensions =
|
private static readonly HashSet<string> VideoFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||||
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
{".mp4", ".webm"};
|
||||||
{".mp4", ".webm"};
|
|
||||||
|
|
||||||
private static readonly HashSet<string> AudioFileExtensions =
|
private static readonly HashSet<string> AudioFileExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||||
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
{".mp3", ".wav", ".ogg", ".flac", ".m4a"};
|
||||||
{".mp3", ".wav", ".ogg", ".flac", ".m4a"};
|
|
||||||
|
|
||||||
public static Attachment Parse(JsonElement json)
|
public static Attachment Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var id = json.GetProperty("id").GetString();
|
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||||
var url = json.GetProperty("url").GetString();
|
var url = json.GetProperty("url").GetString();
|
||||||
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
||||||
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
|
{
|
||||||
|
// 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 = 0,
|
||||||
|
DirectTextChat,
|
||||||
|
GuildVoiceChat,
|
||||||
|
DirectGroupTextChat,
|
||||||
|
GuildCategory,
|
||||||
|
GuildNews,
|
||||||
|
GuildStore
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-17
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models.Common
|
namespace DiscordChatExporter.Core.Discord.Data.Common
|
||||||
{
|
{
|
||||||
// Loosely based on https://github.com/omar/ByteSize (MIT license)
|
// Loosely based on https://github.com/omar/ByteSize (MIT license)
|
||||||
public readonly partial struct FileSize
|
public readonly partial struct FileSize
|
||||||
@@ -10,19 +10,11 @@ namespace DiscordChatExporter.Domain.Discord.Models.Common
|
|||||||
public double TotalKiloBytes => TotalBytes / 1024.0;
|
public double TotalKiloBytes => TotalBytes / 1024.0;
|
||||||
public double TotalMegaBytes => TotalKiloBytes / 1024.0;
|
public double TotalMegaBytes => TotalKiloBytes / 1024.0;
|
||||||
public double TotalGigaBytes => TotalMegaBytes / 1024.0;
|
public double TotalGigaBytes => TotalMegaBytes / 1024.0;
|
||||||
public double TotalTeraBytes => TotalGigaBytes / 1024.0;
|
|
||||||
public double TotalPetaBytes => TotalTeraBytes / 1024.0;
|
|
||||||
|
|
||||||
public FileSize(long bytes) => TotalBytes = bytes;
|
public FileSize(long bytes) => TotalBytes = bytes;
|
||||||
|
|
||||||
private double GetLargestWholeNumberValue()
|
private double GetLargestWholeNumberValue()
|
||||||
{
|
{
|
||||||
if (Math.Abs(TotalPetaBytes) >= 1)
|
|
||||||
return TotalPetaBytes;
|
|
||||||
|
|
||||||
if (Math.Abs(TotalTeraBytes) >= 1)
|
|
||||||
return TotalTeraBytes;
|
|
||||||
|
|
||||||
if (Math.Abs(TotalGigaBytes) >= 1)
|
if (Math.Abs(TotalGigaBytes) >= 1)
|
||||||
return TotalGigaBytes;
|
return TotalGigaBytes;
|
||||||
|
|
||||||
@@ -37,12 +29,6 @@ namespace DiscordChatExporter.Domain.Discord.Models.Common
|
|||||||
|
|
||||||
private string GetLargestWholeNumberSymbol()
|
private string GetLargestWholeNumberSymbol()
|
||||||
{
|
{
|
||||||
if (Math.Abs(TotalPetaBytes) >= 1)
|
|
||||||
return "PB";
|
|
||||||
|
|
||||||
if (Math.Abs(TotalTeraBytes) >= 1)
|
|
||||||
return "TB";
|
|
||||||
|
|
||||||
if (Math.Abs(TotalGigaBytes) >= 1)
|
if (Math.Abs(TotalGigaBytes) >= 1)
|
||||||
return "GB";
|
return "GB";
|
||||||
|
|
||||||
@@ -52,7 +38,7 @@ namespace DiscordChatExporter.Domain.Discord.Models.Common
|
|||||||
if (Math.Abs(TotalKiloBytes) >= 1)
|
if (Math.Abs(TotalKiloBytes) >= 1)
|
||||||
return "KB";
|
return "KB";
|
||||||
|
|
||||||
return "B";
|
return "bytes";
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}";
|
public override string ToString() => $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}";
|
||||||
@@ -60,6 +46,6 @@ namespace DiscordChatExporter.Domain.Discord.Models.Common
|
|||||||
|
|
||||||
public partial struct FileSize
|
public partial struct FileSize
|
||||||
{
|
{
|
||||||
public static FileSize FromBytes(long bytes) => new FileSize(bytes);
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-3
@@ -3,9 +3,10 @@ using System.Collections.Generic;
|
|||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#embed-object
|
// https://discord.com/developers/docs/resources/channel#embed-object
|
||||||
public partial class Embed
|
public partial class Embed
|
||||||
@@ -54,6 +55,8 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
Footer = footer;
|
Footer = footer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public YouTubeVideoEmbedProjection? TryGetYouTubeVideo() => YouTubeVideoEmbedProjection.TryResolve(this);
|
||||||
|
|
||||||
public override string ToString() => Title ?? "<untitled embed>";
|
public override string ToString() => Title ?? "<untitled embed>";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,10 +65,10 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
public static Embed Parse(JsonElement json)
|
public static Embed Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var title = json.GetPropertyOrNull("title")?.GetString();
|
var title = json.GetPropertyOrNull("title")?.GetString();
|
||||||
var description = json.GetPropertyOrNull("description")?.GetString();
|
|
||||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||||
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffset();
|
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffset();
|
||||||
var color = json.GetPropertyOrNull("color")?.GetInt32().Pipe(System.Drawing.Color.FromArgb).ResetAlpha();
|
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 author = json.GetPropertyOrNull("author")?.Pipe(EmbedAuthor.Parse);
|
||||||
var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse);
|
var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse);
|
||||||
+8
-4
@@ -1,7 +1,7 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure
|
// https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure
|
||||||
public partial class EmbedAuthor
|
public partial class EmbedAuthor
|
||||||
@@ -12,11 +12,14 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public string? IconUrl { get; }
|
public string? IconUrl { get; }
|
||||||
|
|
||||||
public EmbedAuthor(string? name, string? url, string? iconUrl)
|
public string? IconProxyUrl { get; }
|
||||||
|
|
||||||
|
public EmbedAuthor(string? name, string? url, string? iconUrl, string? iconProxyUrl)
|
||||||
{
|
{
|
||||||
Name = name;
|
Name = name;
|
||||||
Url = url;
|
Url = url;
|
||||||
IconUrl = iconUrl;
|
IconUrl = iconUrl;
|
||||||
|
IconProxyUrl = iconProxyUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => Name ?? "<unnamed author>";
|
public override string ToString() => Name ?? "<unnamed author>";
|
||||||
@@ -29,8 +32,9 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
var name = json.GetPropertyOrNull("name")?.GetString();
|
var name = json.GetPropertyOrNull("name")?.GetString();
|
||||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||||
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
||||||
|
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetString();
|
||||||
|
|
||||||
return new EmbedAuthor(name, url, iconUrl);
|
return new EmbedAuthor(name, url, iconUrl, iconProxyUrl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure
|
// https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure
|
||||||
public partial class EmbedField
|
public partial class EmbedField
|
||||||
+8
-4
@@ -1,7 +1,7 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure
|
// https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure
|
||||||
public partial class EmbedFooter
|
public partial class EmbedFooter
|
||||||
@@ -10,10 +10,13 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public string? IconUrl { get; }
|
public string? IconUrl { get; }
|
||||||
|
|
||||||
public EmbedFooter(string text, string? iconUrl)
|
public string? IconProxyUrl { get; }
|
||||||
|
|
||||||
|
public EmbedFooter(string text, string? iconUrl, string? iconProxyUrl)
|
||||||
{
|
{
|
||||||
Text = text;
|
Text = text;
|
||||||
IconUrl = iconUrl;
|
IconUrl = iconUrl;
|
||||||
|
IconProxyUrl = iconProxyUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => Text;
|
public override string ToString() => Text;
|
||||||
@@ -25,8 +28,9 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
{
|
{
|
||||||
var text = json.GetProperty("text").GetString();
|
var text = json.GetProperty("text").GetString();
|
||||||
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetString();
|
||||||
|
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetString();
|
||||||
|
|
||||||
return new EmbedFooter(text, iconUrl);
|
return new EmbedFooter(text, iconUrl, iconProxyUrl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+8
-4
@@ -1,20 +1,23 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
|
// https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
|
||||||
public partial class EmbedImage
|
public partial class EmbedImage
|
||||||
{
|
{
|
||||||
public string? Url { get; }
|
public string? Url { get; }
|
||||||
|
|
||||||
|
public string? ProxyUrl { get; }
|
||||||
|
|
||||||
public int? Width { get; }
|
public int? Width { get; }
|
||||||
|
|
||||||
public int? Height { get; }
|
public int? Height { get; }
|
||||||
|
|
||||||
public EmbedImage(string? url, int? width, int? height)
|
public EmbedImage(string? url, string? proxyUrl, int? width, int? height)
|
||||||
{
|
{
|
||||||
Url = url;
|
Url = url;
|
||||||
|
ProxyUrl = proxyUrl;
|
||||||
Height = height;
|
Height = height;
|
||||||
Width = width;
|
Width = width;
|
||||||
}
|
}
|
||||||
@@ -25,10 +28,11 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
public static EmbedImage Parse(JsonElement json)
|
public static EmbedImage Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var url = json.GetPropertyOrNull("url")?.GetString();
|
var url = json.GetPropertyOrNull("url")?.GetString();
|
||||||
|
var proxyUrl = json.GetPropertyOrNull("proxy_url")?.GetString();
|
||||||
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
var width = json.GetPropertyOrNull("width")?.GetInt32();
|
||||||
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
var height = json.GetPropertyOrNull("height")?.GetInt32();
|
||||||
|
|
||||||
return new EmbedImage(url, width, height);
|
return new EmbedImage(url, proxyUrl, width, height);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using System.Text.Json;
|
||||||
|
using DiscordChatExporter.Core.Utils;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
using Tyrrrz.Extensions;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
|
{
|
||||||
|
// https://discord.com/developers/docs/resources/emoji#emoji-object
|
||||||
|
public partial class Emoji
|
||||||
|
{
|
||||||
|
// Only present on custom emoji
|
||||||
|
public string? Id { get; }
|
||||||
|
|
||||||
|
// Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂)
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
|
// Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile)
|
||||||
|
public string Code => !string.IsNullOrWhiteSpace(Id)
|
||||||
|
? Name
|
||||||
|
: EmojiIndex.TryGetCode(Name) ?? Name;
|
||||||
|
|
||||||
|
public bool IsAnimated { get; }
|
||||||
|
|
||||||
|
public string ImageUrl { get; }
|
||||||
|
|
||||||
|
public Emoji(string? id, string name, bool isAnimated, string imageUrl)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
Name = name;
|
||||||
|
IsAnimated = isAnimated;
|
||||||
|
ImageUrl = imageUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class Emoji
|
||||||
|
{
|
||||||
|
private static string GetTwemojiName(string name) => name
|
||||||
|
.GetRunes()
|
||||||
|
// Variant selector rune is skipped in Twemoji names
|
||||||
|
.Where(r => r.Value != 0xfe0f)
|
||||||
|
.Select(r => r.Value.ToString("x"))
|
||||||
|
.JoinToString("-");
|
||||||
|
|
||||||
|
public static string GetImageUrl(string? id, string name, bool isAnimated)
|
||||||
|
{
|
||||||
|
// Custom emoji
|
||||||
|
if (!string.IsNullOrWhiteSpace(id))
|
||||||
|
{
|
||||||
|
return isAnimated
|
||||||
|
? $"https://cdn.discordapp.com/emojis/{id}.gif"
|
||||||
|
: $"https://cdn.discordapp.com/emojis/{id}.png";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard emoji
|
||||||
|
var twemojiName = GetTwemojiName(name);
|
||||||
|
return $"https://twemoji.maxcdn.com/2/svg/{twemojiName}.svg";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Emoji Parse(JsonElement json)
|
||||||
|
{
|
||||||
|
var id = json.GetPropertyOrNull("id")?.GetString();
|
||||||
|
var name = json.GetProperty("name").GetString();
|
||||||
|
var isAnimated = json.GetPropertyOrNull("animated")?.GetBoolean() ?? false;
|
||||||
|
|
||||||
|
var imageUrl = GetImageUrl(id, name, isAnimated);
|
||||||
|
|
||||||
|
return new Emoji(id, name, isAnimated, imageUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+12
-8
@@ -1,18 +1,19 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/guild#guild-object
|
// https://discord.com/developers/docs/resources/guild#guild-object
|
||||||
public partial class Guild : IHasId
|
public partial class Guild : IHasId
|
||||||
{
|
{
|
||||||
public string Id { get; }
|
public Snowflake Id { get; }
|
||||||
|
|
||||||
public string Name { get; }
|
public string Name { get; }
|
||||||
|
|
||||||
public string IconUrl { get; }
|
public string IconUrl { get; }
|
||||||
|
|
||||||
public Guild(string id, string name, string iconUrl)
|
public Guild(Snowflake id, string name, string iconUrl)
|
||||||
{
|
{
|
||||||
Id = id;
|
Id = id;
|
||||||
Name = name;
|
Name = name;
|
||||||
@@ -24,18 +25,21 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public partial class Guild
|
public partial class Guild
|
||||||
{
|
{
|
||||||
public static Guild DirectMessages { get; } =
|
public static Guild DirectMessages { get; } = new(
|
||||||
new Guild("@me", "Direct Messages", GetDefaultIconUrl());
|
Snowflake.Zero,
|
||||||
|
"Direct Messages",
|
||||||
|
GetDefaultIconUrl()
|
||||||
|
);
|
||||||
|
|
||||||
private static string GetDefaultIconUrl() =>
|
private static string GetDefaultIconUrl() =>
|
||||||
"https://cdn.discordapp.com/embed/avatars/0.png";
|
"https://cdn.discordapp.com/embed/avatars/0.png";
|
||||||
|
|
||||||
private static string GetIconUrl(string id, string iconHash) =>
|
private static string GetIconUrl(Snowflake id, string iconHash) =>
|
||||||
$"https://cdn.discordapp.com/icons/{id}/{iconHash}.png";
|
$"https://cdn.discordapp.com/icons/{id}/{iconHash}.png";
|
||||||
|
|
||||||
public static Guild Parse(JsonElement json)
|
public static Guild Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var id = json.GetProperty("id").GetString();
|
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||||
var name = json.GetProperty("name").GetString();
|
var name = json.GetProperty("name").GetString();
|
||||||
var iconHash = json.GetProperty("icon").GetString();
|
var iconHash = json.GetProperty("icon").GetString();
|
||||||
|
|
||||||
+16
-12
@@ -2,26 +2,27 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/guild#guild-member-object
|
// https://discord.com/developers/docs/resources/guild#guild-member-object
|
||||||
public partial class Member : IHasId
|
public partial class Member : IHasId
|
||||||
{
|
{
|
||||||
public string Id => User.Id;
|
public Snowflake Id => User.Id;
|
||||||
|
|
||||||
public User User { get; }
|
public User User { get; }
|
||||||
|
|
||||||
public string Nick { get; }
|
public string Nick { get; }
|
||||||
|
|
||||||
public IReadOnlyList<string> RoleIds { get; }
|
public IReadOnlyList<Snowflake> RoleIds { get; }
|
||||||
|
|
||||||
public Member(User user, string? nick, IReadOnlyList<string> roleIds)
|
public Member(User user, string nick, IReadOnlyList<Snowflake> roleIds)
|
||||||
{
|
{
|
||||||
User = user;
|
User = user;
|
||||||
Nick = nick ?? user.Name;
|
Nick = nick;
|
||||||
RoleIds = roleIds;
|
RoleIds = roleIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,8 +31,11 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public partial class Member
|
public partial class Member
|
||||||
{
|
{
|
||||||
public static Member CreateForUser(User user) =>
|
public static Member CreateForUser(User user) => new(
|
||||||
new Member(user, null, Array.Empty<string>());
|
user,
|
||||||
|
user.Name,
|
||||||
|
Array.Empty<Snowflake>()
|
||||||
|
);
|
||||||
|
|
||||||
public static Member Parse(JsonElement json)
|
public static Member Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
@@ -39,12 +43,12 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
var nick = json.GetPropertyOrNull("nick")?.GetString();
|
var nick = json.GetPropertyOrNull("nick")?.GetString();
|
||||||
|
|
||||||
var roleIds =
|
var roleIds =
|
||||||
json.GetPropertyOrNull("roles")?.EnumerateArray().Select(j => j.GetString()).ToArray() ??
|
json.GetPropertyOrNull("roles")?.EnumerateArray().Select(j => j.GetString()).Select(Snowflake.Parse).ToArray() ??
|
||||||
Array.Empty<string>();
|
Array.Empty<Snowflake>();
|
||||||
|
|
||||||
return new Member(
|
return new Member(
|
||||||
user,
|
user,
|
||||||
nick,
|
nick ?? user.Name,
|
||||||
roleIds
|
roleIds
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+31
-17
@@ -2,28 +2,30 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#message-object-message-types
|
// https://discord.com/developers/docs/resources/channel#message-object-message-types
|
||||||
public enum MessageType
|
public enum MessageType
|
||||||
{
|
{
|
||||||
Default,
|
Default = 0,
|
||||||
RecipientAdd,
|
RecipientAdd = 1,
|
||||||
RecipientRemove,
|
RecipientRemove = 2,
|
||||||
Call,
|
Call = 3,
|
||||||
ChannelNameChange,
|
ChannelNameChange = 4,
|
||||||
ChannelIconChange,
|
ChannelIconChange = 5,
|
||||||
ChannelPinnedMessage,
|
ChannelPinnedMessage = 6,
|
||||||
GuildMemberJoin
|
GuildMemberJoin = 7,
|
||||||
|
Reply = 19
|
||||||
}
|
}
|
||||||
|
|
||||||
// https://discord.com/developers/docs/resources/channel#message-object
|
// https://discord.com/developers/docs/resources/channel#message-object
|
||||||
public partial class Message : IHasId
|
public partial class Message : IHasId
|
||||||
{
|
{
|
||||||
public string Id { get; }
|
public Snowflake Id { get; }
|
||||||
|
|
||||||
public MessageType Type { get; }
|
public MessageType Type { get; }
|
||||||
|
|
||||||
@@ -47,8 +49,12 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public IReadOnlyList<User> MentionedUsers { get; }
|
public IReadOnlyList<User> MentionedUsers { get; }
|
||||||
|
|
||||||
|
public MessageReference? Reference { get; }
|
||||||
|
|
||||||
|
public Message? ReferencedMessage { get; }
|
||||||
|
|
||||||
public Message(
|
public Message(
|
||||||
string id,
|
Snowflake id,
|
||||||
MessageType type,
|
MessageType type,
|
||||||
User author,
|
User author,
|
||||||
DateTimeOffset timestamp,
|
DateTimeOffset timestamp,
|
||||||
@@ -59,7 +65,9 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
IReadOnlyList<Attachment> attachments,
|
IReadOnlyList<Attachment> attachments,
|
||||||
IReadOnlyList<Embed> embeds,
|
IReadOnlyList<Embed> embeds,
|
||||||
IReadOnlyList<Reaction> reactions,
|
IReadOnlyList<Reaction> reactions,
|
||||||
IReadOnlyList<User> mentionedUsers)
|
IReadOnlyList<User> mentionedUsers,
|
||||||
|
MessageReference? messageReference,
|
||||||
|
Message? referencedMessage)
|
||||||
{
|
{
|
||||||
Id = id;
|
Id = id;
|
||||||
Type = type;
|
Type = type;
|
||||||
@@ -73,6 +81,8 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
Embeds = embeds;
|
Embeds = embeds;
|
||||||
Reactions = reactions;
|
Reactions = reactions;
|
||||||
MentionedUsers = mentionedUsers;
|
MentionedUsers = mentionedUsers;
|
||||||
|
Reference = messageReference;
|
||||||
|
ReferencedMessage = referencedMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override string ToString() => Content;
|
public override string ToString() => Content;
|
||||||
@@ -82,20 +92,22 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
{
|
{
|
||||||
public static Message Parse(JsonElement json)
|
public static Message Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var id = json.GetProperty("id").GetString();
|
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||||
var author = json.GetProperty("author").Pipe(User.Parse);
|
var author = json.GetProperty("author").Pipe(User.Parse);
|
||||||
var timestamp = json.GetProperty("timestamp").GetDateTimeOffset();
|
var timestamp = json.GetProperty("timestamp").GetDateTimeOffset();
|
||||||
var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffset();
|
var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffset();
|
||||||
var callEndedTimestamp = json.GetPropertyOrNull("call")?.GetPropertyOrNull("ended_timestamp")?.GetDateTimeOffset();
|
var callEndedTimestamp = json.GetPropertyOrNull("call")?.GetPropertyOrNull("ended_timestamp")?.GetDateTimeOffset();
|
||||||
var type = (MessageType) json.GetProperty("type").GetInt32();
|
var type = (MessageType) json.GetProperty("type").GetInt32();
|
||||||
var isPinned = json.GetPropertyOrNull("pinned")?.GetBoolean() ?? false;
|
var isPinned = json.GetPropertyOrNull("pinned")?.GetBoolean() ?? false;
|
||||||
|
var messageReference = json.GetPropertyOrNull("message_reference")?.Pipe(MessageReference.Parse);
|
||||||
|
var referencedMessage = json.GetPropertyOrNull("referenced_message")?.Pipe(Parse);
|
||||||
|
|
||||||
var content = type switch
|
var content = type switch
|
||||||
{
|
{
|
||||||
MessageType.RecipientAdd => "Added a recipient.",
|
MessageType.RecipientAdd => "Added a recipient.",
|
||||||
MessageType.RecipientRemove => "Removed a recipient.",
|
MessageType.RecipientRemove => "Removed a recipient.",
|
||||||
MessageType.Call =>
|
MessageType.Call =>
|
||||||
$"Started a call that lasted {callEndedTimestamp?.Pipe(t => t - timestamp).Pipe(t => (int) t.TotalMinutes) ?? 0} minutes.",
|
$"Started a call that lasted {callEndedTimestamp?.Pipe(t => t - timestamp).Pipe(t => (int) t.TotalMinutes) ?? 0} minutes.",
|
||||||
MessageType.ChannelNameChange => "Changed the channel name.",
|
MessageType.ChannelNameChange => "Changed the channel name.",
|
||||||
MessageType.ChannelIconChange => "Changed the channel icon.",
|
MessageType.ChannelIconChange => "Changed the channel icon.",
|
||||||
MessageType.ChannelPinnedMessage => "Pinned a message.",
|
MessageType.ChannelPinnedMessage => "Pinned a message.",
|
||||||
@@ -131,7 +143,9 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
attachments,
|
attachments,
|
||||||
embeds,
|
embeds,
|
||||||
reactions,
|
reactions,
|
||||||
mentionedUsers
|
mentionedUsers,
|
||||||
|
messageReference,
|
||||||
|
referencedMessage
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
|
{
|
||||||
|
// https://discord.com/developers/docs/resources/channel#message-object-message-reference-structure
|
||||||
|
public partial class MessageReference
|
||||||
|
{
|
||||||
|
public Snowflake? MessageId { get; }
|
||||||
|
|
||||||
|
public Snowflake? ChannelId { get; }
|
||||||
|
|
||||||
|
public Snowflake? GuildId { get; }
|
||||||
|
|
||||||
|
public MessageReference(Snowflake? messageId, Snowflake? channelId, Snowflake? guildId)
|
||||||
|
{
|
||||||
|
MessageId = messageId;
|
||||||
|
ChannelId = channelId;
|
||||||
|
GuildId = guildId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => MessageId?.ToString() ?? "<unknown reference>";
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class MessageReference
|
||||||
|
{
|
||||||
|
public static MessageReference Parse(JsonElement json)
|
||||||
|
{
|
||||||
|
var messageId = json.GetPropertyOrNull("message_id")?.GetString().Pipe(Snowflake.Parse);
|
||||||
|
var channelId = json.GetPropertyOrNull("channel_id")?.GetString().Pipe(Snowflake.Parse);
|
||||||
|
var guildId = json.GetPropertyOrNull("guild_id")?.GetString().Pipe(Snowflake.Parse);
|
||||||
|
|
||||||
|
return new MessageReference(messageId, channelId, guildId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/channel#reaction-object
|
// https://discord.com/developers/docs/resources/channel#reaction-object
|
||||||
public partial class Reaction
|
public partial class Reaction
|
||||||
@@ -23,8 +23,8 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
{
|
{
|
||||||
public static Reaction Parse(JsonElement json)
|
public static Reaction Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var count = json.GetProperty("count").GetInt32();
|
|
||||||
var emoji = json.GetProperty("emoji").Pipe(Emoji.Parse);
|
var emoji = json.GetProperty("emoji").Pipe(Emoji.Parse);
|
||||||
|
var count = json.GetProperty("count").GetInt32();
|
||||||
|
|
||||||
return new Reaction(emoji, count);
|
return new Reaction(emoji, count);
|
||||||
}
|
}
|
||||||
+14
-7
@@ -1,13 +1,15 @@
|
|||||||
using System.Drawing;
|
using System.Drawing;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/topics/permissions#role-object
|
// https://discord.com/developers/docs/topics/permissions#role-object
|
||||||
public partial class Role
|
public partial class Role : IHasId
|
||||||
{
|
{
|
||||||
public string Id { get; }
|
public Snowflake Id { get; }
|
||||||
|
|
||||||
public string Name { get; }
|
public string Name { get; }
|
||||||
|
|
||||||
@@ -15,7 +17,11 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
|
|
||||||
public Color? Color { get; }
|
public Color? Color { get; }
|
||||||
|
|
||||||
public Role(string id, string name, int position, Color? color)
|
public Role(
|
||||||
|
Snowflake id,
|
||||||
|
string name,
|
||||||
|
int position,
|
||||||
|
Color? color)
|
||||||
{
|
{
|
||||||
Id = id;
|
Id = id;
|
||||||
Name = name;
|
Name = name;
|
||||||
@@ -30,11 +36,12 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
{
|
{
|
||||||
public static Role Parse(JsonElement json)
|
public static Role Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var id = json.GetProperty("id").GetString();
|
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||||
var name = json.GetProperty("name").GetString();
|
var name = json.GetProperty("name").GetString();
|
||||||
var position = json.GetProperty("position").GetInt32();
|
var position = json.GetProperty("position").GetInt32();
|
||||||
|
|
||||||
var color = json.GetPropertyOrNull("color")?
|
var color = json
|
||||||
|
.GetPropertyOrNull("color")?
|
||||||
.GetInt32()
|
.GetInt32()
|
||||||
.Pipe(System.Drawing.Color.FromArgb)
|
.Pipe(System.Drawing.Color.FromArgb)
|
||||||
.ResetAlpha()
|
.ResetAlpha()
|
||||||
+19
-11
@@ -1,26 +1,34 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord.Models
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
{
|
{
|
||||||
// https://discord.com/developers/docs/resources/user#user-object
|
// https://discord.com/developers/docs/resources/user#user-object
|
||||||
public partial class User : IHasId
|
public partial class User : IHasId
|
||||||
{
|
{
|
||||||
public string Id { get; }
|
public Snowflake Id { get; }
|
||||||
|
|
||||||
public bool IsBot { get; }
|
public bool IsBot { get; }
|
||||||
|
|
||||||
public int Discriminator { get; }
|
public int Discriminator { get; }
|
||||||
|
|
||||||
|
public string DiscriminatorFormatted => $"{Discriminator:0000}";
|
||||||
|
|
||||||
public string Name { get; }
|
public string Name { get; }
|
||||||
|
|
||||||
public string FullName => $"{Name}#{Discriminator:0000}";
|
public string FullName => $"{Name}#{DiscriminatorFormatted}";
|
||||||
|
|
||||||
public string AvatarUrl { get; }
|
public string AvatarUrl { get; }
|
||||||
|
|
||||||
public User(string id, bool isBot, int discriminator, string name, string avatarUrl)
|
public User(
|
||||||
|
Snowflake id,
|
||||||
|
bool isBot,
|
||||||
|
int discriminator,
|
||||||
|
string name,
|
||||||
|
string avatarUrl)
|
||||||
{
|
{
|
||||||
Id = id;
|
Id = id;
|
||||||
IsBot = isBot;
|
IsBot = isBot;
|
||||||
@@ -37,23 +45,23 @@ namespace DiscordChatExporter.Domain.Discord.Models
|
|||||||
private static string GetDefaultAvatarUrl(int discriminator) =>
|
private static string GetDefaultAvatarUrl(int discriminator) =>
|
||||||
$"https://cdn.discordapp.com/embed/avatars/{discriminator % 5}.png";
|
$"https://cdn.discordapp.com/embed/avatars/{discriminator % 5}.png";
|
||||||
|
|
||||||
private static string GetAvatarUrl(string id, string avatarHash)
|
private static string GetAvatarUrl(Snowflake id, string avatarHash)
|
||||||
{
|
{
|
||||||
// Animated
|
// Animated
|
||||||
if (avatarHash.StartsWith("a_", StringComparison.Ordinal))
|
if (avatarHash.StartsWith("a_", StringComparison.Ordinal))
|
||||||
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.gif";
|
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.gif?size=40";
|
||||||
|
|
||||||
// Non-animated
|
// Non-animated
|
||||||
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.png";
|
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.png?size=40";
|
||||||
}
|
}
|
||||||
|
|
||||||
public static User Parse(JsonElement json)
|
public static User Parse(JsonElement json)
|
||||||
{
|
{
|
||||||
var id = json.GetProperty("id").GetString();
|
var id = json.GetProperty("id").GetString().Pipe(Snowflake.Parse);
|
||||||
|
var isBot = json.GetPropertyOrNull("bot")?.GetBoolean() ?? false;
|
||||||
var discriminator = json.GetProperty("discriminator").GetString().Pipe(int.Parse);
|
var discriminator = json.GetProperty("discriminator").GetString().Pipe(int.Parse);
|
||||||
var name = json.GetProperty("username").GetString();
|
var name = json.GetProperty("username").GetString();
|
||||||
var avatarHash = json.GetProperty("avatar").GetString();
|
var avatarHash = json.GetProperty("avatar").GetString();
|
||||||
var isBot = json.GetPropertyOrNull("bot")?.GetBoolean() ?? false;
|
|
||||||
|
|
||||||
var avatarUrl = !string.IsNullOrWhiteSpace(avatarHash)
|
var avatarUrl = !string.IsNullOrWhiteSpace(avatarHash)
|
||||||
? GetAvatarUrl(id, avatarHash)
|
? GetAvatarUrl(id, avatarHash)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Discord.Data
|
||||||
|
{
|
||||||
|
public partial class YouTubeVideoEmbedProjection
|
||||||
|
{
|
||||||
|
public string VideoId { get; }
|
||||||
|
|
||||||
|
public string Url { get; }
|
||||||
|
|
||||||
|
public YouTubeVideoEmbedProjection(string videoId, string url)
|
||||||
|
{
|
||||||
|
VideoId = videoId;
|
||||||
|
Url = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => Url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class YouTubeVideoEmbedProjection
|
||||||
|
{
|
||||||
|
// Adapted from YoutubeExplode
|
||||||
|
// https://github.com/Tyrrrz/YoutubeExplode/blob/5be164be20019783913f76fcc98f18c65aebe9f0/YoutubeExplode/Videos/VideoId.cs#L34-L64
|
||||||
|
private static string? TryParseVideoId(string embedUrl)
|
||||||
|
{
|
||||||
|
// Regular URL
|
||||||
|
// https://www.youtube.com/watch?v=yIVRs6YSbOM
|
||||||
|
var regularMatch = Regex.Match(embedUrl, @"youtube\..+?/watch.*?v=(.*?)(?:&|/|$)").Groups[1].Value;
|
||||||
|
if (!string.IsNullOrWhiteSpace(regularMatch))
|
||||||
|
return regularMatch;
|
||||||
|
|
||||||
|
// Short URL
|
||||||
|
// https://youtu.be/yIVRs6YSbOM
|
||||||
|
var shortMatch = Regex.Match(embedUrl, @"youtu\.be/(.*?)(?:\?|&|/|$)").Groups[1].Value;
|
||||||
|
if (!string.IsNullOrWhiteSpace(shortMatch))
|
||||||
|
return shortMatch;
|
||||||
|
|
||||||
|
// Embed URL
|
||||||
|
// https://www.youtube.com/embed/yIVRs6YSbOM
|
||||||
|
var embedMatch = Regex.Match(embedUrl, @"youtube\..+?/embed/(.*?)(?:\?|&|/|$)").Groups[1].Value;
|
||||||
|
if (!string.IsNullOrWhiteSpace(embedMatch))
|
||||||
|
return embedMatch;
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static YouTubeVideoEmbedProjection? TryResolve(Embed embed)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(embed.Url))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var videoId = TryParseVideoId(embed.Url);
|
||||||
|
if (string.IsNullOrWhiteSpace(videoId))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var url = $"https://www.youtube.com/embed/{videoId}";
|
||||||
|
|
||||||
|
return new YouTubeVideoEmbedProjection(videoId, url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+81
-49
@@ -5,19 +5,21 @@ using System.Net;
|
|||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exceptions;
|
using DiscordChatExporter.Core.Exceptions;
|
||||||
using DiscordChatExporter.Domain.Internal;
|
using DiscordChatExporter.Core.Utils;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using JsonExtensions.Http;
|
||||||
|
using JsonExtensions.Reading;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Discord
|
namespace DiscordChatExporter.Core.Discord
|
||||||
{
|
{
|
||||||
public class DiscordClient
|
public class DiscordClient
|
||||||
{
|
{
|
||||||
private readonly HttpClient _httpClient;
|
private readonly HttpClient _httpClient;
|
||||||
private readonly AuthToken _token;
|
private readonly AuthToken _token;
|
||||||
|
|
||||||
private readonly Uri _baseUri = new Uri("https://discord.com/api/v6/", UriKind.Absolute);
|
private readonly Uri _baseUri = new("https://discord.com/api/v8/", UriKind.Absolute);
|
||||||
|
|
||||||
public DiscordClient(HttpClient httpClient, AuthToken token)
|
public DiscordClient(HttpClient httpClient, AuthToken token)
|
||||||
{
|
{
|
||||||
@@ -26,13 +28,15 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
}
|
}
|
||||||
|
|
||||||
public DiscordClient(AuthToken token)
|
public DiscordClient(AuthToken token)
|
||||||
: this(Http.Client, token) {}
|
: this(Http.Client, token)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
private async ValueTask<HttpResponseMessage> GetResponseAsync(string url) =>
|
private async ValueTask<HttpResponseMessage> GetResponseAsync(string url) =>
|
||||||
await Http.ResponsePolicy.ExecuteAsync(async () =>
|
await Http.ResponsePolicy.ExecuteAsync(async () =>
|
||||||
{
|
{
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
|
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
|
||||||
request.Headers.Authorization = _token.GetAuthorizationHeader();
|
request.Headers.Authorization = _token.GetAuthenticationHeader();
|
||||||
|
|
||||||
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
|
||||||
});
|
});
|
||||||
@@ -47,7 +51,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
{
|
{
|
||||||
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(),
|
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(),
|
||||||
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(),
|
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(),
|
||||||
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(),
|
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(url),
|
||||||
_ => DiscordChatExporterException.FailedHttpRequest(response)
|
_ => DiscordChatExporterException.FailedHttpRequest(response)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -61,20 +65,21 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
|
|
||||||
return response.IsSuccessStatusCode
|
return response.IsSuccessStatusCode
|
||||||
? await response.Content.ReadAsJsonAsync()
|
? await response.Content.ReadAsJsonAsync()
|
||||||
: (JsonElement?) null;
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async IAsyncEnumerable<Guild> GetUserGuildsAsync()
|
public async IAsyncEnumerable<Guild> GetUserGuildsAsync()
|
||||||
{
|
{
|
||||||
yield return Guild.DirectMessages;
|
yield return Guild.DirectMessages;
|
||||||
|
|
||||||
var afterId = "";
|
var currentAfter = Snowflake.Zero;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
var url = new UrlBuilder()
|
var url = new UrlBuilder()
|
||||||
.SetPath("users/@me/guilds")
|
.SetPath("users/@me/guilds")
|
||||||
.SetQueryParameter("limit", "100")
|
.SetQueryParameter("limit", "100")
|
||||||
.SetQueryParameter("after", afterId)
|
.SetQueryParameter("after", currentAfter.ToString())
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var response = await GetJsonResponseAsync(url);
|
var response = await GetJsonResponseAsync(url);
|
||||||
@@ -84,7 +89,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
{
|
{
|
||||||
yield return guild;
|
yield return guild;
|
||||||
|
|
||||||
afterId = guild.Id;
|
currentAfter = guild.Id;
|
||||||
isEmpty = false;
|
isEmpty = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +98,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async ValueTask<Guild> GetGuildAsync(string guildId)
|
public async ValueTask<Guild> GetGuildAsync(Snowflake guildId)
|
||||||
{
|
{
|
||||||
if (guildId == Guild.DirectMessages.Id)
|
if (guildId == Guild.DirectMessages.Id)
|
||||||
return Guild.DirectMessages;
|
return Guild.DirectMessages;
|
||||||
@@ -102,7 +107,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
return Guild.Parse(response);
|
return Guild.Parse(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async IAsyncEnumerable<Channel> GetGuildChannelsAsync(string guildId)
|
public async IAsyncEnumerable<Channel> GetGuildChannelsAsync(Snowflake guildId)
|
||||||
{
|
{
|
||||||
if (guildId == Guild.DirectMessages.Id)
|
if (guildId == Guild.DirectMessages.Id)
|
||||||
{
|
{
|
||||||
@@ -114,32 +119,37 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
{
|
{
|
||||||
var response = await GetJsonResponseAsync($"guilds/{guildId}/channels");
|
var response = await GetJsonResponseAsync($"guilds/{guildId}/channels");
|
||||||
|
|
||||||
var categories = response
|
var responseOrdered = response
|
||||||
.EnumerateArray()
|
.EnumerateArray()
|
||||||
.ToDictionary(
|
.OrderBy(j => j.GetProperty("position").GetInt32())
|
||||||
j => j.GetProperty("id").GetString(),
|
.ThenBy(j => Snowflake.Parse(j.GetProperty("id").GetString()))
|
||||||
j => j.GetProperty("name").GetString()
|
.ToArray();
|
||||||
);
|
|
||||||
|
|
||||||
foreach (var channelJson in response.EnumerateArray())
|
var categories = responseOrdered
|
||||||
|
.Where(j => j.GetProperty("type").GetInt32() == (int) ChannelType.GuildCategory)
|
||||||
|
.Select((j, index) => ChannelCategory.Parse(j, index + 1))
|
||||||
|
.ToDictionary(j => j.Id.ToString(), StringComparer.Ordinal);
|
||||||
|
|
||||||
|
var position = 0;
|
||||||
|
|
||||||
|
foreach (var channelJson in responseOrdered)
|
||||||
{
|
{
|
||||||
var parentId = channelJson.GetPropertyOrNull("parent_id")?.GetString();
|
var parentId = channelJson.GetPropertyOrNull("parent_id")?.GetString();
|
||||||
|
|
||||||
var category = !string.IsNullOrWhiteSpace(parentId)
|
var category = !string.IsNullOrWhiteSpace(parentId)
|
||||||
? categories.GetValueOrDefault(parentId)
|
? categories.GetValueOrDefault(parentId)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
var channel = Channel.Parse(channelJson, category);
|
var channel = Channel.Parse(channelJson, category, position);
|
||||||
|
|
||||||
// Skip non-text channels
|
position++;
|
||||||
if (!channel.IsTextChannel)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
yield return channel;
|
yield return channel;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async IAsyncEnumerable<Role> GetGuildRolesAsync(string guildId)
|
public async IAsyncEnumerable<Role> GetGuildRolesAsync(Snowflake guildId)
|
||||||
{
|
{
|
||||||
if (guildId == Guild.DirectMessages.Id)
|
if (guildId == Guild.DirectMessages.Id)
|
||||||
yield break;
|
yield break;
|
||||||
@@ -150,7 +160,7 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
yield return Role.Parse(roleJson);
|
yield return Role.Parse(roleJson);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async ValueTask<Member?> TryGetGuildMemberAsync(string guildId, User user)
|
public async ValueTask<Member?> TryGetGuildMemberAsync(Snowflake guildId, User user)
|
||||||
{
|
{
|
||||||
if (guildId == Guild.DirectMessages.Id)
|
if (guildId == Guild.DirectMessages.Id)
|
||||||
return Member.CreateForUser(user);
|
return Member.CreateForUser(user);
|
||||||
@@ -159,30 +169,40 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
return response?.Pipe(Member.Parse);
|
return response?.Pipe(Member.Parse);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async ValueTask<string> GetChannelCategoryAsync(string channelParentId)
|
public async ValueTask<ChannelCategory> GetChannelCategoryAsync(Snowflake channelId)
|
||||||
{
|
{
|
||||||
var response = await GetJsonResponseAsync($"channels/{channelParentId}");
|
try
|
||||||
return response.GetProperty("name").GetString();
|
{
|
||||||
|
var response = await GetJsonResponseAsync($"channels/{channelId}");
|
||||||
|
return ChannelCategory.Parse(response);
|
||||||
|
}
|
||||||
|
// In some cases, the Discord API returns an empty body when requesting channel category.
|
||||||
|
// Instead, we use an empty channel category as a fallback.
|
||||||
|
catch (DiscordChatExporterException)
|
||||||
|
{
|
||||||
|
return ChannelCategory.Empty;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async ValueTask<Channel> GetChannelAsync(string channelId)
|
public async ValueTask<Channel> GetChannelAsync(Snowflake channelId)
|
||||||
{
|
{
|
||||||
var response = await GetJsonResponseAsync($"channels/{channelId}");
|
var response = await GetJsonResponseAsync($"channels/{channelId}");
|
||||||
|
|
||||||
var parentId = response.GetPropertyOrNull("parent_id")?.GetString();
|
var parentId = response.GetPropertyOrNull("parent_id")?.GetString().Pipe(Snowflake.Parse);
|
||||||
var category = !string.IsNullOrWhiteSpace(parentId)
|
|
||||||
? await GetChannelCategoryAsync(parentId)
|
var category = parentId is not null
|
||||||
|
? await GetChannelCategoryAsync(parentId.Value)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
return Channel.Parse(response, category);
|
return Channel.Parse(response, category);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async ValueTask<Message?> TryGetLastMessageAsync(string channelId, DateTimeOffset? before = null)
|
private async ValueTask<Message?> TryGetLastMessageAsync(Snowflake channelId, Snowflake? before = null)
|
||||||
{
|
{
|
||||||
var url = new UrlBuilder()
|
var url = new UrlBuilder()
|
||||||
.SetPath($"channels/{channelId}/messages")
|
.SetPath($"channels/{channelId}/messages")
|
||||||
.SetQueryParameter("limit", "1")
|
.SetQueryParameter("limit", "1")
|
||||||
.SetQueryParameter("before", before?.ToSnowflake())
|
.SetQueryParameter("before", before?.ToString())
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var response = await GetJsonResponseAsync(url);
|
var response = await GetJsonResponseAsync(url);
|
||||||
@@ -190,29 +210,29 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async IAsyncEnumerable<Message> GetMessagesAsync(
|
public async IAsyncEnumerable<Message> GetMessagesAsync(
|
||||||
string channelId,
|
Snowflake channelId,
|
||||||
DateTimeOffset? after = null,
|
Snowflake? after = null,
|
||||||
DateTimeOffset? before = null,
|
Snowflake? before = null,
|
||||||
IProgress<double>? progress = null)
|
IProgress<double>? progress = null)
|
||||||
{
|
{
|
||||||
// Get the last message in the specified range.
|
// Get the last message in the specified range.
|
||||||
// This snapshots the boundaries, which means that messages posted after the exported started
|
// This snapshots the boundaries, which means that messages posted after the export started
|
||||||
// will not appear in the output.
|
// will not appear in the output.
|
||||||
// Additionally, it provides the date of the last message, which is used to calculate progress.
|
// Additionally, it provides the date of the last message, which is used to calculate progress.
|
||||||
var lastMessage = await TryGetLastMessageAsync(channelId, before);
|
var lastMessage = await TryGetLastMessageAsync(channelId, before);
|
||||||
if (lastMessage == null || lastMessage.Timestamp < after)
|
if (lastMessage is null || lastMessage.Timestamp < after?.ToDate())
|
||||||
yield break;
|
yield break;
|
||||||
|
|
||||||
// Keep track of first message in range in order to calculate progress
|
// Keep track of first message in range in order to calculate progress
|
||||||
var firstMessage = default(Message);
|
var firstMessage = default(Message);
|
||||||
var afterId = after?.ToSnowflake() ?? "0";
|
var currentAfter = after ?? Snowflake.Zero;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
var url = new UrlBuilder()
|
var url = new UrlBuilder()
|
||||||
.SetPath($"channels/{channelId}/messages")
|
.SetPath($"channels/{channelId}/messages")
|
||||||
.SetQueryParameter("limit", "100")
|
.SetQueryParameter("limit", "100")
|
||||||
.SetQueryParameter("after", afterId)
|
.SetQueryParameter("after", currentAfter.ToString())
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var response = await GetJsonResponseAsync(url);
|
var response = await GetJsonResponseAsync(url);
|
||||||
@@ -235,14 +255,26 @@ namespace DiscordChatExporter.Domain.Discord
|
|||||||
if (message.Timestamp > lastMessage.Timestamp)
|
if (message.Timestamp > lastMessage.Timestamp)
|
||||||
yield break;
|
yield break;
|
||||||
|
|
||||||
// Report progress based on the duration of parsed messages divided by total
|
// Report progress based on the duration of exported messages divided by total
|
||||||
progress?.Report(
|
if (progress is not null)
|
||||||
(message.Timestamp - firstMessage.Timestamp) /
|
{
|
||||||
(lastMessage.Timestamp - firstMessage.Timestamp)
|
var exportedDuration = (message.Timestamp - firstMessage.Timestamp).Duration();
|
||||||
);
|
var totalDuration = (lastMessage.Timestamp - firstMessage.Timestamp).Duration();
|
||||||
|
|
||||||
|
if (totalDuration > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
progress.Report(exportedDuration / totalDuration);
|
||||||
|
}
|
||||||
|
// Avoid division by zero if all messages have the exact same timestamp
|
||||||
|
// (which may be the case if there's only one message in the channel)
|
||||||
|
else
|
||||||
|
{
|
||||||
|
progress.Report(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
yield return message;
|
yield return message;
|
||||||
afterId = message.Id;
|
currentAfter = message.Id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
using System;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Discord
|
||||||
|
{
|
||||||
|
public readonly partial struct Snowflake
|
||||||
|
{
|
||||||
|
public ulong Value { get; }
|
||||||
|
|
||||||
|
public Snowflake(ulong value) => Value = value;
|
||||||
|
|
||||||
|
public DateTimeOffset ToDate() => DateTimeOffset.FromUnixTimeMilliseconds(
|
||||||
|
(long) ((Value >> 22) + 1420070400000UL)
|
||||||
|
).ToLocalTime();
|
||||||
|
|
||||||
|
public override string ToString() => Value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial struct Snowflake
|
||||||
|
{
|
||||||
|
public static Snowflake Zero { get; } = new(0);
|
||||||
|
|
||||||
|
public static Snowflake FromDate(DateTimeOffset date)
|
||||||
|
{
|
||||||
|
var value = ((ulong) date.ToUnixTimeMilliseconds() - 1420070400000UL) << 22;
|
||||||
|
return new Snowflake(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Snowflake? TryParse(string? str, IFormatProvider? formatProvider = null)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(str))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
// As number
|
||||||
|
if (Regex.IsMatch(str, @"^\d+$") &&
|
||||||
|
ulong.TryParse(str, NumberStyles.Number, formatProvider, out var value))
|
||||||
|
{
|
||||||
|
return new Snowflake(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// As date
|
||||||
|
if (DateTimeOffset.TryParse(str, formatProvider, DateTimeStyles.None, out var date))
|
||||||
|
{
|
||||||
|
return FromDate(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Snowflake Parse(string str, IFormatProvider? formatProvider) =>
|
||||||
|
TryParse(str, formatProvider) ?? throw new FormatException($"Invalid snowflake '{str}'.");
|
||||||
|
|
||||||
|
public static Snowflake Parse(string str) => Parse(str, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial struct Snowflake : IComparable<Snowflake>, IEquatable<Snowflake>
|
||||||
|
{
|
||||||
|
public int CompareTo(Snowflake other) => Value.CompareTo(other.Value);
|
||||||
|
|
||||||
|
public bool Equals(Snowflake other) => CompareTo(other) == 0;
|
||||||
|
|
||||||
|
public override bool Equals(object? obj) => obj is Snowflake other && Equals(other);
|
||||||
|
|
||||||
|
public override int GetHashCode() => Value.GetHashCode();
|
||||||
|
|
||||||
|
public static bool operator ==(Snowflake left, Snowflake right) => left.Equals(right);
|
||||||
|
|
||||||
|
public static bool operator !=(Snowflake left, Snowflake right) => !(left == right);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="JsonExtensions" Version="1.1.0" />
|
||||||
|
<PackageReference Include="MiniRazor.CodeGen" Version="2.1.2" />
|
||||||
|
<PackageReference Include="Polly" Version="7.2.2" />
|
||||||
|
<PackageReference Include="Superpower" Version="2.3.0" />
|
||||||
|
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AdditionalFiles Include="Exporting\Writers\Html\*.cshtml" IsRazorTemplate="true" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
+11
-21
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exceptions
|
namespace DiscordChatExporter.Core.Exceptions
|
||||||
{
|
{
|
||||||
public partial class DiscordChatExporterException : Exception
|
public partial class DiscordChatExporterException : Exception
|
||||||
{
|
{
|
||||||
@@ -21,35 +21,25 @@ namespace DiscordChatExporter.Domain.Exceptions
|
|||||||
var message = $@"
|
var message = $@"
|
||||||
Failed to perform an HTTP request.
|
Failed to perform an HTTP request.
|
||||||
|
|
||||||
|
[Request]
|
||||||
{response.RequestMessage}
|
{response.RequestMessage}
|
||||||
|
|
||||||
|
[Response]
|
||||||
{response}";
|
{response}";
|
||||||
|
|
||||||
return new DiscordChatExporterException(message.Trim(), true);
|
return new DiscordChatExporterException(message.Trim(), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static DiscordChatExporterException Unauthorized()
|
internal static DiscordChatExporterException Unauthorized() =>
|
||||||
{
|
new("Authentication token is invalid.");
|
||||||
const string message = "Authentication token is invalid.";
|
|
||||||
return new DiscordChatExporterException(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static DiscordChatExporterException Forbidden()
|
internal static DiscordChatExporterException Forbidden() =>
|
||||||
{
|
new("Access is forbidden.");
|
||||||
const string message = "Access is forbidden.";
|
|
||||||
return new DiscordChatExporterException(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static DiscordChatExporterException NotFound()
|
internal static DiscordChatExporterException NotFound(string resourceId) =>
|
||||||
{
|
new($"Requested resource ({resourceId}) does not exist.");
|
||||||
const string message = "Requested resource does not exist.";
|
|
||||||
return new DiscordChatExporterException(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static DiscordChatExporterException ChannelIsEmpty(string channel)
|
internal static DiscordChatExporterException ChannelIsEmpty() =>
|
||||||
{
|
new("No messages found for the specified period.");
|
||||||
var message = $"Channel '{channel}' contains no messages for the specified period.";
|
|
||||||
return new DiscordChatExporterException(message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+11
-7
@@ -2,13 +2,13 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord;
|
using DiscordChatExporter.Core.Discord;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Discord.Models.Common;
|
using DiscordChatExporter.Core.Discord.Data.Common;
|
||||||
using DiscordChatExporter.Domain.Exceptions;
|
using DiscordChatExporter.Core.Exceptions;
|
||||||
using DiscordChatExporter.Domain.Utilities;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
public class ChannelExporter
|
public class ChannelExporter
|
||||||
{
|
{
|
||||||
@@ -39,6 +39,10 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
var encounteredUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
|
var encounteredUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
|
||||||
await foreach (var message in _discord.GetMessagesAsync(request.Channel.Id, request.After, request.Before, progress))
|
await foreach (var message in _discord.GetMessagesAsync(request.Channel.Id, request.After, request.Before, progress))
|
||||||
{
|
{
|
||||||
|
// Skips any messages that fail to pass the supplied filter
|
||||||
|
if (!request.MessageFilter.Filter(message))
|
||||||
|
continue;
|
||||||
|
|
||||||
// Resolve members for referenced users
|
// Resolve members for referenced users
|
||||||
foreach (var referencedUser in message.MentionedUsers.Prepend(message.Author))
|
foreach (var referencedUser in message.MentionedUsers.Prepend(message.Author))
|
||||||
{
|
{
|
||||||
@@ -59,7 +63,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
|
|
||||||
// Throw if no messages were exported
|
// Throw if no messages were exported
|
||||||
if (!exportedAnything)
|
if (!exportedAnything)
|
||||||
throw DiscordChatExporterException.ChannelIsEmpty(request.Channel.Name);
|
throw DiscordChatExporterException.ChannelIsEmpty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+11
-13
@@ -5,11 +5,12 @@ using System.IO;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
using Tyrrrz.Extensions;
|
using Tyrrrz.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
internal class ExportContext
|
internal class ExportContext
|
||||||
{
|
{
|
||||||
@@ -44,22 +45,19 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
var dateFormat => date.ToLocalString(dateFormat)
|
var dateFormat => date.ToLocalString(dateFormat)
|
||||||
};
|
};
|
||||||
|
|
||||||
public Member? TryGetMember(string id) =>
|
public Member? TryGetMember(Snowflake id) => Members.FirstOrDefault(m => m.Id == id);
|
||||||
Members.FirstOrDefault(m => m.Id == id);
|
|
||||||
|
|
||||||
public Channel? TryGetChannel(string id) =>
|
public Channel? TryGetChannel(Snowflake id) => Channels.FirstOrDefault(c => c.Id == id);
|
||||||
Channels.FirstOrDefault(c => c.Id == id);
|
|
||||||
|
|
||||||
public Role? TryGetRole(string id) =>
|
public Role? TryGetRole(Snowflake id) => Roles.FirstOrDefault(r => r.Id == id);
|
||||||
Roles.FirstOrDefault(r => r.Id == id);
|
|
||||||
|
|
||||||
public Color? TryGetUserColor(string id)
|
public Color? TryGetUserColor(Snowflake id)
|
||||||
{
|
{
|
||||||
var member = TryGetMember(id);
|
var member = TryGetMember(id);
|
||||||
var roles = member?.RoleIds.Join(Roles, i => i, r => r.Id, (_, role) => role);
|
var roles = member?.RoleIds.Join(Roles, i => i, r => r.Id, (_, role) => role);
|
||||||
|
|
||||||
return roles?
|
return roles?
|
||||||
.Where(r => r.Color != null)
|
.Where(r => r.Color is not null)
|
||||||
.OrderByDescending(r => r.Position)
|
.OrderByDescending(r => r.Position)
|
||||||
.Select(r => r.Color)
|
.Select(r => r.Color)
|
||||||
.FirstOrDefault();
|
.FirstOrDefault();
|
||||||
@@ -81,7 +79,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
: filePath;
|
: filePath;
|
||||||
|
|
||||||
// HACK: for HTML, we need to format the URL properly
|
// HACK: for HTML, we need to format the URL properly
|
||||||
if (Request.Format == ExportFormat.HtmlDark || Request.Format == ExportFormat.HtmlLight)
|
if (Request.Format is ExportFormat.HtmlDark or ExportFormat.HtmlLight)
|
||||||
{
|
{
|
||||||
// Need to escape each path segment while keeping the directory separators intact
|
// Need to escape each path segment while keeping the directory separators intact
|
||||||
return relativeFilePath
|
return relativeFilePath
|
||||||
@@ -95,7 +93,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
// Try to catch only exceptions related to failed HTTP requests
|
// Try to catch only exceptions related to failed HTTP requests
|
||||||
// https://github.com/Tyrrrz/DiscordChatExporter/issues/332
|
// https://github.com/Tyrrrz/DiscordChatExporter/issues/332
|
||||||
// https://github.com/Tyrrrz/DiscordChatExporter/issues/372
|
// https://github.com/Tyrrrz/DiscordChatExporter/issues/372
|
||||||
catch (Exception ex) when (ex is HttpRequestException || ex is OperationCanceledException)
|
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
|
||||||
{
|
{
|
||||||
// TODO: add logging so we can be more liberal with catching exceptions
|
// TODO: add logging so we can be more liberal with catching exceptions
|
||||||
// We don't want this to crash the exporting process in case of failure
|
// We don't want this to crash the exporting process in case of failure
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
public enum ExportFormat
|
public enum ExportFormat
|
||||||
{
|
{
|
||||||
+48
-20
@@ -1,10 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using System.Text.RegularExpressions;
|
||||||
using DiscordChatExporter.Domain.Internal;
|
using DiscordChatExporter.Core.Discord;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
using DiscordChatExporter.Core.Exporting.Filtering;
|
||||||
|
using DiscordChatExporter.Core.Exporting.Partitioning;
|
||||||
|
using DiscordChatExporter.Core.Utils;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
public partial class ExportRequest
|
public partial class ExportRequest
|
||||||
{
|
{
|
||||||
@@ -22,11 +26,13 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
|
|
||||||
public ExportFormat Format { get; }
|
public ExportFormat Format { get; }
|
||||||
|
|
||||||
public DateTimeOffset? After { get; }
|
public Snowflake? After { get; }
|
||||||
|
|
||||||
public DateTimeOffset? Before { get; }
|
public Snowflake? Before { get; }
|
||||||
|
|
||||||
public int? PartitionLimit { get; }
|
public PartitionLimit PartitionLimit { get; }
|
||||||
|
|
||||||
|
public MessageFilter MessageFilter { get; }
|
||||||
|
|
||||||
public bool ShouldDownloadMedia { get; }
|
public bool ShouldDownloadMedia { get; }
|
||||||
|
|
||||||
@@ -39,9 +45,10 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
Channel channel,
|
Channel channel,
|
||||||
string outputPath,
|
string outputPath,
|
||||||
ExportFormat format,
|
ExportFormat format,
|
||||||
DateTimeOffset? after,
|
Snowflake? after,
|
||||||
DateTimeOffset? before,
|
Snowflake? before,
|
||||||
int? partitionLimit,
|
PartitionLimit partitionLimit,
|
||||||
|
MessageFilter messageFilter,
|
||||||
bool shouldDownloadMedia,
|
bool shouldDownloadMedia,
|
||||||
bool shouldReuseMedia,
|
bool shouldReuseMedia,
|
||||||
string dateFormat)
|
string dateFormat)
|
||||||
@@ -53,6 +60,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
After = after;
|
After = after;
|
||||||
Before = before;
|
Before = before;
|
||||||
PartitionLimit = partitionLimit;
|
PartitionLimit = partitionLimit;
|
||||||
|
MessageFilter = messageFilter;
|
||||||
ShouldDownloadMedia = shouldDownloadMedia;
|
ShouldDownloadMedia = shouldDownloadMedia;
|
||||||
ShouldReuseMedia = shouldReuseMedia;
|
ShouldReuseMedia = shouldReuseMedia;
|
||||||
DateFormat = dateFormat;
|
DateFormat = dateFormat;
|
||||||
@@ -78,9 +86,29 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
Channel channel,
|
Channel channel,
|
||||||
string outputPath,
|
string outputPath,
|
||||||
ExportFormat format,
|
ExportFormat format,
|
||||||
DateTimeOffset? after = null,
|
Snowflake? after = null,
|
||||||
DateTimeOffset? before = null)
|
Snowflake? before = null)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
// Formats path
|
||||||
|
outputPath = Regex.Replace(outputPath, "%.", m =>
|
||||||
|
PathEx.EscapePath(m.Value switch
|
||||||
|
{
|
||||||
|
"%g" => guild.Id.ToString(),
|
||||||
|
"%G" => guild.Name,
|
||||||
|
"%t" => channel.Category.Id.ToString(),
|
||||||
|
"%T" => channel.Category.Name,
|
||||||
|
"%c" => channel.Id.ToString(),
|
||||||
|
"%C" => channel.Name,
|
||||||
|
"%p" => channel.Position?.ToString() ?? "0",
|
||||||
|
"%P" => channel.Category.Position?.ToString() ?? "0",
|
||||||
|
"%a" => (after ?? Snowflake.Zero).ToDate().ToString("yyyy-MM-dd"),
|
||||||
|
"%b" => (before?.ToDate() ?? DateTime.Now).ToString("yyyy-MM-dd"),
|
||||||
|
"%%" => "%",
|
||||||
|
_ => m.Value
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
// Output is a directory
|
// Output is a directory
|
||||||
if (Directory.Exists(outputPath) || string.IsNullOrWhiteSpace(Path.GetExtension(outputPath)))
|
if (Directory.Exists(outputPath) || string.IsNullOrWhiteSpace(Path.GetExtension(outputPath)))
|
||||||
{
|
{
|
||||||
@@ -96,33 +124,33 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
Guild guild,
|
Guild guild,
|
||||||
Channel channel,
|
Channel channel,
|
||||||
ExportFormat format,
|
ExportFormat format,
|
||||||
DateTimeOffset? after = null,
|
Snowflake? after = null,
|
||||||
DateTimeOffset? before = null)
|
Snowflake? before = null)
|
||||||
{
|
{
|
||||||
var buffer = new StringBuilder();
|
var buffer = new StringBuilder();
|
||||||
|
|
||||||
// Guild and channel names
|
// Guild and channel names
|
||||||
buffer.Append($"{guild.Name} - {channel.Category} - {channel.Name} [{channel.Id}]");
|
buffer.Append($"{guild.Name} - {channel.Category.Name} - {channel.Name} [{channel.Id}]");
|
||||||
|
|
||||||
// Date range
|
// Date range
|
||||||
if (after != null || before != null)
|
if (after is not null || before is not null)
|
||||||
{
|
{
|
||||||
buffer.Append(" (");
|
buffer.Append(" (");
|
||||||
|
|
||||||
// Both 'after' and 'before' are set
|
// Both 'after' and 'before' are set
|
||||||
if (after != null && before != null)
|
if (after is not null && before is not null)
|
||||||
{
|
{
|
||||||
buffer.Append($"{after:yyyy-MM-dd} to {before:yyyy-MM-dd}");
|
buffer.Append($"{after?.ToDate():yyyy-MM-dd} to {before?.ToDate():yyyy-MM-dd}");
|
||||||
}
|
}
|
||||||
// Only 'after' is set
|
// Only 'after' is set
|
||||||
else if (after != null)
|
else if (after is not null)
|
||||||
{
|
{
|
||||||
buffer.Append($"after {after:yyyy-MM-dd}");
|
buffer.Append($"after {after?.ToDate():yyyy-MM-dd}");
|
||||||
}
|
}
|
||||||
// Only 'before' is set
|
// Only 'before' is set
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
buffer.Append($"before {before:yyyy-MM-dd}");
|
buffer.Append($"before {before?.ToDate():yyyy-MM-dd}");
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.Append(")");
|
buffer.Append(")");
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal enum BinaryExpressionKind
|
||||||
|
{
|
||||||
|
Or,
|
||||||
|
And
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class BinaryExpressionMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly MessageFilter _first;
|
||||||
|
private readonly MessageFilter _second;
|
||||||
|
private readonly BinaryExpressionKind _kind;
|
||||||
|
|
||||||
|
public BinaryExpressionMessageFilter(MessageFilter first, MessageFilter second, BinaryExpressionKind kind)
|
||||||
|
{
|
||||||
|
_first = first;
|
||||||
|
_second = second;
|
||||||
|
_kind = kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Filter(Message message) => _kind switch
|
||||||
|
{
|
||||||
|
BinaryExpressionKind.Or => _first.Filter(message) || _second.Filter(message),
|
||||||
|
BinaryExpressionKind.And => _first.Filter(message) && _second.Filter(message),
|
||||||
|
_ => throw new InvalidOperationException($"Unknown binary expression kind '{_kind}'.")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class ContainsMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly string _text;
|
||||||
|
|
||||||
|
public ContainsMessageFilter(string text) => _text = text;
|
||||||
|
|
||||||
|
public override bool Filter(Message message) => Regex.IsMatch(
|
||||||
|
message.Content,
|
||||||
|
"\\b" + _text + "\\b",
|
||||||
|
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class FromMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly string _value;
|
||||||
|
|
||||||
|
public FromMessageFilter(string value) => _value = value;
|
||||||
|
|
||||||
|
public override bool Filter(Message message) =>
|
||||||
|
string.Equals(_value, message.Author.Name, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(_value, message.Author.FullName, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(_value, message.Author.Id.ToString(), StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class HasMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly MessageContentMatchKind _kind;
|
||||||
|
|
||||||
|
public HasMessageFilter(MessageContentMatchKind kind) => _kind = kind;
|
||||||
|
|
||||||
|
public override bool Filter(Message message) => _kind switch
|
||||||
|
{
|
||||||
|
MessageContentMatchKind.Link => Regex.IsMatch(message.Content, "https?://\\S*[^\\.,:;\"\'\\s]"),
|
||||||
|
MessageContentMatchKind.Embed => message.Embeds.Any(),
|
||||||
|
MessageContentMatchKind.File => message.Attachments.Any(),
|
||||||
|
MessageContentMatchKind.Video => message.Attachments.Any(file => file.IsVideo),
|
||||||
|
MessageContentMatchKind.Image => message.Attachments.Any(file => file.IsImage),
|
||||||
|
MessageContentMatchKind.Sound => message.Attachments.Any(file => file.IsAudio),
|
||||||
|
_ => throw new InvalidOperationException($"Unknown message content match kind '{_kind}'.")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class MentionsMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly string _value;
|
||||||
|
|
||||||
|
public MentionsMessageFilter(string value) => _value = value;
|
||||||
|
|
||||||
|
public override bool Filter(Message message) => message.MentionedUsers.Any(user =>
|
||||||
|
string.Equals(_value, user.Name, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(_value, user.FullName, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(_value, user.Id.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal enum MessageContentMatchKind
|
||||||
|
{
|
||||||
|
Link,
|
||||||
|
Embed,
|
||||||
|
File,
|
||||||
|
Video,
|
||||||
|
Image,
|
||||||
|
Sound
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
using DiscordChatExporter.Core.Exporting.Filtering.Parsing;
|
||||||
|
using Superpower;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
public abstract partial class MessageFilter
|
||||||
|
{
|
||||||
|
public abstract bool Filter(Message message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class MessageFilter
|
||||||
|
{
|
||||||
|
public static MessageFilter Null { get; } = new NullMessageFilter();
|
||||||
|
|
||||||
|
public static MessageFilter Parse(string value) => FilterGrammar.Filter.Parse(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class NegatedMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
private readonly MessageFilter _filter;
|
||||||
|
|
||||||
|
public NegatedMessageFilter(MessageFilter filter) => _filter = filter;
|
||||||
|
|
||||||
|
public override bool Filter(Message message) => !_filter.Filter(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering
|
||||||
|
{
|
||||||
|
internal class NullMessageFilter : MessageFilter
|
||||||
|
{
|
||||||
|
public override bool Filter(Message message) => true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
using System.Linq;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
using Superpower;
|
||||||
|
using Superpower.Parsers;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Filtering.Parsing
|
||||||
|
{
|
||||||
|
internal static class FilterGrammar
|
||||||
|
{
|
||||||
|
// Choice(a, b) looks cleaner than a.Or(b)
|
||||||
|
private static TextParser<T> Choice<T>(params TextParser<T>[] parsers) =>
|
||||||
|
parsers.Aggregate((current, next) => current.Or(next));
|
||||||
|
|
||||||
|
private static readonly TextParser<char> EscapedCharacter =
|
||||||
|
Character.EqualTo('\\').IgnoreThen(Character.AnyChar);
|
||||||
|
|
||||||
|
private static readonly TextParser<string> QuotedString =
|
||||||
|
from open in Character.In('"', '\'')
|
||||||
|
from value in Choice(EscapedCharacter, Character.Except(open)).Many().Text()
|
||||||
|
from close in Character.EqualTo(open)
|
||||||
|
select value;
|
||||||
|
|
||||||
|
private static readonly TextParser<char> FreeCharacter =
|
||||||
|
Character.Matching(c =>
|
||||||
|
!char.IsWhiteSpace(c) &&
|
||||||
|
// Avoid all special tokens used by the grammar
|
||||||
|
c is not ('(' or ')' or '"' or '\'' or '-' or '|' or '&'),
|
||||||
|
"any character except whitespace or `(`, `)`, `\"`, `'`, `-`, `|`, `&`"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static readonly TextParser<string> UnquotedString =
|
||||||
|
Choice(EscapedCharacter, FreeCharacter).AtLeastOnce().Text();
|
||||||
|
|
||||||
|
private static readonly TextParser<string> String =
|
||||||
|
Choice(QuotedString, UnquotedString).Named("text string");
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> ContainsFilter =
|
||||||
|
String.Select(v => (MessageFilter) new ContainsMessageFilter(v));
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> FromFilter = Span
|
||||||
|
.EqualToIgnoreCase("from:")
|
||||||
|
.IgnoreThen(String)
|
||||||
|
.Select(v => (MessageFilter) new FromMessageFilter(v))
|
||||||
|
.Named("from:<value>");
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> MentionsFilter = Span
|
||||||
|
.EqualToIgnoreCase("mentions:")
|
||||||
|
.IgnoreThen(String)
|
||||||
|
.Select(v => (MessageFilter) new MentionsMessageFilter(v))
|
||||||
|
.Named("mentions:<value>");
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> HasFilter = Span
|
||||||
|
.EqualToIgnoreCase("has:")
|
||||||
|
.IgnoreThen(Choice(
|
||||||
|
Span.EqualToIgnoreCase("link").IgnoreThen(Parse.Return(MessageContentMatchKind.Link)),
|
||||||
|
Span.EqualToIgnoreCase("embed").IgnoreThen(Parse.Return(MessageContentMatchKind.Embed)),
|
||||||
|
Span.EqualToIgnoreCase("video").IgnoreThen(Parse.Return(MessageContentMatchKind.Video)),
|
||||||
|
Span.EqualToIgnoreCase("image").IgnoreThen(Parse.Return(MessageContentMatchKind.Image)),
|
||||||
|
Span.EqualToIgnoreCase("sound").IgnoreThen(Parse.Return(MessageContentMatchKind.Sound))
|
||||||
|
))
|
||||||
|
.Select(k => (MessageFilter) new HasMessageFilter(k))
|
||||||
|
.Named("has:<value>");
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> NegatedFilter = Character
|
||||||
|
.EqualTo('-')
|
||||||
|
.IgnoreThen(Parse.Ref(() => StandaloneFilter))
|
||||||
|
.Select(f => (MessageFilter) new NegatedMessageFilter(f));
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> GroupedFilter =
|
||||||
|
from open in Character.EqualTo('(')
|
||||||
|
from content in Parse.Ref(() => BinaryExpressionFilter).Token()
|
||||||
|
from close in Character.EqualTo(')')
|
||||||
|
select content;
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> StandaloneFilter = Choice(
|
||||||
|
GroupedFilter,
|
||||||
|
FromFilter,
|
||||||
|
MentionsFilter,
|
||||||
|
HasFilter,
|
||||||
|
ContainsFilter
|
||||||
|
);
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> UnaryExpressionFilter = Choice(
|
||||||
|
NegatedFilter,
|
||||||
|
StandaloneFilter
|
||||||
|
);
|
||||||
|
|
||||||
|
private static readonly TextParser<MessageFilter> BinaryExpressionFilter = Parse.Chain(
|
||||||
|
Choice(
|
||||||
|
// Explicit operator
|
||||||
|
Character.In('|', '&').Token().Try(),
|
||||||
|
// Implicit operator (resolves to 'and')
|
||||||
|
Character.WhiteSpace.AtLeastOnce().IgnoreThen(Parse.Return(' '))
|
||||||
|
),
|
||||||
|
UnaryExpressionFilter,
|
||||||
|
(op, left, right) => op switch
|
||||||
|
{
|
||||||
|
'|' => new BinaryExpressionMessageFilter(left, right, BinaryExpressionKind.Or),
|
||||||
|
_ => new BinaryExpressionMessageFilter(left, right, BinaryExpressionKind.And)
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
public static readonly TextParser<MessageFilter> Filter =
|
||||||
|
BinaryExpressionFilter.Token().AtEnd();
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
-9
@@ -1,15 +1,16 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Internal;
|
using DiscordChatExporter.Core.Utils;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
internal partial class MediaDownloader
|
internal partial class MediaDownloader
|
||||||
{
|
{
|
||||||
@@ -18,8 +19,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
private readonly bool _reuseMedia;
|
private readonly bool _reuseMedia;
|
||||||
|
|
||||||
// URL -> Local file path
|
// URL -> Local file path
|
||||||
private readonly Dictionary<string, string> _pathCache =
|
private readonly Dictionary<string, string> _pathCache = new(StringComparer.Ordinal);
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal);
|
|
||||||
|
|
||||||
public MediaDownloader(HttpClient httpClient, string workingDirPath, bool reuseMedia)
|
public MediaDownloader(HttpClient httpClient, string workingDirPath, bool reuseMedia)
|
||||||
{
|
{
|
||||||
@@ -43,12 +43,41 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
if (_reuseMedia && File.Exists(filePath))
|
if (_reuseMedia && File.Exists(filePath))
|
||||||
return _pathCache[url] = filePath;
|
return _pathCache[url] = filePath;
|
||||||
|
|
||||||
// Download it
|
|
||||||
Directory.CreateDirectory(_workingDirPath);
|
Directory.CreateDirectory(_workingDirPath);
|
||||||
|
|
||||||
|
// This retries on IOExceptions which is dangerous as we're also working with files
|
||||||
await Http.ExceptionPolicy.ExecuteAsync(async () =>
|
await Http.ExceptionPolicy.ExecuteAsync(async () =>
|
||||||
{
|
{
|
||||||
// This catches IOExceptions which is dangerous as we're working also with files
|
// Download the file
|
||||||
await _httpClient.DownloadAsync(url, filePath);
|
using var response = await _httpClient.GetAsync(url);
|
||||||
|
await using (var output = File.Create(filePath))
|
||||||
|
{
|
||||||
|
await response.Content.CopyToAsync(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to set the file date according to the last-modified header
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var lastModified = response.Content.Headers.TryGetValue("Last-Modified")?.Pipe(s =>
|
||||||
|
DateTimeOffset.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
|
||||||
|
? date
|
||||||
|
: (DateTimeOffset?) null
|
||||||
|
);
|
||||||
|
|
||||||
|
if (lastModified is not null)
|
||||||
|
{
|
||||||
|
File.SetCreationTimeUtc(filePath, lastModified.Value.UtcDateTime);
|
||||||
|
File.SetLastWriteTimeUtc(filePath, lastModified.Value.UtcDateTime);
|
||||||
|
File.SetLastAccessTimeUtc(filePath, lastModified.Value.UtcDateTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// This can apparently fail for some reason.
|
||||||
|
// https://github.com/Tyrrrz/DiscordChatExporter/issues/585
|
||||||
|
// Updating file dates is not a critical task, so we'll just
|
||||||
|
// ignore exceptions thrown here.
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return _pathCache[url] = filePath;
|
return _pathCache[url] = filePath;
|
||||||
@@ -83,4 +112,4 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
return PathEx.EscapePath(fileNameWithoutExtension.Truncate(42) + '-' + urlHash + fileExtension);
|
return PathEx.EscapePath(fileNameWithoutExtension.Truncate(42) + '-' + urlHash + fileExtension);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+8
-17
@@ -1,16 +1,15 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exporting.Writers;
|
using DiscordChatExporter.Core.Exporting.Writers;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting
|
namespace DiscordChatExporter.Core.Exporting
|
||||||
{
|
{
|
||||||
internal partial class MessageExporter : IAsyncDisposable
|
internal partial class MessageExporter : IAsyncDisposable
|
||||||
{
|
{
|
||||||
private readonly ExportContext _context;
|
private readonly ExportContext _context;
|
||||||
|
|
||||||
private long _messageCount;
|
|
||||||
private int _partitionIndex;
|
private int _partitionIndex;
|
||||||
private MessageWriter? _writer;
|
private MessageWriter? _writer;
|
||||||
|
|
||||||
@@ -19,15 +18,9 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
_context = context;
|
_context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsPartitionLimitReached() =>
|
|
||||||
_messageCount > 0 &&
|
|
||||||
_context.Request.PartitionLimit != null &&
|
|
||||||
_context.Request.PartitionLimit != 0 &&
|
|
||||||
_messageCount % _context.Request.PartitionLimit == 0;
|
|
||||||
|
|
||||||
private async ValueTask ResetWriterAsync()
|
private async ValueTask ResetWriterAsync()
|
||||||
{
|
{
|
||||||
if (_writer != null)
|
if (_writer is not null)
|
||||||
{
|
{
|
||||||
await _writer.WritePostambleAsync();
|
await _writer.WritePostambleAsync();
|
||||||
await _writer.DisposeAsync();
|
await _writer.DisposeAsync();
|
||||||
@@ -38,14 +31,15 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
private async ValueTask<MessageWriter> GetWriterAsync()
|
private async ValueTask<MessageWriter> GetWriterAsync()
|
||||||
{
|
{
|
||||||
// Ensure partition limit has not been exceeded
|
// Ensure partition limit has not been exceeded
|
||||||
if (IsPartitionLimitReached())
|
if (_writer is not null &&
|
||||||
|
_context.Request.PartitionLimit.IsReached(_writer.MessagesWritten, _writer.BytesWritten))
|
||||||
{
|
{
|
||||||
await ResetWriterAsync();
|
await ResetWriterAsync();
|
||||||
_partitionIndex++;
|
_partitionIndex++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Writer is still valid - return
|
// Writer is still valid - return
|
||||||
if (_writer != null)
|
if (_writer is not null)
|
||||||
return _writer;
|
return _writer;
|
||||||
|
|
||||||
var filePath = GetPartitionFilePath(_context.Request.OutputBaseFilePath, _partitionIndex);
|
var filePath = GetPartitionFilePath(_context.Request.OutputBaseFilePath, _partitionIndex);
|
||||||
@@ -64,7 +58,6 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
{
|
{
|
||||||
var writer = await GetWriterAsync();
|
var writer = await GetWriterAsync();
|
||||||
await writer.WriteMessageAsync(message);
|
await writer.WriteMessageAsync(message);
|
||||||
_messageCount++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async ValueTask DisposeAsync() => await ResetWriterAsync();
|
public async ValueTask DisposeAsync() => await ResetWriterAsync();
|
||||||
@@ -72,9 +65,7 @@ namespace DiscordChatExporter.Domain.Exporting
|
|||||||
|
|
||||||
internal partial class MessageExporter
|
internal partial class MessageExporter
|
||||||
{
|
{
|
||||||
private static string GetPartitionFilePath(
|
private static string GetPartitionFilePath(string baseFilePath, int partitionIndex)
|
||||||
string baseFilePath,
|
|
||||||
int partitionIndex)
|
|
||||||
{
|
{
|
||||||
// First partition - don't change file name
|
// First partition - don't change file name
|
||||||
if (partitionIndex <= 0)
|
if (partitionIndex <= 0)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Partitioning
|
||||||
|
{
|
||||||
|
internal class FileSizePartitionLimit : PartitionLimit
|
||||||
|
{
|
||||||
|
private readonly long _limit;
|
||||||
|
|
||||||
|
public FileSizePartitionLimit(long limit) => _limit = limit;
|
||||||
|
|
||||||
|
public override bool IsReached(long messagesWritten, long bytesWritten) =>
|
||||||
|
bytesWritten >= _limit;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Partitioning
|
||||||
|
{
|
||||||
|
internal class MessageCountPartitionLimit : PartitionLimit
|
||||||
|
{
|
||||||
|
private readonly long _limit;
|
||||||
|
|
||||||
|
public MessageCountPartitionLimit(long limit) => _limit = limit;
|
||||||
|
|
||||||
|
public override bool IsReached(long messagesWritten, long bytesWritten) =>
|
||||||
|
messagesWritten >= _limit;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Partitioning
|
||||||
|
{
|
||||||
|
internal class NullPartitionLimit : PartitionLimit
|
||||||
|
{
|
||||||
|
public override bool IsReached(long messagesWritten, long bytesWritten) => false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Exporting.Partitioning
|
||||||
|
{
|
||||||
|
public abstract partial class PartitionLimit
|
||||||
|
{
|
||||||
|
public abstract bool IsReached(long messagesWritten, long bytesWritten);
|
||||||
|
}
|
||||||
|
|
||||||
|
public partial class PartitionLimit
|
||||||
|
{
|
||||||
|
public static PartitionLimit Null { get; } = new NullPartitionLimit();
|
||||||
|
|
||||||
|
private static long? TryParseFileSizeBytes(string value, IFormatProvider? formatProvider = null)
|
||||||
|
{
|
||||||
|
var match = Regex.Match(value, @"^\s*(\d+[\.,]?\d*)\s*(\w)?b\s*$", RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
// Number part
|
||||||
|
if (!double.TryParse(
|
||||||
|
match.Groups[1].Value,
|
||||||
|
NumberStyles.Float,
|
||||||
|
formatProvider,
|
||||||
|
out var number))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Magnitude part
|
||||||
|
var magnitude = match.Groups[2].Value.ToUpperInvariant() switch
|
||||||
|
{
|
||||||
|
"G" => 1_000_000_000,
|
||||||
|
"M" => 1_000_000,
|
||||||
|
"K" => 1_000,
|
||||||
|
"" => 1,
|
||||||
|
_ => -1
|
||||||
|
};
|
||||||
|
|
||||||
|
if (magnitude < 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (long) (number * magnitude);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PartitionLimit? TryParse(string value, IFormatProvider? formatProvider = null)
|
||||||
|
{
|
||||||
|
var fileSizeLimit = TryParseFileSizeBytes(value, formatProvider);
|
||||||
|
if (fileSizeLimit is not null)
|
||||||
|
return new FileSizePartitionLimit(fileSizeLimit.Value);
|
||||||
|
|
||||||
|
if (int.TryParse(value, NumberStyles.Integer, formatProvider, out var messageCountLimit))
|
||||||
|
return new MessageCountPartitionLimit(messageCountLimit);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PartitionLimit Parse(string value, IFormatProvider? formatProvider = null) =>
|
||||||
|
TryParse(value, formatProvider) ?? throw new FormatException($"Invalid partition limit '{value}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-5
@@ -2,11 +2,11 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
using DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
namespace DiscordChatExporter.Core.Exporting.Writers
|
||||||
{
|
{
|
||||||
internal partial class CsvMessageWriter : MessageWriter
|
internal partial class CsvMessageWriter : MessageWriter
|
||||||
{
|
{
|
||||||
@@ -58,8 +58,10 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
public override async ValueTask WriteMessageAsync(Message message)
|
public override async ValueTask WriteMessageAsync(Message message)
|
||||||
{
|
{
|
||||||
|
await base.WriteMessageAsync(message);
|
||||||
|
|
||||||
// Author ID
|
// Author ID
|
||||||
await _writer.WriteAsync(CsvEncode(message.Author.Id));
|
await _writer.WriteAsync(CsvEncode(message.Author.Id.ToString()));
|
||||||
await _writer.WriteAsync(',');
|
await _writer.WriteAsync(',');
|
||||||
|
|
||||||
// Author name
|
// Author name
|
||||||
+23
-5
@@ -1,9 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers.Html
|
namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
{
|
{
|
||||||
// Used for grouping contiguous messages in HTML export
|
// Used for grouping contiguous messages in HTML export
|
||||||
internal partial class MessageGroup
|
internal partial class MessageGroup
|
||||||
@@ -14,10 +14,21 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.Html
|
|||||||
|
|
||||||
public IReadOnlyList<Message> Messages { get; }
|
public IReadOnlyList<Message> Messages { get; }
|
||||||
|
|
||||||
public MessageGroup(User author, DateTimeOffset timestamp, IReadOnlyList<Message> messages)
|
public MessageReference? Reference { get; }
|
||||||
|
|
||||||
|
public Message? ReferencedMessage {get; }
|
||||||
|
|
||||||
|
public MessageGroup(
|
||||||
|
User author,
|
||||||
|
DateTimeOffset timestamp,
|
||||||
|
MessageReference? reference,
|
||||||
|
Message? referencedMessage,
|
||||||
|
IReadOnlyList<Message> messages)
|
||||||
{
|
{
|
||||||
Author = author;
|
Author = author;
|
||||||
Timestamp = timestamp;
|
Timestamp = timestamp;
|
||||||
|
Reference = reference;
|
||||||
|
ReferencedMessage = referencedMessage;
|
||||||
Messages = messages;
|
Messages = messages;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -25,9 +36,14 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.Html
|
|||||||
internal partial class MessageGroup
|
internal partial class MessageGroup
|
||||||
{
|
{
|
||||||
public static bool CanJoin(Message message1, Message message2) =>
|
public static bool CanJoin(Message message1, Message message2) =>
|
||||||
string.Equals(message1.Author.Id, message2.Author.Id, StringComparison.Ordinal) &&
|
// Must be from the same author
|
||||||
|
message1.Author.Id == message2.Author.Id &&
|
||||||
|
// Author's name must not have changed between messages
|
||||||
string.Equals(message1.Author.FullName, message2.Author.FullName, StringComparison.Ordinal) &&
|
string.Equals(message1.Author.FullName, message2.Author.FullName, StringComparison.Ordinal) &&
|
||||||
(message2.Timestamp - message1.Timestamp).Duration().TotalMinutes <= 7;
|
// Duration between messages must be 7 minutes or less
|
||||||
|
(message2.Timestamp - message1.Timestamp).Duration().TotalMinutes <= 7 &&
|
||||||
|
// Other message must not be a reply
|
||||||
|
message2.Reference is null;
|
||||||
|
|
||||||
public static MessageGroup Join(IReadOnlyList<Message> messages)
|
public static MessageGroup Join(IReadOnlyList<Message> messages)
|
||||||
{
|
{
|
||||||
@@ -36,6 +52,8 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.Html
|
|||||||
return new MessageGroup(
|
return new MessageGroup(
|
||||||
first.Author,
|
first.Author,
|
||||||
first.Timestamp,
|
first.Timestamp,
|
||||||
|
first.Reference,
|
||||||
|
first.ReferencedMessage,
|
||||||
messages
|
messages
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
+160
-57
@@ -1,7 +1,10 @@
|
|||||||
@using System
|
@using System
|
||||||
@using System.Linq
|
@using System.Linq
|
||||||
@using System.Threading.Tasks
|
@using System.Threading.Tasks
|
||||||
@inherits MiniRazor.MiniRazorTemplateBase<DiscordChatExporter.Domain.Exporting.Writers.Html.MessageGroupTemplateContext>
|
@using DiscordChatExporter.Core.Exporting.Writers.Html;
|
||||||
|
|
||||||
|
@namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
|
@inherits MiniRazor.TemplateBase<MessageGroupTemplateContext>
|
||||||
|
|
||||||
@{
|
@{
|
||||||
string FormatDate(DateTimeOffset date) => Model.ExportContext.FormatDate(date);
|
string FormatDate(DateTimeOffset date) => Model.ExportContext.FormatDate(date);
|
||||||
@@ -13,40 +16,108 @@
|
|||||||
ValueTask<string> ResolveUrlAsync(string url) => Model.ExportContext.ResolveMediaUrlAsync(url);
|
ValueTask<string> ResolveUrlAsync(string url) => Model.ExportContext.ResolveMediaUrlAsync(url);
|
||||||
|
|
||||||
var userMember = Model.ExportContext.TryGetMember(Model.MessageGroup.Author.Id);
|
var userMember = Model.ExportContext.TryGetMember(Model.MessageGroup.Author.Id);
|
||||||
var userColor = Model.ExportContext.TryGetUserColor(Model.MessageGroup.Author.Id);
|
|
||||||
var userNick = Model.MessageGroup.Author.IsBot ? Model.MessageGroup.Author.Name : userMember?.Nick ?? Model.MessageGroup.Author.Name;
|
|
||||||
|
|
||||||
var userColorStyle = userColor != null
|
var userColor = Model.ExportContext.TryGetUserColor(Model.MessageGroup.Author.Id);
|
||||||
|
|
||||||
|
var userColorStyle = userColor is not null
|
||||||
? $"color: rgb({userColor?.R},{userColor?.G},{userColor?.B})"
|
? $"color: rgb({userColor?.R},{userColor?.G},{userColor?.B})"
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
var userNick = Model.MessageGroup.Author.IsBot
|
||||||
|
? Model.MessageGroup.Author.Name
|
||||||
|
: userMember?.Nick ?? Model.MessageGroup.Author.Name;
|
||||||
|
|
||||||
|
var referencedUserMember = Model.MessageGroup.ReferencedMessage is not null
|
||||||
|
? Model.ExportContext.TryGetMember(Model.MessageGroup.ReferencedMessage.Author.Id)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
var referencedUserColor = Model.MessageGroup.ReferencedMessage is not null
|
||||||
|
? Model.ExportContext.TryGetUserColor(Model.MessageGroup.ReferencedMessage.Author.Id)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
var referencedUserColorStyle = referencedUserColor is not null
|
||||||
|
? $"color: rgb({referencedUserColor?.R},{referencedUserColor?.G},{referencedUserColor?.B})"
|
||||||
|
: null;
|
||||||
|
|
||||||
|
var referencedUserNick = Model.MessageGroup.ReferencedMessage is not null
|
||||||
|
? Model.MessageGroup.ReferencedMessage.Author.IsBot
|
||||||
|
? Model.MessageGroup.ReferencedMessage.Author.Name
|
||||||
|
: referencedUserMember?.Nick ?? Model.MessageGroup.ReferencedMessage.Author.Name
|
||||||
|
: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="chatlog__message-group">
|
<div class="chatlog__message-group">
|
||||||
|
@{/* Referenced message */}
|
||||||
|
@if (Model.MessageGroup.Reference is not null)
|
||||||
|
{
|
||||||
|
<div class="chatlog__reference-symbol"></div>
|
||||||
|
<div class="chatlog__reference">
|
||||||
|
@if (Model.MessageGroup.ReferencedMessage is not null)
|
||||||
|
{
|
||||||
|
<img class="chatlog__reference-avatar" src="@await ResolveUrlAsync(Model.MessageGroup.ReferencedMessage.Author.AvatarUrl)" alt="Avatar" loading="lazy">
|
||||||
|
<span class="chatlog__reference-name" title="@Model.MessageGroup.ReferencedMessage.Author.FullName" style="@referencedUserColorStyle">@referencedUserNick</span>
|
||||||
|
<div class="chatlog__reference-content">
|
||||||
|
<span class="chatlog__reference-link" onclick="scrollToMessage(event, '@Model.MessageGroup.ReferencedMessage.Id')">
|
||||||
|
@if (!string.IsNullOrWhiteSpace(Model.MessageGroup.ReferencedMessage.Content))
|
||||||
|
{
|
||||||
|
@Raw(FormatEmbedMarkdown(Model.MessageGroup.ReferencedMessage.Content))
|
||||||
|
}
|
||||||
|
else if (Model.MessageGroup.ReferencedMessage.Attachments.Any() || Model.MessageGroup.ReferencedMessage.Embeds.Any())
|
||||||
|
{
|
||||||
|
<em>Click to see attachment</em> <span>🖼️</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<em>Click to see original message</em>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
@if (Model.MessageGroup.ReferencedMessage.EditedTimestamp is not null)
|
||||||
|
{
|
||||||
|
<span class="chatlog__reference-edited-timestamp" title="@FormatDate(Model.MessageGroup.ReferencedMessage.EditedTimestamp.Value)">(edited)</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="chatlog__reference-unknown">
|
||||||
|
Original message was deleted.
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@{/* Avatar */}
|
||||||
<div class="chatlog__author-avatar-container">
|
<div class="chatlog__author-avatar-container">
|
||||||
<img class="chatlog__author-avatar" src="@await ResolveUrlAsync(Model.MessageGroup.Author.AvatarUrl)" alt="Avatar">
|
<img class="chatlog__author-avatar" src="@await ResolveUrlAsync(Model.MessageGroup.Author.AvatarUrl)" alt="Avatar" loading="lazy">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="chatlog__messages">
|
<div class="chatlog__messages">
|
||||||
|
@{/* Author name */}
|
||||||
<span class="chatlog__author-name" title="@Model.MessageGroup.Author.FullName" data-user-id="@Model.MessageGroup.Author.Id" style="@userColorStyle">@userNick</span>
|
<span class="chatlog__author-name" title="@Model.MessageGroup.Author.FullName" data-user-id="@Model.MessageGroup.Author.Id" style="@userColorStyle">@userNick</span>
|
||||||
|
|
||||||
|
@{/* Bot tag */}
|
||||||
@if (Model.MessageGroup.Author.IsBot)
|
@if (Model.MessageGroup.Author.IsBot)
|
||||||
{
|
{
|
||||||
<span class="chatlog__bot-tag">BOT</span>
|
<span class="chatlog__bot-tag">BOT</span>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Message timestamp */}
|
||||||
<span class="chatlog__timestamp">@FormatDate(Model.MessageGroup.Timestamp)</span>
|
<span class="chatlog__timestamp">@FormatDate(Model.MessageGroup.Timestamp)</span>
|
||||||
|
|
||||||
|
@{/* Messages in a group */}
|
||||||
@foreach (var message in Model.MessageGroup.Messages)
|
@foreach (var message in Model.MessageGroup.Messages)
|
||||||
{
|
{
|
||||||
var isPinnedStyle = message.IsPinned ? "chatlog__message--pinned" : null;
|
<div class="chatlog__message @(message.IsPinned ? "chatlog__message--pinned" : null)" data-message-id="@message.Id" id="message-@message.Id" title="Message sent: @FormatDate(message.Timestamp)">
|
||||||
|
@if (!string.IsNullOrWhiteSpace(message.Content) || message.EditedTimestamp is not null)
|
||||||
<div class="chatlog__message @isPinnedStyle" data-message-id="@message.Id" id="message-@message.Id">
|
|
||||||
@if (!string.IsNullOrWhiteSpace(message.Content) || message.EditedTimestamp != null)
|
|
||||||
{
|
{
|
||||||
<div class="chatlog__content">
|
<div class="chatlog__content">
|
||||||
<div class="markdown">
|
<div class="markdown">
|
||||||
|
@{/* Message content */}
|
||||||
<span class="preserve-whitespace">@Raw(FormatMarkdown(message.Content))</span>
|
<span class="preserve-whitespace">@Raw(FormatMarkdown(message.Content))</span>
|
||||||
|
|
||||||
@if (message.EditedTimestamp != null)
|
@{/* Edit timestamp */}
|
||||||
|
@if (message.EditedTimestamp is not null)
|
||||||
{
|
{
|
||||||
<span class="chatlog__edited-timestamp" title="@FormatDate(message.EditedTimestamp.Value)">(edited)</span>
|
<span class="chatlog__edited-timestamp" title="@FormatDate(message.EditedTimestamp.Value)">(edited)</span>
|
||||||
}
|
}
|
||||||
@@ -54,47 +125,64 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Attachments */}
|
||||||
@foreach (var attachment in message.Attachments)
|
@foreach (var attachment in message.Attachments)
|
||||||
{
|
{
|
||||||
<div class="chatlog__attachment">
|
<div class="chatlog__attachment @(attachment.IsSpoiler ? "chatlog__attachment--hidden" : "")" onclick="@(attachment.IsSpoiler ? "showSpoiler(event, this)" : "")">
|
||||||
<div class="@(attachment.IsSpoiler ? "spoiler spoiler--hidden" : "")" onclick="@(attachment.IsSpoiler ? "showSpoiler(event, this)" : "")">
|
@{/* Spoiler caption */}
|
||||||
<div class="@(attachment.IsSpoiler ? "spoiler-image" : "")">
|
@if (attachment.IsSpoiler)
|
||||||
@if (attachment.IsImage)
|
{
|
||||||
{
|
<div class="chatlog__attachment-spoiler-caption">SPOILER</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@{/* Attachment preview */}
|
||||||
|
@if (attachment.IsImage)
|
||||||
|
{
|
||||||
|
<a href="@await ResolveUrlAsync(attachment.Url)">
|
||||||
|
<img class="chatlog__attachment-media" src="@await ResolveUrlAsync(attachment.Url)" alt="Image attachment" title="@($"Image: {attachment.FileName} ({attachment.FileSize})")" loading="lazy">
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
else if (attachment.IsVideo)
|
||||||
|
{
|
||||||
|
<video class="chatlog__attachment-media" controls>
|
||||||
|
<source src="@await ResolveUrlAsync(attachment.Url)" alt="Video attachment" title="@($"Video: {attachment.FileName} ({attachment.FileSize})")">
|
||||||
|
</video>
|
||||||
|
}
|
||||||
|
else if (attachment.IsAudio)
|
||||||
|
{
|
||||||
|
<audio class="chatlog__attachment-media" controls>
|
||||||
|
<source src="@await ResolveUrlAsync(attachment.Url)" alt="Audio attachment" title="@($"Audio: {attachment.FileName} ({attachment.FileSize})")">
|
||||||
|
</audio>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="chatlog__attachment-generic">
|
||||||
|
<svg class="chatlog__attachment-generic-icon">
|
||||||
|
<use href="#icon-attachment" />
|
||||||
|
</svg>
|
||||||
|
<div class="chatlog__attachment-generic-name">
|
||||||
<a href="@await ResolveUrlAsync(attachment.Url)">
|
<a href="@await ResolveUrlAsync(attachment.Url)">
|
||||||
<img class="chatlog__attachment-thumbnail" src="@await ResolveUrlAsync(attachment.Url)" alt="Image attachment" title="@($"Image: {attachment.FileName} ({attachment.FileSize})")">
|
@attachment.FileName
|
||||||
</a>
|
</a>
|
||||||
}
|
</div>
|
||||||
else if (attachment.IsVideo)
|
<div class="chatlog__attachment-generic-size">
|
||||||
{
|
@attachment.FileSize
|
||||||
<video controls class="chatlog__attachment-thumbnail">
|
</div>
|
||||||
<source src="@await ResolveUrlAsync(attachment.Url)" alt="Video attachment" title="@($"Video: {attachment.FileName} ({attachment.FileSize})")">
|
|
||||||
</video>
|
|
||||||
}
|
|
||||||
else if (attachment.IsAudio)
|
|
||||||
{
|
|
||||||
<audio controls class="chatlog__attachment-thumbnail">
|
|
||||||
<source src="@await ResolveUrlAsync(attachment.Url)" alt="Audio attachment" title="@($"Audio: {attachment.FileName} ({attachment.FileSize})")">
|
|
||||||
</audio>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<a href="@await ResolveUrlAsync(attachment.Url)">
|
|
||||||
@($"Attachment: {attachment.FileName} ({attachment.FileSize})")
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Embeds */}
|
||||||
@foreach (var embed in message.Embeds)
|
@foreach (var embed in message.Embeds)
|
||||||
{
|
{
|
||||||
|
var youTubeVideo = embed.TryGetYouTubeVideo();
|
||||||
|
|
||||||
<div class="chatlog__embed">
|
<div class="chatlog__embed">
|
||||||
@if (embed.Color != null)
|
@{/* Color pill */}
|
||||||
|
@if (embed.Color is not null)
|
||||||
{
|
{
|
||||||
var embedColorStyle = $"background-color: rgba({embed.Color?.R},{embed.Color?.G},{embed.Color?.B},{embed.Color?.A})";
|
<div class="chatlog__embed-color-pill" style="background-color: rgba(@embed.Color?.R,@embed.Color?.G,@embed.Color?.B,@embed.Color?.A)"></div>
|
||||||
<div class="chatlog__embed-color-pill" style="@embedColorStyle"></div>
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -104,12 +192,13 @@
|
|||||||
<div class="chatlog__embed-content-container">
|
<div class="chatlog__embed-content-container">
|
||||||
<div class="chatlog__embed-content">
|
<div class="chatlog__embed-content">
|
||||||
<div class="chatlog__embed-text">
|
<div class="chatlog__embed-text">
|
||||||
@if (embed.Author != null)
|
@{/* Embed author */}
|
||||||
|
@if (embed.Author is not null)
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-author">
|
<div class="chatlog__embed-author">
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Author.IconUrl))
|
@if (!string.IsNullOrWhiteSpace(embed.Author.IconUrl))
|
||||||
{
|
{
|
||||||
<img class="chatlog__embed-author-icon" src="@await ResolveUrlAsync(embed.Author.IconUrl)" alt="Author icon">
|
<img class="chatlog__embed-author-icon" src="@await ResolveUrlAsync(embed.Author.IconProxyUrl ?? embed.Author.IconUrl)" alt="Author icon" loading="lazy" onerror="this.style.visibility='hidden'">
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Author.Name))
|
@if (!string.IsNullOrWhiteSpace(embed.Author.Name))
|
||||||
@@ -128,6 +217,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Embed title */}
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Title))
|
@if (!string.IsNullOrWhiteSpace(embed.Title))
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-title">
|
<div class="chatlog__embed-title">
|
||||||
@@ -144,21 +234,27 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Description))
|
@{/* Embed description (with special casing for YouTube videos) */}
|
||||||
|
@if (youTubeVideo is not null)
|
||||||
|
{
|
||||||
|
<div class="chatlog__embed-youtube-container">
|
||||||
|
<iframe class="chatlog__embed-youtube" src="@youTubeVideo.Url" width="400" height="225"></iframe>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
else if (!string.IsNullOrWhiteSpace(embed.Description))
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-description">
|
<div class="chatlog__embed-description">
|
||||||
<div class="markdown preserve-whitespace">@Raw(FormatEmbedMarkdown(embed.Description))</div>
|
<div class="markdown preserve-whitespace">@Raw(FormatEmbedMarkdown(embed.Description))</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Embed fields */}
|
||||||
@if (embed.Fields.Any())
|
@if (embed.Fields.Any())
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-fields">
|
<div class="chatlog__embed-fields">
|
||||||
@foreach (var field in embed.Fields)
|
@foreach (var field in embed.Fields)
|
||||||
{
|
{
|
||||||
var isInlineStyle = field.IsInline ? "chatlog__embed-field--inline" : null;
|
<div class="chatlog__embed-field @(field.IsInline ? "chatlog__embed-field--inline" : null)">
|
||||||
|
|
||||||
<div class="chatlog__embed-field @isInlineStyle">
|
|
||||||
@if (!string.IsNullOrWhiteSpace(field.Name))
|
@if (!string.IsNullOrWhiteSpace(field.Name))
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-field-name">
|
<div class="chatlog__embed-field-name">
|
||||||
@@ -178,45 +274,51 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (embed.Thumbnail != null)
|
@{/* Embed content (not shown for YouTube videos) */}
|
||||||
|
@if (embed.Thumbnail is not null && !string.IsNullOrWhiteSpace(embed.Thumbnail.Url) && youTubeVideo is null)
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-thumbnail-container">
|
<div class="chatlog__embed-thumbnail-container">
|
||||||
<a class="chatlog__embed-thumbnail-link" href="@await ResolveUrlAsync(embed.Thumbnail.Url)">
|
<a class="chatlog__embed-thumbnail-link" href="@await ResolveUrlAsync(embed.Thumbnail.ProxyUrl ?? embed.Thumbnail.Url)">
|
||||||
<img class="chatlog__embed-thumbnail" src="@await ResolveUrlAsync(embed.Thumbnail.Url)" alt="Thumbnail">
|
<img class="chatlog__embed-thumbnail" src="@await ResolveUrlAsync(embed.Thumbnail.ProxyUrl ?? embed.Thumbnail.Url)" alt="Thumbnail" loading="lazy">
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (embed.Image != null)
|
@{/* Embed image */}
|
||||||
|
@if (embed.Image is not null && !string.IsNullOrWhiteSpace(embed.Image.Url))
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-image-container">
|
<div class="chatlog__embed-image-container">
|
||||||
<a class="chatlog__embed-image-link" href="@await ResolveUrlAsync(embed.Image.Url)">
|
<a class="chatlog__embed-image-link" href="@await ResolveUrlAsync(embed.Image.ProxyUrl ?? embed.Image.Url)">
|
||||||
<img class="chatlog__embed-image" src="@await ResolveUrlAsync(embed.Image.Url)" alt="Image">
|
<img class="chatlog__embed-image" src="@await ResolveUrlAsync(embed.Image.ProxyUrl ?? embed.Image.Url)" alt="Image" loading="lazy">
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (embed.Footer != null || embed.Timestamp != null)
|
@{/* Embed footer & icon */}
|
||||||
|
@if (embed.Footer is not null || embed.Timestamp is not null)
|
||||||
{
|
{
|
||||||
<div class="chatlog__embed-footer">
|
<div class="chatlog__embed-footer">
|
||||||
|
@{/* Footer icon */}
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Footer?.IconUrl))
|
@if (!string.IsNullOrWhiteSpace(embed.Footer?.IconUrl))
|
||||||
{
|
{
|
||||||
<img class="chatlog__embed-footer-icon" src="@await ResolveUrlAsync(embed.Footer.IconUrl)" alt="Footer icon">
|
<img class="chatlog__embed-footer-icon" src="@await ResolveUrlAsync(embed.Footer.IconProxyUrl ?? embed.Footer.IconUrl)" alt="Footer icon" loading="lazy">
|
||||||
}
|
}
|
||||||
|
|
||||||
<span class="chatlog__embed-footer-text">
|
<span class="chatlog__embed-footer-text">
|
||||||
|
@{/* Footer text */}
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Footer?.Text))
|
@if (!string.IsNullOrWhiteSpace(embed.Footer?.Text))
|
||||||
{
|
{
|
||||||
@embed.Footer.Text
|
@embed.Footer.Text
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (!string.IsNullOrWhiteSpace(embed.Footer?.Text) && embed.Timestamp != null)
|
@if (!string.IsNullOrWhiteSpace(embed.Footer?.Text) && embed.Timestamp is not null)
|
||||||
{
|
{
|
||||||
@(" • ")
|
@(" • ")
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (embed.Timestamp != null)
|
@{/* Embed timestamp */}
|
||||||
|
@if (embed.Timestamp is not null)
|
||||||
{
|
{
|
||||||
@FormatDate(embed.Timestamp.Value)
|
@FormatDate(embed.Timestamp.Value)
|
||||||
}
|
}
|
||||||
@@ -227,13 +329,14 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@{/* Message reactions */}
|
||||||
@if (message.Reactions.Any())
|
@if (message.Reactions.Any())
|
||||||
{
|
{
|
||||||
<div class="chatlog__reactions">
|
<div class="chatlog__reactions">
|
||||||
@foreach (var reaction in message.Reactions)
|
@foreach (var reaction in message.Reactions)
|
||||||
{
|
{
|
||||||
<div class="chatlog__reaction">
|
<div class="chatlog__reaction" title="@reaction.Emoji.Code">
|
||||||
<img class="emoji emoji--small" alt="@reaction.Emoji.Name" title="@reaction.Emoji.Name" src="@await ResolveUrlAsync(reaction.Emoji.ImageUrl)">
|
<img class="emoji emoji--small" alt="@reaction.Emoji.Name" src="@await ResolveUrlAsync(reaction.Emoji.ImageUrl)" loading="lazy">
|
||||||
<span class="chatlog__reaction-count">@reaction.Count</span>
|
<span class="chatlog__reaction-count">@reaction.Count</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
using DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers.Html
|
namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
{
|
{
|
||||||
internal class MessageGroupTemplateContext
|
internal class MessageGroupTemplateContext
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
@using DiscordChatExporter.Core.Exporting.Writers.Html;
|
||||||
|
|
||||||
|
@namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
|
@inherits MiniRazor.TemplateBase<PostambleTemplateContext>
|
||||||
|
|
||||||
|
@{/* Close elements opened by preamble */}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="postamble">
|
||||||
|
<div class="postamble__entry">Exported @Model.MessagesWritten.ToString("N0") message(s)</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
|
{
|
||||||
|
internal class PostambleTemplateContext
|
||||||
|
{
|
||||||
|
public ExportContext ExportContext { get; }
|
||||||
|
|
||||||
|
public long MessagesWritten { get; }
|
||||||
|
|
||||||
|
public PostambleTemplateContext(ExportContext exportContext, long messagesWritten)
|
||||||
|
{
|
||||||
|
ExportContext = exportContext;
|
||||||
|
MessagesWritten = messagesWritten;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,703 @@
|
|||||||
|
@using System
|
||||||
|
@using System.Threading.Tasks
|
||||||
|
@using DiscordChatExporter.Core.Exporting.Writers.Html;
|
||||||
|
|
||||||
|
@namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
|
@inherits MiniRazor.TemplateBase<PreambleTemplateContext>
|
||||||
|
|
||||||
|
@{
|
||||||
|
string Themed(string darkVariant, string lightVariant) =>
|
||||||
|
string.Equals(Model.ThemeName, "Dark", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? darkVariant
|
||||||
|
: lightVariant;
|
||||||
|
|
||||||
|
string FormatDate(DateTimeOffset date) => Model.ExportContext.FormatDate(date);
|
||||||
|
|
||||||
|
ValueTask<string> ResolveUrlAsync(string url) => Model.ExportContext.ResolveMediaUrlAsync(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<title>@Model.ExportContext.Request.Guild.Name - @Model.ExportContext.Request.Channel.Name</title>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width">
|
||||||
|
|
||||||
|
@{/* Styling */}
|
||||||
|
<style>
|
||||||
|
@@font-face {
|
||||||
|
font-family: Whitney;
|
||||||
|
src: url(https://cdn.jsdelivr.net/gh/Tyrrrz/DiscordFonts@master/whitney-300.woff);
|
||||||
|
font-weight: 300;
|
||||||
|
}
|
||||||
|
|
||||||
|
@@font-face {
|
||||||
|
font-family: Whitney;
|
||||||
|
src: url(https://cdn.jsdelivr.net/gh/Tyrrrz/DiscordFonts@master/whitney-400.woff);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
@@font-face {
|
||||||
|
font-family: Whitney;
|
||||||
|
src: url(https://cdn.jsdelivr.net/gh/Tyrrrz/DiscordFonts@master/whitney-500.woff);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
@@font-face {
|
||||||
|
font-family: Whitney;
|
||||||
|
src: url(https://cdn.jsdelivr.net/gh/Tyrrrz/DiscordFonts@master/whitney-600.woff);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
@@font-face {
|
||||||
|
font-family: Whitney;
|
||||||
|
src: url(https://cdn.jsdelivr.net/gh/Tyrrrz/DiscordFonts@master/whitney-700.woff);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: @Themed("#36393e", "#ffffff");
|
||||||
|
color: @Themed("#dcddde", "#23262a");
|
||||||
|
font-family: "Whitney", "Helvetica Neue", Helvetica, Arial, sans-serif;
|
||||||
|
font-size: 17px;
|
||||||
|
font-weight: @Themed("400", "500");
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: @Themed("#00aff4", "#0068e0");
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown {
|
||||||
|
max-width: 100%;
|
||||||
|
line-height: 1.3;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preserve-whitespace {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spoiler-text {
|
||||||
|
background-color: @Themed("rgba(255, 255, 255, 0.1)", "rgba(0, 0, 0, 0.1)");
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.spoiler-text--hidden {
|
||||||
|
cursor: pointer;
|
||||||
|
background-color: @Themed("#202225", "#b9bbbe");
|
||||||
|
color: rgba(0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.spoiler-text--hidden:hover {
|
||||||
|
background-color: @Themed("rgba(32, 34, 37, 0.8)", "rgba(185, 187, 190, 0.8)");
|
||||||
|
}
|
||||||
|
|
||||||
|
.spoiler-text--hidden::selection {
|
||||||
|
color: rgba(0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quote {
|
||||||
|
margin: 0.1em 0;
|
||||||
|
padding-left: 0.6em;
|
||||||
|
border-left: 4px solid @Themed("#4f545c", "#c7ccd1");
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pre {
|
||||||
|
background-color: @Themed("#2f3136", "#f9f9f9");
|
||||||
|
font-family: "Consolas", "Courier New", Courier, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pre--multiline {
|
||||||
|
margin-top: 0.25em;
|
||||||
|
padding: 0.5em;
|
||||||
|
border: 2px solid @Themed("#282b30", "#f3f3f3");
|
||||||
|
border-radius: 5px;
|
||||||
|
color: @Themed("#b9bbbe", "#657b83");
|
||||||
|
}
|
||||||
|
|
||||||
|
@{/* Override Highlight.js styles with a higher specificity selector */}
|
||||||
|
.pre--multiline.hljs {
|
||||||
|
background-color: @Themed("#2f3136", "#f9f9f9");
|
||||||
|
color: @Themed("#b9bbbe", "#657b83");
|
||||||
|
}
|
||||||
|
|
||||||
|
.pre--inline {
|
||||||
|
padding: 2px;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-size: 0.85em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mention {
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 2px;
|
||||||
|
color: #7289da;
|
||||||
|
background-color: rgba(114, 137, 218, .1);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.timestamp {
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 2px;
|
||||||
|
background-color: @Themed("rgba(255, 255, 255, 0.06)", "rgba(6, 6, 7, 0.08)");
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji {
|
||||||
|
width: 1.325em;
|
||||||
|
height: 1.325em;
|
||||||
|
margin: 0 0.06em;
|
||||||
|
vertical-align: -0.4em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji--small {
|
||||||
|
width: 1em;
|
||||||
|
height: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emoji--large {
|
||||||
|
width: 2.8em;
|
||||||
|
height: 2.8em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
color: @Themed("#ffffff", "#2f3136");
|
||||||
|
}
|
||||||
|
|
||||||
|
.preamble__entry--small {
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__message-group {
|
||||||
|
display: grid;
|
||||||
|
margin: 0 0.6em;
|
||||||
|
padding: 0.9em 0;
|
||||||
|
border-top: 1px solid @Themed("rgba(255, 255, 255, 0.1)", "#eceeef");
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-symbol {
|
||||||
|
grid-column: 1;
|
||||||
|
margin: 8px 4px 4px 18px;
|
||||||
|
border-left: 2px solid @Themed("#4f545c", "#c7ccd1");
|
||||||
|
border-top: 2px solid @Themed("#4f545c", "#c7ccd1");
|
||||||
|
border-radius: 8px 0 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference {
|
||||||
|
display: flex;
|
||||||
|
grid-column: 2;
|
||||||
|
margin-bottom: 0.25em;
|
||||||
|
font-size: 0.875em;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
align-items: center;
|
||||||
|
color: @Themed("#b5b6b8", "#5f5f60");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-avatar {
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
margin-right: 0.25em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-name {
|
||||||
|
margin-right: 0.25em;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-content {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-content a:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-link {
|
||||||
|
cursor: pointer;
|
||||||
|
color: @Themed("#b5b6b8", "#5f5f60");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-link * {
|
||||||
|
display: inline;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-link:hover {
|
||||||
|
color: @Themed("#ffffff", "#2f3136");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-link:hover *:not(.spoiler-text) {
|
||||||
|
color: @Themed("#ffffff", "#2f3136");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reference-edited-timestamp {
|
||||||
|
margin-left: 0.25em;
|
||||||
|
font-size: 0.8em;
|
||||||
|
color: @Themed("rgba(255, 255, 255, 0.2)", "#747f8d");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__author-avatar-container {
|
||||||
|
grid-column: 1;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
margin-right: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__author-avatar {
|
||||||
|
border-radius: 50%;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__messages {
|
||||||
|
grid-column: 2;
|
||||||
|
min-width: 50%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__author-name {
|
||||||
|
font-weight: @Themed("500", "600");
|
||||||
|
color: @Themed("#ffffff", "#2f3136");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__timestamp {
|
||||||
|
margin-left: 0.3em;
|
||||||
|
font-size: 0.75em;
|
||||||
|
color: @Themed("rgba(255, 255, 255, 0.2)", "#747f8d");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__message {
|
||||||
|
padding: 0.1em 0.3em;
|
||||||
|
margin: 0 -0.3em;
|
||||||
|
background-color: transparent;
|
||||||
|
transition: background-color 1s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__message--highlighted {
|
||||||
|
background-color: @Themed("rgba(114, 137, 218, 0.2)", "rgba(114, 137, 218, 0.2)");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__message--pinned {
|
||||||
|
background-color: @Themed("rgba(249, 168, 37, 0.05)", "rgba(249, 168, 37, 0.05)");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__content {
|
||||||
|
font-size: 0.95em;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__edited-timestamp {
|
||||||
|
margin-left: 0.15em;
|
||||||
|
font-size: 0.8em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment {
|
||||||
|
display: inline-block;
|
||||||
|
position: relative;
|
||||||
|
margin-top: 0.3em;
|
||||||
|
border-radius: 3px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden {
|
||||||
|
cursor: pointer;
|
||||||
|
box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden * {
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-spoiler-caption {
|
||||||
|
display: none;
|
||||||
|
z-index: 999;
|
||||||
|
position: absolute;
|
||||||
|
left: 50%;
|
||||||
|
top: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
padding: 0.4em 0.8em;
|
||||||
|
background-color: rgba(0, 0, 0, 0.9);
|
||||||
|
border-radius: 20px;
|
||||||
|
color: #dcddde;
|
||||||
|
font-size: 0.9em;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden .chatlog__attachment-spoiler-caption {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden:hover .chatlog__attachment-spoiler-caption {
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-media {
|
||||||
|
vertical-align: top;
|
||||||
|
max-width: 45vw;
|
||||||
|
max-height: 500px;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden .chatlog__attachment-media {
|
||||||
|
filter: blur(44px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-generic {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 520px;
|
||||||
|
height: 40px;
|
||||||
|
padding: 10px;
|
||||||
|
background-color: @Themed("#2f3136", "#f2f3f5");
|
||||||
|
border: 1px solid @Themed("#292b2f", "#ebedef");
|
||||||
|
border-radius: 3px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment--hidden .chatlog__attachment-generic {
|
||||||
|
filter: blur(44px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-generic-icon {
|
||||||
|
float: left;
|
||||||
|
width: 30px;
|
||||||
|
height: 100%;
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-generic-size {
|
||||||
|
color: #72767d;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__attachment-generic-name {
|
||||||
|
overflow: hidden;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__edited-timestamp {
|
||||||
|
color: @Themed("rgba(255, 255, 255, 0.2)", "#747f8d");
|
||||||
|
}
|
||||||
|
|
||||||
|
.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-color-pill--default {
|
||||||
|
background-color: @Themed("#202225", "rgba(227, 229, 232, 1)");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-content-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 0.5em 0.6em;
|
||||||
|
background-color: @Themed("rgba(46, 48, 54, 0.3)", "rgba(249, 249, 249, 0.3)");
|
||||||
|
border: 1px solid @Themed("rgba(46, 48, 54, 0.6)", "rgba(204, 204, 204, 0.3)");
|
||||||
|
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;
|
||||||
|
color: @Themed("#ffffff", "#4f545c")
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-author-name-link {
|
||||||
|
color: @Themed("#ffffff", "#4f545c");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-title {
|
||||||
|
margin-bottom: 0.2em;
|
||||||
|
font-size: 0.875em;
|
||||||
|
font-weight: 600;
|
||||||
|
color: @Themed("#ffffff", "#4f545c");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-description {
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.85em;
|
||||||
|
color: @Themed("#dcddde", "#2e3338");
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
color: @Themed("#ffffff", "#36393e");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-field-value {
|
||||||
|
font-weight: 500;
|
||||||
|
color: @Themed("#dcddde", "#2e3338");
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
color: @Themed("#dcddde", "#2e3338");
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-footer-icon {
|
||||||
|
margin-right: 0.2em;
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-footer-text {
|
||||||
|
vertical-align: middle;
|
||||||
|
font-size: 0.75em;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-youtube-container {
|
||||||
|
margin-top: 0.6em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__embed-youtube {
|
||||||
|
border: 0;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.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;
|
||||||
|
background-color: @Themed("rgba(255, 255, 255, 0.05)", "rgba(79, 84, 92, 0.06)");
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chatlog__reaction-count {
|
||||||
|
min-width: 9px;
|
||||||
|
margin-left: 0.35em;
|
||||||
|
font-size: 0.875em;
|
||||||
|
color: @Themed("rgba(255, 255, 255, 0.3)", "#747f8d");
|
||||||
|
}
|
||||||
|
|
||||||
|
.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-color: #5865F2;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 0.625em;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.postamble {
|
||||||
|
margin: 1.4em 0.3em 0.6em 0.3em;
|
||||||
|
padding: 1em;
|
||||||
|
border-top: 1px solid @Themed("rgba(255, 255, 255, 0.1)", "#eceeef");
|
||||||
|
}
|
||||||
|
|
||||||
|
.postamble__entry {
|
||||||
|
color: @Themed("#ffffff", "#2f3136");
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
|
@{/* Syntax highlighting */}
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/styles/solarized-@(Model.ThemeName.ToLowerInvariant()).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>
|
||||||
|
|
||||||
|
@{/* Scripts */}
|
||||||
|
<script>
|
||||||
|
function scrollToMessage(event, id) {
|
||||||
|
var element = document.getElementById('message-' + id);
|
||||||
|
|
||||||
|
if (element) {
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
element.classList.add('chatlog__message--highlighted');
|
||||||
|
|
||||||
|
window.scrollTo({
|
||||||
|
top: element.getBoundingClientRect().top - document.body.getBoundingClientRect().top - (window.innerHeight / 2),
|
||||||
|
behavior: 'smooth'
|
||||||
|
});
|
||||||
|
|
||||||
|
window.setTimeout(function() {
|
||||||
|
element.classList.remove('chatlog__message--highlighted');
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSpoiler(event, element) {
|
||||||
|
if (element && element.classList.contains('spoiler-text--hidden')) {
|
||||||
|
event.preventDefault();
|
||||||
|
element.classList.remove('spoiler-text--hidden');
|
||||||
|
}
|
||||||
|
if (element && element.classList.contains('chatlog__attachment--hidden')) {
|
||||||
|
event.preventDefault();
|
||||||
|
element.classList.remove('chatlog__attachment--hidden');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
@{/* Icons */}
|
||||||
|
<svg style="display: none">
|
||||||
|
<symbol id="icon-attachment" viewBox="0 0 720 960">
|
||||||
|
<path fill="#f4f5fb" d="M50,935a25,25,0,0,1-25-25V50A25,25,0,0,1,50,25H519.6L695,201.32V910a25,25,0,0,1-25,25Z" />
|
||||||
|
<path fill="#7789c4" d="M509.21,50,670,211.63V910H50V50H509.21M530,0H50A50,50,0,0,0,0,50V910a50,50,0,0,0,50,50H670a50,50,0,0,0,50-50h0V191Z" />
|
||||||
|
<path fill="#f4f5fb" d="M530,215a25,25,0,0,1-25-25V50a25,25,0,0,1,16.23-23.41L693.41,198.77A25,25,0,0,1,670,215Z" />
|
||||||
|
<path fill="#7789c4" d="M530,70.71,649.29,190H530V70.71M530,0a50,50,0,0,0-50,50V190a50,50,0,0,0,50,50H670a50,50,0,0,0,50-50Z" />
|
||||||
|
</symbol>
|
||||||
|
</svg>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="preamble">
|
||||||
|
<div class="preamble__guild-icon-container">
|
||||||
|
<img class="preamble__guild-icon" src="@await ResolveUrlAsync(Model.ExportContext.Request.Guild.IconUrl)" alt="Guild icon" loading="lazy">
|
||||||
|
</div>
|
||||||
|
<div class="preamble__entries-container">
|
||||||
|
<div class="preamble__entry">@Model.ExportContext.Request.Guild.Name</div>
|
||||||
|
<div class="preamble__entry">@Model.ExportContext.Request.Channel.Category / @Model.ExportContext.Request.Channel.Name</div>
|
||||||
|
|
||||||
|
@if (!string.IsNullOrWhiteSpace(Model.ExportContext.Request.Channel.Topic))
|
||||||
|
{
|
||||||
|
<div class="preamble__entry preamble__entry--small">@Model.ExportContext.Request.Channel.Topic</div>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (Model.ExportContext.Request.After is not null || Model.ExportContext.Request.Before is not null)
|
||||||
|
{
|
||||||
|
<div class="preamble__entry preamble__entry--small">
|
||||||
|
@if (Model.ExportContext.Request.After is not null && Model.ExportContext.Request.Before is not null)
|
||||||
|
{
|
||||||
|
@($"Between {FormatDate(Model.ExportContext.Request.After.Value.ToDate())} and {FormatDate(Model.ExportContext.Request.Before.Value.ToDate())}")
|
||||||
|
}
|
||||||
|
else if (Model.ExportContext.Request.After is not null)
|
||||||
|
{
|
||||||
|
@($"After {FormatDate(Model.ExportContext.Request.After.Value.ToDate())}")
|
||||||
|
}
|
||||||
|
else if (Model.ExportContext.Request.Before is not null)
|
||||||
|
{
|
||||||
|
@($"Before {FormatDate(Model.ExportContext.Request.Before.Value.ToDate())}")
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@{/* Preamble cuts off at this point */}
|
||||||
|
<div class="chatlog">
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Exporting.Writers.Html
|
||||||
|
{
|
||||||
|
internal class PreambleTemplateContext
|
||||||
|
{
|
||||||
|
public ExportContext ExportContext { get; }
|
||||||
|
|
||||||
|
public string ThemeName { get; }
|
||||||
|
|
||||||
|
public PreambleTemplateContext(ExportContext exportContext, string themeName)
|
||||||
|
{
|
||||||
|
ExportContext = exportContext;
|
||||||
|
ThemeName = themeName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-17
@@ -2,19 +2,17 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exporting.Writers.Html;
|
using DiscordChatExporter.Core.Exporting.Writers.Html;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
namespace DiscordChatExporter.Core.Exporting.Writers
|
||||||
{
|
{
|
||||||
internal class HtmlMessageWriter : MessageWriter
|
internal class HtmlMessageWriter : MessageWriter
|
||||||
{
|
{
|
||||||
private readonly TextWriter _writer;
|
private readonly TextWriter _writer;
|
||||||
private readonly string _themeName;
|
private readonly string _themeName;
|
||||||
|
|
||||||
private readonly List<Message> _messageGroupBuffer = new List<Message>();
|
private readonly List<Message> _messageGroupBuffer = new();
|
||||||
|
|
||||||
private long _messageCount;
|
|
||||||
|
|
||||||
public HtmlMessageWriter(Stream stream, ExportContext context, string themeName)
|
public HtmlMessageWriter(Stream stream, ExportContext context, string themeName)
|
||||||
: base(stream, context)
|
: base(stream, context)
|
||||||
@@ -25,26 +23,26 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
public override async ValueTask WritePreambleAsync()
|
public override async ValueTask WritePreambleAsync()
|
||||||
{
|
{
|
||||||
var templateContext = new LayoutTemplateContext(Context, _themeName, _messageCount);
|
var templateContext = new PreambleTemplateContext(Context, _themeName);
|
||||||
var templateBundle = await TemplateBundle.ResolveAsync();
|
|
||||||
|
|
||||||
await _writer.WriteLineAsync(
|
await _writer.WriteLineAsync(
|
||||||
await templateBundle.PreambleTemplate.RenderAsync(templateContext)
|
await PreambleTemplate.RenderAsync(templateContext)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async ValueTask WriteMessageGroupAsync(MessageGroup messageGroup)
|
private async ValueTask WriteMessageGroupAsync(MessageGroup messageGroup)
|
||||||
{
|
{
|
||||||
var templateContext = new MessageGroupTemplateContext(Context, messageGroup);
|
var templateContext = new MessageGroupTemplateContext(Context, messageGroup);
|
||||||
var templateBundle = await TemplateBundle.ResolveAsync();
|
|
||||||
|
|
||||||
await _writer.WriteLineAsync(
|
await _writer.WriteLineAsync(
|
||||||
await templateBundle.MessageGroupTemplate.RenderAsync(templateContext)
|
await MessageGroupTemplate.RenderAsync(templateContext)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async ValueTask WriteMessageAsync(Message message)
|
public override async ValueTask WriteMessageAsync(Message message)
|
||||||
{
|
{
|
||||||
|
await base.WriteMessageAsync(message);
|
||||||
|
|
||||||
// If message group is empty or the given message can be grouped, buffer the given message
|
// If message group is empty or the given message can be grouped, buffer the given message
|
||||||
if (!_messageGroupBuffer.Any() || MessageGroup.CanJoin(_messageGroupBuffer.Last(), message))
|
if (!_messageGroupBuffer.Any() || MessageGroup.CanJoin(_messageGroupBuffer.Last(), message))
|
||||||
{
|
{
|
||||||
@@ -58,9 +56,6 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_messageGroupBuffer.Clear();
|
_messageGroupBuffer.Clear();
|
||||||
_messageGroupBuffer.Add(message);
|
_messageGroupBuffer.Add(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Increment message count
|
|
||||||
_messageCount++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async ValueTask WritePostambleAsync()
|
public override async ValueTask WritePostambleAsync()
|
||||||
@@ -69,11 +64,10 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
if (_messageGroupBuffer.Any())
|
if (_messageGroupBuffer.Any())
|
||||||
await WriteMessageGroupAsync(MessageGroup.Join(_messageGroupBuffer));
|
await WriteMessageGroupAsync(MessageGroup.Join(_messageGroupBuffer));
|
||||||
|
|
||||||
var templateContext = new LayoutTemplateContext(Context, _themeName, _messageCount);
|
var templateContext = new PostambleTemplateContext(Context, MessagesWritten);
|
||||||
var templateBundle = await TemplateBundle.ResolveAsync();
|
|
||||||
|
|
||||||
await _writer.WriteLineAsync(
|
await _writer.WriteLineAsync(
|
||||||
await templateBundle.PostambleTemplate.RenderAsync(templateContext)
|
await PostambleTemplate.RenderAsync(templateContext)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
+48
-31
@@ -1,25 +1,28 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
using DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors;
|
||||||
using DiscordChatExporter.Domain.Internal.Extensions;
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
using JsonExtensions.Writing;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
namespace DiscordChatExporter.Core.Exporting.Writers
|
||||||
{
|
{
|
||||||
internal class JsonMessageWriter : MessageWriter
|
internal class JsonMessageWriter : MessageWriter
|
||||||
{
|
{
|
||||||
private readonly Utf8JsonWriter _writer;
|
private readonly Utf8JsonWriter _writer;
|
||||||
|
|
||||||
private long _messageCount;
|
|
||||||
|
|
||||||
public JsonMessageWriter(Stream stream, ExportContext context)
|
public JsonMessageWriter(Stream stream, ExportContext context)
|
||||||
: base(stream, context)
|
: base(stream, context)
|
||||||
{
|
{
|
||||||
_writer = new Utf8JsonWriter(stream, new JsonWriterOptions
|
_writer = new Utf8JsonWriter(stream, new JsonWriterOptions
|
||||||
{
|
{
|
||||||
Indented = true
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
Indented = true,
|
||||||
|
// Validation errors may mask actual failures
|
||||||
|
// https://github.com/Tyrrrz/DiscordChatExporter/issues/413
|
||||||
|
SkipValidation = true
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +33,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
{
|
{
|
||||||
_writer.WriteStartObject();
|
_writer.WriteStartObject();
|
||||||
|
|
||||||
_writer.WriteString("id", attachment.Id);
|
_writer.WriteString("id", attachment.Id.ToString());
|
||||||
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(attachment.Url));
|
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(attachment.Url));
|
||||||
_writer.WriteString("fileName", attachment.FileName);
|
_writer.WriteString("fileName", attachment.FileName);
|
||||||
_writer.WriteNumber("fileSizeBytes", attachment.FileSize.TotalBytes);
|
_writer.WriteNumber("fileSizeBytes", attachment.FileSize.TotalBytes);
|
||||||
@@ -47,7 +50,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_writer.WriteString("url", embedAuthor.Url);
|
_writer.WriteString("url", embedAuthor.Url);
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embedAuthor.IconUrl))
|
if (!string.IsNullOrWhiteSpace(embedAuthor.IconUrl))
|
||||||
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedAuthor.IconUrl));
|
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedAuthor.IconProxyUrl ?? embedAuthor.IconUrl));
|
||||||
|
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
await _writer.FlushAsync();
|
await _writer.FlushAsync();
|
||||||
@@ -58,7 +61,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_writer.WriteStartObject("thumbnail");
|
_writer.WriteStartObject("thumbnail");
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embedThumbnail.Url))
|
if (!string.IsNullOrWhiteSpace(embedThumbnail.Url))
|
||||||
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(embedThumbnail.Url));
|
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(embedThumbnail.ProxyUrl ?? embedThumbnail.Url));
|
||||||
|
|
||||||
_writer.WriteNumber("width", embedThumbnail.Width);
|
_writer.WriteNumber("width", embedThumbnail.Width);
|
||||||
_writer.WriteNumber("height", embedThumbnail.Height);
|
_writer.WriteNumber("height", embedThumbnail.Height);
|
||||||
@@ -72,7 +75,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_writer.WriteStartObject("image");
|
_writer.WriteStartObject("image");
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embedImage.Url))
|
if (!string.IsNullOrWhiteSpace(embedImage.Url))
|
||||||
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(embedImage.Url));
|
_writer.WriteString("url", await Context.ResolveMediaUrlAsync(embedImage.ProxyUrl ?? embedImage.Url));
|
||||||
|
|
||||||
_writer.WriteNumber("width", embedImage.Width);
|
_writer.WriteNumber("width", embedImage.Width);
|
||||||
_writer.WriteNumber("height", embedImage.Height);
|
_writer.WriteNumber("height", embedImage.Height);
|
||||||
@@ -88,7 +91,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_writer.WriteString("text", embedFooter.Text);
|
_writer.WriteString("text", embedFooter.Text);
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embedFooter.IconUrl))
|
if (!string.IsNullOrWhiteSpace(embedFooter.IconUrl))
|
||||||
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedFooter.IconUrl));
|
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(embedFooter.IconProxyUrl ?? embedFooter.IconUrl));
|
||||||
|
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
await _writer.FlushAsync();
|
await _writer.FlushAsync();
|
||||||
@@ -115,19 +118,19 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
_writer.WriteString("timestamp", embed.Timestamp);
|
_writer.WriteString("timestamp", embed.Timestamp);
|
||||||
_writer.WriteString("description", FormatMarkdown(embed.Description));
|
_writer.WriteString("description", FormatMarkdown(embed.Description));
|
||||||
|
|
||||||
if (embed.Color != null)
|
if (embed.Color is not null)
|
||||||
_writer.WriteString("color", embed.Color.Value.ToHex());
|
_writer.WriteString("color", embed.Color.Value.ToHex());
|
||||||
|
|
||||||
if (embed.Author != null)
|
if (embed.Author is not null)
|
||||||
await WriteEmbedAuthorAsync(embed.Author);
|
await WriteEmbedAuthorAsync(embed.Author);
|
||||||
|
|
||||||
if (embed.Thumbnail != null)
|
if (embed.Thumbnail is not null)
|
||||||
await WriteEmbedThumbnailAsync(embed.Thumbnail);
|
await WriteEmbedThumbnailAsync(embed.Thumbnail);
|
||||||
|
|
||||||
if (embed.Image != null)
|
if (embed.Image is not null)
|
||||||
await WriteEmbedImageAsync(embed.Image);
|
await WriteEmbedImageAsync(embed.Image);
|
||||||
|
|
||||||
if (embed.Footer != null)
|
if (embed.Footer is not null)
|
||||||
await WriteEmbedFooterAsync(embed.Footer);
|
await WriteEmbedFooterAsync(embed.Footer);
|
||||||
|
|
||||||
// Fields
|
// Fields
|
||||||
@@ -164,9 +167,9 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
{
|
{
|
||||||
_writer.WriteStartObject();
|
_writer.WriteStartObject();
|
||||||
|
|
||||||
_writer.WriteString("id", mentionedUser.Id);
|
_writer.WriteString("id", mentionedUser.Id.ToString());
|
||||||
_writer.WriteString("name", mentionedUser.Name);
|
_writer.WriteString("name", mentionedUser.Name);
|
||||||
_writer.WriteNumber("discriminator", mentionedUser.Discriminator);
|
_writer.WriteString("discriminator", mentionedUser.DiscriminatorFormatted);
|
||||||
_writer.WriteString("nickname", Context.TryGetMember(mentionedUser.Id)?.Nick ?? mentionedUser.Name);
|
_writer.WriteString("nickname", Context.TryGetMember(mentionedUser.Id)?.Nick ?? mentionedUser.Name);
|
||||||
_writer.WriteBoolean("isBot", mentionedUser.IsBot);
|
_writer.WriteBoolean("isBot", mentionedUser.IsBot);
|
||||||
|
|
||||||
@@ -181,24 +184,25 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
// Guild
|
// Guild
|
||||||
_writer.WriteStartObject("guild");
|
_writer.WriteStartObject("guild");
|
||||||
_writer.WriteString("id", Context.Request.Guild.Id);
|
_writer.WriteString("id", Context.Request.Guild.Id.ToString());
|
||||||
_writer.WriteString("name", Context.Request.Guild.Name);
|
_writer.WriteString("name", Context.Request.Guild.Name);
|
||||||
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(Context.Request.Guild.IconUrl));
|
_writer.WriteString("iconUrl", await Context.ResolveMediaUrlAsync(Context.Request.Guild.IconUrl));
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
|
|
||||||
// Channel
|
// Channel
|
||||||
_writer.WriteStartObject("channel");
|
_writer.WriteStartObject("channel");
|
||||||
_writer.WriteString("id", Context.Request.Channel.Id);
|
_writer.WriteString("id", Context.Request.Channel.Id.ToString());
|
||||||
_writer.WriteString("type", Context.Request.Channel.Type.ToString());
|
_writer.WriteString("type", Context.Request.Channel.Type.ToString());
|
||||||
_writer.WriteString("category", Context.Request.Channel.Category);
|
_writer.WriteString("categoryId", Context.Request.Channel.Category.Id.ToString());
|
||||||
|
_writer.WriteString("category", Context.Request.Channel.Category.Name);
|
||||||
_writer.WriteString("name", Context.Request.Channel.Name);
|
_writer.WriteString("name", Context.Request.Channel.Name);
|
||||||
_writer.WriteString("topic", Context.Request.Channel.Topic);
|
_writer.WriteString("topic", Context.Request.Channel.Topic);
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
|
|
||||||
// Date range
|
// Date range
|
||||||
_writer.WriteStartObject("dateRange");
|
_writer.WriteStartObject("dateRange");
|
||||||
_writer.WriteString("after", Context.Request.After);
|
_writer.WriteString("after", Context.Request.After?.ToDate());
|
||||||
_writer.WriteString("before", Context.Request.Before);
|
_writer.WriteString("before", Context.Request.Before?.ToDate());
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
|
|
||||||
// Message array (start)
|
// Message array (start)
|
||||||
@@ -208,10 +212,12 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
public override async ValueTask WriteMessageAsync(Message message)
|
public override async ValueTask WriteMessageAsync(Message message)
|
||||||
{
|
{
|
||||||
|
await base.WriteMessageAsync(message);
|
||||||
|
|
||||||
_writer.WriteStartObject();
|
_writer.WriteStartObject();
|
||||||
|
|
||||||
// Metadata
|
// Metadata
|
||||||
_writer.WriteString("id", message.Id);
|
_writer.WriteString("id", message.Id.ToString());
|
||||||
_writer.WriteString("type", message.Type.ToString());
|
_writer.WriteString("type", message.Type.ToString());
|
||||||
_writer.WriteString("timestamp", message.Timestamp);
|
_writer.WriteString("timestamp", message.Timestamp);
|
||||||
_writer.WriteString("timestampEdited", message.EditedTimestamp);
|
_writer.WriteString("timestampEdited", message.EditedTimestamp);
|
||||||
@@ -223,9 +229,11 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
// Author
|
// Author
|
||||||
_writer.WriteStartObject("author");
|
_writer.WriteStartObject("author");
|
||||||
_writer.WriteString("id", message.Author.Id);
|
_writer.WriteString("id", message.Author.Id.ToString());
|
||||||
_writer.WriteString("name", message.Author.Name);
|
_writer.WriteString("name", message.Author.Name);
|
||||||
_writer.WriteString("discriminator", $"{message.Author.Discriminator:0000}");
|
_writer.WriteString("discriminator", message.Author.DiscriminatorFormatted);
|
||||||
|
_writer.WriteString("nickname", Context.TryGetMember(message.Author.Id)?.Nick ?? message.Author.Name);
|
||||||
|
_writer.WriteString("color", Context.TryGetUserColor(message.Author.Id)?.ToHex());
|
||||||
_writer.WriteBoolean("isBot", message.Author.IsBot);
|
_writer.WriteBoolean("isBot", message.Author.IsBot);
|
||||||
_writer.WriteString("avatarUrl", await Context.ResolveMediaUrlAsync(message.Author.AvatarUrl));
|
_writer.WriteString("avatarUrl", await Context.ResolveMediaUrlAsync(message.Author.AvatarUrl));
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
@@ -256,15 +264,24 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
// Mentions
|
// Mentions
|
||||||
_writer.WriteStartArray("mentions");
|
_writer.WriteStartArray("mentions");
|
||||||
|
|
||||||
foreach (var mention in message.MentionedUsers)
|
foreach (var mention in message.MentionedUsers)
|
||||||
await WriteMentionAsync(mention);
|
await WriteMentionAsync(mention);
|
||||||
|
|
||||||
_writer.WriteEndArray();
|
_writer.WriteEndArray();
|
||||||
|
|
||||||
|
// Message reference
|
||||||
|
if (message.Reference is not null)
|
||||||
|
{
|
||||||
|
_writer.WriteStartObject("reference");
|
||||||
|
_writer.WriteString("messageId", message.Reference.MessageId?.ToString());
|
||||||
|
_writer.WriteString("channelId", message.Reference.ChannelId?.ToString());
|
||||||
|
_writer.WriteString("guildId", message.Reference.GuildId?.ToString());
|
||||||
|
_writer.WriteEndObject();
|
||||||
|
}
|
||||||
|
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
await _writer.FlushAsync();
|
await _writer.FlushAsync();
|
||||||
|
|
||||||
_messageCount++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async ValueTask WritePostambleAsync()
|
public override async ValueTask WritePostambleAsync()
|
||||||
@@ -272,7 +289,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
// Message array (end)
|
// Message array (end)
|
||||||
_writer.WriteEndArray();
|
_writer.WriteEndArray();
|
||||||
|
|
||||||
_writer.WriteNumber("messageCount", _messageCount);
|
_writer.WriteNumber("messageCount", MessagesWritten);
|
||||||
|
|
||||||
// Root object (end)
|
// Root object (end)
|
||||||
_writer.WriteEndObject();
|
_writer.WriteEndObject();
|
||||||
+79
-65
@@ -3,11 +3,13 @@ using System.Linq;
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord;
|
||||||
using DiscordChatExporter.Domain.Markdown;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
using DiscordChatExporter.Core.Markdown;
|
||||||
|
using DiscordChatExporter.Core.Markdown.Parsing;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
namespace DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors
|
||||||
{
|
{
|
||||||
internal partial class HtmlMarkdownVisitor : MarkdownVisitor
|
internal partial class HtmlMarkdownVisitor : MarkdownVisitor
|
||||||
{
|
{
|
||||||
@@ -37,7 +39,7 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
|||||||
TextFormatting.Underline => ("<u>", "</u>"),
|
TextFormatting.Underline => ("<u>", "</u>"),
|
||||||
TextFormatting.Strikethrough => ("<s>", "</s>"),
|
TextFormatting.Strikethrough => ("<s>", "</s>"),
|
||||||
TextFormatting.Spoiler => (
|
TextFormatting.Spoiler => (
|
||||||
"<span class=\"spoiler spoiler--hidden\" onclick=\"showSpoiler(event, this)\"><span class=\"spoiler-text\">", "</span></span>"),
|
"<span class=\"spoiler-text spoiler-text--hidden\" onclick=\"showSpoiler(event, this)\">", "</span>"),
|
||||||
TextFormatting.Quote => ("<div class=\"quote\">", "</div>"),
|
TextFormatting.Quote => ("<div class=\"quote\">", "</div>"),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(formatted.Formatting))
|
_ => throw new ArgumentOutOfRangeException(nameof(formatted.Formatting))
|
||||||
};
|
};
|
||||||
@@ -73,66 +75,6 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
|||||||
return base.VisitMultiLineCodeBlock(multiLineCodeBlock);
|
return base.VisitMultiLineCodeBlock(multiLineCodeBlock);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override MarkdownNode VisitMention(MentionNode mention)
|
|
||||||
{
|
|
||||||
if (mention.Type == MentionType.Meta)
|
|
||||||
{
|
|
||||||
_buffer
|
|
||||||
.Append("<span class=\"mention\">")
|
|
||||||
.Append("@").Append(HtmlEncode(mention.Id))
|
|
||||||
.Append("</span>");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.User)
|
|
||||||
{
|
|
||||||
var member = _context.TryGetMember(mention.Id);
|
|
||||||
var fullName = member?.User.FullName ?? "Unknown";
|
|
||||||
var nick = member?.Nick ?? "Unknown";
|
|
||||||
|
|
||||||
_buffer
|
|
||||||
.Append($"<span class=\"mention\" title=\"{HtmlEncode(fullName)}\">")
|
|
||||||
.Append("@").Append(HtmlEncode(nick))
|
|
||||||
.Append("</span>");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.Channel)
|
|
||||||
{
|
|
||||||
var channel = _context.TryGetChannel(mention.Id);
|
|
||||||
var name = channel?.Name ?? "deleted-channel";
|
|
||||||
|
|
||||||
_buffer
|
|
||||||
.Append("<span class=\"mention\">")
|
|
||||||
.Append("#").Append(HtmlEncode(name))
|
|
||||||
.Append("</span>");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.Role)
|
|
||||||
{
|
|
||||||
var role = _context.TryGetRole(mention.Id);
|
|
||||||
var name = role?.Name ?? "deleted-role";
|
|
||||||
var color = role?.Color;
|
|
||||||
|
|
||||||
var style = color != null
|
|
||||||
? $"color: rgb({color?.R}, {color?.G}, {color?.B}); background-color: rgba({color?.R}, {color?.G}, {color?.B}, 0.1);"
|
|
||||||
: "";
|
|
||||||
|
|
||||||
_buffer
|
|
||||||
.Append($"<span class=\"mention\" style=\"{style}\">")
|
|
||||||
.Append("@").Append(HtmlEncode(name))
|
|
||||||
.Append("</span>");
|
|
||||||
}
|
|
||||||
|
|
||||||
return base.VisitMention(mention);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override MarkdownNode VisitEmoji(EmojiNode emoji)
|
|
||||||
{
|
|
||||||
var emojiImageUrl = Emoji.GetImageUrl(emoji.Id, emoji.Name, emoji.IsAnimated);
|
|
||||||
var jumboClass = _isJumbo ? "emoji--large" : "";
|
|
||||||
|
|
||||||
_buffer
|
|
||||||
.Append($"<img class=\"emoji {jumboClass}\" alt=\"{emoji.Name}\" title=\"{emoji.Name}\" src=\"{emojiImageUrl}\">");
|
|
||||||
|
|
||||||
return base.VisitEmoji(emoji);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override MarkdownNode VisitLink(LinkNode link)
|
protected override MarkdownNode VisitLink(LinkNode link)
|
||||||
{
|
{
|
||||||
// Extract message ID if the link points to a Discord message
|
// Extract message ID if the link points to a Discord message
|
||||||
@@ -155,6 +97,78 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
|||||||
|
|
||||||
return base.VisitLink(link);
|
return base.VisitLink(link);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected override MarkdownNode VisitEmoji(EmojiNode emoji)
|
||||||
|
{
|
||||||
|
var emojiImageUrl = Emoji.GetImageUrl(emoji.Id, emoji.Name, emoji.IsAnimated);
|
||||||
|
var jumboClass = _isJumbo ? "emoji--large" : "";
|
||||||
|
|
||||||
|
_buffer
|
||||||
|
.Append($"<img loading=\"lazy\" class=\"emoji {jumboClass}\" alt=\"{emoji.Name}\" title=\"{emoji.Code}\" src=\"{emojiImageUrl}\">");
|
||||||
|
|
||||||
|
return base.VisitEmoji(emoji);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override MarkdownNode VisitMention(MentionNode mention)
|
||||||
|
{
|
||||||
|
var mentionId = Snowflake.TryParse(mention.Id);
|
||||||
|
if (mention.Kind == MentionKind.Meta)
|
||||||
|
{
|
||||||
|
_buffer
|
||||||
|
.Append("<span class=\"mention\">")
|
||||||
|
.Append("@").Append(HtmlEncode(mention.Id))
|
||||||
|
.Append("</span>");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.User)
|
||||||
|
{
|
||||||
|
var member = mentionId?.Pipe(_context.TryGetMember);
|
||||||
|
var fullName = member?.User.FullName ?? "Unknown";
|
||||||
|
var nick = member?.Nick ?? "Unknown";
|
||||||
|
|
||||||
|
_buffer
|
||||||
|
.Append($"<span class=\"mention\" title=\"{HtmlEncode(fullName)}\">")
|
||||||
|
.Append("@").Append(HtmlEncode(nick))
|
||||||
|
.Append("</span>");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.Channel)
|
||||||
|
{
|
||||||
|
var channel = mentionId?.Pipe(_context.TryGetChannel);
|
||||||
|
var symbol = channel?.IsVoiceChannel == true ? "🔊" : "#";
|
||||||
|
var name = channel?.Name ?? "deleted-channel";
|
||||||
|
|
||||||
|
_buffer
|
||||||
|
.Append("<span class=\"mention\">")
|
||||||
|
.Append(symbol).Append(HtmlEncode(name))
|
||||||
|
.Append("</span>");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.Role)
|
||||||
|
{
|
||||||
|
var role = mentionId?.Pipe(_context.TryGetRole);
|
||||||
|
var name = role?.Name ?? "deleted-role";
|
||||||
|
var color = role?.Color;
|
||||||
|
|
||||||
|
var style = color is not null
|
||||||
|
? $"color: rgb({color?.R}, {color?.G}, {color?.B}); background-color: rgba({color?.R}, {color?.G}, {color?.B}, 0.1);"
|
||||||
|
: "";
|
||||||
|
|
||||||
|
_buffer
|
||||||
|
.Append($"<span class=\"mention\" style=\"{style}\">")
|
||||||
|
.Append("@").Append(HtmlEncode(name))
|
||||||
|
.Append("</span>");
|
||||||
|
}
|
||||||
|
|
||||||
|
return base.VisitMention(mention);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override MarkdownNode VisitUnixTimestamp(UnixTimestampNode timestamp)
|
||||||
|
{
|
||||||
|
_buffer
|
||||||
|
.Append("<span class=\"timestamp\">")
|
||||||
|
.Append(HtmlEncode(_context.FormatDate(timestamp.Value)))
|
||||||
|
.Append("</span>");
|
||||||
|
|
||||||
|
return base.VisitUnixTimestamp(timestamp);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal partial class HtmlMarkdownVisitor
|
internal partial class HtmlMarkdownVisitor
|
||||||
+50
-34
@@ -1,8 +1,10 @@
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using DiscordChatExporter.Domain.Markdown;
|
using DiscordChatExporter.Core.Discord;
|
||||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
using DiscordChatExporter.Core.Markdown;
|
||||||
|
using DiscordChatExporter.Core.Markdown.Parsing;
|
||||||
|
using DiscordChatExporter.Core.Utils.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
namespace DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors
|
||||||
{
|
{
|
||||||
internal partial class PlainTextMarkdownVisitor : MarkdownVisitor
|
internal partial class PlainTextMarkdownVisitor : MarkdownVisitor
|
||||||
{
|
{
|
||||||
@@ -21,37 +23,6 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
|||||||
return base.VisitText(text);
|
return base.VisitText(text);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override MarkdownNode VisitMention(MentionNode mention)
|
|
||||||
{
|
|
||||||
if (mention.Type == MentionType.Meta)
|
|
||||||
{
|
|
||||||
_buffer.Append($"@{mention.Id}");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.User)
|
|
||||||
{
|
|
||||||
var member = _context.TryGetMember(mention.Id);
|
|
||||||
var name = member?.User.Name ?? "Unknown";
|
|
||||||
|
|
||||||
_buffer.Append($"@{name}");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.Channel)
|
|
||||||
{
|
|
||||||
var channel = _context.TryGetChannel(mention.Id);
|
|
||||||
var name = channel?.Name ?? "deleted-channel";
|
|
||||||
|
|
||||||
_buffer.Append($"#{name}");
|
|
||||||
}
|
|
||||||
else if (mention.Type == MentionType.Role)
|
|
||||||
{
|
|
||||||
var role = _context.TryGetRole(mention.Id);
|
|
||||||
var name = role?.Name ?? "deleted-role";
|
|
||||||
|
|
||||||
_buffer.Append($"@{name}");
|
|
||||||
}
|
|
||||||
|
|
||||||
return base.VisitMention(mention);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override MarkdownNode VisitEmoji(EmojiNode emoji)
|
protected override MarkdownNode VisitEmoji(EmojiNode emoji)
|
||||||
{
|
{
|
||||||
_buffer.Append(
|
_buffer.Append(
|
||||||
@@ -62,6 +33,51 @@ namespace DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors
|
|||||||
|
|
||||||
return base.VisitEmoji(emoji);
|
return base.VisitEmoji(emoji);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected override MarkdownNode VisitMention(MentionNode mention)
|
||||||
|
{
|
||||||
|
var mentionId = Snowflake.TryParse(mention.Id);
|
||||||
|
if (mention.Kind == MentionKind.Meta)
|
||||||
|
{
|
||||||
|
_buffer.Append($"@{mention.Id}");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.User)
|
||||||
|
{
|
||||||
|
var member = mentionId?.Pipe(_context.TryGetMember);
|
||||||
|
var name = member?.User.Name ?? "Unknown";
|
||||||
|
|
||||||
|
_buffer.Append($"@{name}");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.Channel)
|
||||||
|
{
|
||||||
|
var channel = mentionId?.Pipe(_context.TryGetChannel);
|
||||||
|
var name = channel?.Name ?? "deleted-channel";
|
||||||
|
|
||||||
|
_buffer.Append($"#{name}");
|
||||||
|
|
||||||
|
// Voice channel marker
|
||||||
|
if (channel?.IsVoiceChannel == true)
|
||||||
|
_buffer.Append(" [voice]");
|
||||||
|
}
|
||||||
|
else if (mention.Kind == MentionKind.Role)
|
||||||
|
{
|
||||||
|
var role = mentionId?.Pipe(_context.TryGetRole);
|
||||||
|
var name = role?.Name ?? "deleted-role";
|
||||||
|
|
||||||
|
_buffer.Append($"@{name}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return base.VisitMention(mention);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override MarkdownNode VisitUnixTimestamp(UnixTimestampNode timestamp)
|
||||||
|
{
|
||||||
|
_buffer.Append(
|
||||||
|
_context.FormatDate(timestamp.Value)
|
||||||
|
);
|
||||||
|
|
||||||
|
return base.VisitUnixTimestamp(timestamp);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal partial class PlainTextMarkdownVisitor
|
internal partial class PlainTextMarkdownVisitor
|
||||||
+11
-3
@@ -1,9 +1,9 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
namespace DiscordChatExporter.Core.Exporting.Writers
|
||||||
{
|
{
|
||||||
internal abstract class MessageWriter : IAsyncDisposable
|
internal abstract class MessageWriter : IAsyncDisposable
|
||||||
{
|
{
|
||||||
@@ -11,6 +11,10 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
protected ExportContext Context { get; }
|
protected ExportContext Context { get; }
|
||||||
|
|
||||||
|
public long MessagesWritten { get; private set; }
|
||||||
|
|
||||||
|
public long BytesWritten => Stream.Length;
|
||||||
|
|
||||||
protected MessageWriter(Stream stream, ExportContext context)
|
protected MessageWriter(Stream stream, ExportContext context)
|
||||||
{
|
{
|
||||||
Stream = stream;
|
Stream = stream;
|
||||||
@@ -19,7 +23,11 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
public virtual ValueTask WritePreambleAsync() => default;
|
public virtual ValueTask WritePreambleAsync() => default;
|
||||||
|
|
||||||
public abstract ValueTask WriteMessageAsync(Message message);
|
public virtual ValueTask WriteMessageAsync(Message message)
|
||||||
|
{
|
||||||
|
MessagesWritten++;
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
public virtual ValueTask WritePostambleAsync() => default;
|
public virtual ValueTask WritePostambleAsync() => default;
|
||||||
|
|
||||||
+16
-15
@@ -2,18 +2,16 @@
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using DiscordChatExporter.Domain.Discord.Models;
|
using DiscordChatExporter.Core.Discord.Data;
|
||||||
using DiscordChatExporter.Domain.Exporting.Writers.MarkdownVisitors;
|
using DiscordChatExporter.Core.Exporting.Writers.MarkdownVisitors;
|
||||||
using Tyrrrz.Extensions;
|
using Tyrrrz.Extensions;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Exporting.Writers
|
namespace DiscordChatExporter.Core.Exporting.Writers
|
||||||
{
|
{
|
||||||
internal class PlainTextMessageWriter : MessageWriter
|
internal class PlainTextMessageWriter : MessageWriter
|
||||||
{
|
{
|
||||||
private readonly TextWriter _writer;
|
private readonly TextWriter _writer;
|
||||||
|
|
||||||
private long _messageCount;
|
|
||||||
|
|
||||||
public PlainTextMessageWriter(Stream stream, ExportContext context)
|
public PlainTextMessageWriter(Stream stream, ExportContext context)
|
||||||
: base(stream, context)
|
: base(stream, context)
|
||||||
{
|
{
|
||||||
@@ -77,10 +75,10 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embed.Thumbnail?.Url))
|
if (!string.IsNullOrWhiteSpace(embed.Thumbnail?.Url))
|
||||||
await _writer.WriteLineAsync(await Context.ResolveMediaUrlAsync(embed.Thumbnail.Url));
|
await _writer.WriteLineAsync(await Context.ResolveMediaUrlAsync(embed.Thumbnail.ProxyUrl ?? embed.Thumbnail.Url));
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embed.Image?.Url))
|
if (!string.IsNullOrWhiteSpace(embed.Image?.Url))
|
||||||
await _writer.WriteLineAsync(await Context.ResolveMediaUrlAsync(embed.Image.Url));
|
await _writer.WriteLineAsync(await Context.ResolveMediaUrlAsync(embed.Image.ProxyUrl ?? embed.Image.Url));
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(embed.Footer?.Text))
|
if (!string.IsNullOrWhiteSpace(embed.Footer?.Text))
|
||||||
await _writer.WriteLineAsync(embed.Footer.Text);
|
await _writer.WriteLineAsync(embed.Footer.Text);
|
||||||
@@ -113,16 +111,16 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
{
|
{
|
||||||
await _writer.WriteLineAsync('='.Repeat(62));
|
await _writer.WriteLineAsync('='.Repeat(62));
|
||||||
await _writer.WriteLineAsync($"Guild: {Context.Request.Guild.Name}");
|
await _writer.WriteLineAsync($"Guild: {Context.Request.Guild.Name}");
|
||||||
await _writer.WriteLineAsync($"Channel: {Context.Request.Channel.Category} / {Context.Request.Channel.Name}");
|
await _writer.WriteLineAsync($"Channel: {Context.Request.Channel.Category.Name} / {Context.Request.Channel.Name}");
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(Context.Request.Channel.Topic))
|
if (!string.IsNullOrWhiteSpace(Context.Request.Channel.Topic))
|
||||||
await _writer.WriteLineAsync($"Topic: {Context.Request.Channel.Topic}");
|
await _writer.WriteLineAsync($"Topic: {Context.Request.Channel.Topic}");
|
||||||
|
|
||||||
if (Context.Request.After != null)
|
if (Context.Request.After is not null)
|
||||||
await _writer.WriteLineAsync($"After: {Context.FormatDate(Context.Request.After.Value)}");
|
await _writer.WriteLineAsync($"After: {Context.FormatDate(Context.Request.After.Value.ToDate())}");
|
||||||
|
|
||||||
if (Context.Request.Before != null)
|
if (Context.Request.Before is not null)
|
||||||
await _writer.WriteLineAsync($"Before: {Context.FormatDate(Context.Request.Before.Value)}");
|
await _writer.WriteLineAsync($"Before: {Context.FormatDate(Context.Request.Before.Value.ToDate())}");
|
||||||
|
|
||||||
await _writer.WriteLineAsync('='.Repeat(62));
|
await _writer.WriteLineAsync('='.Repeat(62));
|
||||||
await _writer.WriteLineAsync();
|
await _writer.WriteLineAsync();
|
||||||
@@ -130,26 +128,29 @@ namespace DiscordChatExporter.Domain.Exporting.Writers
|
|||||||
|
|
||||||
public override async ValueTask WriteMessageAsync(Message message)
|
public override async ValueTask WriteMessageAsync(Message message)
|
||||||
{
|
{
|
||||||
|
await base.WriteMessageAsync(message);
|
||||||
|
|
||||||
|
// Header
|
||||||
await WriteMessageHeaderAsync(message);
|
await WriteMessageHeaderAsync(message);
|
||||||
|
|
||||||
|
// Content
|
||||||
if (!string.IsNullOrWhiteSpace(message.Content))
|
if (!string.IsNullOrWhiteSpace(message.Content))
|
||||||
await _writer.WriteLineAsync(FormatMarkdown(message.Content));
|
await _writer.WriteLineAsync(FormatMarkdown(message.Content));
|
||||||
|
|
||||||
await _writer.WriteLineAsync();
|
await _writer.WriteLineAsync();
|
||||||
|
|
||||||
|
// Attachments, embeds, reactions
|
||||||
await WriteAttachmentsAsync(message.Attachments);
|
await WriteAttachmentsAsync(message.Attachments);
|
||||||
await WriteEmbedsAsync(message.Embeds);
|
await WriteEmbedsAsync(message.Embeds);
|
||||||
await WriteReactionsAsync(message.Reactions);
|
await WriteReactionsAsync(message.Reactions);
|
||||||
|
|
||||||
await _writer.WriteLineAsync();
|
await _writer.WriteLineAsync();
|
||||||
|
|
||||||
_messageCount++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async ValueTask WritePostambleAsync()
|
public override async ValueTask WritePostambleAsync()
|
||||||
{
|
{
|
||||||
await _writer.WriteLineAsync('='.Repeat(62));
|
await _writer.WriteLineAsync('='.Repeat(62));
|
||||||
await _writer.WriteLineAsync($"Exported {_messageCount:N0} message(s)");
|
await _writer.WriteLineAsync($"Exported {MessagesWritten:N0} message(s)");
|
||||||
await _writer.WriteLineAsync('='.Repeat(62));
|
await _writer.WriteLineAsync('='.Repeat(62));
|
||||||
}
|
}
|
||||||
|
|
||||||
+10
-1
@@ -1,11 +1,20 @@
|
|||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
using DiscordChatExporter.Core.Utils;
|
||||||
|
|
||||||
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal class EmojiNode : MarkdownNode
|
internal class EmojiNode : MarkdownNode
|
||||||
{
|
{
|
||||||
|
// Only present on custom emoji
|
||||||
public string? Id { get; }
|
public string? Id { get; }
|
||||||
|
|
||||||
|
// Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂)
|
||||||
public string Name { get; }
|
public string Name { get; }
|
||||||
|
|
||||||
|
// Name of custom emoji (e.g. LUL) or name of standard emoji (e.g. slight_smile)
|
||||||
|
public string Code => !string.IsNullOrWhiteSpace(Id)
|
||||||
|
? Name
|
||||||
|
: EmojiIndex.TryGetCode(Name) ?? Name;
|
||||||
|
|
||||||
public bool IsAnimated { get; }
|
public bool IsAnimated { get; }
|
||||||
|
|
||||||
public bool IsCustomEmoji => !string.IsNullOrWhiteSpace(Id);
|
public bool IsCustomEmoji => !string.IsNullOrWhiteSpace(Id);
|
||||||
+1
-11
@@ -1,17 +1,7 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal enum TextFormatting
|
|
||||||
{
|
|
||||||
Bold,
|
|
||||||
Italic,
|
|
||||||
Underline,
|
|
||||||
Strikethrough,
|
|
||||||
Spoiler,
|
|
||||||
Quote
|
|
||||||
}
|
|
||||||
|
|
||||||
internal class FormattedNode : MarkdownNode
|
internal class FormattedNode : MarkdownNode
|
||||||
{
|
{
|
||||||
public TextFormatting Formatting { get; }
|
public TextFormatting Formatting { get; }
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal class InlineCodeBlockNode : MarkdownNode
|
internal class InlineCodeBlockNode : MarkdownNode
|
||||||
{
|
{
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal class LinkNode : MarkdownNode
|
internal class LinkNode : MarkdownNode
|
||||||
{
|
{
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal abstract class MarkdownNode
|
internal abstract class MarkdownNode
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
|
{
|
||||||
|
internal enum MentionKind
|
||||||
|
{
|
||||||
|
Meta,
|
||||||
|
User,
|
||||||
|
Channel,
|
||||||
|
Role
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
|
{
|
||||||
|
internal class MentionNode : MarkdownNode
|
||||||
|
{
|
||||||
|
public string Id { get; }
|
||||||
|
|
||||||
|
public MentionKind Kind { get; }
|
||||||
|
|
||||||
|
public MentionNode(string id, MentionKind kind)
|
||||||
|
{
|
||||||
|
Id = id;
|
||||||
|
Kind = kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => $"<{Kind} mention> {Id}";
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace DiscordChatExporter.Domain.Markdown.Ast
|
namespace DiscordChatExporter.Core.Markdown
|
||||||
{
|
{
|
||||||
internal class MultiLineCodeBlockNode : MarkdownNode
|
internal class MultiLineCodeBlockNode : MarkdownNode
|
||||||
{
|
{
|
||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
namespace DiscordChatExporter.Core.Markdown.Parsing
|
||||||
{
|
{
|
||||||
internal class AggregateMatcher<T> : IMatcher<T>
|
internal class AggregateMatcher<T> : IMatcher<T>
|
||||||
{
|
{
|
||||||
@@ -27,11 +27,11 @@ namespace DiscordChatExporter.Domain.Markdown.Matching
|
|||||||
var match = matcher.TryMatch(stringPart);
|
var match = matcher.TryMatch(stringPart);
|
||||||
|
|
||||||
// If there's no match - continue
|
// If there's no match - continue
|
||||||
if (match == null)
|
if (match is null)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
// If this match is earlier than previous earliest - replace
|
// If this match is earlier than previous earliest - replace
|
||||||
if (earliestMatch == null || match.StringPart.StartIndex < earliestMatch.StringPart.StartIndex)
|
if (earliestMatch is null || match.StringPart.StartIndex < earliestMatch.StringPart.StartIndex)
|
||||||
earliestMatch = match;
|
earliestMatch = match;
|
||||||
|
|
||||||
// If the earliest match starts at the very beginning - break,
|
// If the earliest match starts at the very beginning - break,
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Markdown.Matching
|
namespace DiscordChatExporter.Core.Markdown.Parsing
|
||||||
{
|
{
|
||||||
internal interface IMatcher<T>
|
internal interface IMatcher<T>
|
||||||
{
|
{
|
||||||
@@ -21,7 +21,7 @@ namespace DiscordChatExporter.Domain.Markdown.Matching
|
|||||||
var match = matcher.TryMatch(stringPart.Slice(currentIndex, stringPart.EndIndex - currentIndex));
|
var match = matcher.TryMatch(stringPart.Slice(currentIndex, stringPart.EndIndex - currentIndex));
|
||||||
|
|
||||||
// If there's no match - break
|
// If there's no match - break
|
||||||
if (match == null)
|
if (match is null)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
// If this match doesn't start immediately at current index - transform and yield fallback first
|
// If this match doesn't start immediately at current index - transform and yield fallback first
|
||||||
+127
-49
@@ -1,82 +1,101 @@
|
|||||||
using System.Collections.Generic;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using DiscordChatExporter.Domain.Markdown.Ast;
|
using DiscordChatExporter.Core.Utils;
|
||||||
using DiscordChatExporter.Domain.Markdown.Matching;
|
|
||||||
|
|
||||||
namespace DiscordChatExporter.Domain.Markdown
|
namespace DiscordChatExporter.Core.Markdown.Parsing
|
||||||
{
|
{
|
||||||
// The following parsing logic is meant to replicate Discord's markdown grammar as close as possible
|
// The following parsing logic is meant to replicate Discord's markdown grammar as close as possible
|
||||||
internal static partial class MarkdownParser
|
internal static partial class MarkdownParser
|
||||||
{
|
{
|
||||||
private const RegexOptions DefaultRegexOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline;
|
private const RegexOptions DefaultRegexOptions =
|
||||||
|
RegexOptions.Compiled |
|
||||||
|
RegexOptions.CultureInvariant |
|
||||||
|
RegexOptions.Multiline;
|
||||||
|
|
||||||
/* Formatting */
|
/* Formatting */
|
||||||
|
|
||||||
// Capture any character until the earliest double asterisk not followed by an asterisk
|
// Capture any character until the earliest double asterisk not followed by an asterisk
|
||||||
private static readonly IMatcher<MarkdownNode> BoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> BoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("\\*\\*(.+?)\\*\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Bold, Parse(p.Slice(m.Groups[1]))));
|
(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
|
// Capture any character until the earliest single asterisk not preceded or followed by an asterisk
|
||||||
// Opening asterisk must not be followed by whitespace
|
// Opening asterisk must not be followed by whitespace
|
||||||
// Closing asterisk must not be preceded by whitespace
|
// Closing asterisk must not be preceded by whitespace
|
||||||
private static readonly IMatcher<MarkdownNode> ItalicFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ItalicFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("\\*(?!\\s)(.+?)(?<!\\s|\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]))));
|
(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
|
// Capture any character until the earliest triple asterisk not followed by an asterisk
|
||||||
private static readonly IMatcher<MarkdownNode> ItalicBoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ItalicBoldFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\*(\\*\\*.+?\\*\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("\\*(\\*\\*.+?\\*\\*)\\*(?!\\*)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]), BoldFormattedNodeMatcher)));
|
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]), BoldFormattedNodeMatcher))
|
||||||
|
);
|
||||||
|
|
||||||
// Capture any character except underscore until an underscore
|
// Capture any character except underscore until an underscore
|
||||||
// Closing underscore must not be followed by a word character
|
// Closing underscore must not be followed by a word character
|
||||||
private static readonly IMatcher<MarkdownNode> ItalicAltFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ItalicAltFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("_([^_]+)_(?!\\w)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("_([^_]+)_(?!\\w)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]))));
|
(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
|
// Capture any character until the earliest double underscore not followed by an underscore
|
||||||
private static readonly IMatcher<MarkdownNode> UnderlineFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> UnderlineFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("__(.+?)__(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("__(.+?)__(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Underline, Parse(p.Slice(m.Groups[1]))));
|
(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
|
// Capture any character until the earliest triple underscore not followed by an underscore
|
||||||
private static readonly IMatcher<MarkdownNode> ItalicUnderlineFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ItalicUnderlineFormattedNodeMatcher =
|
||||||
new Regex("_(__.+?__)_(?!_)", DefaultRegexOptions | RegexOptions.Singleline),
|
new RegexMatcher<MarkdownNode>(
|
||||||
(p, m) => new FormattedNode(TextFormatting.Italic, Parse(p.Slice(m.Groups[1]), UnderlineFormattedNodeMatcher)));
|
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
|
// Capture any character until the earliest double tilde
|
||||||
private static readonly IMatcher<MarkdownNode> StrikethroughFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> StrikethroughFormattedNodeMatcher =
|
||||||
new Regex("~~(.+?)~~", DefaultRegexOptions | RegexOptions.Singleline),
|
new RegexMatcher<MarkdownNode>(
|
||||||
(p, m) => new FormattedNode(TextFormatting.Strikethrough, Parse(p.Slice(m.Groups[1]))));
|
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
|
// Capture any character until the earliest double pipe
|
||||||
private static readonly IMatcher<MarkdownNode> SpoilerFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> SpoilerFormattedNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\|\\|(.+?)\\|\\|", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("\\|\\|(.+?)\\|\\|", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Spoiler, Parse(p.Slice(m.Groups[1]))));
|
(p, m) => new FormattedNode(TextFormatting.Spoiler, Parse(p.Slice(m.Groups[1])))
|
||||||
|
);
|
||||||
|
|
||||||
// Capture any character until the end of the line
|
// Capture any character until the end of the line
|
||||||
// Opening 'greater than' character must be followed by whitespace
|
// Opening 'greater than' character must be followed by whitespace
|
||||||
private static readonly IMatcher<MarkdownNode> SingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> SingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("^>\\s(.+\n?)", DefaultRegexOptions),
|
new Regex("^>\\s(.+\n?)", DefaultRegexOptions),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1]))));
|
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1])))
|
||||||
|
);
|
||||||
|
|
||||||
// Repeatedly capture any character until the end of the line
|
// Repeatedly capture any character until the end of the line
|
||||||
// This one is tricky as it ends up producing multiple separate captures which need to be joined
|
// This one is tricky as it ends up producing multiple separate captures which need to be joined
|
||||||
private static readonly IMatcher<MarkdownNode> RepeatedSingleLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> RepeatedSingleLineQuoteNodeMatcher =
|
||||||
new Regex("(?:^>\\s(.+\n?)){2,}", DefaultRegexOptions),
|
new RegexMatcher<MarkdownNode>(
|
||||||
(p, m) =>
|
new Regex("(?:^>\\s(.+\n?)){2,}", DefaultRegexOptions),
|
||||||
{
|
(_, m) =>
|
||||||
var content = string.Concat(m.Groups[1].Captures.Select(c => c.Value));
|
{
|
||||||
return new FormattedNode(TextFormatting.Quote, Parse(content));
|
var content = string.Concat(m.Groups[1].Captures.Select(c => c.Value));
|
||||||
});
|
return new FormattedNode(TextFormatting.Quote, Parse(content));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Capture any character until the end of the input
|
// Capture any character until the end of the input
|
||||||
// Opening 'greater than' characters must be followed by whitespace
|
// Opening 'greater than' characters must be followed by whitespace
|
||||||
private static readonly IMatcher<MarkdownNode> MultiLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> MultiLineQuoteNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("^>>>\\s(.+)", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("^>>>\\s(.+)", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1]))));
|
(p, m) => new FormattedNode(TextFormatting.Quote, Parse(p.Slice(m.Groups[1])))
|
||||||
|
);
|
||||||
|
|
||||||
/* Code blocks */
|
/* Code blocks */
|
||||||
|
|
||||||
@@ -85,41 +104,48 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
// There can be either one or two backticks, but equal number on both sides
|
// There can be either one or two backticks, but equal number on both sides
|
||||||
private static readonly IMatcher<MarkdownNode> InlineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> InlineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("(`{1,2})([^`]+)\\1", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("(`{1,2})([^`]+)\\1", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
m => new InlineCodeBlockNode(m.Groups[2].Value.Trim('\r', '\n')));
|
(_, m) => new InlineCodeBlockNode(m.Groups[2].Value.Trim('\r', '\n'))
|
||||||
|
);
|
||||||
|
|
||||||
// Capture language identifier and then any character until the earliest triple backtick
|
// 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
|
// Language identifier is one word immediately after opening backticks, followed immediately by newline
|
||||||
// Blank lines at the beginning and end of content are trimmed
|
// Blank lines at the beginning and end of content are trimmed
|
||||||
private static readonly IMatcher<MarkdownNode> MultiLineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> MultiLineCodeBlockNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("```(?:(\\w*)\\n)?(.+?)```", DefaultRegexOptions | RegexOptions.Singleline),
|
new Regex("```(?:(\\w*)\\n)?(.+?)```", DefaultRegexOptions | RegexOptions.Singleline),
|
||||||
m => new MultiLineCodeBlockNode(m.Groups[1].Value, m.Groups[2].Value.Trim('\r', '\n')));
|
(_, m) => new MultiLineCodeBlockNode(m.Groups[1].Value, m.Groups[2].Value.Trim('\r', '\n'))
|
||||||
|
);
|
||||||
|
|
||||||
/* Mentions */
|
/* Mentions */
|
||||||
|
|
||||||
// Capture @everyone
|
// Capture @everyone
|
||||||
private static readonly IMatcher<MarkdownNode> EveryoneMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> EveryoneMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||||
"@everyone",
|
"@everyone",
|
||||||
p => new MentionNode("everyone", MentionType.Meta));
|
_ => new MentionNode("everyone", MentionKind.Meta)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture @here
|
// Capture @here
|
||||||
private static readonly IMatcher<MarkdownNode> HereMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> HereMentionNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||||
"@here",
|
"@here",
|
||||||
p => new MentionNode("here", MentionType.Meta));
|
_ => new MentionNode("here", MentionKind.Meta)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture <@123456> or <@!123456>
|
// Capture <@123456> or <@!123456>
|
||||||
private static readonly IMatcher<MarkdownNode> UserMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> UserMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("<@!?(\\d+)>", DefaultRegexOptions),
|
new Regex("<@!?(\\d+)>", DefaultRegexOptions),
|
||||||
m => new MentionNode(m.Groups[1].Value, MentionType.User));
|
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.User)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture <#123456>
|
// Capture <#123456>
|
||||||
private static readonly IMatcher<MarkdownNode> ChannelMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ChannelMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("<#(\\d+)>", DefaultRegexOptions),
|
new Regex("<#!?(\\d+)>", DefaultRegexOptions),
|
||||||
m => new MentionNode(m.Groups[1].Value, MentionType.Channel));
|
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.Channel)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture <@&123456>
|
// Capture <@&123456>
|
||||||
private static readonly IMatcher<MarkdownNode> RoleMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> RoleMentionNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("<@&(\\d+)>", DefaultRegexOptions),
|
new Regex("<@&(\\d+)>", DefaultRegexOptions),
|
||||||
m => new MentionNode(m.Groups[1].Value, MentionType.Role));
|
(_, m) => new MentionNode(m.Groups[1].Value, MentionKind.Role)
|
||||||
|
);
|
||||||
|
|
||||||
/* Emojis */
|
/* Emojis */
|
||||||
|
|
||||||
@@ -130,29 +156,46 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
// (this does not match all emojis in Discord but it's reasonably accurate enough)
|
// (this does not match all emojis in Discord but it's reasonably accurate enough)
|
||||||
private static readonly IMatcher<MarkdownNode> StandardEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> StandardEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("((?:[\\uD83C][\\uDDE6-\\uDDFF]){2}|[\\u2600-\\u26FF]|\\p{Cs}{2}|\\d\\p{Me})", DefaultRegexOptions),
|
new Regex("((?:[\\uD83C][\\uDDE6-\\uDDFF]){2}|[\\u2600-\\u26FF]|\\p{Cs}{2}|\\d\\p{Me})", DefaultRegexOptions),
|
||||||
m => new EmojiNode(m.Groups[1].Value));
|
(_, m) => new EmojiNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Capture :thinking: (but only for known emoji codes)
|
||||||
|
private static readonly IMatcher<MarkdownNode> CodedStandardEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
|
new Regex(":([\\w_]+):", DefaultRegexOptions),
|
||||||
|
(_, m) =>
|
||||||
|
{
|
||||||
|
var name = EmojiIndex.TryGetName(m.Groups[1].Value);
|
||||||
|
return name is not null
|
||||||
|
? new EmojiNode(name)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Capture <:lul:123456> or <a:lul:123456>
|
// Capture <:lul:123456> or <a:lul:123456>
|
||||||
private static readonly IMatcher<MarkdownNode> CustomEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> CustomEmojiNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("<(a)?:(.+?):(\\d+?)>", DefaultRegexOptions),
|
new Regex("<(a)?:(.+?):(\\d+?)>", DefaultRegexOptions),
|
||||||
m => new EmojiNode(m.Groups[3].Value, m.Groups[2].Value, !string.IsNullOrWhiteSpace(m.Groups[1].Value)));
|
(_, m) => new EmojiNode(m.Groups[3].Value, m.Groups[2].Value, !string.IsNullOrWhiteSpace(m.Groups[1].Value))
|
||||||
|
);
|
||||||
|
|
||||||
/* Links */
|
/* Links */
|
||||||
|
|
||||||
// Capture [title](link)
|
// Capture [title](link)
|
||||||
private static readonly IMatcher<MarkdownNode> TitledLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> TitledLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\[(.+?)\\]\\((.+?)\\)", DefaultRegexOptions),
|
new Regex("\\[(.+?)\\]\\((.+?)\\)", DefaultRegexOptions),
|
||||||
m => new LinkNode(m.Groups[2].Value, m.Groups[1].Value));
|
(_, 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
|
// Capture any non-whitespace character after http:// or https:// until the last punctuation character or whitespace
|
||||||
private static readonly IMatcher<MarkdownNode> AutoLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> AutoLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("(https?://\\S*[^\\.,:;\"\'\\s])", DefaultRegexOptions),
|
new Regex("(https?://\\S*[^\\.,:;\"\'\\s])", DefaultRegexOptions),
|
||||||
m => new LinkNode(m.Groups[1].Value));
|
(_, m) => new LinkNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
// Same as auto link but also surrounded by angular brackets
|
// Same as auto link but also surrounded by angular brackets
|
||||||
private static readonly IMatcher<MarkdownNode> HiddenLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> HiddenLinkNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("<(https?://\\S*[^\\.,:;\"\'\\s])>", DefaultRegexOptions),
|
new Regex("<(https?://\\S*[^\\.,:;\"\'\\s])>", DefaultRegexOptions),
|
||||||
m => new LinkNode(m.Groups[1].Value));
|
(_, m) => new LinkNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
/* Text */
|
/* Text */
|
||||||
|
|
||||||
@@ -160,25 +203,49 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
// This escapes it from matching for formatting
|
// This escapes it from matching for formatting
|
||||||
private static readonly IMatcher<MarkdownNode> ShrugTextNodeMatcher = new StringMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> ShrugTextNodeMatcher = new StringMatcher<MarkdownNode>(
|
||||||
@"¯\_(ツ)_/¯",
|
@"¯\_(ツ)_/¯",
|
||||||
p => new TextNode(p.ToString()));
|
p => new TextNode(p.ToString())
|
||||||
|
);
|
||||||
|
|
||||||
// Capture some specific emojis that don't get rendered
|
// Capture some specific emojis that don't get rendered
|
||||||
// This escapes it from matching for emoji
|
// This escapes it from matching for emoji
|
||||||
private static readonly IMatcher<MarkdownNode> IgnoredEmojiTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> IgnoredEmojiTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("(\\u26A7|\\u2640|\\u2642|\\u2695|\\u267E|\\u00A9|\\u00AE|\\u2122)", DefaultRegexOptions),
|
new Regex("(\\u26A7|\\u2640|\\u2642|\\u2695|\\u267E|\\u00A9|\\u00AE|\\u2122)", DefaultRegexOptions),
|
||||||
m => new TextNode(m.Groups[1].Value));
|
(_, m) => new TextNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture any "symbol/other" character or surrogate pair preceded by a backslash
|
// Capture any "symbol/other" character or surrogate pair preceded by a backslash
|
||||||
// This escapes it from matching for emoji
|
// This escapes it from matching for emoji
|
||||||
private static readonly IMatcher<MarkdownNode> EscapedSymbolTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> EscapedSymbolTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\\\(\\p{So}|\\p{Cs}{2})", DefaultRegexOptions),
|
new Regex("\\\\(\\p{So}|\\p{Cs}{2})", DefaultRegexOptions),
|
||||||
m => new TextNode(m.Groups[1].Value));
|
(_, m) => new TextNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
// Capture any non-whitespace, non latin alphanumeric character preceded by a backslash
|
// Capture any non-whitespace, non latin alphanumeric character preceded by a backslash
|
||||||
// This escapes it from matching for formatting or other tokens
|
// This escapes it from matching for formatting or other tokens
|
||||||
private static readonly IMatcher<MarkdownNode> EscapedCharacterTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
private static readonly IMatcher<MarkdownNode> EscapedCharacterTextNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
new Regex("\\\\([^a-zA-Z0-9\\s])", DefaultRegexOptions),
|
new Regex("\\\\([^a-zA-Z0-9\\s])", DefaultRegexOptions),
|
||||||
m => new TextNode(m.Groups[1].Value));
|
(_, m) => new TextNode(m.Groups[1].Value)
|
||||||
|
);
|
||||||
|
|
||||||
|
/* Misc */
|
||||||
|
|
||||||
|
// Capture <t:12345678> or <t:12345678:R>
|
||||||
|
private static readonly IMatcher<MarkdownNode> UnixTimestampNodeMatcher = new RegexMatcher<MarkdownNode>(
|
||||||
|
new Regex("<t:(\\d+)(?::\\w)?>", DefaultRegexOptions),
|
||||||
|
(_, m) =>
|
||||||
|
{
|
||||||
|
// We don't care about the 'R' parameter because we're not going to
|
||||||
|
// show relative timestamps in an export anyway.
|
||||||
|
|
||||||
|
if (!long.TryParse(m.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture,
|
||||||
|
out var offset))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new UnixTimestampNode(DateTimeOffset.UnixEpoch + TimeSpan.FromSeconds(offset));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Combine all matchers into one
|
// Combine all matchers into one
|
||||||
// Matchers that have similar patterns are ordered from most specific to least specific
|
// Matchers that have similar patterns are ordered from most specific to least specific
|
||||||
@@ -220,7 +287,11 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
|
|
||||||
// Emoji
|
// Emoji
|
||||||
StandardEmojiNodeMatcher,
|
StandardEmojiNodeMatcher,
|
||||||
CustomEmojiNodeMatcher
|
CustomEmojiNodeMatcher,
|
||||||
|
CodedStandardEmojiNodeMatcher,
|
||||||
|
|
||||||
|
// Misc
|
||||||
|
UnixTimestampNodeMatcher
|
||||||
);
|
);
|
||||||
|
|
||||||
// Minimal set of matchers for non-multimedia formats (e.g. plain text)
|
// Minimal set of matchers for non-multimedia formats (e.g. plain text)
|
||||||
@@ -233,7 +304,10 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
RoleMentionNodeMatcher,
|
RoleMentionNodeMatcher,
|
||||||
|
|
||||||
// Emoji
|
// Emoji
|
||||||
CustomEmojiNodeMatcher
|
CustomEmojiNodeMatcher,
|
||||||
|
|
||||||
|
// Misc
|
||||||
|
UnixTimestampNodeMatcher
|
||||||
);
|
);
|
||||||
|
|
||||||
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart, IMatcher<MarkdownNode> matcher) =>
|
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart, IMatcher<MarkdownNode> matcher) =>
|
||||||
@@ -245,12 +319,16 @@ namespace DiscordChatExporter.Domain.Markdown
|
|||||||
|
|
||||||
internal static partial class MarkdownParser
|
internal static partial class MarkdownParser
|
||||||
{
|
{
|
||||||
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart) => Parse(stringPart, AggregateNodeMatcher);
|
private static IReadOnlyList<MarkdownNode> Parse(StringPart stringPart) =>
|
||||||
|
Parse(stringPart, AggregateNodeMatcher);
|
||||||
|
|
||||||
private static IReadOnlyList<MarkdownNode> ParseMinimal(StringPart stringPart) => Parse(stringPart, MinimalAggregateNodeMatcher);
|
private static IReadOnlyList<MarkdownNode> ParseMinimal(StringPart stringPart) =>
|
||||||
|
Parse(stringPart, MinimalAggregateNodeMatcher);
|
||||||
|
|
||||||
public static IReadOnlyList<MarkdownNode> Parse(string input) => Parse(new StringPart(input));
|
public static IReadOnlyList<MarkdownNode> Parse(string input) =>
|
||||||
|
Parse(new StringPart(input));
|
||||||
|
|
||||||
public static IReadOnlyList<MarkdownNode> ParseMinimal(string input) => ParseMinimal(new StringPart(input));
|
public static IReadOnlyList<MarkdownNode> ParseMinimal(string input) =>
|
||||||
|
ParseMinimal(new StringPart(input));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user