Compare commits

...

563 Commits

Author SHA1 Message Date
Oleksii Holub 6c484d1f88 Update version 2022-01-27 18:36:28 +02:00
Oleksii Holub c36b8df8e7 Update NuGet packages 2022-01-27 18:25:21 +02:00
Dhananjay-JSR 0408096746 Update token extraction guide (#791) 2022-01-25 15:11:22 -08:00
Tyrrrz 40d833cd57 Update my name to match correct spelling 2022-01-15 03:27:19 +02:00
Tyrrrz 0de1f47310 More parsing leniency
Closes #767
2022-01-09 22:24:02 +02:00
Tyrrrz e31ff55e33 Handle invalid dates more gracefully
Closes #766
2022-01-05 18:54:23 +02:00
Tyrrrz 81525a1076 Update license 2022-01-05 18:31:16 +02:00
Tyrrrz 65ab003ff5 Relax parsing rules for embed fields
Closes #765
2022-01-04 22:44:03 +02:00
Alexey Golub 2156c6cd0c Automatically detect token kind (#764) 2022-01-03 14:52:16 -08:00
Tyrrrz e97151cd19 Update NuGet packages 2022-01-03 00:36:10 +02:00
Tyrrrz 271a478a0e Minor GUI tweaks 2021-12-15 16:30:23 +02:00
Tyrrrz b40a88c4d3 Add border to settings view too 2021-12-15 16:13:48 +02:00
Tyrrrz f03f5f8072 Update version 2021-12-15 15:35:00 +02:00
Tyrrrz bfa5d10761 Handle null name in Emoji.Parse(...) 2021-12-15 02:05:19 +02:00
Tyrrrz 7a9e25c1f0 Improve settings view in GUI 2021-12-14 01:54:17 +02:00
Tyrrrz 4599e64f0a Update NuGet packages 2021-12-14 01:28:43 +02:00
Tyrrrz 4389b4e0bc Improve GUI 2021-12-14 01:26:59 +02:00
Tyrrrz 008bb2f591 Use .NET 6's ParallelForEachAsync(...) 2021-12-13 21:02:11 +02:00
Tyrrrz b8567d384f More defensive programming 2021-12-12 23:45:52 +02:00
Tyrrrz a06b448f4a Don't use GetNonWhiteSpaceString() with nullable JSON fields
Fixes #747
2021-12-11 16:50:09 +02:00
Tyrrrz ba4ece9325 Share things from .github repo 2021-12-11 00:15:31 +02:00
Tyrrrz 880f400e2c C#10ify 2021-12-08 23:50:21 +02:00
Tyrrrz 8e7baee8a5 Update version 2021-12-06 16:44:37 +02:00
Tyrrrz f7c4b80a2d Update nuget packages 2021-12-05 23:14:37 +02:00
Tyrrrz a0e7d8e3af Update readme 2021-12-05 22:15:51 +02:00
Tyrrrz 72b0bb37f4 Update readme 2021-12-05 21:59:13 +02:00
Tyrrrz 6c70ff0963 Update nuget packages 2021-12-05 19:23:07 +02:00
Tyrrrz 9def32d67e Update DotnetRuntimeBootstrapper 2021-12-05 01:28:21 +02:00
Tyrrrz 4974fe5292 Refer to Category.Name explicitly instead of relying on ToString() 2021-11-19 22:18:15 +02:00
Tyrrrz 1db2bb4170 Remove Tyrrrz.Extensions package 2021-11-15 18:50:46 +02:00
Tyrrrz 720e53caab [GUI] Fix outdated binding 2021-11-15 18:06:10 +02:00
Tyrrrz da9536bd1b Update NuGet packages 2021-11-15 18:02:41 +02:00
Tyrrrz d8de3bf779 Re-add IComparable<T> to Snowflake 2021-11-09 23:31:27 +02:00
Tyrrrz 7c88a21543 Convert several types to records 2021-11-09 23:15:56 +02:00
Tyrrrz 2393a6a472 Remove XAMLStyler 2021-11-08 23:26:04 +02:00
Tyrrrz 214d5e3bdb Fix nullability errors 2021-11-08 23:16:37 +02:00
Tyrrrz f456297881 Update to .NET 6
Closes #521
2021-11-08 22:44:38 +02:00
Artem 092f0cade9 Align design with Discord (#728) 2021-10-25 11:08:03 -07:00
Emily fc6cfcfcc6 Fix RTL rendering in HTML exports (#727) 2021-10-18 09:18:23 -07:00
Emily 46450367e3 Add markdown support for channel topics in HTML export (#720)
Co-authored-by: Alexey Golub <1935960+Tyrrrz@users.noreply.github.com>
2021-10-16 06:29:59 -07:00
Tyrrrz 21d89afa70 Add managed cancellation support
Closes #716
2021-10-07 17:06:05 +03:00
Tyrrrz 2f3e165988 Update NuGet packages 2021-10-07 15:54:01 +03:00
Tyrrrz b64dff1eab Don't run tests against PRs 2021-09-28 20:40:48 +03:00
Tyrrrz acfe102e7f Simplify HTTP client management 2021-09-28 18:50:43 +03:00
Tyrrrz ea31b1b270 Refactor 2021-09-16 01:08:14 +03:00
Tyrrrz af11064a85 Some more tests 2021-09-15 00:33:53 +03:00
Tyrrrz 402b5cc7d0 Add tests for attachments 2021-09-10 01:55:28 +03:00
Tyrrrz 44f64a2cb3 Update NuGet packages 2021-09-10 01:03:02 +03:00
Tyrrrz 471d0d01cf Rethink test folder structure and add some more 2021-09-08 17:36:25 +03:00
Tyrrrz 67313f2b22 Clean up tests 2021-09-08 01:18:35 +03:00
Tyrrrz 301bca0633 Rename MessageFilter.Filter(...) to MessageFilter.IsMatch(...) 2021-09-01 18:18:20 +03:00
Tyrrrz 6b8170ab89 Allow the contains filter to also search on embed content
Closes #670
2021-09-01 00:01:39 +03:00
Tyrrrz e849c9516c Update version 2021-08-28 19:51:11 +03:00
Tyrrrz 524d0a1bb2 Fix breaking changes in tests 2021-08-28 19:47:51 +03:00
Tyrrrz f0a4410ee0 Update NuGet packages 2021-08-28 19:44:02 +03:00
Tyrrrz a98772e46e Try using ConcurrentDictionary for caching in tests 2021-08-28 19:41:50 +03:00
Tyrrrz b6fdea11a2 Refactor webhook trigger in CD 2021-08-28 19:27:34 +03:00
Tyrrrz fcca052165 Ignore unix timestamp markers with invalid offsets
Fixes #681
2021-08-28 19:17:57 +03:00
Chris Helder ac7ebd6f91 Use higher resolution for user profile pictures (#685) 2021-08-27 05:03:51 -07:00
Lucas LaBuff 9303383662 Fix parsing of "has:file" filter (#678) 2021-08-08 13:49:50 -07:00
Tyrrrz 7fa908ce34 Fix Docker CD workflow 2021-08-08 19:13:15 +03:00
Tyrrrz 345dc568c0 Update version 2021-08-08 18:57:43 +03:00
Alexey Golub 5c0b657e0e Update CD 2021-07-28 15:07:30 -07:00
Tyrrrz 265cb71dfd Add note explaining why Razor templates are not rendered directly 2021-07-27 13:02:53 +03:00
Alexey Golub 0a6fea1ce9 Use powershell for Discord webhook 2021-07-26 15:27:30 -07:00
Tyrrrz ebb36de354 Trigger Discord webhook on deploy 2021-07-26 19:16:46 +03:00
Tyrrrz 48539084f7 Add mentions of the Discord server 2021-07-26 18:55:46 +03:00
Tyrrrz 9ec95670c5 Update readme 2021-07-26 18:05:34 +03:00
Tyrrrz a449c02dd5 Authenticate Docker jobs 2021-07-26 18:02:44 +03:00
Tyrrrz 89b1f9924b Switch to manual Docker builds 2021-07-26 17:53:49 +03:00
Tyrrrz 99f94425c2 Stop pluralizing "emoji" as "emojis" 2021-07-26 17:07:02 +03:00
Tyrrrz ab71b035fc Update tests readme 2021-07-24 18:17:07 +03:00
Tyrrrz fdc3c1b012 Add test instructions 2021-07-24 18:15:16 +03:00
Tyrrrz 6fa6df981e [HTML] Fix bot tag positioning 2021-07-24 17:46:27 +03:00
Tyrrrz eec4123b98 [HTML] Add horizontal gap between embed fields 2021-07-24 17:39:45 +03:00
Tyrrrz 6fa7cbe568 Allow link nodes to have markdown children instead of just text
Closes #640
2021-07-24 17:20:28 +03:00
Tyrrrz aae3790a5f [HTML] Special case plain image embeds
Closes #537
2021-07-23 02:29:05 +03:00
Tyrrrz 28b2039a33 [HTML] Update quote style
Closes #654
2021-07-23 01:28:49 +03:00
Tyrrrz f40589dea6 [HTML] Special case Spotify embeds
Closes #657
2021-07-23 00:54:00 +03:00
Tyrrrz bb4db21b87 Add missing formats to the list of supported image and video attachments 2021-07-23 00:18:38 +03:00
Tyrrrz 38bc259ab6 [HTML] Render full date in tooltips on unix timestamps
Closes #656
2021-07-21 19:14:27 +03:00
Tyrrrz 530e2c50a9 Simplify User.GetAvatarUrl(...) 2021-07-21 17:29:05 +03:00
Tyrrrz 63c92047a1 Test improvements 2021-07-19 23:13:52 +03:00
Tyrrrz 7d9d3ca5fb Exclude EmojiIndex from coverage 2021-07-19 22:37:04 +03:00
Tyrrrz cad6baba48 Fix coverage collection in tests 2021-07-19 22:28:30 +03:00
Tyrrrz 9c25bceabf Fix isolation in tests 2021-07-19 21:07:36 +03:00
Tyrrrz 28de1053f6 Workaround for Spectre parallelization issue in tests 2021-07-19 20:59:48 +03:00
Tyrrrz ec0494c038 More tests 2021-07-19 20:35:27 +03:00
Tyrrrz d735d2acd3 Improve tests 2021-07-19 20:19:32 +03:00
Tyrrrz 85d53d0e94 Basic automated tests through the CLI 2021-07-19 20:09:35 +03:00
Tyrrrz daa8c0a735 [HTML] Update fallback text when referenced message is deleted or could not be loaded
Closes #645
2021-07-19 15:30:18 +03:00
Tyrrrz d4eba75036 Normalize namings ("...Type" -> "...Kind") 2021-07-19 02:07:19 +03:00
Tyrrrz de773467b6 Update version 2021-07-19 01:58:23 +03:00
Tyrrrz 92766b580b [HTML] Show "Click to see attachment" on replies to attachment or embed messages without content
Closes #634
2021-07-19 01:12:30 +03:00
Tyrrrz abf7498667 Add support for timestamp markers
Closes #637
2021-07-18 16:04:39 +03:00
Tyrrrz ae42554621 Render voice channel mentions
Closes #636
2021-07-18 02:19:50 +03:00
Tyrrrz b58e67776c [HTML] Improve how the reference symbol looks
Closes #650
2021-07-18 01:09:52 +03:00
Tyrrrz 7fc6e0cfe0 Update readme 2021-07-18 00:19:25 +03:00
Tyrrrz 35264e8a12 Improve "Requested resource does not exist" exception message to give slightly more context 2021-07-18 00:15:06 +03:00
Tyrrrz 2ab6773c17 [GUI] Show error in a dialog when pull or export fails, instead of crashing the whole app 2021-07-18 00:02:28 +03:00
Tyrrrz 650c55bbd1 Refactor 2021-07-17 23:53:13 +03:00
Cliff J e1726683f8 Hide author icon when loading returns an error (#644)
Fixes #643
2021-07-13 14:56:36 -07:00
Yudi 70a1755c50 Update the in-app instructions for getting user token (#639)
Co-authored-by: virtuallyvlad <37453320+virtuallyvlad@users.noreply.github.com>
Co-authored-by: Alexey Golub <tyrrrrrr@gmail.com>
2021-07-13 07:26:26 -07:00
Tyrrrz 524b30b09b Update CliFx to fix NotSupportedException
Fixes #631
2021-07-09 22:53:12 +03:00
Lucas LaBuff d39fc212b6 Filter which messages are exported (#622) 2021-07-07 12:14:40 -07:00
Tyrrrz 95cd6cb50c Further cleanup issue forms 2021-06-24 20:46:42 +03:00
Tyrrrz 79a9ac0462 Refactor issue forms and add pull request template 2021-06-24 19:29:15 +03:00
Tyrrrz 5b5a53dbf4 [HTML] More template cleanup 2021-06-22 20:03:30 +03:00
Tyrrrz 2b0fa4213b [HTML] Cleanup templates slightly 2021-06-22 14:16:08 +03:00
Tyrrrz fd9d367bad [HTML] Cleanup formatting in stylesheet 2021-06-21 20:52:30 +03:00
Tyrrrz dbc3209160 [HTML] Merge all static stylesheets into a single dynamic stylesheet 2021-06-21 20:44:36 +03:00
Tyrrrz 3bcde0c534 [HTML] Move stylesheets into their own template 2021-06-21 19:57:15 +03:00
Tyrrrz 903882e35b Fix typos in changelog 2021-06-20 23:06:39 +03:00
Luke 3c6d9d74a4 Lazy load images (#613) 2021-06-20 05:50:14 -07:00
Tyrrrz 1e53f50ca3 [HTML] Simplify disabling jumbo in referenced message content 2021-06-19 23:09:07 +03:00
Tyrrrz cba5a934df Update version 2021-06-19 20:50:22 +03:00
Tyrrrz cd05058cf7 Prefer proxy URLs for embed content everywhere 2021-06-19 20:25:50 +03:00
Tyrrrz e9c3872701 [HTML] Prevent click events on elements inside referenced message
Closes #545
2021-06-19 20:17:36 +03:00
Tyrrrz 88c4330a66 [HTML] Link to pre-resized avatar image for better image quality 2021-06-19 20:15:18 +03:00
Tyrrrz 998bdaf2d4 [HTML] Use svg variants of Twemoji for better resize quality 2021-06-19 19:57:29 +03:00
Tyrrrz 24a80f915f [HTML] Recognize standard emoji by code and show emoji code in tooltips
Closes #549
Closes #599
2021-06-19 19:49:53 +03:00
Tyrrrz de57cd714d [HTML] Prepend "Message sent: " to message timestamp tooltips 2021-06-19 18:56:47 +03:00
Tyrrrz f9ab269b29 [HTML] Don't jumbo emojis in referenced messages
Closes #544
2021-06-19 15:49:16 +03:00
Tyrrrz 33feaccee7 Only use DotnetRuntimeBootstrapper in release build 2021-06-17 22:08:11 +03:00
Tyrrrz 4fd6f8272e [HTML] Update styling to match Discord 2021-06-16 18:15:58 +03:00
Tyrrrz b28f029382 Refactor YouTube embeds 2021-06-16 17:54:35 +03:00
Tyrrrz 29552be6e5 Cleanup 2021-06-16 16:52:18 +03:00
Tyrrrz 9491e18e2f Update NuGet packages 2021-06-15 22:41:06 +03:00
quentinmay 4b1c9660be Render YouTube iframe for applicable video embeds (#607) 2021-06-15 07:19:19 -07:00
Tyrrrz 950625e671 [HTML] Show timestamps of individual messages
Closes #536
2021-06-14 22:55:42 +03:00
Tyrrrz ce2dedff6b [HTML] Use a clickable <div> instead of <a> for reply reference link
Fixes #546
2021-06-14 21:33:20 +03:00
Tyrrrz baac419538 [HTML] Fix embed footer styling 2021-06-14 20:48:20 +03:00
Tyrrrz bd40dbde48 Don't throw if file dates cannot be modified when downloading media
Fixes #585
2021-06-14 20:43:44 +03:00
Tyrrrz cbe4bc593c [HTML] Prefer proxy URLs for resolving embed media
Closes #590
2021-06-14 20:38:19 +03:00
Tyrrrz cb32cee5f5 Update DotnetRuntimeBootstrapper 2021-06-14 04:51:32 +03:00
Tyrrrz 82f364a887 Update readme 2021-06-08 18:04:19 +03:00
Tyrrrz 152e8c8dcb Update version 2021-06-08 17:54:58 +03:00
John Zabroski 260139ab25 Fix .NET v3.1 to say .NET Core v3.1 in readme (#605) 2021-06-08 07:25:12 -07:00
Tyrrrz 11e9c0f15c Downgrade MDIX 2021-06-08 01:32:21 +03:00
Tyrrrz ac809d1a3f Update packages 2021-06-08 01:23:00 +03:00
Tyrrrz 36fa346299 Use DotnetRuntimeBootstrapper 2021-06-08 00:53:41 +03:00
Tyrrrz 8c3a5bd096 Update issue templates 2021-05-12 21:38:12 +03:00
Tyrrrz 021682899a [CLI] Move Markup.Escape(...) to ConsoleExtensions 2021-04-26 19:47:25 +03:00
Lucas LaBuff 0ec6027a93 Escape brackets in category name in CLI (#558) 2021-04-26 09:37:37 -07:00
Tyrrrz eb49d0bd16 Update version 2021-04-24 21:26:49 +03:00
Tyrrrz e7c2564f6f Update NuGet packages 2021-04-24 21:08:57 +03:00
Tyrrrz d1b70cf5f6 Add wiki to issue templates 2021-04-22 21:48:45 +03:00
Tyrrrz b73d6a78a9 Fix issue templates 2021-04-22 21:47:05 +03:00
Tyrrrz b9f04bc4d9 Use issue forms 2021-04-22 21:40:47 +03:00
Tyrrrz d01ed13041 Update NuGet packages 2021-04-18 19:32:59 +03:00
Tyrrrz ed35a36eaa Update NuGet.config 2021-04-17 21:25:52 +03:00
Tyrrrz 2ddfb46c31 Add IFormatProvider to FileSize.TryParse(...) and PartitionLimit.Parse(...) 2021-04-17 14:07:07 +03:00
rtm516 3c5beeba79 Export channel category id to JSON (#554) 2021-04-17 13:56:27 +03:00
Tyrrrz ed915443e6 Update contribution guidelines 2021-04-17 00:21:23 +03:00
Tyrrrz f8d55f406c [GUI] Cleanup ExportSetupViewModel & RootViewModel 2021-04-16 23:39:36 +03:00
Tyrrrz 15b605f5a7 Fix typo 2021-04-16 23:29:19 +03:00
Tyrrrz 511af1e35c Refactor 2021-04-16 23:09:08 +03:00
rtm516 2fea455c64 [JSON] Write user color (#552) 2021-04-15 19:21:16 +03:00
Tyrrrz c64133f717 Add contribution guidelines 2021-04-14 21:42:41 +03:00
Alexey Golub d18d2e0307 Update readme 2021-04-14 15:04:42 +03:00
Alexey Golub 86633b858c Update readme
Fixes #551
2021-04-14 15:02:06 +03:00
Tyrrrz c390c64316 Remove GHA workarounds 2021-04-13 22:33:06 +03:00
Tyrrrz af3a59ce0f Add NuGet.config 2021-04-13 22:23:14 +03:00
Andrew Kolos eb89ea5b40 Add partition by file size (#497) 2021-04-12 13:50:32 +03:00
Tyrrrz ad3655396f [CLI] Remove redundant whitespace 2021-03-25 00:44:21 +02:00
Tyrrrz 1b8af364d3 [CLI] Cleanup 2021-03-24 22:39:27 +02:00
Tyrrrz 58464d8708 Improve error messages 2021-03-24 22:39:01 +02:00
Tyrrrz 026927265a [CLI] Remove ExportMultipleCommandBase and allow multiple channel IDs in ExportChannelCommand 2021-03-24 03:04:46 +02:00
Tyrrrz 390735032e [CLI] Hack Spectre.Console so that it properly supports CliFx encoding 2021-03-24 02:51:11 +02:00
Tyrrrz 461d474498 [CLI] Update CliFx 2021-03-24 02:50:54 +02:00
Tyrrrz 017ed5ae6d [CLI] Update CliFx and use Spectre.Console for progress reporting 2021-03-23 22:38:44 +02:00
Tyrrrz 6f90c367b9 Clamp progress in DiscordClient.GetMessagesAsync(...) 2021-03-23 21:41:37 +02:00
Tyrrrz f866c16355 Update NuGet packages 2021-03-23 18:43:09 +02:00
Tyrrrz 072d4c1fe6 Use MiniRazor.CodeGen instead of MiniRazor 2021-03-23 00:48:56 +02:00
Lucas LaBuff 6365e0a080 Fix JSON discriminator and nickname fields (#524) 2021-03-19 16:58:28 +02:00
Tyrrrz 7b140fd450 Try to fix nullability warning 2021-03-18 02:13:15 +02:00
Tyrrrz e237e00600 Fix CI/CD Windows issue 2021-03-16 01:24:00 +02:00
Tyrrrz 3aef7faa1e Use is null/is not null 2021-03-09 21:57:26 +02:00
Tyrrrz ebe4d58a42 Cleanup 2021-02-22 03:15:22 +02:00
Lucas LaBuff bed0ade732 [JSON] Skip validation (#499) 2021-02-15 01:07:28 +02:00
Alexey Golub 06e89538cb Drop xs:code 2021-02-10 08:28:27 +02:00
Alexey Golub 7903869f9f Update Readme.md 2021-02-10 02:44:55 +02:00
Tyrrrz 32443c5a5b Update readme 2021-02-10 02:26:58 +02:00
Tyrrrz d477159907 Update readme 2021-02-10 02:05:08 +02:00
Tyrrrz 93578abe24 Normalize snackbar style 2021-02-09 00:50:18 +02:00
Tyrrrz f22b048d32 Update version 2021-02-06 21:22:42 +02:00
Lucas LaBuff a8031ad3aa Fix crash when parsing position on DM channels (#496) 2021-02-06 17:00:29 +02:00
Frederic Portaria-Janicki e49cf997ea [CLI] Fix missing channel category bug when API returns empty string (#492) 2021-02-02 14:42:04 +02:00
Lucas LaBuff 8b9afe45b9 [CLI] Fix sorting by channel/category position (#490) 2021-01-31 17:23:46 +02:00
Lucas LaBuff 77b7977324 Formatting output paths (#472) 2021-01-28 22:01:13 +02:00
Lucas LaBuff 915f4c8d9f Fix crash on encountering invalid snowflake (#479) 2021-01-18 19:21:22 +02:00
Tyrrrz 0872d6d44b Update screenshots 2020-12-29 21:06:45 +02:00
Tyrrrz 3aa90bb27b Update version 2020-12-29 21:02:46 +02:00
Tyrrrz 51acffc92e [HTML] Fix up replies 2020-12-29 20:49:34 +02:00
Tyrrrz 39a33538fe Cleanup last PR 2020-12-28 22:10:46 +02:00
Sanqui 07ac805677 Add support for replies (#455) 2020-12-28 22:03:30 +02:00
Alexey Golub 097a75e326 Update readme 2020-12-28 18:38:22 +02:00
Tyrrrz 3d9ee3b339 Embrace Snowflake as first class citizen 2020-12-27 19:42:21 +02:00
multisignature 4ff7990967 Fix grammar in readme (#466) 2020-12-23 21:00:33 +02:00
Andrew Kolos 730fed075f [CLI] Allow passing after and before message ids instead of dates (#462) 2020-12-22 17:41:40 +02:00
Alexey Golub 600c354ab2 Use Discord API v8 2020-12-19 18:37:38 +02:00
Alexey Golub d8dc12b3f7 Update readme 2020-12-19 18:22:03 +02:00
Alexey Golub 33a6d49d76 Use .NET 5.0 SDK in Docker 2020-12-19 18:11:31 +02:00
Tyrrrz 3861dba60c Refactor last PR 2020-12-17 17:49:35 +02:00
Andrew Kolos 69acb5bf76 Set last write time on downloaded media to the value provided in the Last-Modified header (#459) 2020-12-17 17:13:47 +02:00
Tyrrrz 0e67dcbf2e Update readme 2020-12-15 17:47:00 +02:00
Tyrrrz 45d2be549d Install dotnet 5 on CI/CD so that source generators work 2020-12-15 16:17:37 +02:00
Tyrrrz 9394824943 Update MiniRazor to use build-time template compilation 2020-12-15 03:44:13 +02:00
Sanqui 43c50324d8 [JSON] Don't escape Unicode characters when possible (#453)
While UnsafeRelaxedJsonEscaping sounds scary, there is no risk
here since the JSON data is saved directly into a file.  See #450
2020-12-14 21:57:48 +02:00
Alexey Golub a6353de2a7 Use preview language version 2020-12-14 18:48:34 +02:00
Sanqui d020652f50 [CLI] Display channel name for errors during ExportMultipleAsync (#452) 2020-12-14 18:48:11 +02:00
Tyrrrz 63803f98aa Use C#9 features 2020-12-14 17:45:42 +02:00
Tyrrrz 9dda9cfc27 Use floating dotnet versions on CI/CD 2020-12-14 17:37:49 +02:00
Tyrrrz 61d0ddeced Update project structure 2020-12-10 16:52:05 +02:00
Tyrrrz 4c64977b71 Expect null result in WaitAndRetry logic in http retry handler
Fixes #447
2020-12-07 16:24:33 +02:00
Tyrrrz 8bc5b547ef Remove gitattributes and simplify gitignore 2020-12-07 16:23:53 +02:00
Lucas LaBuff 286981d9f8 [HTML] Prettier attachment preview for non-media files (#448) 2020-12-07 16:20:38 +02:00
Tyrrrz 5a62ce6af9 Update JsonExtensions to 1.0.1 2020-11-29 00:42:05 +02:00
Tyrrrz d72fe594b4 Use JsonExtensions package 2020-11-29 00:17:58 +02:00
Tyrrrz 9df98b0405 Update version 2020-11-23 17:04:08 +02:00
Tyrrrz 0d2b9e8bc0 Refactor last PR 2020-11-23 16:53:22 +02:00
Andrew Kolos 53cebd82eb [CLI] Print error and exit if reuse-media option is used without media option (#433) 2020-11-22 20:45:19 +02:00
Tyrrrz 37fcee2f21 Fix relative path extraction in ExportContext when base directory is empty
Fixes #437
Fixes #434
2020-11-20 16:56:30 +02:00
Tyrrrz 047dccef7f Refactor last PR 2020-11-18 19:04:53 +02:00
sas41 cb47902d10 [HTML] Rich rendering support for audio and video embeds (#432) 2020-11-16 15:49:57 +02:00
Alexey Golub dca8b8ceb2 Update .NET runtime links 2020-11-11 15:23:43 +02:00
Tyrrrz a8e7c85b99 Update docker image references 2020-11-11 01:56:53 +02:00
Tyrrrz edd51e0838 Revert last change, .net5 doesn't work 2020-11-11 00:02:56 +02:00
Tyrrrz 5e04accdff Update build infra 2020-11-10 23:58:05 +02:00
Andrew Kolos 547bf0a463 [JSON] Add core user mentions to output (#416) 2020-10-25 23:00:30 +02:00
Tyrrrz 948fab7c86 Update readme 2020-10-25 01:53:32 +03:00
Tyrrrz 5038b8541e Update version 2020-10-24 21:26:34 +03:00
Tyrrrz 1da80956dd Refactor 2020-10-24 21:15:58 +03:00
Tyrrrz 0763a99765 [JSON] Fix incorrect embed color output 2020-10-24 17:45:54 +03:00
Tyrrrz eda5b21684 Update github actions 2020-10-24 00:02:32 +03:00
Tyrrrz 2c7b054c24 Update nuget packages 2020-10-24 00:02:32 +03:00
Andrew Kolos 520e023aff Stop redundantly downloading media when re-exporting (#395) 2020-10-23 16:38:15 +03:00
Alexey Golub 949c9d3f1e Update readme 2020-10-17 20:25:21 +03:00
Andrew Kolos fa825fce47 [GUI] Fix content bg color on first screen to match the second screen (#411) 2020-10-16 14:20:58 +03:00
Andrew Kolos 09acfcff59 Add retry policy to MediaDownloader to accommodate short network outages during download (#404) 2020-10-12 23:03:14 +03:00
Andrew Kolos ddb4856516 Add "unix" and "unixms" options for date format (#405) 2020-10-12 13:41:49 +03:00
Andrew Kolos c4007d4a80 [JSON] Add embed color (#403) 2020-10-10 16:10:56 +03:00
Alexey Golub 2a432c0ed2 Treat nullability warnings as errors 2020-10-07 15:33:59 +03:00
Alexey Golub c5eeb5f464 Update nuget packages 2020-10-07 15:33:47 +03:00
Alexey Golub a6bf546e79 [GUI] Clean up the UI 2020-10-05 17:41:09 +03:00
Alexey Golub 239c47c06e [GUI] Clean up theme management 2020-10-05 17:10:00 +03:00
Andrew Kolos 19f678ca01 [GUI] Add dark theme (#388) 2020-10-05 16:31:37 +03:00
Pegasis 08442f21b7 Add AUR package to README (#379) 2020-09-20 15:52:44 +03:00
Alexey Golub 921f348769 Update version 2020-09-14 15:37:36 +03:00
Alexey Golub a25e809671 Extend try/catch in media downloading to OperationCanceledException
Closes #372
2020-09-14 15:09:57 +03:00
Alexey Golub fa80c82468 Cleanup 2020-09-05 17:10:15 +03:00
Alexey Golub 91f4f02a35 Refactor last commit 2020-09-05 17:05:18 +03:00
wyattscarpenter 6d2880ce26 [CLI] Add command to export all channels across all guilds (#373) 2020-09-05 00:23:06 +03:00
Ahmed Massoud 355b8cb8cf Add call time for call status messages (#365) 2020-08-22 22:14:13 +03:00
Alexey Golub 82945ac3cf [HTML] Use CDN for Whitney fonts
Related to #322
2020-08-21 20:36:59 +03:00
Alexey Golub 5009b90a3e Update screenshots 2020-08-15 13:47:47 +03:00
Alexey Golub 1495ed9b90 Update version 2020-08-12 19:21:24 +03:00
Alexey Golub be66c74c08 Update nuget packages 2020-08-12 19:11:18 +03:00
Alexey Golub 6f54c09d96 [GUI] Refactor sorting 2020-08-12 19:09:12 +03:00
Alexey Golub 45926b0990 Refactor last commit 2020-08-07 21:41:10 +03:00
CarJem Generations 25d29dc079 [GUI] Add controls to configure export time limits in addition to dates (#355) 2020-08-07 21:06:49 +03:00
Alexey Golub efde9931c9 Refactor & optimize changes in last commit 2020-08-07 21:00:43 +03:00
CarJem Generations 2c3b461d49 [GUI] Make categories collapsible in channel list (#354) 2020-08-07 19:42:59 +03:00
CarJem Generations b405052fd6 [HTML] Workaround for Tupperbox nicknames (#352) 2020-08-05 21:58:17 +03:00
Alexey Golub da6d903f36 Update version 2020-07-30 16:03:27 +03:00
Alexey Golub e1b1755fba Don't escape media URL on non-HTML formats 2020-07-30 16:02:00 +03:00
Alexey Golub 1ff026eba6 [GUI] Trim spaces in token input 2020-07-29 20:58:49 +03:00
Alexey Golub 1fe4ecb3af Truncate long file names in MediaDownloader
Fixes #344
2020-07-29 20:58:38 +03:00
Alexey Golub 47a1518cd9 Update nuget packages 2020-07-29 20:49:08 +03:00
Alexey Golub d78c10ebb7 Remove default cap on MakeUniqueFilePath 2020-07-29 20:47:58 +03:00
Alexey Golub 3db29b520c Switch from RazorLight to MiniRazor 2020-07-29 20:08:51 +03:00
Alexey Golub 752003abc3 Fix media downloading 2020-07-28 23:07:31 +03:00
Alexey Golub e26a0660d1 Use Razor instead of Scriban 2020-07-28 22:43:45 +03:00
Alexey Golub 7dfc3b2723 Add link to extra services in readme 2020-07-26 15:54:30 +03:00
Alexey Golub 06c33373de Sanitize file names when exporting media
Fixes #332
2020-07-25 21:17:05 +03:00
Alexey Golub 563f5cb67b Update version 2020-07-19 19:09:45 +03:00
Alexey Golub 1f20915b4d Use original file names for downloaded media
Closes #327
2020-07-19 14:19:40 +03:00
Alexey Golub e58c7aefff Ignore failures when downloading media 2020-07-18 22:08:06 +03:00
Alexey Golub ac5ccc3fa4 Update version 2020-07-18 16:32:02 +03:00
Alexey Golub 2fc0aa43e8 Change "discordapp.com" to "discord.com" where appropriate 2020-07-18 16:04:47 +03:00
Alexey Golub ba66b52fa4 Use ValueTask instead of Task where possible 2020-07-18 15:57:51 +03:00
Alexey Golub ac64d9943a Self-contained export (#321) 2020-07-18 15:45:09 +03:00
Alexey Golub 94a85cdb01 Update nuget packages 2020-05-11 21:50:38 +03:00
Alexey Golub a1d34e8fb6 Update version 2020-04-27 13:24:31 +03:00
Alexey Golub 4a35a7b530 Cleanup and minor fixes 2020-04-27 13:24:20 +03:00
Alexey Golub 247f3a9c5b Include channel category in default export file name
Closes #188
2020-04-27 00:02:55 +03:00
Alexey Golub be73f0b92c [CLI] Show channel categories
Closes 195
2020-04-27 00:01:37 +03:00
Alexey Golub d03be8b1dd More refactoring 2020-04-26 23:55:31 +03:00
Alexey Golub 9d0d7cd5dd More refactoring 2020-04-23 00:32:48 +03:00
Alexey Golub b2a48d338a Update nuget packages 2020-04-23 00:30:37 +03:00
Alexey Golub 88a4fa792b Refactor more 2020-04-22 21:59:10 +03:00
Alexey Golub dc79813ad7 Refactor 2020-04-22 20:44:14 +03:00
Alexey Golub 6a430cdc76 [HTML] Fix unclosed tags and inconsistencies 2020-04-22 19:38:49 +03:00
Alexey Golub 2a02894d64 [HTML] Fix weird inline code block behavior with two backticks 2020-04-22 19:23:56 +03:00
Alexey Golub 8685a3d7e3 Rework architecture 2020-04-22 19:23:31 +03:00
Alexey Golub 130c0b6fe2 Use System.Text.Json instead of Newtonsoft.Json 2020-04-21 18:15:28 +03:00
Alexey Golub f153aad3f1 Simplify FileSize 2020-04-21 14:38:09 +03:00
Alexey Golub 6f1c944cb3 [HTML] Split message group if usernames are different
Closes #290
2020-04-17 18:47:06 +03:00
Alexey Golub de9e7caaeb [HTML] Fix repeated single quotes behavior with nested formatting
Closes #288
2020-04-15 13:22:20 +03:00
Alexey Golub 9711a8cca4 [HTML] Match repeated single quotes as a multiline quote
Closes #288
2020-04-14 22:27:29 +03:00
Alexey Golub 4ab6607e78 [HTML] Update quote style 2020-04-14 22:26:50 +03:00
Alexey Golub d74e6453f6 [CLI] Use environment variable fallbacks for token 2020-04-07 16:10:12 +03:00
Alexey Golub ca7fc4d8d1 [HTML] Fix a few more issues 2020-04-06 19:50:53 +03:00
Alexey Golub 81ed85a3e0 [HTML] Clean up a bit 2020-04-06 15:44:03 +03:00
FM-96 18979c6a38 [HTML] Full spoiler support (#285) 2020-04-05 21:30:15 +03:00
Alexey Golub 5bce4b52ff [GUI] Add a link to project's wiki
Closes #284
2020-04-05 00:31:01 +03:00
Alexey Golub dac7c664d9 [GUI] Ensure update has been prepared before attempting to install it 2020-04-02 20:08:16 +03:00
Alexey Golub 6a8579787d Update XamlStyler 2020-03-30 10:09:13 +03:00
Alexey Golub dbf15c7bee Update version 2020-03-26 23:32:51 +02:00
Alexey Golub a41a4ca8a7 [HTML] Fix occasionally wrong user colors 2020-03-26 23:32:41 +02:00
Alexey Golub c098f4b137 [HTML] Use nicknames when rendering mentions 2020-03-26 23:22:21 +02:00
Alexey Golub ff15257d23 Fix bugs in previous PR 2020-03-26 22:59:36 +02:00
Will Kennedy 79e43c4144 Add support for Guild Member object & included data (#279) 2020-03-26 14:36:55 +02:00
Alexey Golub 7bb8038ce9 Revert "[GUI] Publish as 32-bit for maximum compatibility"
This reverts commit ee27167998.
2020-03-26 14:02:13 +02:00
Alexey Golub ee27167998 [GUI] Publish as 32-bit for maximum compatibility
Closes #243
2020-03-25 22:25:24 +02:00
Alexey Golub 9f4277ae84 Add parallel exporting
Closes #264
2020-03-25 19:22:33 +02:00
Alexey Golub 70a1c9db8c Clean up warnings 2020-03-23 19:11:15 +02:00
Will Kennedy 378f0a20db [HTML] Update CSS for mentions (#278) 2020-03-14 14:21:53 +02:00
Alexey Golub a24fe3906c Update GitHub Actions workflows 2020-02-16 20:33:30 +02:00
Alexey Golub eececb6701 Update version 2020-02-04 14:05:44 +02:00
Alexey Golub d3adf19500 Simplify display text for export formats 2020-02-04 14:04:26 +02:00
Alexey Golub a01835efb6 [CLI] Cleanup 2020-02-04 12:14:53 +02:00
Alexey Golub 1d39fe9c53 Update readme 2020-02-03 18:10:06 +02:00
Alexey Golub 9f6090b3af Add JSON message writer
Closes #103
2020-02-03 17:47:42 +02:00
Alexey Golub 9fa40dca00 Add text search in the channel list
Closes #184
2020-02-03 14:18:27 +02:00
Alexey Golub 8a4f306012 Update CliFx to v1.0 2020-01-30 16:34:36 +02:00
Alexey Golub 37be80e9e1 Update version 2020-01-12 21:14:00 +02:00
Alexey Golub 1475ffaf0e Use the new Rune API for handling emoji code points 2020-01-12 21:04:02 +02:00
Alexey Golub aa50dd6dc7 [HTML] Clean up layouts and styles 2020-01-12 20:16:08 +02:00
Alexey Golub 539f57f455 [HTML/TXT] Render exported message count at the bottom
Closes #249
2020-01-11 18:03:07 +02:00
Alexey Golub e1f83997aa [GUI] Fix token textbox alignment 2020-01-11 18:01:35 +02:00
Alexey Golub 26d713a17c Refactor 2020-01-11 17:28:01 +02:00
Alexey Golub 5c2e725739 Move partitioning to message renderer facade 2020-01-11 14:18:04 +02:00
Alexey Golub bf56902134 Refactor partitioning, don't create empty files
Closes #246
2020-01-10 21:05:07 +02:00
Alexey Golub b4df267372 Update NuGet packages 2020-01-10 20:10:01 +02:00
Alexey Golub 4ebc681327 Format XAML with XAMLStyler 2020-01-10 20:06:13 +02:00
Alexey Golub 5cb6adf19e Add an option to not save token
Closes #252
2020-01-10 20:03:31 +02:00
Alexey Golub cec8409ac4 Check if auto-update is enabled in UpdateService 2020-01-03 21:44:30 +02:00
Alexey Golub 3af9421304 Add changelog to CD 2019-12-15 15:35:32 +02:00
Alexey Golub cc6f930dc6 Update readme 2019-12-10 19:27:41 +02:00
Alexey Golub e6aac3cdb9 Update changelog and readme 2019-12-08 14:00:12 +02:00
Alexey Golub 8f1aec241b Update version 2019-12-08 13:45:45 +02:00
Alexey Golub 41c828eb3e [HTML] Refactor renderer 2019-12-07 22:22:39 +02:00
Alexey Golub 964317dac0 Make StringPart readonly struct 2019-12-07 20:16:53 +02:00
Alexey Golub 2a223599f9 Streaming exporter
Fixes #125
Closes #177
2019-12-07 18:43:24 +02:00
Alexey Golub fc38afe6a0 Refactor models and add IHasId/IdBasedEqualityComparer 2019-12-06 00:17:14 +02:00
Alexey Golub 23512dae64 Update dockerfile 2019-12-05 21:04:39 +02:00
Alexey Golub 8382ca725d Migrate to net core 3.1 2019-12-05 21:03:49 +02:00
Alexey Golub 457e14d0b6 Refactor DataService
In preparation for #177
2019-12-03 23:32:48 +02:00
Alexey Golub b830014a46 Make emoji parser less greedy
Fixes #230

Emoji parsing is a terrible endeavour. I'm leaning towards matching fewer emojis and then blaming Unicode for lack of proper classification, than matching a few too many characters.
2019-12-02 21:05:42 +02:00
boomanaiden154 35e1114318 [CSV] Use commas instead of semicolons (#236) 2019-12-01 18:10:24 +02:00
Alexey Golub 610bf4baa3 Fallback channel name to channel ID
Fixes #227
2019-12-01 18:09:23 +02:00
Alexey Golub d84222ea09 Use Polly instead of Failsafe 2019-12-01 17:53:10 +02:00
Alexey Golub cc1bb924e7 [HTML] Adjust embed color to theme 2019-12-01 17:50:10 +02:00
Alexey Golub 0d2ae8b5db Add support for announcement channels
Closes #222
2019-12-01 17:35:56 +02:00
Alexey Golub 632b9f953b Use shared props file 2019-12-01 16:00:45 +02:00
Alexey Golub 9a52c6a6f6 Update readme 2019-11-30 23:31:01 +02:00
Alexey Golub fc8c1c5914 Mention that user tokens are against TOS
Closes #211
2019-11-25 17:22:04 +02:00
Alexey Golub 279a6aee84 Update donation info 2019-11-19 21:17:05 +02:00
Alexey Golub 73ab983056 Mention wiki in readme 2019-11-16 21:00:56 +02:00
Alexey Golub e5a2852165 Use nullable 2019-11-13 19:19:36 +02:00
Alexey Golub 1bf9d9e2e2 Use GitHub actions 2019-11-06 21:04:16 +02:00
Alexey Golub 9299b95250 [CLI] Use Microsoft.Extensions.DependencyInjection instead of Stylet 2019-11-06 00:26:43 +02:00
Alexey Golub 5e0a2c6761 Update dockerfile 2019-11-06 00:09:25 +02:00
Alexey Golub ccbd11e526 Update readme 2019-11-04 15:30:13 +02:00
Alexey Golub 2c36f6a826 Target .NET Core 3 in libraries instead of .NET Std 2.1 2019-09-29 14:19:03 +03:00
Alexey Golub d6980cef8d Cleanup 2019-09-27 01:02:46 +03:00
Alexey Golub fa4bb3b693 [GUI] Move to Microsoft.Xaml.Behaviors.Wpf from System.Windows.Interactivity.WPF 2019-09-27 00:49:29 +03:00
Alexey Golub 05c551f80c Refactor 2019-09-26 20:44:28 +03:00
Alexey Golub 69cfe1845b Migrate to .NET Core 3 2019-09-26 20:06:35 +03:00
Alexey Golub 3a0d351143 Update version 2019-09-15 22:36:02 +03:00
Alexey Golub f04719c4bd [TXT] Indicate whether a message is pinned 2019-09-15 21:31:24 +03:00
Alexey Golub d88cd9b228 [HTML] Add support for block quotes
Closes #208
2019-09-15 21:25:04 +03:00
Alexey Golub cd042e5368 Rework markdown parser and improve its performance for non-HTML formats 2019-09-15 21:24:07 +03:00
Alexey Golub 533671c59f [GUI] Allow the app to crash in DEBUG mode 2019-09-15 20:30:10 +03:00
Alexey Golub 29c35f6754 [HTML] Mark code blocks without language so that highlight.js doesn't touch them 2019-09-15 16:18:30 +03:00
Alexey Golub 7b32101517 [HTML] Fix incorrect extraction for linked message ID when used in guild and not in DM 2019-09-15 15:47:34 +03:00
Alexey Golub 9bb88128b0 [HTML] Fix messages not being highlighted when they are pinned 2019-09-15 14:16:24 +03:00
Alexey Golub 12a5091d73 Streamline auto-update process and refactor 2019-09-15 14:11:06 +03:00
Alexey Golub 82af36c90d [HTML] Add smooth highlight transition when navigating to message via link 2019-09-14 23:35:49 +03:00
Alexey Golub a2beb9836b [HTML] Jump to linked Discord messages
Closes #128
2019-09-14 20:28:27 +03:00
Alexey Golub 60f46bad29 [HTML] Update light theme to match the current one in Discord 2019-09-14 19:54:25 +03:00
Alexey Golub 2cdb230b1e [HTML] Add indication for pinned messages
Closes #193
2019-09-14 19:31:24 +03:00
Alexey Golub 9241b7d2d1 [GUI] Add some tooltips 2019-09-14 18:38:55 +03:00
Alexey Golub 40f54d9a98 Update nuget packages 2019-09-14 18:35:42 +03:00
Alexey Golub f2faf823b9 [CSV] Add user ID to output
Closes #197
2019-09-14 18:34:25 +03:00
Alexey Golub 5b9eaa57f5 Move screenshots to repository 2019-09-06 20:27:53 +03:00
Alexey Golub 58ba99e0c6 Migrate DiscordChatExporter.Cli to CliFx 2019-08-20 18:33:27 +03:00
Alexey Golub 117d1b7e4a Create FUNDING.yml 2019-07-27 02:00:54 +03:00
Alexey Golub 835910ee22 Update nuget packages 2019-07-17 13:09:00 +03:00
Malcolm Diller 5630020d88 Add message ids in HTML export (#196) 2019-07-14 21:12:13 +03:00
Alexey Golub 71e6a8de7a Update version 2019-06-15 18:16:17 +03:00
Alexey Golub 592b8b6294 Update nuget packages 2019-06-15 18:09:56 +03:00
Alexey Golub e6edcd27a4 [CSV] Render reactions
Addresses the other part of #168
2019-06-11 22:45:19 +03:00
Alexey Golub 557b5be844 [TXT] Render reactions
Addresses part of #168
2019-06-11 22:39:17 +03:00
Alexey Golub 02fe2a46e8 [TXT] Add support for embeds and change how attachments are rendered
Closes #165
2019-06-10 22:16:37 +03:00
Alexey Golub 76c7f9b419 Update version 2019-06-06 23:38:06 +03:00
Alexey Golub 9a383d2bd4 Convert from DateTime to DateTimeOffset instead of parsing it directly
Json.NET is really not meant to be used with DateTimeOffset it seems

Fixes #179
2019-06-06 23:31:40 +03:00
Oleksii Holub 2ed374ee5c [HTML] Render user ID inside data-user-id attribute
Closes #93
2019-06-06 17:43:30 +03:00
Alexey Golub 0ced31ca4a Update version 2019-05-15 01:04:21 +03:00
Alexey Golub 3bb5638b56 Improve usage instructions slightly 2019-05-15 00:56:50 +03:00
Malcolm Diller 3b5d752c95 Add bot tags and some CSS fixes (#172) 2019-05-09 13:52:46 +03:00
Alexey Golub 2b1f599cbe Add logo image 2019-04-25 22:14:17 +03:00
Alexey Golub 7cb1c21897 Refactor 2019-04-18 22:21:20 +03:00
Alexey Golub 37bcea86e3 [CLI] Update usage guide to explain steps needed to extract DM channel ID 2019-04-18 22:19:26 +03:00
Alexey Golub 559ef71d2f Get rid of Chocolatey 2019-04-17 00:59:22 +03:00
Alexey Golub ab0ce478db Move UpdateService to GUI project 2019-04-16 23:08:38 +03:00
Alexey Golub afb9f52221 Update FodyWeavers.xsd 2019-04-16 23:08:22 +03:00
Alexey Golub d65ca409b1 Update nuget packages 2019-04-13 02:42:03 +03:00
Oleksii Holub 7784383ea7 Fix grammar mistakes in comments 2019-04-12 17:13:12 +03:00
Oleksii Holub 26322da800 [GUI] Notify when all exports are done instead of each of them separately 2019-04-12 16:24:17 +03:00
Oleksii Holub 1325edb135 Use latest C# version in all projects 2019-04-12 16:10:28 +03:00
Oleksii Holub dec2c26d83 Update appveyor image to vs2019 2019-04-12 16:01:01 +03:00
Oleksii Holub 82b0b8cb0a [GUI] Block UI when an export is underway 2019-04-12 15:23:07 +03:00
Oleksii Holub a7da90943f Remove trailing whitespace 2019-04-12 13:48:13 +03:00
Alexey Golub 1edeaf9d3a Update changelog 2019-04-12 01:03:42 +03:00
Alexey Golub 9c043376f9 Update version 2019-04-12 00:14:54 +03:00
Alexey Golub 77366cc9b4 Escape specific emojis in markdown
Fixes a part of #146
2019-04-12 00:11:01 +03:00
Alexey Golub ffdca7b799 [HTML] Fix multiple emojis not getting jumbo 2019-04-11 23:31:29 +03:00
Alexey Golub 30cba7959f Refactor string checks and fix exception when exporting multiple channels
Fix #164
2019-04-11 22:56:29 +03:00
Alexey Golub 7951703cf2 Update version 2019-04-11 01:52:50 +03:00
Alexey Golub 795dfbb213 [CLI] Don't show 'completed' when export failed 2019-04-11 01:36:39 +03:00
Alexey Golub 6d9bc3625f Switch from DateTime to DateTimeOffset 2019-04-11 01:20:52 +03:00
Alexey Golub 4bfb2ec7fd Improve performance (#162) 2019-04-10 23:45:21 +03:00
Oleksii Holub 359278afec Optimize chocolatey package 2019-04-09 18:15:17 +03:00
Oleksii Holub 19f58f2c8c Update readme 2019-04-09 16:32:24 +03:00
Alexey Golub 640b1f5866 Add deploy via chocolatey 2019-04-07 13:01:38 +03:00
Oleksii Holub d13d04e75b Add donation info 2019-04-03 18:33:34 +03:00
Oleksii Holub 6bf0ce3790 Fix dockerfile again 2019-03-25 15:22:51 +02:00
Oleksii Holub aef8a1f6d2 Fix default output directory in dockerfile 2019-03-25 14:35:24 +02:00
Oleksii Holub a63bf95212 Update dockerfile 2019-03-25 11:04:51 +02:00
Oleksii Holub af9855fc15 [CLI] Copy nuget dependencies to output 2019-03-25 11:00:13 +02:00
Alexey Golub 4113101c0c Get rid of ByteSize in favor of our own class 2019-03-24 12:36:25 +02:00
Oleksii Holub cac48b3541 Optimize dockerfile 2019-03-22 15:09:07 +02:00
Alexey Golub 0a60dea5c1 Use net46, netstd2.0, and netcoreapp2.1 for target frameworks
Closes #154
2019-03-22 00:07:13 +02:00
Alexey Golub 889446fff7 Update nuget packages 2019-03-21 22:54:12 +02:00
Alexey Golub 6d1cfef729 Update Onova 2019-03-21 00:55:24 +02:00
Oleksii Holub 77bf32aa5a Update version 2019-03-14 16:36:55 +02:00
Oleksii Holub ac2b450892 Retry on any 5xx HTTP response in DataService
Closes #157
2019-03-14 16:30:27 +02:00
Oleksii Holub 4046fd0ad9 [HTML] Add syntax highlighting via Highlight.js
Closes #138
2019-03-14 16:02:39 +02:00
Alexey Golub 6fa61bf75a Update version 2019-03-10 14:45:39 +02:00
Alexey Golub 1976e3ad08 [CLI] Don't write progress if output is redirected
FIxes #155
2019-03-10 14:40:08 +02:00
Alexey Golub adbe544c57 Add some margin at the end of the chatlog in HTML 2019-03-07 22:15:21 +02:00
Alexey Golub 6f4d1c3d77 Refactor message grouping 2019-03-07 22:13:00 +02:00
Alexey Golub 33f71c1612 Remove message group limit setting 2019-03-07 21:14:11 +02:00
Alexey Golub 9b78472e05 Update message grouping algorithm to match Discord's
Fixes #152
2019-03-07 21:10:22 +02:00
Alexey Golub 1f6d1f21e6 Update version 2019-03-06 23:00:56 +02:00
Alexey Golub 918cb4820f Add alt text to emoji images
Closes #151
2019-03-06 22:57:18 +02:00
Alexey Golub 32af1aa05d Fix incorrect regex for capturing standard emojis
Fixes #147
2019-03-06 22:48:24 +02:00
Alexey Golub dda32d8af2 Fix markdown grammar being too greedy in some places
Fixes #150
2019-03-06 22:37:36 +02:00
Alexey Golub d1d82f975b Add license file to releasable artifacts 2019-03-03 22:26:02 +02:00
Alexey Golub b1de9c4eca Update version 2019-03-03 21:48:03 +02:00
Alexey Golub 48ec4d085a Fix bad overflow wrapping 2019-03-03 21:33:27 +02:00
Alexey Golub 668ac70fae Fix some parsing issues 2019-03-03 21:24:37 +02:00
Alexey Golub 0d1ce38489 Jumboable emojis 2019-03-03 21:09:47 +02:00
Alexey Golub 666f2d8d4a Fix emoji and reaction css 2019-03-03 20:47:24 +02:00
Alexey Golub 2dd0742c1c Fix video attachments getting rendered as images
Fixes #120
2019-03-03 20:20:01 +02:00
Alexey Golub 69fe8af87a Update Failsafe 2019-03-03 20:08:47 +02:00
Alexey Golub e493357a9f Add progress reporting to CLI
Closes #143
2019-03-03 19:59:23 +02:00
Alexey Golub 492003c75a Fix incorrect standard emoji rendering in plaintext 2019-03-03 18:41:54 +02:00
Alexey Golub 28175e2110 Parse emojis in markdown and render them using Twemoji
Closes #140
2019-03-03 18:36:12 +02:00
Alexey Golub a564906719 Use ByteSize for file size in attachments 2019-03-03 16:38:41 +02:00
Alexey Golub 019278f6d4 Fix dockerfile 2019-03-03 16:05:09 +02:00
Alexey Golub 5161593e0f Forgot to commit DataService.Parsers 2019-03-03 15:40:26 +02:00
Alexey Golub 847a05a269 Refactor reaction emojis into a separate class, add support for animations and standard emojis via twemoji
Closes #71
2019-03-03 15:24:31 +02:00
Alexey Golub f09f30c7bd Implement a more sophisticated markdown parsing engine (#145) 2019-03-03 14:16:12 +02:00
Alexey Golub 88727a1fe6 Forgot one more place 2019-02-17 19:55:48 +02:00
Alexey Golub bb98049df7 Remove years from copyright 2019-02-17 19:48:54 +02:00
Alexey Golub e519bdcc6f Update license 2019-02-17 19:31:26 +02:00
Oleksii Holub 1356d4483a Add a checkmark that displays whether a channel is selected 2019-02-15 13:01:30 +02:00
Alexey Golub 4a3dc5c5ee Bind export button visibility on the guard property 2019-02-14 22:29:52 +02:00
Alexey Golub e665356890 Show export progress in taskbar 2019-02-14 21:52:36 +02:00
Alexey Golub 7b614ed448 Update version 2019-02-10 17:27:45 +02:00
Alexey Golub 6531462220 Fix getting last message when there's no date range
Fixes #137
2019-02-10 17:26:18 +02:00
Alexey Golub e89f2735a0 Update version 2019-02-09 21:26:15 +02:00
Alexey Golub 01d276a9dc Use UTF8 encoding in UpdateVersion.ps1 2019-02-09 21:20:20 +02:00
Alexey Golub c446d4069a Export single channel by double-clicking in GUI 2019-02-09 21:05:31 +02:00
Alexey Golub ba5718aaf5 Improve GUI a bit 2019-02-09 20:07:30 +02:00
Alexey Golub 20ff4a15eb Refactor output path usage in CLI 2019-02-09 19:41:08 +02:00
Alexey Golub 991dfccf3c Retry on 503 status code 2019-02-09 19:39:21 +02:00
Alexey Golub 524c86b8f2 Add channel ID to default export file name to avoid collisions 2019-02-09 19:20:13 +02:00
Alexey Golub e4b0d60c40 Add multichannel export to GUI
Closes #12
2019-02-09 19:03:34 +02:00
Alexey Golub 65c5df89f4 Use Failsafe 2019-02-08 20:37:53 +02:00
Oleksii Holub 659c499bd0 Small clenaup 2019-02-01 15:33:06 +02:00
Alexey Golub b6fcbac030 Refactor 2019-01-30 23:14:17 +02:00
Oleksii Holub b3e2dd3994 Group channels by category in GUI
Closes #77
2019-01-30 18:16:46 +02:00
Alexey Golub ba5790e312 Remove reference to Tyrrrz.Settings in GUI project 2019-01-21 23:21:35 +02:00
Alexey Golub 2859a740eb Update nuget packages 2019-01-07 18:29:36 +02:00
Oleksii Holub b88a1f8b47 Some refactor 2018-12-21 15:37:14 +02:00
Alexey Golub 78b44aed19 Use embedded style for dialog host 2018-12-19 21:51:03 +02:00
Oleksii Holub 13925c69af Refactor CLI and add 'exportdm' command to export all direct message channels 2018-12-19 17:29:36 +02:00
Oleksii Holub e22e1c03fb Cleanup 2018-12-19 17:15:54 +02:00
TVdata bf5cedb646 Add CLI command to export all available channels in a guild (#123) 2018-12-19 16:53:21 +02:00
Alexey Golub 17b0161ade Make dialogs white again 2018-12-16 00:07:17 +02:00
Alexey Golub fa1e84b518 Refactor UI 2018-12-15 23:53:52 +02:00
Alexey Golub 6d5ed9e9ca Improve UI 2018-12-14 01:00:57 +02:00
Oleksii Holub bdaeea5512 Refactor busy state and progress reporting 2018-12-11 18:03:32 +02:00
Alexey Golub dddb13fcc5 Refactor default file name generation and add date ranges there
Closes #29
2018-12-10 23:16:15 +02:00
Alexey Golub cacbb58683 Improve usage instructions a bit 2018-12-08 23:56:04 +02:00
Alexey Golub ca727e9f23 Improve naming of exported partition files 2018-12-08 23:55:49 +02:00
Oleksii Holub fd15b62adf Improve UI layout and usage instructions 2018-12-07 18:14:27 +02:00
Oleksii Holub 78d01b47b4 Add some tooltips 2018-12-07 17:05:17 +02:00
Oleksii Holub daf38153f4 Improve UI some more 2018-12-05 18:45:13 +02:00
Oleksii Holub ac91c536dd Improve ExportSetupView UI 2018-12-05 18:20:20 +02:00
Alexey Golub 0dbd619244 Remove unsused library from readme 2018-11-29 20:55:20 +02:00
Alexey Golub 0d3510222e Migrate to Stylet and refactor view/view-model framework 2018-11-29 19:18:44 +02:00
Alexey Golub 083bdef419 Move screenshots section below features section in readme 2018-11-17 23:22:25 +02:00
Oleksii Holub d620010e85 Add some safeguarding in case partition limit is less or equal to zero 2018-11-15 10:26:54 +02:00
Oleksii Holub beadc25e61 Cleanup GroupMessages 2018-11-14 18:15:07 +02:00
Oleksii Holub 8bc29c4928 Refactor SplitIntoPartitions 2018-11-14 17:51:03 +02:00
Oleksii Holub 0b14952346 Add a script to update version in all projects 2018-11-05 13:31:42 +02:00
Alexey Golub b518fb2f59 Update version 2018-11-03 23:51:19 +02:00
Alexey Golub 94165dcd8d Don't render the template in memory to avoid out of memory exceptions
Fixes #88
2018-11-03 23:04:26 +02:00
Alexey Golub d6507598fa Fix not being able to reset partition limit in GUI 2018-11-03 23:01:58 +02:00
Alexey Golub a0359b1e43 Split output file into multiple partitions (#116) 2018-11-03 22:53:20 +02:00
Oleksii Holub aa53cecd4e Don't open exported file on completion
Fixes #85
2018-11-02 17:12:17 +02:00
Oleksii Holub 4144911208 Remove autoupdate feature from CLI entirely 2018-11-02 16:24:06 +02:00
Oleksii Holub d28e81f8dc Don't replace new lines in csv
Part of #102
2018-11-01 18:33:29 +02:00
Oleksii Holub 761cb032d7 Don't group messages in PlainText export
Part of #102
2018-11-01 18:27:41 +02:00
Oleksii Holub 47f0561c71 Refactor message grouping from data layer to render layer 2018-11-01 18:16:23 +02:00
Oleksii Holub 23116b776b Show unhandled exceptions to users 2018-11-01 14:43:21 +02:00
Oleksii Holub ba27a9f909 Rename ExportService.Export to ExportChatLog for consistency 2018-10-31 17:54:13 +02:00
Oleksii Holub 52684c264f Change order of parameters in ExportService.Export 2018-10-31 17:35:28 +02:00
Oleksii Holub bcad5b4ed1 Set ChatLog.TotalMessageCount from ChatLogService 2018-10-31 17:34:57 +02:00
Alexey Golub 95a4217ab3 Refactor resolving chat log to a separate service to allow reusability across CLI and GUI 2018-10-30 22:52:28 +02:00
Alexey Golub 4e8fb80ac5 Use PackageReference 2018-10-28 15:25:22 +02:00
Alexey Golub 7ae560dde0 Fix changelog 2018-09-14 00:36:31 +03:00
Alexey Golub 97a36028b9 Update version 2018-09-14 00:34:18 +03:00
Alexey Golub f0d99676a3 Disable UpdateAppOptions in CLI 2018-09-14 00:25:21 +03:00
Alexey Golub 8e38adae7e Update instructions to obtain token
Fixes #76
2018-09-14 00:23:23 +03:00
Alexey Golub d95bc37592 Link to dockerhub from readme 2018-09-13 23:32:09 +03:00
Hyeon Kim 3f6354053c Dockerize the application (#92) 2018-09-13 22:50:15 +03:00
Alexey Golub a9bab60ba6 Update instructions to obtain token 2018-08-14 00:49:32 +03:00
Alexey Golub 614bd8590d Generate file name if given output path CLI argument is a directory
Closes #67
2018-08-13 23:25:06 +03:00
Alexey Golub bd9dc6455f Refactor CLI (#81) 2018-08-13 22:49:13 +03:00
Alexey Golub 0faa427970 Invert if condition in authentication header 2018-08-03 00:13:44 +03:00
Alexey Golub dd9da4831e Change how user token is sent in requests 2018-08-03 00:00:51 +03:00
Oleksii Holub 0d816cee5d Update readme 2018-07-26 18:25:47 +03:00
Oleksii Holub f63ea41188 Update version 2018-07-25 11:53:05 +03:00
Alexey Golub 3572a21aad Allow using bot token instead of user token (#70) 2018-07-24 22:47:45 +03:00
Alexey Golub 37ee0b8be3 Cleanup templates and change how model is referenced 2018-07-03 22:58:46 +03:00
trainboy2019 ed146bac22 Add support for animated avatars (#66) 2018-07-02 21:12:32 +03:00
Alexey Golub b9c449709f Update version 2018-07-01 21:12:06 +03:00
Alexey Golub 25207c5093 Improve the templates a bit 2018-07-01 21:04:03 +03:00
Alexey Golub 4fbec95208 Fix CSV and PlainText outputs not rendering timestamps correctly
Fixes #65
2018-07-01 16:53:33 +03:00
Alexey Golub 0a48da4c56 Update version 2018-06-28 00:36:26 +03:00
Alexey Golub 3f5f62585c Make emojis larger if they are the only thing in content 2018-06-28 00:29:47 +03:00
Alexey Golub 49f39c7097 Add retry policy for 429 responses 2018-06-28 00:20:31 +03:00
Alexey Golub e3eac10fb8 Bring HTML light theme in line with dark theme 2018-06-27 23:16:28 +03:00
Alexey Golub 23f9331e4e Cleanup 2018-06-27 00:45:29 +03:00
Alexey Golub 69088b83eb Html-encode date ranges in html export 2018-06-26 23:23:18 +03:00
Alexey Golub 7ecf90d1cb Refactor css for 'pre' with modifiers 2018-06-26 01:14:54 +03:00
Alexey Golub f0cd2dce1b Improve reactions 2018-06-26 01:09:23 +03:00
IntriguingTiles e8436faf66 Add support for reactions (#62) 2018-06-26 00:27:45 +03:00
Alexey Golub 61dce7c1a8 Small cleanup 2018-06-25 23:48:40 +03:00
Alexey Golub 6fee160bc7 Show an error when trying to export deleted channel
Closes #51
2018-06-25 23:34:29 +03:00
Alexey Golub 8678043f0d Implement progress reporting when downloading messages (#57) 2018-06-25 23:11:34 +03:00
Oleksii Holub e4f0b8193f Output date range in the export file
Closes #56
2018-06-25 18:44:50 +03:00
Oleksii Holub df811d0b1a Add loading placeholder for guild icons 2018-06-25 17:38:28 +03:00
Oleksii Holub 08da5d685b Prevent choosing invalid from/to dates 2018-06-25 17:11:52 +03:00
Alexey Golub c2cebe99e3 Fix wrong json node being used to parse mentioned users in messages 2018-06-25 02:28:38 +03:00
Alexey Golub 481991bd00 Architecture refactor (#63) 2018-06-25 01:59:15 +03:00
Malcolm Diller d958f613a3 Add support for embeds (#46) 2018-05-06 13:09:25 +03:00
241 changed files with 20273 additions and 3792 deletions
-63
View File
@@ -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
+64
View File
@@ -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
+11
View File
@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: 💬 Discord server
url: https://discord.gg/2SUWKFnHSm
about: Chat with the project community.
- 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
+30
View File
@@ -0,0 +1,30 @@
name: Docker CD
on:
push:
tags:
- "*"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Get release version
id: get_version
uses: dawidd6/action-get-tag@v1
- name: Login
run: docker login -u tyrrrz -p ${{ secrets.DOCKER_TOKEN }}
- name: Build
run: docker build -t tyrrrz/discordchatexporter:${{ steps.get_version.outputs.tag }} -t tyrrrz/discordchatexporter:stable .
- name: Deploy (version)
run: docker push tyrrrz/discordchatexporter:${{ steps.get_version.outputs.tag }}
- name: Deploy (stable)
run: docker push tyrrrz/discordchatexporter:stable
+84
View File
@@ -0,0 +1,84 @@
name: CD
on:
push:
tags:
- "*"
jobs:
build:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Get release version
id: get_version
uses: dawidd6/action-get-tag@v1
- name: Install .NET
uses: actions/setup-dotnet@v1.7.2
with:
dotnet-version: 6.0.x
- name: Build & publish (CLI)
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
- name: Build & publish (GUI)
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
- name: Pack (CLI)
run: Compress-Archive -Path DiscordChatExporter.Cli/bin/Publish/* -DestinationPath DiscordChatExporter.Cli/bin/Publish/Archive.zip -Force
shell: pwsh
- name: Pack (GUI)
run: Compress-Archive -Path DiscordChatExporter.Gui/bin/Publish/* -DestinationPath DiscordChatExporter.Gui/bin/Publish/Archive.zip -Force
shell: pwsh
- name: Create release
id: create_release
uses: actions/create-release@v1.0.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
body: |
[Changelog](https://github.com/Tyrrrz/DiscordChatExporter/blob/master/Changelog.md)
draft: false
prerelease: false
- name: Upload release asset (CLI)
uses: actions/upload-release-asset@v1.0.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: DiscordChatExporter.Cli/bin/Publish/Archive.zip
asset_name: DiscordChatExporter.CLI.zip
asset_content_type: application/zip
- name: Upload release asset (GUI)
uses: actions/upload-release-asset@v1.0.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: DiscordChatExporter.Gui/bin/Publish/Archive.zip
asset_name: DiscordChatExporter.zip
asset_content_type: application/zip
- name: Notify Discord
uses: satak/webrequest-action@v1.2.4
with:
url: ${{ secrets.DISCORD_WEBHOOK }}
method: POST
headers: |
{
"ContentType": "application/json; charset=UTF-8"
}
payload: |
{
"content": "**DiscordChatExporter** new version released!\nVersion: `${{ steps.get_version.outputs.tag }}`\nChangelog: <https://github.com/Tyrrrz/DiscordChatExporter/blob/${{ steps.get_version.outputs.tag }}/Changelog.md>"
}
+23
View File
@@ -0,0 +1,23 @@
name: Docker CI
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Login
run: docker login -u tyrrrz -p ${{ secrets.DOCKER_TOKEN }}
- name: Build
run: docker build -t tyrrrz/discordchatexporter:latest .
- name: Deploy (latest)
run: docker push tyrrrz/discordchatexporter:latest
+47
View File
@@ -0,0 +1,47 @@
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v2.3.3
- name: Install .NET
uses: actions/setup-dotnet@v1.7.2
with:
dotnet-version: 6.0.x
- name: Build & test
# Tests need access to secrets, so we can't run them against PRs because of limited trust
if: ${{ github.event_name != 'pull_request' }}
run: dotnet test --configuration Release --logger GitHubActions
env:
DISCORD_TOKEN: ${{ secrets.DISCORD_TOKEN }}
DISCORD_TOKEN_BOT: true
- name: Upload coverage
uses: codecov/codecov-action@v1.0.5
with:
token: ${{ secrets.CODECOV_TOKEN }}
- name: Build & publish (CLI)
run: dotnet publish DiscordChatExporter.Cli/ -o DiscordChatExporter.Cli/bin/Publish/ --configuration Release
- name: Build & publish (GUI)
run: dotnet publish DiscordChatExporter.Gui/ -o DiscordChatExporter.Gui/bin/Publish/ --configuration Release
- name: Upload build artifacts (CLI)
uses: actions/upload-artifact@v1
with:
name: DiscordChatExporter.CLI
path: DiscordChatExporter.Cli/bin/Publish/
- name: Upload build artifact (GUI)
uses: actions/upload-artifact@v1
with:
name: DiscordChatExporter
path: DiscordChatExporter.Gui/bin/Publish/
+9 -245
View File
@@ -1,261 +1,25 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
.idea/
.vs/
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Coverage
*.opencover.xml
# 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
# Secrets
*.secret
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+343 -1
View File
@@ -1,3 +1,345 @@
### v2.32 (15-Dec-2021)
- Token kind (user or bot) is now detected automatically. Removed the button to switch token kind in GUI. Option `-b|--bot` in CLI is now deprecated and does nothing.
- Updated user token extraction guide to reflect the fact that devtools are no longer accessible in the desktop version of Discord client. The recommended workaround is to open Discord in browser. (Thanks [@Dhananjay-JSR](https://github.com/Dhananjay-JSR))
- Fixed an issue which caused an error when parsing invalid date timestamps. Such timestamps are now rendered as "Invalid date", similarly to how the Discord client does it.
- Fixed an issue which caused an error when parsing certain embed fields.
- Fixed an issue which caused an error when parsing a mention to a user that has no username.
- [GUI] Minor visual fixes.
### v2.31.1 (15-Dec-2021)
- Fixed an issue which caused an error when parsing certain custom emoji reactions.
- [GUI] Improved user interface.
### v2.31 (06-Dec-2021)
- Changed target runtime of the application (both GUI and CLI) from .NET 3.1 to .NET 6. Those using the GUI version will not need to take any action as the application should install the necessary prerequisites automatically. Those using the CLI version will need to download and install .NET 6 runtime manually [from here](https://dotnet.microsoft.com/download/dotnet/6.0) (look for ".NET Runtime 6.0.x" section on the right and choose the distribution appropriate for your system).
- [HTML] Updated layout design to match Discord more closely. (Thanks [@Artem](https://github.com/Scarg))
- [HTML] Fixed an issue where markdown inside channel topic was not rendered correctly. (Thanks [@Emily](https://github.com/emillly-b))
- [HTML] Fixed an issue where the layout was broken for messages containing text in right-to-left languages. (Thanks [@Emily](https://github.com/emillly-b))
- Fixed an issue where text filters weren't matching content inside of embeds.
- [GUI] Fixed a multitude of issues related to the bootstrapper.
### v2.30.1 (28-Aug-2021)
- [HTML] Changed user avatars to render using higher resolution images. (Thanks [@Chris Helder](https://github.com/TheDude53))
- Fixed an issue where `has:file` message filter was not recognized. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- Fixed an issue where a unix timestamp marker with an invalid offset crashed the export process.
### v2.30 (08-Aug-2021)
- [HTML] Added special casing for Spotify track embeds to render them directly using an embedded player.
- [HTML] Added special casing for plain image embeds to render them like image attachments.
- [HTML] Added tooltip text for unix timestamp markers which shows the full date represented by the timestamp, regardless of configured date format.
- [HTML] Updated the fallback text shown when the referenced message could not be loaded to make it more explicit.
- [HTML] Updated styling of quoted text in markdown to more closely resemble how it looks in Discord.
- [HTML] Fixed an issue where some file formats were not correctly recognized as image or video attachments, which affected how they were rendered.
- [HTML] Fixed an issue where formatting inside named links (e.g. `[**Bold link**](https://example.com)`) was not being parsed.
- [HTML] Fixed an issue where inline embed fields were missing horizontal spacing between columns.
- [HTML] Fixed other minor styling issues.
### v2.29 (19-Jul-2021)
- Added support for message filtering, which is accessible as an additional export parameter in the GUI and as the `--filter` option in the CLI. Message filters use a special syntax similar to Discord's search query syntax to allow specifying which messages should be included in the export. For example, you can limit the export to only include messages that contain image attachments (`has:image`) or messages from a certain user (`from:Tyrrrz`) or messages containing certain words (`hello world`), etc. You can also combine filters together (`hi mentions:Tyrrrz`, `from:Tyrrrz | from:96-LB`, `(mentions:Tyrrrz | from:Tyrrrz) has:image`) or negate them (`-has:link`). More thorough documentation coming soon. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- Added support for rendering mentions of voice channels, in addition to text channels.
- Added support for rendering unix timestamp markers. Currently, style markers are ignored and timestamps are always rendered with the format configured in settings (or provided via `--date-format` option).
- Updated in-app instructions for obtaining a user token. (Thanks [@Yudi](https://github.com/Yudi) and [@virtuallyvlad](https://github.com/virtuallyvlad))
- [HTML] Improved visual appearance of the reference symbol (Г-shaped line in replies) to make it more closely resemble Discord's styling.
- [HTML] Added more specific fallback text used when rendering referenced messages that contain no text content but have attachments or embeds.
- [HTML] Fixed an issue where a broken embed author icon occupied visual space, ruining the embed layout. (Thanks [@Cliff J.](https://github.com/CliffJameston))
- [GUI] Improved handling for fatal errors that may occur when attempting to export a channel. These errors are now displayed in a popup, allowing the user to try again instead of having the application crash completely.
- [CLI] Fixed an issue where an attempt to export a channel resulted in `NotSupportedException` when the default encoding was set to `UTF8`.
- [CLI] Fixed an issue where providing an incorrectly formatted partition limit via `-p|--partition` option resulted in a non-descriptive and unhelpful error.
- Improved "Requested resource does not exist" error message by including the ID of the requested resource.
### v2.28 (19-Jun-2021)
- [HTML] Added special casing for YouTube video embeds to render them directly using an embedded player. (Thanks [@quentinmay](https://github.com/quentinmay))
- [HTML] Added support for rendering standard emoji by code. Such emoji may sometimes be found in messages sent by bots or through webhooks. (Thanks [@CanePlayz](https://github.com/CanePlayz) and [@Lucas LaBuff](https://github.com/96-LB))
- [HTML] Changed tooltips on standard emoji to show emoji code instead of their raw string representations. (Thanks [@CanePlayz](https://github.com/CanePlayz) and [@Lucas LaBuff](https://github.com/96-LB))
- [HTML] Added tooltips on individual messages to show when those messages were sent.
- [HTML] Updated colors and minor styling elements to match Discord's new style direction after rebranding.
- [HTML] Updated Twemoji URLs to use SVG image variants for better rendering quality.
- [HTML] Changed user avatar URLs to include predetermined size query parameter for better rendering quality.
- Changed embed rendering logic to prefer Discord-proxied URLs for external content, in order to avoid unnecessary HTTP requests to third parties.
- Fixed an issue where exporting with media sometimes resulted in a crash due to lack of permissions to change file attributes. These errors are now ignored, which means that the creation, write, and access dates of downloaded files may sometimes not match the dates provided by Discord's CDN.
- [HTML] Fixed styling issues when rendering embed footers.
- [HTML] Fixed an issue where links didn't render properly inside referenced messages.
- [HTML] Fixed an issue where standalone emoji were incorrectly enlarged inside referenced messages.
- [HTML] Fixed an issue where clicking on a referenced message revealed spoilers inside of it.
- [GUI] Fixed an issue where the list of missing components, reported by the prerequisite check at application startup, included Windows updates that were not applicable to the user's system due to the fact that other superseding updates have already been installed. This issue only affected users running DiscordChatExporter on Windows 7.
- [GUI] Fixed a few other minor issues related to the prerequisite installation window.
### v2.27.1 (08-Jun-2021)
- [GUI] Application will now detect if the required .NET Runtime or any of its prerequisites are missing and prompt the user to download and install them automatically. **Experimental feature, please test it out and report any issues you may find!**
- [CLI] Fixed an issue where the application crashed when exporting a channel that had square brackets as part of its name or category name. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
### v2.27 (24-Apr-2021)
- Added partitioning by file size. You can now use values such as `10mb` to indicate a size-based cut off point, in addition to values like `10` to indicate a number of messages. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- [CLI] Improved formatting and progress reporting.
- [CLI] Changed `export` command so that it can accept multiple channel IDs passed to `-c|--channel` option. This makes it possible to export multiple channels at once while benefiting from parallelization.
- [JSON] Added `color` field to message author. This is a hex string that represents user's color, inherited from their roles. (Thanks [@rtm516](https://github.com/rtm516))
- [JSON] Added `categoryId` field to the root. This represents the ID of the category channel that the currently exported channel belongs to. (Thanks [@rtm516](https://github.com/rtm516))
- [JSON] Fixed an issue where user discriminator was written without leading zeroes. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- [JSON] Fixed an issue where the application sometimes crashed with an error saying `']' invalid without a matching open`, which was just a validation message that masked the actual error behind the failure. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- Fixed an issue where progress was not reported correctly if the channel didn't have any messages in the specified time range.
### v2.26.1 (06-Feb-2021)
- [CLI] Added support for file name templates, which allow you to dynamically generate output file names based on channel and guild metadata. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- Fixed an issue where the application sometimes crashed with `Invalid snowflake` message when exporting chat logs that contained invalid or outdated mentions. (Thanks [@Lucas LaBuff](https://github.com/96-LB))
### v2.26 (29-Dec-2020)
- [HTML] Added support for replies. (Thanks [@Sanqui](https://github.com/Sanqui))
- [HTML] Improved styling of non-media attachments (regular files, i.e. not video, audio, or image). (Thanks [@Lucas LaBuff](https://github.com/96-LB))
- [HTML] Improved initial export performance.
- [JSON] Relaxed escaping rules for unicode characters. (Thanks [@Sanqui](https://github.com/Sanqui))
- [JSON] Added support for replies. (Thanks [@Sanqui](https://github.com/Sanqui))
- [CLI] Added channel names to errors shown on failures when exporting multiple channels. (Thanks [@Sanqui](https://github.com/Sanqui))
- [CLI] Added support for passing message IDs (snowflakes) to `--after` and `--before` options. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- Files downloaded by the "download referenced media" option now have their dates set according to the `Last-Modified` header provided by Discord CDN. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- Fixed an issue where the application sometimes crashed with `NullReferenceException` when retrying a failed HTTP request.
- Migrated to Discord API v8.
### v2.25 (23-Nov-2020)
- [JSON] Added `mentions` property to the output. This contains users referenced inside the message text, but doesn't include mentions in embeds. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- [HTML] Added better previews for attached video and audio. They are now rendered using a browser native player element. The actual file path can still be retrieved by right clicking and selecting "Copy file path". (Thanks [@sas41](https://github.com/sas41))
- [CLI] Fixed an issue where using `--media` option without providing a rooted path via `--output` option triggered an error.
- [CLI] Fixed an issue where using `--reuse-media` option without also providing `--media` option was accepted, but didn't actually do anything. Now this produces an error instead. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
### v2.24 (24-Oct-2020)
- [CLI] Updated to [CliFx v1.5](https://github.com/Tyrrrz/CliFx), which brings some UX improvements.
- [GUI] Added dark mode, which can be enabled in settings. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- [GUI] Improved the UX in a few minor places.
- [JSON] Added `embed.color` property to the output. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- Added additional date formats: `unix` to write dates as a unix timestamp and `unixms` for the milliseconds version. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- Added retry policy for downloading media content. This is mostly a workaround for transient failures that sometimes may occur when downloading assets referenced from embeds. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
- Added an option to reuse already downloaded media to avoid redundant network requests. It can be enabled in settings in GUI, or by passing `--reuse-media` in CLI. To facilitate this feature, the file name strategy has been changed as well -- now instead of relying on the original file name and adding `(n)` to the end in case of duplicates, a URL hash is injected in every file name. This also means that when the "reuse media" option is disabled, existing files inside the media directory may be overwritten. (Thanks [@Andrew Kolos](https://github.com/andrewkolos))
### v2.23 (14-Sep-2020)
- [CLI] Added a command to export all channels across all servers. Use `exportall` to do it. (Thanks [@wyattscarpenter](https://github.com/wyattscarpenter))
- [HTML] Fixed an issue where Whitney fonts were not being loaded properly, causing the browser to fall back to Helvetica.
- Fixed an issue where self-contained export crashed occasionally. This usually happened when the server hosting the file did not serve the stream properly. Such files are now ignored after the first failed attempt.
### v2.22 (12-Aug-2020)
- [GUI] Improved the channel list by adding collapsible category groups. (Thanks [@CarJem Generations](https://github.com/CarJem))
- [GUI] Improved exporting options by adding a set of controls that can be used to limit the date range of the export down to minutes. Previously it was only possible to configure the date range without the time component. (Thanks [@CarJem Generations](https://github.com/CarJem))
- [HTML] Fixed an issue where the export didn't reflect changes in nicknames between messages sent by bots. This affected chat logs that contained interactions with the Tupperbox bot. (Thanks [@CarJem Generations](https://github.com/CarJem))
- [CLI] Fixed an issue where the application crashed if there were two environment variables defined that had the same name but in different case.
### v2.21.2 (30-Jul-2020)
- [GUI] When copy-pasting token, any surrounding spaces are now discarded, in addition to double quotes.
- [HTML] Changed underlying templating engine to provide higher performance and better error messages. New templating engine adds a small cold start, but any export after the first should be faster.
- Changed naming schema for downloaded media so that it follows `<original filename> (nn)` format rather than `<original filename>-salt`.
- [HTML] Fixed an issue where downloaded media was sometimes inaccessible due to reserved characters appearing in the URL.
- Fixed an issue where the application crashed when trying to download media with a file name that exceeds system's maximum allowed length.
- Fixed an issue where the application crashed when trying to download media with illegal characters in the file name.
### v2.21.1 (19-Jul-2020)
- Fixed an issue where the export crashed if an embedded image has been deleted. Such media files are now ignored.
- Changed the naming convention for downloaded media files so that the original file names are used when possible.
### v2.21 (18-Jul-2020)
- Added a new option that enables self-contained exports for all output formats. You can turn it on in the export setup dialog in GUI or using the `--media` option in CLI. When using this, the application will additionally download any media content directly referenced from the exported file instead of linking back to Discord CDN. The files which are downloaded include: guild icons, user avatars, attachments, embedded images, reaction emoji. Note that only files which are actually referenced by the export are downloaded, which means that, for example, user avatars will not be downloaded when using plain text export format. This option is not meant to enable complete offline viewing for HTML exports, but rather to make it easier to archive media content that may eventually get deleted from Discord servers. Also keep in mind that this option may make the export drastically slower and the total file size larger.
- Changed "discordapp.com" to "discord.com" where applicable as Discord is migrating to a new domain. CDN will remain on "cdn.discordapp.com" for the foreseeable future.
Note that all existing and current HTML exports will likely not render accurately because Discord enabled CORS for their font resources, which prevents them from loading locally. Please refer to [issue #322](https://github.com/Tyrrrz/DiscordChatExporter/issues/322) for discussion on this topic.
### v2.20 (27-Apr-2020)
- [CLI] Added environment variables as fallback for `--token` and `--bot` options. They are `DISCORD_TOKEN` and `DISCORD_TOKEN_BOT` respectively.
- [GUI] Fixed a crash that occurred if the application was closed in the middle of an auto-update.
- [GUI] Added a link to project's wiki in the usage guide.
- [HTML] Added full spoiler support for text and images. To spoil the hidden content you now need to click on it, similarly to how it works in Discord. (Thanks [@FM-96](https://github.com/FM-96))
- [HTML] Updated grammar for consecutive single-line quotes. Previously they appeared separately, now they're grouped together as if it was one multi-line quote instead.
- [HTML] Fixed an issue where messages sent by the same bot but with different usernames were grouped together when they shouldn't be.
- [HTML] Updated grammar for single-line code blocks to accept double backticks as synonymous with single backticks. This change makes code blocks appear the same, whether they were inserted manually or using Discord's buggy markdown preview mode.
- [HTML] Fixed styling inconsistencies and other minor issues.
- [TXT/JSON] Fixed an issue where markdown was not parsed correctly in embed fields.
- [HTML] Changed markdown formatting in embeds so it follows the same set of rules as in Discord.
- Added channel category to the default file name used when exporting chat logs.
- [HTML/TXT/JSON] Added channel category to exported metadata.
- [CLI] Updated commands to also show channel category as well as channel name wherever relevant.
- Starting with this release, Docker images will have new tags: `stable` for latest stable release and `2.20` for a specific version.
### v2.19 (26-Mar-2020)
- Added parallel exporting. This option allows you to export multiple channels faster by doing it in parallel. You can configure the parallel limit in settings (GUI) or with the `--parallel` option (CLI). Default value is `1`, which means there is no parallelization. Warning: be careful when using this option, as this will result in higher volume of concurrent HTTP requests sent to Discord, which might get you flagged. Use at your own risk.
- [HTML] Added support for user colors. User names are now appropriately colored according to the assigned guild roles.
- [HTML] Added support for nicknames. User names are replaced with nicknames where it's applicable. It's still possible to see the full user name by hovering your mouse over the nickname.
- [HTML] Improved styling for mentions to bring it more in line with how it looks in Discord.
### v2.18 (04-Feb-2020)
- Added JSON export format. It's a structured data format which is easy to parse. If you're using DiscordChatExporter to export chat logs for further ingestion by another tool, this is most likely the format you will want to use.
- [GUI] You can now quickly jump to a specific channel in a list. For example, if you want to jump to a channel named "General", you can simply press the 'g' key in the channel list view. You can also press 'g', 'e' and 'n' in quick succession which will jump to the next channel that starts with "gen". This mechanic is consistent with other Windows applications.
- [CLI] Improved help text screen.
### v2.17 (12-Jan-2020)
- Fixed an issue where an empty file was produced when exporting a channel with no messages (for specified period). With the new behavior, no file will be created and instead a message will be shown to the user informing of the failure.
- [HTML/TXT] Added message count to the bottom of the file. This number shows how many messages were exported as part of the current file. Prior to 2.16 this number was present along with the rest of the metadata at the top, then removed due to changes in the exporter, and now brought back at the end of the file instead.
- [HTML] Fixed an issue where some emoji were not properly rendered.
- [GUI] Added a setting that lets you configure whether to remember the last used token. Previously it was the default behavior, but now you can disable it if you don't want the token persisted on your system.
### v2.16 (08-Dec-2019)
- Migrated from .NET Framework to .NET Core. To run this and future versions of DiscordChatExporter you will need [.NET Core runtime for desktop apps](https://dotnet.microsoft.com/download/dotnet-core/3.1/runtime) (for GUI/CLI version on Windows) or [.NET Core base runtime](https://dotnet.microsoft.com/download/dotnet-core/3.1) (for CLI version on Windows, Linux or macOS).
- Reworked the exporter engine to render output using streaming data source. This means that only a very small portion of messages are cached in memory when exporting. In other words, you are only limited by storage space and not how much RAM you have, so you can now export terabytes of chat logs without hitting out of memory exceptions. I still recommend using partitions if you're exporting very large chat logs (250k+ messages) to HTML, unless you want your computer to catch fire when you try to open the export in browser.
- Changed how partitioned files are named, due to the fact that total number of partitions is no longer known ahead of time.
- Added a warning about automating user accounts to the usage guide in both GUI and CLI versions.
- Added support for announcement (news) channels. You will now be able to see them in the list and export them.
- Fixed various issues that resulted in exceptions during export process.
- [HTML/TXT] Removed message count from the metadata. Due to the fact that the messages are exported as they are streamed, total number of messages is not known ahead of time.
- [HTML] Changed default color of the embed color pill to match the theme.
- [HTML] Changed emoji parser to be less greedy. As a result it should match fewer character sequences that look like emoji but really aren't, but on the other hand it might miss some actual emoji. This means that some standard emoji (i.e. not custom server emoji) may not look like in Discord. This is a compromise I'm willing to take because detecting emoji in text is really hard to get right and not worth it at all.
- [HTML] Some other minor styling adjustments.
- [CSV] Replaced semicolons (;) with (,) as separators.
Please note that CSV export is most likely not going to receive future updates and will remain only as an option for those who wish to use it for text analysis. In other words, it won't contain any of the rich media features like embeds. If you're currently using CSV as a structured output to feed into your program, JSON output will replace that in the future.
### v2.15 (15-Sep-2019)
- Improved markdown parser and made it even faster for non-HTML formats.
- [HTML] Added support for block quotes.
- [HTML] Links pointing to a Discord message will now navigate to the linked message inside exported chat log if it's there.
- [HTML] Updated light theme to match how it looks in Discord after recent changes.
- [HTML] Added indication for when a message is pinned. Pinned messages now have a tinted background.
- [HTML] Fixed an issue where multiline code blocks sometimes had incorrect formatting applied to them.
- [TXT] Added indication for when a message is pinned. Pinned messages now have `(pinned)` next to timestamp and author.
- [CSV] Added message author's user ID to output.
- [GUI] Streamlined auto-update process a bit.
- [GUI] Added some tooltips.
### v2.14 (15-Jun-2019)
- [TXT] Added support for embeds.
- [TXT] Added support for reactions.
- [CSV] Added support for reactions.
- [TXT] Changed how attachments are rendered.
### v2.13.1 (06-Jun-2019)
- Fixed an issue where the app sometimes crashed when exporting due to `System.InvalidCastException`.
- [HTML] Added `data-user-id` attribute to `span.chatlog__author-name`. The value of this attribute is author's Discord user ID.
### v2.13 (15-May-2019)
- Updated usage instructions.
- [HTML] Added BOT tags to messages posted by bots.
- [GUI] UI will now be disabled when exporting.
- [GUI] Notification informing that the export has completed will now appear after all exports have completed, instead of each of them separately.
### v2.12.1 (12-Apr-2019)
- [GUI] Fixed an issue where the app crashed when trying to export multiple channels.
- [HTML] Fixed an issue where some of the emoji were rendered via Twemoji while Discord renders them as plain text.
- [HTML] Fixed an issue where emoji weren't jumbo if there were more than one of them.
### v2.12 (11-Apr-2019)
- Improved markdown parsing performance which speeds up the final stage of exporting by around 4.5 times.
- Improved performance when exporting as PlainText or CSV.
- [GUI] Fixed an issue where the app would freeze up and report as "not responding" during the final stage of exporting.
- [CLI] Fixed an issue where it would say "Completed" after exporting a chat log, even if the process failed.
### v2.11 (14-Mar-2019)
- [HTML] Added syntax highlighting for multiline code blocks via Highlight.js.
- Added retry policy for all 5xx status codes to prevent random crashes.
### v2.10.2 (10-Mar-2019)
- [HTML] Updated message grouping algorithm to make it the same as in Discord. Removed "message group limit" setting and parameter.
- [HTML] Added small margin at the end of the chatlog so it doesn't look like it was truncated.
- [CLI] Fixed an issue where the app would crash if stdout was redirected. Progress will not be reported in such cases.
### v2.10.1 (06-Mar-2019)
- [HTML] Fixed an issue where multiple emoji on a single line would get rendered as one emoji.
- [HTML] Fixed an issue where an open square bracket character would incorrectly render as an emoji.
- [HTML] Added alt text to emoji images so that they will be rendered using default font when Twemoji images are not available.
### v2.10 (03-Mar-2019)
- [HTML] Reworked the entire markdown parsing engine which fixes numerous rendering inconsistencies (over 15 issues fixed).
- [HTML] Added support for animated emoji.
- [HTML] Standard emoji are now rendered using Twemoji, the same image set that Discord uses.
- [HTML] Fixed an issue where video attachments would render incorrectly.
- [HTML] Minor fixes in styling.
- [GUI] Aggregated export progress is now shown in the taskbar.
- [GUI] Checkmarks are now displayed next to channels that are selected.
- [CLI] Added progress reporting when exporting chat logs.
### v2.9.1 (10-Feb-2019)
- Fixed an issue where some of the last messages in a channel would sometimes not get exported.
### v2.9 (09-Feb-2019)
- Added categories to channel list in GUI. Channels are now also grouped by category.
- Added ability to export multiple channels at once in GUI by selecting them with shift or ctrl keys.
- Added CLI command to export all available channels in a guild (`exportguild`).
- Added CLI command to export all direct message channels (`exportdm`).
- Added retry policy for 503 status code errors to prevent random crashes.
- Changed how channels are exported in GUI. Now you need to select them first and then click a button to export. You can also double click a single channel to export it as before.
- Improved default file name generation by adding date ranges and channel ID to the file name.
- Improved naming of files exported with partitioning.
- Improved usage instructions.
- Improved GUI layout and styling.
- Fixed an issue where dialogs would sometimes appear over other windows.
- Fixed an issue where launching DiscordChatExporter from Windows Start Menu would make it crash.
### v2.8 (03-Nov-2018)
- Added support for partitioning which lets you split the output into multiple files by setting the partition message limit (`-p` parameter for CLI).
- Exported file will no longer open automatically on completion.
- Reduced amount of memory used during exporting.
- Disabled message grouping in PlainText export.
- Improved encoding of newlines in CSV export.
- Improved error messages in the GUI app during crashes.
### v2.7 (14-Sep-2018)
- Updated instructions on how to obtain the user token.
- Expanded CLI with new commands: `channels` (get a list of channels in a guild), `dm` (get a list of DM channels), `guilds` (get a list of guilds), on top of `export` (export chatlog).
- Improved help text and error messages in CLI.
- In CLI, the file name will be automatically generated if the provided output file path is a directory.
### v2.6 (25-Jul-2018)
- Added support for bot tokens as an alternative to user tokens. For GUI, use the button in the top-left to switch between user and bot token. For CLI, pass the `--bot` switch to indicate that the given token is a bot token.
- Added support for animated avatars.
### v2.5.1 (01-Jul-2018)
- Fixed a bug that would prevent timestamps from rendering properly in CSV and PlainText exports.
- Fixed incorrect layout in CSV export.
- Improved readability of PlainText export.
### v2.5 (28-Jun-2018)
- Added support for embeds and webhooks (HTML only).
- Implemented progress reporting when downloading messages.
- Added support for reactions (HTML only).
- Selected date range is now shown in the export (HTML and PlainText).
- Added placeholders for guild icons to display while the icons are loading.
- Added support for jumbo emoji (custom emoji only).
- Added basic retry policy for 429 error responses.
- Added validation for from/to dates in the UI which prevents choosing invalid date ranges.
- Added an error message when trying to export a deleted channel.
### v2.4.1 (15-Apr-2018)
- Added CSV export format.
@@ -17,7 +359,7 @@
- Improved message date filtering, it's now marginally faster.
- Fixed underscores not recognized as italics in markdown.
- Added support for custom emojis.
- Added support for custom emoji.
- Added support for user and role mentions.
- Added support for channel mentions.
- Fixed text in pre blocks not being wrapped correctly.
-11
View File
@@ -1,11 +0,0 @@
New-Item "$PSScriptRoot\bin" -ItemType Directory -Force
# GUI
$files = @()
$files += Get-ChildItem -Path "$PSScriptRoot\..\DiscordChatExporter.Gui\bin\Release\*" -Include "*.exe", "*.dll", "*.config"
$files | Compress-Archive -DestinationPath "$PSScriptRoot\bin\DiscordChatExporter.zip" -Force
# CLI
$files = @()
$files += Get-ChildItem -Path "$PSScriptRoot\..\DiscordChatExporter.Cli\bin\Release\net461\*" -Include "*.exe", "*.dll", "*.config"
$files | Compress-Archive -DestinationPath "$PSScriptRoot\bin\DiscordChatExporter.Cli.zip" -Force
+13
View File
@@ -0,0 +1,13 @@
<Project>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Version>2.32</Version>
<Company>Tyrrrz</Company>
<Copyright>Copyright (c) Oleksii Holub</Copyright>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>
</Project>
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<CollectCoverage>true</CollectCoverage>
<CoverletOutputFormat>opencover</CoverletOutputFormat>
<NoWarn>$(NoWarn);xUnit1013</NoWarn>
</PropertyGroup>
<ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
<None Include="*.secret" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AngleSharp" Version="0.16.1" />
<PackageReference Include="FluentAssertions" Version="6.4.0" />
<PackageReference Include="GitHubActionsTestLogger" Version="1.2.0" />
<PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="coverlet.msbuild" Version="3.1.0" PrivateAssets="all" />
<PackageReference Include="System.Reactive" Version="5.0.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DiscordChatExporter.Cli\DiscordChatExporter.Cli.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands;
using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.Utils;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Exporting;
using JsonExtensions;
namespace DiscordChatExporter.Cli.Tests.Fixtures;
public class ExportWrapperFixture : IDisposable
{
private string DirPath { get; } = Path.Combine(
Path.GetDirectoryName(typeof(ExportWrapperFixture).Assembly.Location) ?? Directory.GetCurrentDirectory(),
"ExportCache",
Guid.NewGuid().ToString()
);
public ExportWrapperFixture() => DirectoryEx.Reset(DirPath);
private async ValueTask<string> ExportAsync(Snowflake channelId, ExportFormat format)
{
var fileName = channelId.ToString() + '.' + format.GetFileExtension();
var filePath = Path.Combine(DirPath, fileName);
// Perform export only if it hasn't been done before
if (!File.Exists(filePath))
{
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { channelId },
ExportFormat = format,
OutputPath = filePath
}.ExecuteAsync(new FakeConsole());
}
return await File.ReadAllTextAsync(filePath);
}
public async ValueTask<IHtmlDocument> ExportAsHtmlAsync(Snowflake channelId)
{
var data = await ExportAsync(channelId, ExportFormat.HtmlDark);
return Html.Parse(data);
}
public async ValueTask<JsonElement> ExportAsJsonAsync(Snowflake channelId)
{
var data = await ExportAsync(channelId, ExportFormat.Json);
return Json.Parse(data);
}
public async ValueTask<string> ExportAsPlainTextAsync(Snowflake channelId)
{
var data = await ExportAsync(channelId, ExportFormat.PlainText);
return data;
}
public async ValueTask<string> ExportAsCsvAsync(Snowflake channelId)
{
var data = await ExportAsync(channelId, ExportFormat.Csv);
return data;
}
public async ValueTask<IReadOnlyList<IElement>> GetMessagesAsHtmlAsync(Snowflake channelId)
{
var document = await ExportAsHtmlAsync(channelId);
return document.QuerySelectorAll("[data-message-id]").ToArray();
}
public async ValueTask<IReadOnlyList<JsonElement>> GetMessagesAsJsonAsync(Snowflake channelId)
{
var document = await ExportAsJsonAsync(channelId);
return document.GetProperty("messages").EnumerateArray().ToArray();
}
public async ValueTask<IElement> GetMessageAsHtmlAsync(Snowflake channelId, Snowflake messageId)
{
var messages = await GetMessagesAsHtmlAsync(channelId);
var message = messages.SingleOrDefault(e =>
string.Equals(
e.GetAttribute("data-message-id"),
messageId.ToString(),
StringComparison.OrdinalIgnoreCase
)
);
if (message is null)
{
throw new InvalidOperationException(
$"Message '{messageId}' does not exist in export of channel '{channelId}'."
);
}
return message;
}
public async ValueTask<JsonElement> GetMessageAsJsonAsync(Snowflake channelId, Snowflake messageId)
{
var messages = await GetMessagesAsJsonAsync(channelId);
var message = messages.FirstOrDefault(j =>
string.Equals(
j.GetProperty("id").GetString(),
messageId.ToString(),
StringComparison.OrdinalIgnoreCase
)
);
if (message.ValueKind == JsonValueKind.Undefined)
{
throw new InvalidOperationException(
$"Message '{messageId}' does not exist in export of channel '{channelId}'."
);
}
return message;
}
public void Dispose() => DirectoryEx.DeleteIfExists(DirPath);
}
@@ -0,0 +1,22 @@
using System;
using System.IO;
using DiscordChatExporter.Cli.Tests.Utils;
namespace DiscordChatExporter.Cli.Tests.Fixtures;
public class TempOutputFixture : IDisposable
{
public string DirPath { get; } = Path.Combine(
Path.GetDirectoryName(typeof(TempOutputFixture).Assembly.Location) ?? Directory.GetCurrentDirectory(),
"Temp",
Guid.NewGuid().ToString()
);
public TempOutputFixture() => DirectoryEx.Reset(DirPath);
public string GetTempFilePath(string fileName) => Path.Combine(DirPath, fileName);
public string GetTempFilePath() => GetTempFilePath(Guid.NewGuid() + ".tmp");
public void Dispose() => DirectoryEx.DeleteIfExists(DirPath);
}
@@ -0,0 +1,26 @@
using System;
using System.IO;
namespace DiscordChatExporter.Cli.Tests.Infra;
internal static class Secrets
{
private static readonly Lazy<string> DiscordTokenLazy = new(() =>
{
var fromEnvironment = Environment.GetEnvironmentVariable("DISCORD_TOKEN");
if (!string.IsNullOrWhiteSpace(fromEnvironment))
return fromEnvironment;
var secretFilePath = Path.Combine(
Path.GetDirectoryName(typeof(Secrets).Assembly.Location) ?? Directory.GetCurrentDirectory(),
"DiscordToken.secret"
);
if (File.Exists(secretFilePath))
return File.ReadAllText(secretFilePath);
throw new InvalidOperationException("Discord token not provided for tests.");
});
public static string DiscordToken => DiscordTokenLazy.Value;
}
+14
View File
@@ -0,0 +1,14 @@
# DiscordChatExporter Tests
This test suite runs against a real Discord server, specifically created to exercise different behaviors required by the test scenarios.
In order to run these tests locally, you need to join the test server and configure your authentication token.
1. Join the server: https://discord.gg/eRV8Vap5bm
2. Locate your Discord authentication token
3. Specify your token using a file or an environment variable:
- **Using a file**: put your token in a new `DiscordToken.secret` file created in this directory
- **Using an environment variable**: set `DISCORD_TOKEN` variable to your token
4. Run the tests: `dotnet test`
> If you want to have a new test case or a scenario added, please let me know in your pull request.
Currently, it's not possible to add them by yourself.
@@ -0,0 +1,30 @@
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.CsvWriting;
public record ContentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Messages_are_exported_correctly()
{
// Act
var document = await ExportWrapper.ExportAsCsvAsync(ChannelIds.DateRangeTestCases);
// Assert
document.Should().ContainAll(
"Tyrrrz#5447",
"Hello world",
"Goodbye world",
"Foo bar",
"Hurdle Durdle",
"One",
"Two",
"Three",
"Yeet"
);
}
}
@@ -0,0 +1,156 @@
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Exporting;
using FluentAssertions;
using JsonExtensions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs;
public record DateRangeSpecs(TempOutputFixture TempOutput) : IClassFixture<TempOutputFixture>
{
[Fact]
public async Task Messages_filtered_after_specific_date_only_include_messages_sent_after_that_date()
{
// Arrange
var after = new DateTimeOffset(2021, 07, 24, 0, 0, 0, TimeSpan.Zero);
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.DateRangeTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
After = Snowflake.FromDate(after)
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
var timestamps = document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
.ToArray();
// Assert
timestamps.All(t => t > after).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[]
{
new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero),
new DateTimeOffset(2021, 09, 08, 14, 26, 35, TimeSpan.Zero)
}, o =>
{
return o
.Using<DateTimeOffset>(ctx =>
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
});
}
[Fact]
public async Task Messages_filtered_before_specific_date_only_include_messages_sent_before_that_date()
{
// Arrange
var before = new DateTimeOffset(2021, 07, 24, 0, 0, 0, TimeSpan.Zero);
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.DateRangeTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
Before = Snowflake.FromDate(before)
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
var timestamps = document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
.ToArray();
// Assert
timestamps.All(t => t < before).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[]
{
new DateTimeOffset(2021, 07, 19, 13, 34, 18, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 19, 15, 58, 48, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 19, 17, 23, 58, TimeSpan.Zero)
}, o =>
{
return o
.Using<DateTimeOffset>(ctx =>
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
});
}
[Fact]
public async Task Messages_filtered_between_specific_dates_only_include_messages_sent_between_those_dates()
{
// Arrange
var after = new DateTimeOffset(2021, 07, 24, 0, 0, 0, TimeSpan.Zero);
var before = new DateTimeOffset(2021, 08, 01, 0, 0, 0, TimeSpan.Zero);
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.DateRangeTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
Before = Snowflake.FromDate(before),
After = Snowflake.FromDate(after)
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
var timestamps = document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("timestamp").GetDateTimeOffset())
.ToArray();
// Assert
timestamps.All(t => t < before && t > after).Should().BeTrue();
timestamps.Should().BeEquivalentTo(new[]
{
new DateTimeOffset(2021, 07, 24, 13, 49, 13, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 38, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 39, TimeSpan.Zero),
new DateTimeOffset(2021, 07, 24, 14, 52, 40, TimeSpan.Zero)
}, o =>
{
return o
.Using<DateTimeOffset>(ctx =>
ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(1))
)
.WhenTypeIs<DateTimeOffset>();
});
}
}
@@ -0,0 +1,130 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering;
using FluentAssertions;
using JsonExtensions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs;
public record FilterSpecs(TempOutputFixture TempOutput) : IClassFixture<TempOutputFixture>
{
[Fact]
public async Task Messages_filtered_by_text_only_include_messages_that_contain_that_text()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.FilterTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
MessageFilter = MessageFilter.Parse("some text")
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
// Assert
document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("content").GetString())
.Should()
.ContainSingle("Some random text");
}
[Fact]
public async Task Messages_filtered_by_author_only_include_messages_sent_by_that_author()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.FilterTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
MessageFilter = MessageFilter.Parse("from:Tyrrrz")
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
// Assert
document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("author").GetProperty("name").GetString())
.Should()
.AllBe("Tyrrrz");
}
[Fact]
public async Task Messages_filtered_by_content_only_include_messages_that_have_that_content()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.FilterTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
MessageFilter = MessageFilter.Parse("has:image")
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
// Assert
document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("content").GetString())
.Should()
.ContainSingle("This has image");
}
[Fact]
public async Task Messages_filtered_by_mention_only_include_messages_that_have_that_mention()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.FilterTestCases },
ExportFormat = ExportFormat.Json,
OutputPath = filePath,
MessageFilter = MessageFilter.Parse("mentions:Tyrrrz")
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Json.Parse(data);
// Assert
document
.GetProperty("messages")
.EnumerateArray()
.Select(j => j.GetProperty("content").GetString())
.Should()
.ContainSingle("This has mention");
}
}
@@ -0,0 +1,92 @@
using System.Threading.Tasks;
using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record AttachmentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_a_generic_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885587844989612074")
);
var fileUrl = message.QuerySelector("a")?.GetAttribute("href");
// Assert
message.Text().Should().ContainAll(
"Generic file attachment",
"Test.txt",
"11 bytes"
);
fileUrl.Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt"
);
}
[Fact]
public async Task Message_with_an_image_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885654862656843786")
);
var imageUrl = message.QuerySelector("img")?.GetAttribute("src");
// Assert
message.Text().Should().Contain("Image attachment");
imageUrl.Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png"
);
}
[Fact]
public async Task Message_with_a_video_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885655761919836171")
);
var videoUrl = message.QuerySelector("video source")?.GetAttribute("src");
// Assert
message.Text().Should().Contain("Video attachment");
videoUrl.Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4"
);
}
[Fact]
public async Task Message_with_an_audio_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885656175620808734")
);
var audioUrl = message.QuerySelector("audio source")?.GetAttribute("src");
// Assert
message.Text().Should().Contain("Audio attachment");
audioUrl.Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3"
);
}
}
@@ -0,0 +1,42 @@
using System.Linq;
using System.Threading.Tasks;
using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record ContentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Messages_are_exported_correctly()
{
// Act
var messages = await ExportWrapper.GetMessagesAsHtmlAsync(ChannelIds.DateRangeTestCases);
// Assert
messages.Select(e => e.GetAttribute("data-message-id")).Should().Equal(
"866674314627121232",
"866710679758045195",
"866732113319428096",
"868490009366396958",
"868505966528835604",
"868505969821364245",
"868505973294268457",
"885169254029213696"
);
messages.Select(e => e.QuerySelector(".chatlog__content")?.Text().Trim()).Should().Equal(
"Hello world",
"Goodbye world",
"Foo bar",
"Hurdle Durdle",
"One",
"Two",
"Three",
"Yeet"
);
}
}
@@ -0,0 +1,63 @@
using System.Threading.Tasks;
using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record EmbedSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_an_embed_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.EmbedTestCases,
Snowflake.Parse("866769910729146400")
);
// Assert
message.Text().Should().ContainAll(
"Embed author",
"Embed title",
"Embed description",
"Field 1", "Value 1",
"Field 2", "Value 2",
"Field 3", "Value 3",
"Embed footer"
);
}
[Fact]
public async Task Message_with_a_Spotify_track_is_rendered_using_an_iframe()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.EmbedTestCases,
Snowflake.Parse("867886632203976775")
);
var iframeSrc = message.QuerySelector("iframe")?.GetAttribute("src");
// Assert
iframeSrc.Should().StartWithEquivalentOf("https://open.spotify.com/embed/track/1LHZMWefF9502NPfArRfvP");
}
[Fact]
public async Task Message_with_a_YouTube_video_is_rendered_using_an_iframe()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.EmbedTestCases,
Snowflake.Parse("866472508588294165")
);
var iframeSrc = message.QuerySelector("iframe")?.GetAttribute("src");
// Assert
iframeSrc.Should().StartWithEquivalentOf("https://www.youtube.com/embed/qOWW4OlgbvE");
}
}
@@ -0,0 +1,65 @@
using System.Threading.Tasks;
using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record MentionSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task User_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866458840245076028")
);
// Assert
message.Text().Trim().Should().Be("User mention: @Tyrrrz");
message.InnerHtml.Should().Contain("Tyrrrz#5447");
}
[Fact]
public async Task Text_channel_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459040480624680")
);
// Assert
message.Text().Trim().Should().Be("Text channel mention: #mention-tests");
}
[Fact]
public async Task Voice_channel_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459175462633503")
);
// Assert
message.Text().Trim().Should().Be("Voice channel mention: 🔊chaos-vc");
}
[Fact]
public async Task Role_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459254693429258")
);
// Assert
message.Text().Trim().Should().Be("Role mention: @Role 1");
}
}
@@ -0,0 +1,56 @@
using System.Threading.Tasks;
using AngleSharp.Dom;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.HtmlWriting;
public record ReplySpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Reply_to_a_normal_message_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.ReplyTestCases,
Snowflake.Parse("866460738239725598")
);
// Assert
message.Text().Trim().Should().Be("reply to original");
message.QuerySelector(".chatlog__reference-link")?.Text().Trim().Should().Be("original");
}
[Fact]
public async Task Reply_to_a_deleted_message_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.ReplyTestCases,
Snowflake.Parse("866460975388819486")
);
// Assert
message.Text().Trim().Should().Be("reply to deleted");
message.QuerySelector(".chatlog__reference-link")?.Text().Trim().Should()
.Be("Original message was deleted or could not be loaded.");
}
[Fact]
public async Task Reply_to_a_empty_message_with_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsHtmlAsync(
ChannelIds.ReplyTestCases,
Snowflake.Parse("866462470335627294")
);
// Assert
message.Text().Trim().Should().Be("reply to attachment");
message.QuerySelector(".chatlog__reference-link")?.Text().Trim().Should()
.Be("Click to see attachment 🖼️");
}
}
@@ -0,0 +1,100 @@
using System.Linq;
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.JsonWriting;
public record AttachmentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_a_generic_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885587844989612074")
);
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
// Assert
message.GetProperty("content").GetString().Should().Be("Generic file attachment");
attachments.Should().HaveCount(1);
attachments.Single().GetProperty("url").GetString().Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885587844964417596/Test.txt"
);
attachments.Single().GetProperty("fileName").GetString().Should().Be("Test.txt");
attachments.Single().GetProperty("fileSizeBytes").GetInt64().Should().Be(11);
}
[Fact]
public async Task Message_with_an_image_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885654862656843786")
);
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
// Assert
message.GetProperty("content").GetString().Should().Be("Image attachment");
attachments.Should().HaveCount(1);
attachments.Single().GetProperty("url").GetString().Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885654862430359613/bird-thumbnail.png"
);
attachments.Single().GetProperty("fileName").GetString().Should().Be("bird-thumbnail.png");
attachments.Single().GetProperty("fileSizeBytes").GetInt64().Should().Be(466335);
}
[Fact]
public async Task Message_with_a_video_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885655761919836171")
);
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
// Assert
message.GetProperty("content").GetString().Should().Be("Video attachment");
attachments.Should().HaveCount(1);
attachments.Single().GetProperty("url").GetString().Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885655761512968233/file_example_MP4_640_3MG.mp4"
);
attachments.Single().GetProperty("fileName").GetString().Should().Be("file_example_MP4_640_3MG.mp4");
attachments.Single().GetProperty("fileSizeBytes").GetInt64().Should().Be(3114374);
}
[Fact]
public async Task Message_with_an_audio_attachment_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.AttachmentTestCases,
Snowflake.Parse("885656175620808734")
);
var attachments = message.GetProperty("attachments").EnumerateArray().ToArray();
// Assert
message.GetProperty("content").GetString().Should().Be("Audio attachment");
attachments.Should().HaveCount(1);
attachments.Single().GetProperty("url").GetString().Should().StartWithEquivalentOf(
"https://cdn.discordapp.com/attachments/885587741654536192/885656175348187146/file_example_MP3_1MG.mp3"
);
attachments.Single().GetProperty("fileName").GetString().Should().Be("file_example_MP3_1MG.mp3");
attachments.Single().GetProperty("fileSizeBytes").GetInt64().Should().Be(1087849);
}
}
@@ -0,0 +1,41 @@
using System.Linq;
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.JsonWriting;
public record ContentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Messages_are_exported_correctly()
{
// Act
var messages = await ExportWrapper.GetMessagesAsJsonAsync(ChannelIds.DateRangeTestCases);
// Assert
messages.Select(j => j.GetProperty("id").GetString()).Should().Equal(
"866674314627121232",
"866710679758045195",
"866732113319428096",
"868490009366396958",
"868505966528835604",
"868505969821364245",
"868505973294268457",
"885169254029213696"
);
messages.Select(j => j.GetProperty("content").GetString()).Should().Equal(
"Hello world",
"Goodbye world",
"Foo bar",
"Hurdle Durdle",
"One",
"Two",
"Three",
"Yeet"
);
}
}
@@ -0,0 +1,57 @@
using System.Linq;
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.JsonWriting;
public record EmbedSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Message_with_an_embed_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.EmbedTestCases,
Snowflake.Parse("866769910729146400")
);
var embed = message
.GetProperty("embeds")
.EnumerateArray()
.Single();
var embedAuthor = embed.GetProperty("author");
var embedThumbnail = embed.GetProperty("thumbnail");
var embedFooter = embed.GetProperty("footer");
var embedFields = embed.GetProperty("fields").EnumerateArray().ToArray();
// Assert
embed.GetProperty("title").GetString().Should().Be("Embed title");
embed.GetProperty("url").GetString().Should().Be("https://example.com");
embed.GetProperty("timestamp").GetString().Should().Be("2021-07-14T21:00:00+00:00");
embed.GetProperty("description").GetString().Should().Be("**Embed** _description_");
embed.GetProperty("color").GetString().Should().Be("#58B9FF");
embedAuthor.GetProperty("name").GetString().Should().Be("Embed author");
embedAuthor.GetProperty("url").GetString().Should().Be("https://example.com/author");
embedAuthor.GetProperty("iconUrl").GetString().Should().NotBeNullOrWhiteSpace();
embedThumbnail.GetProperty("url").GetString().Should().NotBeNullOrWhiteSpace();
embedThumbnail.GetProperty("width").GetInt32().Should().Be(120);
embedThumbnail.GetProperty("height").GetInt32().Should().Be(120);
embedFooter.GetProperty("text").GetString().Should().Be("Embed footer");
embedFooter.GetProperty("iconUrl").GetString().Should().NotBeNullOrWhiteSpace();
embedFields.Should().HaveCount(3);
embedFields[0].GetProperty("name").GetString().Should().Be("Field 1");
embedFields[0].GetProperty("value").GetString().Should().Be("Value 1");
embedFields[0].GetProperty("isInline").GetBoolean().Should().BeTrue();
embedFields[1].GetProperty("name").GetString().Should().Be("Field 2");
embedFields[1].GetProperty("value").GetString().Should().Be("Value 2");
embedFields[1].GetProperty("isInline").GetBoolean().Should().BeTrue();
embedFields[2].GetProperty("name").GetString().Should().Be("Field 3");
embedFields[2].GetProperty("value").GetString().Should().Be("Value 3");
embedFields[2].GetProperty("isInline").GetBoolean().Should().BeTrue();
}
}
@@ -0,0 +1,70 @@
using System.Linq;
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Discord;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.JsonWriting;
public record MentionSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task User_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866458840245076028")
);
// Assert
message.GetProperty("content").GetString().Should().Be("User mention: @Tyrrrz");
message
.GetProperty("mentions")
.EnumerateArray()
.Select(j => j.GetProperty("id").GetString())
.Should().Contain("128178626683338752");
}
[Fact]
public async Task Text_channel_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459040480624680")
);
// Assert
message.GetProperty("content").GetString().Should().Be("Text channel mention: #mention-tests");
}
[Fact]
public async Task Voice_channel_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459175462633503")
);
// Assert
message.GetProperty("content").GetString().Should().Be("Voice channel mention: #chaos-vc [voice]");
}
[Fact]
public async Task Role_mention_is_rendered_correctly()
{
// Act
var message = await ExportWrapper.GetMessageAsJsonAsync(
ChannelIds.MentionTestCases,
Snowflake.Parse("866459254693429258")
);
// Assert
message.GetProperty("content").GetString().Should().Be("Role mention: @Role 1");
}
}
@@ -0,0 +1,64 @@
using System.IO;
using System.Threading.Tasks;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Partitioning;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs;
public record PartitioningSpecs(TempOutputFixture TempOutput) : IClassFixture<TempOutputFixture>
{
[Fact]
public async Task Messages_partitioned_by_count_are_split_into_multiple_files_correctly()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
var dirPath = Path.GetDirectoryName(filePath) ?? Directory.GetCurrentDirectory();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.DateRangeTestCases },
ExportFormat = ExportFormat.HtmlDark,
OutputPath = filePath,
PartitionLimit = PartitionLimit.Parse("3")
}.ExecuteAsync(new FakeConsole());
// Assert
Directory.EnumerateFiles(dirPath, fileNameWithoutExt + "*")
.Should()
.HaveCount(3);
}
[Fact]
public async Task Messages_partitioned_by_file_size_are_split_into_multiple_files_correctly()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(filePath);
var dirPath = Path.GetDirectoryName(filePath) ?? Directory.GetCurrentDirectory();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.DateRangeTestCases },
ExportFormat = ExportFormat.HtmlDark,
OutputPath = filePath,
PartitionLimit = PartitionLimit.Parse("20kb")
}.ExecuteAsync(new FakeConsole());
// Assert
Directory.EnumerateFiles(dirPath, fileNameWithoutExt + "*")
.Should()
.HaveCount(2);
}
}
@@ -0,0 +1,30 @@
using System.Threading.Tasks;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.TestData;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs.PlainTextWriting;
public record ContentSpecs(ExportWrapperFixture ExportWrapper) : IClassFixture<ExportWrapperFixture>
{
[Fact]
public async Task Messages_are_exported_correctly()
{
// Act
var document = await ExportWrapper.ExportAsPlainTextAsync(ChannelIds.DateRangeTestCases);
// Assert
document.Should().ContainAll(
"Tyrrrz#5447",
"Hello world",
"Goodbye world",
"Foo bar",
"Hurdle Durdle",
"One",
"Two",
"Three",
"Yeet"
);
}
}
@@ -0,0 +1,47 @@
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands;
using DiscordChatExporter.Cli.Tests.Fixtures;
using DiscordChatExporter.Cli.Tests.Infra;
using DiscordChatExporter.Cli.Tests.TestData;
using DiscordChatExporter.Cli.Tests.Utils;
using DiscordChatExporter.Core.Exporting;
using FluentAssertions;
using Xunit;
namespace DiscordChatExporter.Cli.Tests.Specs;
public record SelfContainedSpecs(TempOutputFixture TempOutput) : IClassFixture<TempOutputFixture>
{
[Fact]
public async Task Messages_in_self_contained_export_only_reference_local_file_resources()
{
// Arrange
var filePath = TempOutput.GetTempFilePath();
var dirPath = Path.GetDirectoryName(filePath) ?? Directory.GetCurrentDirectory();
// Act
await new ExportChannelsCommand
{
Token = Secrets.DiscordToken,
ChannelIds = new[] { ChannelIds.SelfContainedTestCases },
ExportFormat = ExportFormat.HtmlDark,
OutputPath = filePath,
ShouldDownloadMedia = true
}.ExecuteAsync(new FakeConsole());
var data = await File.ReadAllTextAsync(filePath);
var document = Html.Parse(data);
// Assert
document
.QuerySelectorAll("body [src]")
.Select(e => e.GetAttribute("src")!)
.Select(f => Path.GetFullPath(f, dirPath))
.All(File.Exists)
.Should()
.BeTrue();
}
}
@@ -0,0 +1,20 @@
using DiscordChatExporter.Core.Discord;
namespace DiscordChatExporter.Cli.Tests.TestData;
public static class ChannelIds
{
public static Snowflake AttachmentTestCases { get; } = Snowflake.Parse("885587741654536192");
public static Snowflake DateRangeTestCases { get; } = Snowflake.Parse("866674248747319326");
public static Snowflake EmbedTestCases { get; } = Snowflake.Parse("866472452459462687");
public static Snowflake FilterTestCases { get; } = Snowflake.Parse("866744075033641020");
public static Snowflake MentionTestCases { get; } = Snowflake.Parse("866458801389174794");
public static Snowflake ReplyTestCases { get; } = Snowflake.Parse("866459871934677052");
public static Snowflake SelfContainedTestCases { get; } = Snowflake.Parse("887441432678379560");
}
@@ -0,0 +1,23 @@
using System.IO;
namespace DiscordChatExporter.Cli.Tests.Utils;
internal static class DirectoryEx
{
public static void DeleteIfExists(string dirPath, bool recursive = true)
{
try
{
Directory.Delete(dirPath, recursive);
}
catch (DirectoryNotFoundException)
{
}
}
public static void Reset(string dirPath)
{
DeleteIfExists(dirPath);
Directory.CreateDirectory(dirPath);
}
}
@@ -0,0 +1,11 @@
using AngleSharp.Html.Dom;
using AngleSharp.Html.Parser;
namespace DiscordChatExporter.Cli.Tests.Utils;
internal static class Html
{
private static readonly IHtmlParser Parser = new HtmlParser();
public static IHtmlDocument Parse(string source) => Parser.ParseDocument(source);
}
@@ -0,0 +1,5 @@
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"methodDisplayOptions": "all",
"methodDisplay": "method"
}
-24
View File
@@ -1,24 +0,0 @@
using System;
using DiscordChatExporter.Core.Models;
namespace DiscordChatExporter.Cli
{
public class CliOptions
{
public string Token { get; set; }
public string ChannelId { get; set; }
public ExportFormat ExportFormat { get; set; }
public string FilePath { get; set; }
public DateTime? From { get; set; }
public DateTime? To { get; set; }
public string DateFormat { get; set; }
public int MessageGroupLimit { get; set; }
}
}
@@ -0,0 +1,165 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Exceptions;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Utils.Extensions;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering;
using DiscordChatExporter.Core.Exporting.Partitioning;
namespace DiscordChatExporter.Cli.Commands.Base;
public abstract class ExportCommandBase : TokenCommandBase
{
[CommandOption("output", 'o', Description = "Output file or directory path.")]
public string OutputPath { get; init; } = Directory.GetCurrentDirectory();
[CommandOption("format", 'f', Description = "Export format.")]
public ExportFormat ExportFormat { get; init; } = ExportFormat.HtmlDark;
[CommandOption("after", Description = "Only include messages sent after this date or message ID.")]
public Snowflake? After { get; init; }
[CommandOption("before", Description = "Only include messages sent before this date or message ID.")]
public Snowflake? Before { get; init; }
[CommandOption("partition", 'p', Description = "Split output into partitions, each limited to this number of messages (e.g. '100') or file size (e.g. '10mb').")]
public PartitionLimit PartitionLimit { get; init; } = PartitionLimit.Null;
[CommandOption("filter", Description = "Only include messages that satisfy this filter (e.g. 'from:foo#1234' or 'has:image').")]
public MessageFilter MessageFilter { get; init; } = MessageFilter.Null;
[CommandOption("parallel", Description = "Limits how many channels can be exported in parallel.")]
public int ParallelLimit { get; init; } = 1;
[CommandOption("media", Description = "Download referenced media content.")]
public bool ShouldDownloadMedia { get; init; }
[CommandOption("reuse-media", Description = "Reuse already existing media content to skip redundant downloads.")]
public bool ShouldReuseMedia { get; init; }
[CommandOption("dateformat", Description = "Format used when writing dates.")]
public string DateFormat { get; init; } = "dd-MMM-yy hh:mm tt";
private ChannelExporter? _channelExporter;
protected ChannelExporter Exporter => _channelExporter ??= new ChannelExporter(Discord);
protected async ValueTask ExecuteAsync(IConsole console, IReadOnlyList<Channel> channels)
{
var cancellationToken = console.RegisterCancellationHandler();
if (ShouldReuseMedia && !ShouldDownloadMedia)
{
throw new CommandException("Option --reuse-media cannot be used without --media.");
}
var errors = new ConcurrentDictionary<Channel, string>();
// Export
await console.Output.WriteLineAsync($"Exporting {channels.Count} channel(s)...");
await console.CreateProgressTicker().StartAsync(async progressContext =>
{
await Parallel.ForEachAsync(
channels,
new ParallelOptions
{
MaxDegreeOfParallelism = Math.Max(1, ParallelLimit),
CancellationToken = cancellationToken
},
async (channel, innerCancellationToken) =>
{
try
{
await progressContext.StartTaskAsync(
$"{channel.Category.Name} / {channel.Name}",
async progress =>
{
var guild = await Discord.GetGuildAsync(channel.GuildId, innerCancellationToken);
var request = new ExportRequest(
guild,
channel,
OutputPath,
ExportFormat,
After,
Before,
PartitionLimit,
MessageFilter,
ShouldDownloadMedia,
ShouldReuseMedia,
DateFormat
);
await Exporter.ExportChannelAsync(request, progress, innerCancellationToken);
}
);
}
catch (DiscordChatExporterException ex) when (!ex.IsFatal)
{
errors[channel] = ex.Message;
}
}
);
});
// Print result
using (console.WithForegroundColor(ConsoleColor.White))
{
await console.Output.WriteLineAsync(
$"Successfully exported {channels.Count - errors.Count} channel(s)."
);
}
// Print errors
if (errors.Any())
{
await console.Output.WriteLineAsync();
using (console.WithForegroundColor(ConsoleColor.Red))
{
await console.Output.WriteLineAsync(
$"Failed to export {errors.Count} channel(s):"
);
}
foreach (var (channel, error) in errors)
{
await console.Output.WriteAsync($"{channel.Category.Name} / {channel.Name}: ");
using (console.WithForegroundColor(ConsoleColor.Red))
await console.Output.WriteLineAsync(error);
}
await console.Output.WriteLineAsync();
}
// Fail the command only if ALL channels failed to export.
// Having some of the channels fail to export is expected.
if (errors.Count >= channels.Count)
{
throw new CommandException("Export failed.");
}
}
protected async ValueTask ExecuteAsync(IConsole console, IReadOnlyList<Snowflake> channelIds)
{
var cancellationToken = console.RegisterCancellationHandler();
var channels = new List<Channel>();
foreach (var channelId in channelIds)
{
var channel = await Discord.GetChannelAsync(channelId, cancellationToken);
channels.Add(channel);
}
await ExecuteAsync(console, channels);
}
}
@@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Core.Discord;
namespace DiscordChatExporter.Cli.Commands.Base;
public abstract class TokenCommandBase : ICommand
{
[CommandOption("token", 't', IsRequired = true, EnvironmentVariable = "DISCORD_TOKEN", Description = "Authentication token.")]
public string Token { get; init; } = "";
[CommandOption("bot", 'b', EnvironmentVariable = "DISCORD_TOKEN_BOT", Description = "This option doesn't do anything. Kept for backwards compatibility.")]
[Obsolete("This option doesn't do anything. Kept for backwards compatibility.")]
public bool IsBotToken { get; init; }
private DiscordClient? _discordClient;
protected DiscordClient Discord => _discordClient ??= new DiscordClient(Token);
public abstract ValueTask ExecuteAsync(IConsole console);
}
@@ -0,0 +1,40 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord.Data;
namespace DiscordChatExporter.Cli.Commands;
[Command("exportall", Description = "Export all accessible channels.")]
public class ExportAllCommand : ExportCommandBase
{
[CommandOption("include-dm", Description = "Include direct message channels.")]
public bool IncludeDirectMessages { get; init; } = true;
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
var channels = new List<Channel>();
await console.Output.WriteLineAsync("Fetching channels...");
await foreach (var guild in Discord.GetUserGuildsAsync(cancellationToken))
{
// Skip DMs if instructed to
if (!IncludeDirectMessages && guild.Id == Guild.DirectMessages.Id)
continue;
await foreach (var channel in Discord.GetGuildChannelsAsync(guild.Id, cancellationToken))
{
// Skip non-text channels
if (!channel.IsTextChannel)
continue;
channels.Add(channel);
}
}
await base.ExecuteAsync(console, channels);
}
}
@@ -0,0 +1,20 @@
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;
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, ChannelIds);
}
@@ -0,0 +1,24 @@
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Cli.Commands;
[Command("exportdm", Description = "Export all direct message channels.")]
public class ExportDirectMessagesCommand : ExportCommandBase
{
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
await console.Output.WriteLineAsync("Fetching channels...");
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken);
var textChannels = channels.Where(c => c.IsTextChannel).ToArray();
await base.ExecuteAsync(console, textChannels);
}
}
@@ -0,0 +1,27 @@
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Cli.Commands;
[Command("exportguild", Description = "Export all channels within specified guild.")]
public class ExportGuildCommand : ExportCommandBase
{
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
public Snowflake GuildId { get; init; }
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
await console.Output.WriteLineAsync("Fetching channels...");
var channels = await Discord.GetGuildChannelsAsync(GuildId, cancellationToken);
var textChannels = channels.Where(c => c.IsTextChannel).ToArray();
await base.ExecuteAsync(console, textChannels);
}
}
@@ -0,0 +1,44 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Cli.Commands;
[Command("channels", Description = "Get the list of channels in a guild.")]
public class GetChannelsCommand : TokenCommandBase
{
[CommandOption("guild", 'g', IsRequired = true, Description = "Guild ID.")]
public Snowflake GuildId { get; init; }
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
var channels = await Discord.GetGuildChannelsAsync(GuildId, cancellationToken);
var textChannels = channels
.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.WriteLineAsync($"{channel.Category.Name} / {channel.Name}");
}
}
}
@@ -0,0 +1,41 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Cli.Commands;
[Command("dm", Description = "Get the list of direct message channels.")]
public class GetDirectMessageChannelsCommand : TokenCommandBase
{
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
var channels = await Discord.GetGuildChannelsAsync(Guild.DirectMessages.Id, cancellationToken);
var textChannels = channels
.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.WriteLineAsync($"{channel.Category.Name} / {channel.Name}");
}
}
}
@@ -0,0 +1,34 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CliFx.Attributes;
using CliFx.Infrastructure;
using DiscordChatExporter.Cli.Commands.Base;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Cli.Commands;
[Command("guilds", Description = "Get the list of accessible guilds.")]
public class GetGuildsCommand : TokenCommandBase
{
public override async ValueTask ExecuteAsync(IConsole console)
{
var cancellationToken = console.RegisterCancellationHandler();
var guilds = await Discord.GetUserGuildsAsync(cancellationToken);
foreach (var guild in guilds.OrderBy(g => g.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.WriteLineAsync(guild.Name);
}
}
}
@@ -0,0 +1,70 @@
using System;
using System.Threading.Tasks;
using CliFx;
using CliFx.Attributes;
using CliFx.Infrastructure;
namespace DiscordChatExporter.Cli.Commands;
[Command("guide", Description = "Explains how to obtain token, guild or channel ID.")]
public class GuideCommand : ICommand
{
public ValueTask ExecuteAsync(IConsole console)
{
// User token
using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("To get user token:");
console.Output.WriteLine(" 1. Open Discord in your web browser and login");
console.Output.WriteLine(" 2. Press Ctrl+Shift+I to show developer tools");
console.Output.WriteLine(" 3. Press Ctrl+Shift+M to toggle device toolbar");
console.Output.WriteLine(" 4. Navigate to the Application tab");
console.Output.WriteLine(" 5. On the left, expand Local Storage and select https://discord.com");
console.Output.WriteLine(" 6. Type \"token\" into the Filter box");
console.Output.WriteLine(" 7. If the token key does not appear, press Ctrl+R to reload");
console.Output.WriteLine(" 8. Copy the value of the token key");
console.Output.WriteLine(" * Automating user accounts is technically against TOS, use at your own risk.");
console.Output.WriteLine();
// Bot token
using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("To get bot token:");
console.Output.WriteLine(" 1. Go to Discord developer portal");
console.Output.WriteLine(" 2. Open your application's settings");
console.Output.WriteLine(" 3. Navigate to the Bot section on the left");
console.Output.WriteLine(" 4. Under Token click Copy");
console.Output.WriteLine();
// Guild or channel ID
using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("To get guild ID or guild channel ID:");
console.Output.WriteLine(" 1. Open Discord");
console.Output.WriteLine(" 2. Open Settings");
console.Output.WriteLine(" 3. Go to Appearance section");
console.Output.WriteLine(" 4. Enable Developer Mode");
console.Output.WriteLine(" 5. Right click on the desired guild or channel and click Copy ID");
console.Output.WriteLine();
// Direct message channel ID
using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("To get direct message channel ID:");
console.Output.WriteLine(" 1. Open Discord");
console.Output.WriteLine(" 2. Open the desired direct message channel");
console.Output.WriteLine(" 3. Press Ctrl+Shift+I to show developer tools");
console.Output.WriteLine(" 4. Navigate to the Console tab");
console.Output.WriteLine(" 5. Type \"window.location.href\" and press Enter");
console.Output.WriteLine(" 6. Copy the first long sequence of numbers inside the URL");
console.Output.WriteLine();
// Wiki link
using (console.WithForegroundColor(ConsoleColor.White))
console.Output.WriteLine("If you have questions or issues, please refer to the wiki:");
using (console.WithForegroundColor(ConsoleColor.DarkCyan))
console.Output.WriteLine("https://github.com/Tyrrrz/DiscordChatExporter/wiki");
return default;
}
}
-37
View File
@@ -1,37 +0,0 @@
using CommonServiceLocator;
using DiscordChatExporter.Cli.ViewModels;
using DiscordChatExporter.Core.Services;
using GalaSoft.MvvmLight.Ioc;
namespace DiscordChatExporter.Cli
{
public class Container
{
public IMainViewModel MainViewModel => Resolve<IMainViewModel>();
public ISettingsService SettingsService => Resolve<ISettingsService>();
private T Resolve<T>(string key = null)
{
return ServiceLocator.Current.GetInstance<T>(key);
}
public void Init()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Reset();
// Services
SimpleIoc.Default.Register<IDataService, DataService>();
SimpleIoc.Default.Register<IExportService, ExportService>();
SimpleIoc.Default.Register<IMessageGroupService, MessageGroupService>();
SimpleIoc.Default.Register<ISettingsService, SettingsService>();
// View models
SimpleIoc.Default.Register<IMainViewModel, MainViewModel>(true);
}
public void Cleanup()
{
}
}
}
@@ -1,23 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net461</TargetFramework>
<Version>2.4.1</Version>
<Company>Tyrrrz</Company>
<Copyright>Copyright (c) 2017-2018 Alexey Golub</Copyright>
<ApplicationIcon>..\favicon.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<ApplicationIcon>..\favicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CommonServiceLocator" Version="2.0.3" />
<PackageReference Include="FluentCommandLineParser" Version="1.4.3" />
<PackageReference Include="MvvmLightLibs" Version="5.4.1" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.5.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CliFx" Version="2.2.1" />
<PackageReference Include="Spectre.Console" Version="0.43.0" />
<PackageReference Include="Gress" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DiscordChatExporter.Core\DiscordChatExporter.Core.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DiscordChatExporter.Core\DiscordChatExporter.Core.csproj" />
</ItemGroup>
</Project>
+5 -110
View File
@@ -1,111 +1,6 @@
using System;
using System.Reflection;
using DiscordChatExporter.Core.Models;
using Fclp;
using Tyrrrz.Extensions;
using CliFx;
namespace DiscordChatExporter.Cli
{
public static class Program
{
private static readonly Container Container = new Container();
private static void ShowHelp()
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
var availableFormats = Enum.GetNames(typeof(ExportFormat));
Console.WriteLine($"=== Discord Chat Exporter (Command Line Interface) v{version} ===");
Console.WriteLine();
Console.WriteLine("[-t] [--token] Discord authorization token.");
Console.WriteLine("[-c] [--channel] Discord channel ID.");
Console.WriteLine("[-f] [--format] Export format. Optional.");
Console.WriteLine("[-o] [--output] Output file path. Optional.");
Console.WriteLine(" [--datefrom] Limit to messages after this date. Optional.");
Console.WriteLine(" [--dateto] Limit to messages before this date. Optional.");
Console.WriteLine(" [--dateformat] Date format. Optional.");
Console.WriteLine(" [--grouplimit] Message group limit. Optional.");
Console.WriteLine();
Console.WriteLine($"Available export formats: {availableFormats.JoinToString(", ")}");
Console.WriteLine();
Console.WriteLine("# To get authorization token:");
Console.WriteLine(" - Open Discord app");
Console.WriteLine(" - Log in if you haven't");
Console.WriteLine(" - Press Ctrl+Shift+I");
Console.WriteLine(" - Navigate to Application tab");
Console.WriteLine(" - Expand Storage > Local Storage > https://discordapp.com");
Console.WriteLine(" - Find \"token\" under key and copy the value");
Console.WriteLine();
Console.WriteLine("# To get channel ID:");
Console.WriteLine(" - Open Discord app");
Console.WriteLine(" - Log in if you haven't");
Console.WriteLine(" - Go to any channel you want to export");
Console.WriteLine(" - Press Ctrl+Shift+I");
Console.WriteLine(" - Navigate to Console tab");
Console.WriteLine(" - Type \"document.URL\" and press Enter");
Console.WriteLine(" - Copy the long sequence of numbers after last slash");
}
private static CliOptions ParseOptions(string[] args)
{
var argsParser = new FluentCommandLineParser<CliOptions>();
var settings = Container.SettingsService;
argsParser.Setup(o => o.Token).As('t', "token").Required();
argsParser.Setup(o => o.ChannelId).As('c', "channel").Required();
argsParser.Setup(o => o.ExportFormat).As('f', "format").SetDefault(ExportFormat.HtmlDark);
argsParser.Setup(o => o.FilePath).As('o', "output").SetDefault(null);
argsParser.Setup(o => o.From).As("datefrom").SetDefault(null);
argsParser.Setup(o => o.To).As("dateto").SetDefault(null);
argsParser.Setup(o => o.DateFormat).As("dateformat").SetDefault(settings.DateFormat);
argsParser.Setup(o => o.MessageGroupLimit).As("grouplimit").SetDefault(settings.MessageGroupLimit);
var parsed = argsParser.Parse(args);
// Show help if no arguments
if (parsed.EmptyArgs)
{
ShowHelp();
Environment.Exit(0);
}
// Show error if there are any
else if (parsed.HasErrors)
{
Console.Error.Write(parsed.ErrorText);
Environment.Exit(-1);
}
return argsParser.Object;
}
public static void Main(string[] args)
{
// Init container
Container.Init();
// Parse options
var options = ParseOptions(args);
// Inject some settings
var settings = Container.SettingsService;
settings.DateFormat = options.DateFormat;
settings.MessageGroupLimit = options.MessageGroupLimit;
// Export
var vm = Container.MainViewModel;
vm.ExportAsync(
options.Token,
options.ChannelId,
options.FilePath,
options.ExportFormat,
options.From,
options.To).GetAwaiter().GetResult();
// Cleanup container
Container.Cleanup();
Console.WriteLine("Export complete.");
}
}
}
return await new CliApplicationBuilder()
.AddCommandsFromThisAssembly()
.Build()
.RunAsync(args);
@@ -0,0 +1,50 @@
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();
}
}
}
@@ -1,12 +0,0 @@
using System;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Models;
namespace DiscordChatExporter.Cli.ViewModels
{
public interface IMainViewModel
{
Task ExportAsync(string token, string channelId, string filePath, ExportFormat format, DateTime? from,
DateTime? to);
}
}
@@ -1,53 +0,0 @@
using System;
using System.IO;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Models;
using DiscordChatExporter.Core.Services;
using Tyrrrz.Extensions;
namespace DiscordChatExporter.Cli.ViewModels
{
public class MainViewModel : IMainViewModel
{
private readonly IDataService _dataService;
private readonly IMessageGroupService _messageGroupService;
private readonly IExportService _exportService;
public MainViewModel(IDataService dataService, IMessageGroupService messageGroupService,
IExportService exportService)
{
_dataService = dataService;
_messageGroupService = messageGroupService;
_exportService = exportService;
}
public async Task ExportAsync(string token, string channelId, string filePath, ExportFormat format, DateTime? from,
DateTime? to)
{
// Get channel and guild
var channel = await _dataService.GetChannelAsync(token, channelId);
var guild = channel.GuildId == Guild.DirectMessages.Id
? Guild.DirectMessages
: await _dataService.GetGuildAsync(token, channel.GuildId);
// Generate file path if not set
if (filePath.IsBlank())
{
filePath = $"{guild.Name} - {channel.Name}.{format.GetFileExtension()}"
.Replace(Path.GetInvalidFileNameChars(), '_');
}
// Get messages
var messages = await _dataService.GetChannelMessagesAsync(token, channelId, from, to);
// Group them
var messageGroups = _messageGroupService.GroupMessages(messages);
// Create log
var log = new ChannelChatLog(guild, channel, messageGroups, messages.Count);
// Export
await _exportService.ExportAsync(format, filePath, log);
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.IO;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#attachment-object
public partial record Attachment(
Snowflake Id,
string Url,
string FileName,
int? Width,
int? Height,
FileSize FileSize) : IHasId
{
public string FileExtension => Path.GetExtension(FileName);
public bool IsImage => FileFormat.IsImage(FileExtension);
public bool IsVideo => FileFormat.IsVideo(FileExtension);
public bool IsAudio => FileFormat.IsAudio(FileExtension);
public bool IsSpoiler => FileName.StartsWith("SPOILER_", StringComparison.Ordinal);
}
public partial record Attachment
{
public static Attachment Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var url = json.GetProperty("url").GetNonWhiteSpaceString();
var width = json.GetPropertyOrNull("width")?.GetInt32OrNull();
var height = json.GetPropertyOrNull("height")?.GetInt32OrNull();
var fileName = json.GetProperty("filename").GetNonNullString();
var fileSize = json.GetProperty("size").GetInt64().Pipe(FileSize.FromBytes);
return new Attachment(id, url, fileName, width, height, fileSize);
}
}
@@ -0,0 +1,78 @@
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#channel-object
public partial record Channel(
Snowflake Id,
ChannelKind Kind,
Snowflake GuildId,
ChannelCategory Category,
string Name,
int? Position,
string? Topic) : IHasId
{
public bool IsTextChannel => Kind is
ChannelKind.GuildTextChat or
ChannelKind.DirectTextChat or
ChannelKind.DirectGroupTextChat or
ChannelKind.GuildNews or
ChannelKind.GuildStore;
public bool IsVoiceChannel => !IsTextChannel;
}
public partial record Channel
{
private static ChannelCategory GetFallbackCategory(ChannelKind channelKind) => new(
Snowflake.Zero,
channelKind switch
{
ChannelKind.GuildTextChat => "Text",
ChannelKind.DirectTextChat => "Private",
ChannelKind.DirectGroupTextChat => "Group",
ChannelKind.GuildNews => "News",
ChannelKind.GuildStore => "Store",
_ => "Default"
},
null
);
public static Channel Parse(JsonElement json, ChannelCategory? category = null, int? positionHint = null)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var guildId = json.GetPropertyOrNull("guild_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
var topic = json.GetPropertyOrNull("topic")?.GetStringOrNull();
var kind = (ChannelKind)json.GetProperty("type").GetInt32();
var name =
// Guild channel
json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ??
// DM channel
json.GetPropertyOrNull("recipients")?
.EnumerateArrayOrNull()?
.Select(User.Parse)
.Select(u => u.Name)
.Pipe(s => string.Join(", ", s)) ??
// Fallback
id.ToString();
var position = positionHint ?? json.GetPropertyOrNull("position")?.GetInt32OrNull();
return new Channel(
id,
kind,
guildId ?? Guild.DirectMessages.Id,
category ?? GetFallbackCategory(kind),
name,
position,
topic
);
}
}
@@ -0,0 +1,23 @@
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
public record ChannelCategory(Snowflake Id, string Name, int? Position) : IHasId
{
public static ChannelCategory Unknown { get; } = new(Snowflake.Zero, "<unknown category>", 0);
public static ChannelCategory Parse(JsonElement json, int? positionHint = null)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var position = positionHint ?? json.GetPropertyOrNull("position")?.GetInt32OrNull();
var name =
json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull() ??
id.ToString();
return new ChannelCategory(id, name, position);
}
}
@@ -0,0 +1,14 @@
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 ChannelKind
{
GuildTextChat = 0,
DirectTextChat,
GuildVoiceChat,
DirectGroupTextChat,
GuildCategory,
GuildNews,
GuildStore
}
@@ -0,0 +1,48 @@
using System;
using System.Diagnostics.CodeAnalysis;
namespace DiscordChatExporter.Core.Discord.Data.Common;
// Loosely based on https://github.com/omar/ByteSize (MIT license)
public readonly partial record struct FileSize(long TotalBytes)
{
public double TotalKiloBytes => TotalBytes / 1024.0;
public double TotalMegaBytes => TotalKiloBytes / 1024.0;
public double TotalGigaBytes => TotalMegaBytes / 1024.0;
private double GetLargestWholeNumberValue()
{
if (Math.Abs(TotalGigaBytes) >= 1)
return TotalGigaBytes;
if (Math.Abs(TotalMegaBytes) >= 1)
return TotalMegaBytes;
if (Math.Abs(TotalKiloBytes) >= 1)
return TotalKiloBytes;
return TotalBytes;
}
private string GetLargestWholeNumberSymbol()
{
if (Math.Abs(TotalGigaBytes) >= 1)
return "GB";
if (Math.Abs(TotalMegaBytes) >= 1)
return "MB";
if (Math.Abs(TotalKiloBytes) >= 1)
return "KB";
return "bytes";
}
[ExcludeFromCodeCoverage]
public override string ToString() => $"{GetLargestWholeNumberValue():0.##} {GetLargestWholeNumberSymbol()}";
}
public partial record struct FileSize
{
public static FileSize FromBytes(long bytes) => new(bytes);
}
@@ -0,0 +1,6 @@
namespace DiscordChatExporter.Core.Discord.Data.Common;
public interface IHasId
{
Snowflake Id { get; }
}
@@ -0,0 +1,12 @@
using System.Collections.Generic;
namespace DiscordChatExporter.Core.Discord.Data.Common;
public class IdBasedEqualityComparer : IEqualityComparer<IHasId>
{
public static IdBasedEqualityComparer Instance { get; } = new();
public bool Equals(IHasId? x, IHasId? y) => x?.Id == y?.Id;
public int GetHashCode(IHasId obj) => obj.Id.GetHashCode();
}
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object
public partial record Embed(
string? Title,
string? Url,
DateTimeOffset? Timestamp,
Color? Color,
EmbedAuthor? Author,
string? Description,
IReadOnlyList<EmbedField> Fields,
EmbedImage? Thumbnail,
EmbedImage? Image,
EmbedFooter? Footer)
{
public PlainImageEmbedProjection? TryGetPlainImage() =>
PlainImageEmbedProjection.TryResolve(this);
public SpotifyTrackEmbedProjection? TryGetSpotifyTrack() =>
SpotifyTrackEmbedProjection.TryResolve(this);
public YouTubeVideoEmbedProjection? TryGetYouTubeVideo() =>
YouTubeVideoEmbedProjection.TryResolve(this);
}
public partial record Embed
{
public static Embed Parse(JsonElement json)
{
var title = json.GetPropertyOrNull("title")?.GetStringOrNull();
var url = json.GetPropertyOrNull("url")?.GetNonWhiteSpaceStringOrNull();
var timestamp = json.GetPropertyOrNull("timestamp")?.GetDateTimeOffset();
var color = json.GetPropertyOrNull("color")?.GetInt32OrNull()?.Pipe(System.Drawing.Color.FromArgb).ResetAlpha();
var description = json.GetPropertyOrNull("description")?.GetStringOrNull();
var author = json.GetPropertyOrNull("author")?.Pipe(EmbedAuthor.Parse);
var thumbnail = json.GetPropertyOrNull("thumbnail")?.Pipe(EmbedImage.Parse);
var image = json.GetPropertyOrNull("image")?.Pipe(EmbedImage.Parse);
var footer = json.GetPropertyOrNull("footer")?.Pipe(EmbedFooter.Parse);
var fields =
json.GetPropertyOrNull("fields")?.EnumerateArrayOrNull()?.Select(EmbedField.Parse).ToArray() ??
Array.Empty<EmbedField>();
return new Embed(
title,
url,
timestamp,
color,
author,
description,
fields,
thumbnail,
image,
footer
);
}
}
@@ -0,0 +1,22 @@
using System.Text.Json;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-author-structure
public record EmbedAuthor(
string? Name,
string? Url,
string? IconUrl,
string? IconProxyUrl)
{
public static EmbedAuthor Parse(JsonElement json)
{
var name = json.GetPropertyOrNull("name")?.GetStringOrNull();
var url = json.GetPropertyOrNull("url")?.GetNonWhiteSpaceStringOrNull();
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetNonWhiteSpaceStringOrNull();
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetNonWhiteSpaceStringOrNull();
return new EmbedAuthor(name, url, iconUrl, iconProxyUrl);
}
}
@@ -0,0 +1,20 @@
using System.Text.Json;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure
public record EmbedField(
string Name,
string Value,
bool IsInline)
{
public static EmbedField Parse(JsonElement json)
{
var name = json.GetProperty("name").GetNonNullString();
var value = json.GetProperty("value").GetNonNullString();
var isInline = json.GetPropertyOrNull("inline")?.GetBooleanOrNull() ?? false;
return new EmbedField(name, value, isInline);
}
}
@@ -0,0 +1,20 @@
using System.Text.Json;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-footer-structure
public record EmbedFooter(
string Text,
string? IconUrl,
string? IconProxyUrl)
{
public static EmbedFooter Parse(JsonElement json)
{
var text = json.GetProperty("text").GetNonNullString();
var iconUrl = json.GetPropertyOrNull("icon_url")?.GetNonWhiteSpaceStringOrNull();
var iconProxyUrl = json.GetPropertyOrNull("proxy_icon_url")?.GetNonWhiteSpaceStringOrNull();
return new EmbedFooter(text, iconUrl, iconProxyUrl);
}
}
@@ -0,0 +1,22 @@
using System.Text.Json;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
// https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
public record EmbedImage(
string? Url,
string? ProxyUrl,
int? Width,
int? Height)
{
public static EmbedImage Parse(JsonElement json)
{
var url = json.GetPropertyOrNull("url")?.GetNonWhiteSpaceStringOrNull();
var proxyUrl = json.GetPropertyOrNull("proxy_url")?.GetNonWhiteSpaceStringOrNull();
var width = json.GetPropertyOrNull("width")?.GetInt32OrNull();
var height = json.GetPropertyOrNull("height")?.GetInt32OrNull();
return new EmbedImage(url, proxyUrl, width, height);
}
}
@@ -0,0 +1,33 @@
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DiscordChatExporter.Core.Utils;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
public record PlainImageEmbedProjection(string Url)
{
public static PlainImageEmbedProjection? TryResolve(Embed embed)
{
if (string.IsNullOrWhiteSpace(embed.Url))
return null;
// Has to be an embed without any data (except URL and image)
if (!string.IsNullOrWhiteSpace(embed.Title) ||
embed.Timestamp is not null ||
embed.Author is not null ||
!string.IsNullOrWhiteSpace(embed.Description) ||
embed.Fields.Any() ||
embed.Footer is not null)
{
return null;
}
// Has to be an image file
var fileName = Regex.Match(embed.Url, @".+/([^?]*)").Groups[1].Value;
if (string.IsNullOrWhiteSpace(fileName) || !FileFormat.IsImage(Path.GetExtension(fileName)))
return null;
return new PlainImageEmbedProjection(embed.Url);
}
}
@@ -0,0 +1,33 @@
using System.Text.RegularExpressions;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
public partial record SpotifyTrackEmbedProjection(string TrackId)
{
public string Url => $"https://open.spotify.com/embed/track/{TrackId}";
}
public partial record SpotifyTrackEmbedProjection
{
private static string? TryParseTrackId(string embedUrl)
{
// https://open.spotify.com/track/1LHZMWefF9502NPfArRfvP?si=3efac6ce9be04f0a
var trackId = Regex.Match(embedUrl, @"spotify\.com/track/(.*?)(?:\?|&|/|$)").Groups[1].Value;
if (!string.IsNullOrWhiteSpace(trackId))
return trackId;
return null;
}
public static SpotifyTrackEmbedProjection? TryResolve(Embed embed)
{
if (string.IsNullOrWhiteSpace(embed.Url))
return null;
var trackId = TryParseTrackId(embed.Url);
if (string.IsNullOrWhiteSpace(trackId))
return null;
return new SpotifyTrackEmbedProjection(trackId);
}
}
@@ -0,0 +1,48 @@
using System.Text.RegularExpressions;
namespace DiscordChatExporter.Core.Discord.Data.Embeds;
public partial record YouTubeVideoEmbedProjection(string VideoId)
{
public string Url => $"https://www.youtube.com/embed/{VideoId}";
}
public partial record 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;
return new YouTubeVideoEmbedProjection(videoId);
}
}
@@ -0,0 +1,72 @@
using System;
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Utils;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/emoji#emoji-object
public partial record Emoji(
// Only present on custom emoji
string? Id,
// Name of custom emoji (e.g. LUL) or actual representation of standard emoji (e.g. 🙂)
string Name,
bool IsAnimated,
string ImageUrl)
{
// 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 partial record Emoji
{
private static string GetTwemojiName(string name) => string.Join("-",
name
.GetRunes()
// Variant selector rune is skipped in Twemoji names
.Where(r => r.Value != 0xfe0f)
.Select(r => r.Value.ToString("x"))
);
private static string GetImageUrl(string id, bool isAnimated) => isAnimated
? $"https://cdn.discordapp.com/emojis/{id}.gif"
: $"https://cdn.discordapp.com/emojis/{id}.png";
private static string GetImageUrl(string name) =>
$"https://twemoji.maxcdn.com/2/svg/{GetTwemojiName(name)}.svg";
public static string GetImageUrl(string? id, string? name, bool isAnimated)
{
// Custom emoji
if (!string.IsNullOrWhiteSpace(id))
return GetImageUrl(id, isAnimated);
// Standard emoji
if (!string.IsNullOrWhiteSpace(name))
return GetImageUrl(name);
// Either ID or name should be set
throw new ApplicationException("Emoji has neither ID nor name set.");
}
public static Emoji Parse(JsonElement json)
{
var id = json.GetPropertyOrNull("id")?.GetNonWhiteSpaceStringOrNull();
var name = json.GetPropertyOrNull("name")?.GetNonWhiteSpaceStringOrNull();
var isAnimated = json.GetPropertyOrNull("animated")?.GetBooleanOrNull() ?? false;
var imageUrl = GetImageUrl(id, name, isAnimated);
return new Emoji(
id,
// Name may be missing if it's an emoji inside a reaction
name ?? "<unknown emoji>",
isAnimated,
imageUrl
);
}
}
@@ -0,0 +1,35 @@
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/guild#guild-object
public record Guild(Snowflake Id, string Name, string IconUrl) : IHasId
{
public static Guild DirectMessages { get; } = new(
Snowflake.Zero,
"Direct Messages",
GetDefaultIconUrl()
);
private static string GetDefaultIconUrl() =>
"https://cdn.discordapp.com/embed/avatars/0.png";
private static string GetIconUrl(Snowflake id, string iconHash) =>
$"https://cdn.discordapp.com/icons/{id}/{iconHash}.png";
public static Guild Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonNullString();
var iconHash = json.GetPropertyOrNull("icon")?.GetNonWhiteSpaceStringOrNull();
var iconUrl = !string.IsNullOrWhiteSpace(iconHash)
? GetIconUrl(id, iconHash)
: GetDefaultIconUrl();
return new Guild(id, name, iconUrl);
}
}
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/guild#guild-member-object
public partial record Member(
User User,
string Nick,
IReadOnlyList<Snowflake> RoleIds) : IHasId
{
public Snowflake Id => User.Id;
}
public partial record Member
{
public static Member CreateForUser(User user) => new(
user,
user.Name,
Array.Empty<Snowflake>()
);
public static Member Parse(JsonElement json)
{
var user = json.GetProperty("user").Pipe(User.Parse);
var nick = json.GetPropertyOrNull("nick")?.GetNonWhiteSpaceStringOrNull();
var roleIds = json
.GetPropertyOrNull("roles")?
.EnumerateArray()
.Select(j => j.GetNonWhiteSpaceString())
.Select(Snowflake.Parse)
.ToArray() ?? Array.Empty<Snowflake>();
return new Member(
user,
nick ?? user.Name,
roleIds
);
}
}
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Discord.Data.Embeds;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#message-object
public record Message(
Snowflake Id,
MessageKind Kind,
User Author,
DateTimeOffset Timestamp,
DateTimeOffset? EditedTimestamp,
DateTimeOffset? CallEndedTimestamp,
bool IsPinned,
string Content,
IReadOnlyList<Attachment> Attachments,
IReadOnlyList<Embed> Embeds,
IReadOnlyList<Reaction> Reactions,
IReadOnlyList<User> MentionedUsers,
MessageReference? Reference,
Message? ReferencedMessage) : IHasId
{
public static Message Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var author = json.GetProperty("author").Pipe(User.Parse);
var timestamp = json.GetProperty("timestamp").GetDateTimeOffset();
var editedTimestamp = json.GetPropertyOrNull("edited_timestamp")?.GetDateTimeOffset();
var callEndedTimestamp = json.GetPropertyOrNull("call")?.GetPropertyOrNull("ended_timestamp")
?.GetDateTimeOffset();
var kind = (MessageKind)json.GetProperty("type").GetInt32();
var isPinned = json.GetPropertyOrNull("pinned")?.GetBooleanOrNull() ?? false;
var messageReference = json.GetPropertyOrNull("message_reference")?.Pipe(MessageReference.Parse);
var referencedMessage = json.GetPropertyOrNull("referenced_message")?.Pipe(Parse);
var content = kind switch
{
MessageKind.RecipientAdd => "Added a recipient.",
MessageKind.RecipientRemove => "Removed a recipient.",
MessageKind.Call =>
$"Started a call that lasted {callEndedTimestamp?.Pipe(t => t - timestamp).Pipe(t => (int)t.TotalMinutes) ?? 0} minutes.",
MessageKind.ChannelNameChange => "Changed the channel name.",
MessageKind.ChannelIconChange => "Changed the channel icon.",
MessageKind.ChannelPinnedMessage => "Pinned a message.",
MessageKind.GuildMemberJoin => "Joined the server.",
_ => json.GetPropertyOrNull("content")?.GetStringOrNull() ?? ""
};
var attachments =
json.GetPropertyOrNull("attachments")?.EnumerateArrayOrNull()?.Select(Attachment.Parse).ToArray() ??
Array.Empty<Attachment>();
var embeds =
json.GetPropertyOrNull("embeds")?.EnumerateArrayOrNull()?.Select(Embed.Parse).ToArray() ??
Array.Empty<Embed>();
var reactions =
json.GetPropertyOrNull("reactions")?.EnumerateArrayOrNull()?.Select(Reaction.Parse).ToArray() ??
Array.Empty<Reaction>();
var mentionedUsers =
json.GetPropertyOrNull("mentions")?.EnumerateArrayOrNull()?.Select(User.Parse).ToArray() ??
Array.Empty<User>();
return new Message(
id,
kind,
author,
timestamp,
editedTimestamp,
callEndedTimestamp,
isPinned,
content,
attachments,
embeds,
reactions,
mentionedUsers,
messageReference,
referencedMessage
);
}
}
@@ -0,0 +1,15 @@
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#message-object-message-types
public enum MessageKind
{
Default = 0,
RecipientAdd = 1,
RecipientRemove = 2,
Call = 3,
ChannelNameChange = 4,
ChannelIconChange = 5,
ChannelPinnedMessage = 6,
GuildMemberJoin = 7,
Reply = 19
}
@@ -0,0 +1,18 @@
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 record MessageReference(Snowflake? MessageId, Snowflake? ChannelId, Snowflake? GuildId)
{
public static MessageReference Parse(JsonElement json)
{
var messageId = json.GetPropertyOrNull("message_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
var channelId = json.GetPropertyOrNull("channel_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
var guildId = json.GetPropertyOrNull("guild_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
return new MessageReference(messageId, channelId, guildId);
}
}
@@ -0,0 +1,16 @@
using System.Text.Json;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/channel#reaction-object
public record Reaction(Emoji Emoji, int Count)
{
public static Reaction Parse(JsonElement json)
{
var emoji = json.GetProperty("emoji").Pipe(Emoji.Parse);
var count = json.GetProperty("count").GetInt32();
return new Reaction(emoji, count);
}
}
@@ -0,0 +1,27 @@
using System.Drawing;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/topics/permissions#role-object
public record Role(Snowflake Id, string Name, int Position, Color? Color) : IHasId
{
public static Role Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var name = json.GetProperty("name").GetNonNullString();
var position = json.GetProperty("position").GetInt32();
var color = json
.GetPropertyOrNull("color")?
.GetInt32()
.Pipe(System.Drawing.Color.FromArgb)
.ResetAlpha()
.NullIf(c => c.ToRgb() <= 0);
return new Role(id, name, position, color);
}
}
@@ -0,0 +1,50 @@
using System;
using System.Text.Json;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord.Data;
// https://discord.com/developers/docs/resources/user#user-object
public partial record User(
Snowflake Id,
bool IsBot,
int Discriminator,
string Name,
string AvatarUrl) : IHasId
{
public string DiscriminatorFormatted => $"{Discriminator:0000}";
public string FullName => $"{Name}#{DiscriminatorFormatted}";
}
public partial record User
{
private static string GetDefaultAvatarUrl(int discriminator) =>
$"https://cdn.discordapp.com/embed/avatars/{discriminator % 5}.png";
private static string GetAvatarUrl(Snowflake id, string avatarHash)
{
var extension = avatarHash.StartsWith("a_", StringComparison.Ordinal)
? "gif"
: "png";
return $"https://cdn.discordapp.com/avatars/{id}/{avatarHash}.{extension}?size=128";
}
public static User Parse(JsonElement json)
{
var id = json.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse);
var isBot = json.GetPropertyOrNull("bot")?.GetBooleanOrNull() ?? false;
var discriminator = json.GetProperty("discriminator").GetNonWhiteSpaceString().Pipe(int.Parse);
var name = json.GetProperty("username").GetNonNullString();
var avatarHash = json.GetPropertyOrNull("avatar")?.GetNonWhiteSpaceStringOrNull();
var avatarUrl = !string.IsNullOrWhiteSpace(avatarHash)
? GetAvatarUrl(id, avatarHash)
: GetDefaultAvatarUrl(discriminator);
return new User(id, isBot, discriminator, name, avatarUrl);
}
}
@@ -0,0 +1,342 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Utils;
using DiscordChatExporter.Core.Utils.Extensions;
using JsonExtensions.Http;
using JsonExtensions.Reading;
namespace DiscordChatExporter.Core.Discord;
public class DiscordClient
{
private readonly string _token;
private readonly Uri _baseUri = new("https://discord.com/api/v8/", UriKind.Absolute);
private TokenKind _tokenKind = TokenKind.Unknown;
public DiscordClient(string token) => _token = token;
private async ValueTask<HttpResponseMessage> GetResponseAsync(
string url,
bool isBot,
CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri(_baseUri, url));
request.Headers.Authorization = isBot
? new AuthenticationHeaderValue("Bot", _token)
: new AuthenticationHeaderValue(_token);
return await Http.Client.SendAsync(
request,
HttpCompletionOption.ResponseHeadersRead,
cancellationToken
);
}
private async ValueTask<HttpResponseMessage> GetResponseAsync(
string url,
CancellationToken cancellationToken = default)
{
return await Http.ResponsePolicy.ExecuteAsync(async innerCancellationToken =>
{
if (_tokenKind == TokenKind.User)
return await GetResponseAsync(url, false, innerCancellationToken);
if (_tokenKind == TokenKind.Bot)
return await GetResponseAsync(url, true, innerCancellationToken);
// Try to authenticate as user
var userResponse = await GetResponseAsync(url, false, innerCancellationToken);
if (userResponse.StatusCode != HttpStatusCode.Unauthorized)
{
_tokenKind = TokenKind.User;
return userResponse;
}
userResponse.Dispose();
// Otherwise, try to authenticate as bot
var botResponse = await GetResponseAsync(url, true, innerCancellationToken);
if (botResponse.StatusCode != HttpStatusCode.Unauthorized)
{
_tokenKind = TokenKind.Bot;
return botResponse;
}
// The token is probably invalid altogether.
// Return the last response anyway, upstream should handle the error.
return botResponse;
}, cancellationToken);
}
private async ValueTask<JsonElement> GetJsonResponseAsync(
string url,
CancellationToken cancellationToken = default)
{
using var response = await GetResponseAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode)
{
throw response.StatusCode switch
{
HttpStatusCode.Unauthorized => DiscordChatExporterException.Unauthorized(),
HttpStatusCode.Forbidden => DiscordChatExporterException.Forbidden(),
HttpStatusCode.NotFound => DiscordChatExporterException.NotFound(url),
_ => DiscordChatExporterException.FailedHttpRequest(response)
};
}
return await response.Content.ReadAsJsonAsync(cancellationToken);
}
private async ValueTask<JsonElement?> TryGetJsonResponseAsync(
string url,
CancellationToken cancellationToken = default)
{
using var response = await GetResponseAsync(url, cancellationToken);
return response.IsSuccessStatusCode
? await response.Content.ReadAsJsonAsync(cancellationToken)
: null;
}
public async IAsyncEnumerable<Guild> GetUserGuildsAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
yield return Guild.DirectMessages;
var currentAfter = Snowflake.Zero;
while (true)
{
var url = new UrlBuilder()
.SetPath("users/@me/guilds")
.SetQueryParameter("limit", "100")
.SetQueryParameter("after", currentAfter.ToString())
.Build();
var response = await GetJsonResponseAsync(url, cancellationToken);
var isEmpty = true;
foreach (var guild in response.EnumerateArray().Select(Guild.Parse))
{
yield return guild;
currentAfter = guild.Id;
isEmpty = false;
}
if (isEmpty)
yield break;
}
}
public async ValueTask<Guild> GetGuildAsync(
Snowflake guildId,
CancellationToken cancellationToken = default)
{
if (guildId == Guild.DirectMessages.Id)
return Guild.DirectMessages;
var response = await GetJsonResponseAsync($"guilds/{guildId}", cancellationToken);
return Guild.Parse(response);
}
public async IAsyncEnumerable<Channel> GetGuildChannelsAsync(
Snowflake guildId,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (guildId == Guild.DirectMessages.Id)
{
var response = await GetJsonResponseAsync("users/@me/channels", cancellationToken);
foreach (var channelJson in response.EnumerateArray())
yield return Channel.Parse(channelJson);
}
else
{
var response = await GetJsonResponseAsync($"guilds/{guildId}/channels", cancellationToken);
var responseOrdered = response
.EnumerateArray()
.OrderBy(j => j.GetProperty("position").GetInt32())
.ThenBy(j => j.GetProperty("id").GetNonWhiteSpaceString().Pipe(Snowflake.Parse))
.ToArray();
var categories = responseOrdered
.Where(j => j.GetProperty("type").GetInt32() == (int) ChannelKind.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")?.GetNonWhiteSpaceStringOrNull();
var category = !string.IsNullOrWhiteSpace(parentId)
? categories.GetValueOrDefault(parentId)
: null;
var channel = Channel.Parse(channelJson, category, position);
position++;
yield return channel;
}
}
}
public async IAsyncEnumerable<Role> GetGuildRolesAsync(
Snowflake guildId,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (guildId == Guild.DirectMessages.Id)
yield break;
var response = await GetJsonResponseAsync($"guilds/{guildId}/roles", cancellationToken);
foreach (var roleJson in response.EnumerateArray())
yield return Role.Parse(roleJson);
}
public async ValueTask<Member> GetGuildMemberAsync(
Snowflake guildId,
User user,
CancellationToken cancellationToken = default)
{
if (guildId == Guild.DirectMessages.Id)
return Member.CreateForUser(user);
var response = await TryGetJsonResponseAsync($"guilds/{guildId}/members/{user.Id}", cancellationToken);
return response?.Pipe(Member.Parse) ?? Member.CreateForUser(user);
}
public async ValueTask<ChannelCategory> GetChannelCategoryAsync(
Snowflake channelId,
CancellationToken cancellationToken = default)
{
try
{
var response = await GetJsonResponseAsync($"channels/{channelId}", cancellationToken);
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.Unknown;
}
}
public async ValueTask<Channel> GetChannelAsync(
Snowflake channelId,
CancellationToken cancellationToken = default)
{
var response = await GetJsonResponseAsync($"channels/{channelId}", cancellationToken);
var parentId = response.GetPropertyOrNull("parent_id")?.GetNonWhiteSpaceStringOrNull()?.Pipe(Snowflake.Parse);
var category = parentId is not null
? await GetChannelCategoryAsync(parentId.Value, cancellationToken)
: null;
return Channel.Parse(response, category);
}
private async ValueTask<Message?> TryGetLastMessageAsync(
Snowflake channelId,
Snowflake? before = null,
CancellationToken cancellationToken = default)
{
var url = new UrlBuilder()
.SetPath($"channels/{channelId}/messages")
.SetQueryParameter("limit", "1")
.SetQueryParameter("before", before?.ToString())
.Build();
var response = await GetJsonResponseAsync(url, cancellationToken);
return response.EnumerateArray().Select(Message.Parse).LastOrDefault();
}
public async IAsyncEnumerable<Message> GetMessagesAsync(
Snowflake channelId,
Snowflake? after = null,
Snowflake? before = null,
IProgress<double>? progress = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Get the last message in the specified range.
// This snapshots the boundaries, which means that messages posted after the export started
// will not appear in the output.
// Additionally, it provides the date of the last message, which is used to calculate progress.
var lastMessage = await TryGetLastMessageAsync(channelId, before, cancellationToken);
if (lastMessage is null || lastMessage.Timestamp < after?.ToDate())
yield break;
// Keep track of first message in range in order to calculate progress
var firstMessage = default(Message);
var currentAfter = after ?? Snowflake.Zero;
while (true)
{
var url = new UrlBuilder()
.SetPath($"channels/{channelId}/messages")
.SetQueryParameter("limit", "100")
.SetQueryParameter("after", currentAfter.ToString())
.Build();
var response = await GetJsonResponseAsync(url, cancellationToken);
var messages = response
.EnumerateArray()
.Select(Message.Parse)
.Reverse() // reverse because messages appear newest first
.ToArray();
// Break if there are no messages (can happen if messages are deleted during execution)
if (!messages.Any())
yield break;
foreach (var message in messages)
{
firstMessage ??= message;
// Ensure messages are in range (take into account that last message could have been deleted)
if (message.Timestamp > lastMessage.Timestamp)
yield break;
// Report progress based on the duration of exported messages divided by total
if (progress is not null)
{
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;
currentAfter = message.Id;
}
}
}
}
@@ -0,0 +1,55 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text.RegularExpressions;
namespace DiscordChatExporter.Core.Discord;
public readonly partial record struct Snowflake(ulong Value)
{
public DateTimeOffset ToDate() => DateTimeOffset.FromUnixTimeMilliseconds(
(long)((Value >> 22) + 1420070400000UL)
).ToLocalTime();
[ExcludeFromCodeCoverage]
public override string ToString() => Value.ToString(CultureInfo.InvariantCulture);
}
public partial record struct Snowflake
{
public static Snowflake Zero { get; } = new(0);
public static Snowflake FromDate(DateTimeOffset date) => new(
((ulong)date.ToUnixTimeMilliseconds() - 1420070400000UL) << 22
);
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 record struct Snowflake : IComparable<Snowflake>
{
public int CompareTo(Snowflake other) => Value.CompareTo(other.Value);
}
@@ -0,0 +1,8 @@
namespace DiscordChatExporter.Core.Discord;
public enum TokenKind
{
Unknown,
User,
Bot
}
@@ -1,25 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<Version>2.4.1</Version>
</PropertyGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\ExportService\DarkTheme.css" />
<EmbeddedResource Include="Resources\ExportService\LightTheme.css" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.0" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="Superpower" Version="3.0.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CsvHelper" Version="7.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Onova" Version="2.1.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.5.0" />
<PackageReference Include="Tyrrrz.Settings" Version="1.3.2" />
</ItemGroup>
<ItemGroup>
<AdditionalFiles Include="Exporting\Writers\Html\*.cshtml" IsRazorTemplate="true" />
</ItemGroup>
</Project>
@@ -0,0 +1,44 @@
using System;
using System.Net.Http;
namespace DiscordChatExporter.Core.Exceptions;
public partial class DiscordChatExporterException : Exception
{
public bool IsFatal { get; }
public DiscordChatExporterException(string message, bool isFatal = false)
: base(message)
{
IsFatal = isFatal;
}
}
public partial class DiscordChatExporterException
{
internal static DiscordChatExporterException FailedHttpRequest(HttpResponseMessage response)
{
var message = $@"
Failed to perform an HTTP request.
[Request]
{response.RequestMessage}
[Response]
{response}";
return new DiscordChatExporterException(message.Trim(), true);
}
internal static DiscordChatExporterException Unauthorized() =>
new("Authentication token is invalid.", true);
internal static DiscordChatExporterException Forbidden() =>
new("Access is forbidden.");
internal static DiscordChatExporterException NotFound(string resourceId) =>
new($"Requested resource ({resourceId}) does not exist.");
internal static DiscordChatExporterException ChannelIsEmpty() =>
new("No messages found for the specified period.");
}
@@ -1,15 +0,0 @@
using System;
using System.Net;
namespace DiscordChatExporter.Core.Exceptions
{
public class HttpErrorStatusCodeException : Exception
{
public HttpStatusCode StatusCode { get; }
public HttpErrorStatusCodeException(HttpStatusCode statusCode)
{
StatusCode = statusCode;
}
}
}
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Discord.Data.Common;
using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Core.Exporting;
public class ChannelExporter
{
private readonly DiscordClient _discord;
public ChannelExporter(DiscordClient discord) => _discord = discord;
public async ValueTask ExportChannelAsync(
ExportRequest request,
IProgress<double>? progress = null,
CancellationToken cancellationToken = default)
{
// Build context
var contextMembers = new HashSet<Member>(IdBasedEqualityComparer.Instance);
var contextChannels = await _discord.GetGuildChannelsAsync(request.Guild.Id, cancellationToken);
var contextRoles = await _discord.GetGuildRolesAsync(request.Guild.Id, cancellationToken);
var context = new ExportContext(
request,
contextMembers,
contextChannels,
contextRoles
);
// Export messages
await using var messageExporter = new MessageExporter(context);
var exportedAnything = false;
var encounteredUsers = new HashSet<User>(IdBasedEqualityComparer.Instance);
await foreach (var message in _discord.GetMessagesAsync(
request.Channel.Id,
request.After,
request.Before,
progress,
cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
// Skips any messages that fail to pass the supplied filter
if (!request.MessageFilter.IsMatch(message))
continue;
// Resolve members for referenced users
foreach (var referencedUser in message.MentionedUsers.Prepend(message.Author))
{
if (!encounteredUsers.Add(referencedUser))
continue;
var member = await _discord.GetGuildMemberAsync(
request.Guild.Id,
referencedUser,
cancellationToken
);
contextMembers.Add(member);
}
// Export message
await messageExporter.ExportMessageAsync(message, cancellationToken);
exportedAnything = true;
}
// Throw if no messages were exported
if (!exportedAnything)
throw DiscordChatExporterException.ChannelIsEmpty();
}
}
@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Utils.Extensions;
namespace DiscordChatExporter.Core.Exporting;
internal class ExportContext
{
private readonly MediaDownloader _mediaDownloader;
public ExportRequest Request { get; }
public IReadOnlyCollection<Member> Members { get; }
public IReadOnlyCollection<Channel> Channels { get; }
public IReadOnlyCollection<Role> Roles { get; }
public ExportContext(
ExportRequest request,
IReadOnlyCollection<Member> members,
IReadOnlyCollection<Channel> channels,
IReadOnlyCollection<Role> roles)
{
Request = request;
Members = members;
Channels = channels;
Roles = roles;
_mediaDownloader = new MediaDownloader(request.OutputMediaDirPath, request.ShouldReuseMedia);
}
public string FormatDate(DateTimeOffset date) => Request.DateFormat switch
{
"unix" => date.ToUnixTimeSeconds().ToString(),
"unixms" => date.ToUnixTimeMilliseconds().ToString(),
var dateFormat => date.ToLocalString(dateFormat)
};
public Member? TryGetMember(Snowflake id) => Members.FirstOrDefault(m => m.Id == id);
public Channel? TryGetChannel(Snowflake id) => Channels.FirstOrDefault(c => c.Id == id);
public Role? TryGetRole(Snowflake id) => Roles.FirstOrDefault(r => r.Id == id);
public Color? TryGetUserColor(Snowflake id)
{
var member = TryGetMember(id);
var roles = member?.RoleIds.Join(Roles, i => i, r => r.Id, (_, role) => role);
return roles?
.Where(r => r.Color is not null)
.OrderByDescending(r => r.Position)
.Select(r => r.Color)
.FirstOrDefault();
}
public async ValueTask<string> ResolveMediaUrlAsync(string url, CancellationToken cancellationToken = default)
{
if (!Request.ShouldDownloadMedia)
return url;
try
{
var filePath = await _mediaDownloader.DownloadAsync(url, cancellationToken);
// We want relative path so that the output files can be copied around without breaking.
// Base directory path may be null if the file is stored at the root or relative to working directory.
var relativeFilePath = !string.IsNullOrWhiteSpace(Request.OutputBaseDirPath)
? Path.GetRelativePath(Request.OutputBaseDirPath, filePath)
: filePath;
// HACK: for HTML, we need to format the URL properly
if (Request.Format is ExportFormat.HtmlDark or ExportFormat.HtmlLight)
{
// Need to escape each path segment while keeping the directory separators intact
return string.Join(
Path.AltDirectorySeparatorChar,
relativeFilePath
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.Select(Uri.EscapeDataString)
);
}
return relativeFilePath;
}
// Try to catch only exceptions related to failed HTTP requests
// https://github.com/Tyrrrz/DiscordChatExporter/issues/332
// https://github.com/Tyrrrz/DiscordChatExporter/issues/372
catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
{
// 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
return url;
}
}
}
@@ -0,0 +1,35 @@
using System;
namespace DiscordChatExporter.Core.Exporting;
public enum ExportFormat
{
PlainText,
HtmlDark,
HtmlLight,
Csv,
Json
}
public static class ExportFormatExtensions
{
public static string GetFileExtension(this ExportFormat format) => format switch
{
ExportFormat.PlainText => "txt",
ExportFormat.HtmlDark => "html",
ExportFormat.HtmlLight => "html",
ExportFormat.Csv => "csv",
ExportFormat.Json => "json",
_ => throw new ArgumentOutOfRangeException(nameof(format))
};
public static string GetDisplayName(this ExportFormat format) => format switch
{
ExportFormat.PlainText => "TXT",
ExportFormat.HtmlDark => "HTML (Dark)",
ExportFormat.HtmlLight => "HTML (Light)",
ExportFormat.Csv => "CSV",
ExportFormat.Json => "JSON",
_ => throw new ArgumentOutOfRangeException(nameof(format))
};
}
@@ -0,0 +1,122 @@
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
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.Core.Exporting;
public partial record ExportRequest(
Guild Guild,
Channel Channel,
string OutputPath,
ExportFormat Format,
Snowflake? After,
Snowflake? Before,
PartitionLimit PartitionLimit,
MessageFilter MessageFilter,
bool ShouldDownloadMedia,
bool ShouldReuseMedia,
string DateFormat)
{
private string? _outputBaseFilePath;
public string OutputBaseFilePath => _outputBaseFilePath ??= GetOutputBaseFilePath(
Guild,
Channel,
OutputPath,
Format,
After,
Before
);
public string OutputBaseDirPath => Path.GetDirectoryName(OutputBaseFilePath) ?? OutputPath;
public string OutputMediaDirPath => $"{OutputBaseFilePath}_Files{Path.DirectorySeparatorChar}";
}
public partial record ExportRequest
{
private static string GetOutputBaseFilePath(
Guild guild,
Channel channel,
string outputPath,
ExportFormat format,
Snowflake? after = null,
Snowflake? before = null)
{
// Formats path
outputPath = Regex.Replace(outputPath, "%.", m =>
PathEx.EscapeFileName(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
if (Directory.Exists(outputPath) || string.IsNullOrWhiteSpace(Path.GetExtension(outputPath)))
{
var fileName = GetDefaultOutputFileName(guild, channel, format, after, before);
return Path.Combine(outputPath, fileName);
}
// Output is a file
return outputPath;
}
public static string GetDefaultOutputFileName(
Guild guild,
Channel channel,
ExportFormat format,
Snowflake? after = null,
Snowflake? before = null)
{
var buffer = new StringBuilder();
// Guild and channel names
buffer.Append($"{guild.Name} - {channel.Category.Name} - {channel.Name} [{channel.Id}]");
// Date range
if (after is not null || before is not null)
{
buffer.Append(" (");
// Both 'after' and 'before' are set
if (after is not null && before is not null)
{
buffer.Append($"{after.Value.ToDate():yyyy-MM-dd} to {before.Value.ToDate():yyyy-MM-dd}");
}
// Only 'after' is set
else if (after is not null)
{
buffer.Append($"after {after.Value.ToDate():yyyy-MM-dd}");
}
// Only 'before' is set
else if (before is not null)
{
buffer.Append($"before {before.Value.ToDate():yyyy-MM-dd}");
}
buffer.Append(")");
}
// File extension
buffer.Append($".{format.GetFileExtension()}");
return PathEx.EscapeFileName(buffer.ToString());
}
}
@@ -0,0 +1,7 @@
namespace DiscordChatExporter.Core.Exporting.Filtering;
internal enum BinaryExpressionKind
{
Or,
And
}
@@ -0,0 +1,25 @@
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 IsMatch(Message message) => _kind switch
{
BinaryExpressionKind.Or => _first.IsMatch(message) || _second.IsMatch(message),
BinaryExpressionKind.And => _first.IsMatch(message) && _second.IsMatch(message),
_ => throw new InvalidOperationException($"Unknown binary expression kind '{_kind}'.")
};
}
@@ -0,0 +1,33 @@
using System.Linq;
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;
private bool IsMatch(string? content) =>
!string.IsNullOrWhiteSpace(content) &&
Regex.IsMatch(
content,
"\\b" + Regex.Escape(_text) + "\\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
);
public override bool IsMatch(Message message) =>
IsMatch(message.Content) ||
message.Embeds.Any(e =>
IsMatch(e.Title) ||
IsMatch(e.Author?.Name) ||
IsMatch(e.Description) ||
IsMatch(e.Footer?.Text) ||
e.Fields.Any(f =>
IsMatch(f.Name) ||
IsMatch(f.Value)
)
);
}
@@ -0,0 +1,16 @@
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 IsMatch(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,24 @@
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 IsMatch(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,18 @@
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 IsMatch(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,11 @@
namespace DiscordChatExporter.Core.Exporting.Filtering;
internal enum MessageContentMatchKind
{
Link,
Embed,
File,
Video,
Image,
Sound
}
@@ -0,0 +1,17 @@
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 IsMatch(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,12 @@
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 IsMatch(Message message) => !_filter.IsMatch(message);
}
@@ -0,0 +1,8 @@
using DiscordChatExporter.Core.Discord.Data;
namespace DiscordChatExporter.Core.Exporting.Filtering;
internal class NullMessageFilter : MessageFilter
{
public override bool IsMatch(Message message) => true;
}
@@ -0,0 +1,101 @@
using DiscordChatExporter.Core.Utils.Extensions;
using Superpower;
using Superpower.Parsers;
namespace DiscordChatExporter.Core.Exporting.Filtering.Parsing;
internal static class FilterGrammar
{
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 Parse.OneOf(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 =
Parse.OneOf(EscapedCharacter, FreeCharacter).AtLeastOnce().Text();
private static readonly TextParser<string> String =
Parse.OneOf(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(Parse.OneOf(
Span.EqualToIgnoreCase("link").IgnoreThen(Parse.Return(MessageContentMatchKind.Link)),
Span.EqualToIgnoreCase("embed").IgnoreThen(Parse.Return(MessageContentMatchKind.Embed)),
Span.EqualToIgnoreCase("file").IgnoreThen(Parse.Return(MessageContentMatchKind.File)),
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 = Parse.OneOf(
GroupedFilter,
FromFilter,
MentionsFilter,
HasFilter,
ContainsFilter
);
private static readonly TextParser<MessageFilter> UnaryExpressionFilter = Parse.OneOf(
NegatedFilter,
StandaloneFilter
);
private static readonly TextParser<MessageFilter> BinaryExpressionFilter = Parse.Chain(
Parse.OneOf(
// 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();
}

Some files were not shown because too many files have changed in this diff Show More