forked from DoaJCBlogger/Talk32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
4791 lines (4285 loc) · 185 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Talk32: A lightweight unofficial Discord client
Copyright © 2020 Designing on a juicy cup
Talk32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#define UNICODE
#include <windows.h>
#include <process.h>
#include <windowsx.h>
#include <initguid.h>
#include <KnownFolders.h>
#include <ShlObj.h>
#include <commctrl.h>
#include <wchar.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <codecvt>
#include <vector>
#include <gdiplus.h>
#include <stdlib.h>
#include <htmlhelp.h>
#include <time.h>
using namespace std;
//Maybe do this for shlobj
//define _WIN32_IE=0x500
#define RAPIDJSON_HAS_STDSTRING 1
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/error/en.h"
#include "rapidjson/prettywriter.h"
using namespace rapidjson;
#define CURL_STATICLIB
#include "libcurl\include\curl\curl.h"
#include "sqlite\sqlite3.h"
#include "emoji.h"
LRESULT CALLBACK leftSidebarProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK serverListProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK contentAreaProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK hoverBtnProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK editProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void AddMenus(HWND);
bool login(bool, bool offlineMode = false);
wstring getUserAgent();
void copyText(string text);
void copyUnicodeText(wstring text);
wstring getUserName(uint64_t id);
wstring getUserNameWithDiscriminator(uint64_t id);
Gdiplus::Bitmap* getUserAvatar(uint64_t id);
void submitMessage();
void recalculateTotalMessageHeight(bool);
unsigned int DrawTextWithColorEmojis(HDC, Gdiplus::Graphics*, unsigned int, unsigned int, unsigned int, bool, unsigned char*, unsigned int, bool, SIZE*);
int UTF8ToCodepoint(unsigned char*, unsigned int*, unsigned int);
int UTF8CodepointIsEmoji(int);
void drawEmoji(Gdiplus::Graphics *GDIPlusOutputObject, int, unsigned int, unsigned int, unsigned int);
int ReadEmoji(unsigned char*, unsigned int*, unsigned int);
unsigned int GetMaxTextLengthForPixelWidth(HDC, unsigned int, wstring, unsigned int*);
void loadBitmaps();
void deleteBitmaps();
void drawServerIcon(HDC hdc, Gdiplus::Bitmap* icon, int x, int y, int roundStyle /* 0=none, 1=round, 2=hover*/);
void GetRoundRectPath(Gdiplus::GraphicsPath *pPath, Gdiplus::Rect r, int dia);
uint64_t GetSystemTimeAsUnixTime();
std::string wstring_to_utf8(const std::wstring&);
curl_socket_t my_opensocketfunc(void*, curlsocktype, struct curl_sockaddr*);
void addMessageToDataModel(uint64_t serverID, uint64_t channelID, uint64_t messageID, uint64_t authorID, string content);
void deleteMessageFromDataModel(uint64_t serverID, uint64_t channelID, uint64_t messageID);
void markChannelAsUnread(uint64_t serverID, uint64_t channelID);
void addMessageToLog(GenericValue<UTF8<>>*);
void markMessageAsDeletedInLog(GenericValue<UTF8<>>*);
int initializeTables(sqlite3*);
void loggingSettings(void* param);
LRESULT CALLBACK loggingSettingsDialogProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
void refreshLoggingServerList(HWND);
wstring unixTimestampToHumanReadableDate(uint64_t);
wstring padZeros(uint64_t i, int length);
bool fileExists(LPCWSTR filename);
bool folderExists(LPCWSTR foldername);
void addServerToLog(uint64_t id, string name, string icon, string currentTimestamp);
void addChannelToLog(uint64_t serverID, uint64_t id, string name, uint64_t category, string topic, int channelType, string timestamp);
void addCategoryToLog(uint64_t serverID, uint64_t id, string name, string timestamp);
//Contains a font fix provided by "Christopher Janzon" on stackoverflow.com
//https://stackoverflow.com/a/17075471
#define IDM_USER_LOGIN 1
#define IDM_USER_LOGOUT 2
#define IDM_USER_PROFILE 3
#define IDM_HELP_USERGUIDE 4
#define IDM_REFRESH 5
#define IDM_SETTINGS 6
#define IDM_COPY_CHANNEL_ID 7
#define IDM_INVITE_TO_CHANNEL 8
#define IDM_NOTIFICATIONS_DEFAULT 9
#define IDM_NOTIFICATIONS_NONE 10
#define IDM_NOTIFICATIONS_ONLY_MENTIONS 11
#define IDM_NOTIFICATIONS_ALL 12
#define IDM_MUTE 13
#define IDM_MUTE_24_HOUR 14
#define IDM_MUTE_8_HOUR 15
#define IDM_MUTE_1_HOUR 16
#define IDM_MUTE_15_MINUTE 17
#define IDM_CHANNEL_MARK_AS_READ 18
#define IDM_VOICE_CHANNEL_HIDE_NAMES 19
#define IDM_VOICE_CHANNEL_INVITE 20
#define IDM_VOICE_CHANNEL_COPY_ID 21
#define IDM_CHANNEL_GROUP_COLLAPSE_UNREAD 22
#define IDM_COPY_SERVER_ID 23
#define IDM_SETTINGS_LOGGING 24
#define IDC_AUTHTOKENFIELD 7
#define IDC_MESSAGEFIELD 8
#define IDC_LOGGING_SERVERS_REFRESH 9
#define AUTH_TOKEN_FIELD_WIDTH 600
#define MINIMUM_WINDOW_WIDTH 985
#define MINIMUM_WINDOW_HEIGHT 480
#define DISCORD_MAX_CHARACTERS 2000
#define MESSAGE_SPACING 20
const wstring versionString = L"Talk32 (https://github.com/DoaJCBlogger/Talk32, 0.1)";
enum Page {LoginPage, MainPage};
enum MainPageSubLocation {Channel, Friends, DM, GroupDM, Explore};
Page location = LoginPage;
MainPageSubLocation sublocation = Friends;
unsigned long long selectedServer = -1;
uint64_t selectedChannel = 1052421969297018910;//-1;
unsigned int selectedChannelGroupIdx = 0;
unsigned int selectedChannelIdxWithinGroup = 0;
string selectedServerName = "";
string selectedChannelName = "";
string selectedChannelTopic = "";
DWORD globalMainThreadID = NULL;
struct LoggingServer {
bool enabled;
uint64_t id;
wstring idString;
wstring name;
wstring filename;
wstring assetFolder;
uint64_t lastMessageTimestamp;
wstring lastMessageTimestampString;
sqlite3 *db;
LoggingServer():enabled(true),id(0),idString(L""),name(L""),filename(L""),assetFolder(L""),lastMessageTimestamp(0),lastMessageTimestampString(L""){}
};
struct ConfigObj {
wstring authToken;
wstring dataDir;
bool showUserList;
bool roundServerIcons;
bool roundUserAvatars;
unsigned int windowX;
unsigned int windowY;
unsigned int windowWidth;
unsigned int windowHeight;
vector<LoggingServer> loggingServers;
};
ConfigObj config;
bool offlineModeEnabled = false;
WNDPROC oldEditProc;
bool CALLBACK SetFont(HWND child, LPARAM font);
bool RectangleWidthHeight(HDC hdc, int x, int y, int w, int h);
bool RoundRectWidthHeight(HDC hdc, int x, int y, int w, int h, int rw, int rh);
void SetRectXYWidthHeight(RECT* r, long x, long y, long w, long h);
unsigned int getMessageHeight(unsigned int, string);
HWND hwndMainWin, statusBar, authTokenBox, messageField, httpResponseLabel, loginBtn, hwndServerList, hwndLeftSidebar, hwndContentArea, offlineBtn;
HBRUSH windowBGBrush, mainGrayColorBrush, messageFieldBGBrush, discordBlueBtnBrush, discordBlueBtnHoverBrush, discordBlueBtnDownBrush, serverListColorBrush, sidebarColorBrush, serverListHoverColor, serverListSelectedColor;// = (HBRUSH)GetStockObject(WHITE_BRUSH);
std::string data;
std::string BearerToken;
bool BearerTokenIsValid = false;
SYSTEMTIME BearerTokenCreatedTime = {0};
SYSTEMTIME LastRequestTime = {0};
Gdiplus::Bitmap *hBmpHomeIcon;
HBITMAP hBmpExploreIcon;
HBITMAP hBmpChannelPoundSign;
HBITMAP hBmpChannelPoundSignLocked;
HBITMAP hBmpChannelPoundSignSelected;
HBITMAP hBmpChannelPoundSignLockedSelected;
HBITMAP hBmpVoiceChannelIcon;
HBITMAP hBmpVoiceChannelLockedIcon;
HBITMAP hBmpLargePoundSign;
RECT YouTubeLogoTopBarRect;
RECT locationBarRect;
RECT searchBarRect;
RECT searchBtnRect;
RECT header3BarsRect;
RECT headerHomeLinkRect;
RECT headerTrendingLinkRect;
RECT headerSubscriptionsLinkRect;
bool homeHeaderLinkHover = false;
bool homeHeaderLinkSelected = true;
bool trendingHeaderLinkHover = false;
bool trendingHeaderLinkSelected = false;
bool subscriptionsHeaderLinkHover = false;
bool subscriptionsHeaderLinkSelected = false;
int smallHeaderTextHeight = 0;
HFONT authTokenPromptFont;
HFONT authTokenBoxFont;
HFONT smallInfoFont;
HFONT channelNameFont;
HFONT userNameFont;
HFONT channelGroupNameFont;
HFONT smallHeaderFont;
HFONT smallHeaderFont500Weight;
HFONT hoverBtnFont;
COLORREF serverListColor = RGB(32, 34, 37);
COLORREF sidebarColor = RGB(47, 49, 54);
COLORREF mainGrayColor = RGB(54, 57, 63); //56, 57, 59
COLORREF discordBlueBtnColor = RGB(114, 137, 218);
COLORREF discordBlueBtnHoverColor = RGB(103, 123, 196);
COLORREF discordBlueBtnDownColor = RGB(91, 110, 174);
COLORREF channelColor = RGB(142, 146, 151);
COLORREF contentAreaHeaderBGColor = RGB(56, 57, 59);
COLORREF messageTextColor = RGB(220, 221, 222);
COLORREF deletedMessageTextColor = RGB(237, 66, 69);
wstring localAppDataPath;
wstring configFilePath;
int scrollPosition = 0;
unsigned int contentAreaWidth;
struct HoverBtnData {
bool mouseIsOver;
bool leftBtnDown;
wstring text;
HoverBtnData():mouseIsOver(false),leftBtnDown(false),text(L""){}
};
struct Message {
unsigned long long id;
unsigned long long authorID;
int messageHeight;
string text;
bool deleted;
};
struct ChannelItem {
string name;
string topic;
uint64_t id;
bool voiceChannel;
bool locked;
bool unread;
bool hideVoiceChannelMembers;
int notificationSetting;
vector<Message> messages;
};
struct ChannelGroup {
string name;
vector<ChannelItem> channels;
uint64_t id;
bool IsCategory;
bool IsExpanded;
bool collapseUnread;
};
struct ServerListItem {
string name;
uint64_t id;
bool unread;
vector<ChannelGroup> dataModel;
Gdiplus::Bitmap *hbmIcon;
};
struct ServerListData {
bool leftBtnDown;
HWND hwndScrollbar;
int serverHoverIdx;
long scrollPos;
unsigned long long rightClickItemID;
vector<ServerListItem> dataModel;
ServerListData():hwndScrollbar(NULL),serverHoverIdx(-1){}
};
struct User {
wstring name;
uint64_t discriminator;
uint64_t id;
Gdiplus::Bitmap* hbmIcon;
};
vector<ServerListItem> globalServerIconList;
vector<User> globalUserList;
struct ContentAreaData *globalContentAreaData;
struct LeftSidebarData *globalLeftSidebarData;
CRITICAL_SECTION globalLeftSidebarDataCS;
struct ServerListData *globalServerListData;
CRITICAL_SECTION globalServerListDataCS;
vector<Message> *globalMessageList = NULL;
HDC tempHDC;
unsigned int messageWidth;
/*struct LeftSidebarItem {
wstring name;
bool unread;
};*/
struct LeftSidebarData {
bool mouseIsOver;
bool leftBtnDown;
HWND hwndScrollbar;
wstring serverName;
long scrollPos;
int selectedIdx;
int hoverIdx;
unsigned long long selectedChannelID;
unsigned long long rightClickItemID;
vector<ChannelGroup> dataModel;
vector<ChannelGroup> *dataModelPtr;
LeftSidebarData():hwndScrollbar(NULL),scrollPos(0){}
};
struct ContentAreaData {
vector<Message> messages;
HWND hwndScrollbar;
bool leftBtnDown;
unsigned long scrollPos;
unsigned long long totalContentHeight;
int oldContentAreaWidth;
bool shouldScrollToBottom;
ContentAreaData():hwndScrollbar(NULL),scrollPos(0),shouldScrollToBottom(true){}
};
const string opcodes[] = {"Dispatch", "Heartbeat", "Identify", "Presence Update", "Voice State Update", "", "Resume", "Reconnect", "Request Guild Members", "Invalid Session", "Hello", "Heartbeat ACK"};
//const string channelTypes[] = {"GuildText", "DM", "GuildVoice", "GroupDM", "GuildCategory", "GuildAnnouncement", "", "", "", "", "AnnouncementThread", "PublicThread", "PrivateThread", "GuildStageVoice", "GuildDirectory", "GuildForum"};
const char* tableNames[7] = {"messages", "attachments", "embeds", "users", "server", "channels", "categories"};
const char* createTableQueries[7] = {
"CREATE TABLE IF NOT EXISTS \"messages\" (\"ID\" BIGINT NOT NULL,\"channelID\" INTEGER,\"content\" TEXT,\"messageType\" TEXT,\"timestamp\" TEXT,\"timestampEdited\" TEXT,\"authorID\" INTEGER,\"pinned\" INTEGER, \"deleted\" INTEGER, PRIMARY KEY(\"ID\", \"channelID\", \"timestampEdited\"));",
"CREATE TABLE IF NOT EXISTS \"attachments\" (\"ID\" INTEGER UNIQUE,\"messageID\" INTEGER,\"idx\" INTEGER,\"filename\" TEXT,\"url\" TEXT,\"filesize\" INTEGER, \"deleted\" INTEGER, PRIMARY KEY(\"ID\",\"messageID\"));",
"CREATE TABLE IF NOT EXISTS \"embeds\" (\"messageID\" TEXT,\"title\" TEXT,\"url\" TEXT,\"description\" TEXT,\"author\" TEXT,\"authorUrl\" TEXT,\"authorIconUrl\" TEXT,\"idx\" INTEGER,\"thumbnailUrl\" TEXT,PRIMARY KEY(\"messageID\",\"idx\"));",
"CREATE TABLE IF NOT EXISTS \"users\" (\"ID\" TEXT,\"name\" TEXT,\"discriminator\" INTEGER,\"isBot\" INTEGER,\"avatarUrl\" TEXT,\"date\" TEXT,PRIMARY KEY(\"ID\",\"name\",\"discriminator\",\"avatarUrl\"));",
"CREATE TABLE IF NOT EXISTS \"server\" (\"ID\" BIGINT NOT NULL,\"name\" TEXT,\"iconUrl\" TEXT,\"date\" TEXT,PRIMARY KEY(\"ID\",\"name\",\"iconUrl\"));",
"CREATE TABLE IF NOT EXISTS \"channels\" (\"ID\" BIGINT NOT NULL,\"type\" TEXT,\"categoryID\" BIGINT,\"name\" TEXT,\"topic\" TEXT,\"date\" TEXT,PRIMARY KEY(\"ID\",\"categoryID\",\"name\",\"topic\"));",
"CREATE TABLE IF NOT EXISTS \"categories\" (\"ID\" BIGINT NOT NULL,\"name\" TEXT,\"date\" TEXT,PRIMARY KEY(\"ID\",\"name\"));"
};
void heartbeatThread(void* param);
CRITICAL_SECTION discordGatewayCurlObjectCS;
struct DownloadManagerJob {
wstring url;
wstring outputFolder;
wstring filename;
boolean replace;
};
vector<DownloadManagerJob> downloadManagerJobs;
wstring downloadManagerCurrentURL;
wstring downloadManagerProgress;
CRITICAL_SECTION downloadManagerJobsCS;
CRITICAL_SECTION downloadManagerStatusCS;
bool shouldStopDownloadManager = false;
void downloadManagerThread(void* param) {
CURL *downloadManagerCurlObject = curl_easy_init();
if (downloadManagerCurlObject) {
while (!shouldStopDownloadManager) {
if (downloadManagerJobs.size() > 0) {
if (downloadManagerJobs.at(0).outputFolder.at(downloadManagerJobs.at(0).outputFolder.length() - 1) != L'\\') downloadManagerJobs.at(0).outputFolder += L"\\";
wstring path = wstring(downloadManagerJobs.at(0).outputFolder + downloadManagerJobs.at(0).filename);
if (downloadManagerJobs.at(0).replace || (!downloadManagerJobs.at(0).replace && !fileExists(path.c_str()))) {
cout << endl << "Downloading " << wstring_to_utf8(downloadManagerJobs.at(0).url) << " to " << wstring_to_utf8(path);
FILE *file = fopen(wstring_to_utf8(wstring(downloadManagerJobs.at(0).outputFolder + downloadManagerJobs.at(0).filename)).c_str(), "wb");
if (file) {
curl_easy_setopt(downloadManagerCurlObject, CURLOPT_URL, wstring_to_utf8(downloadManagerJobs.at(0).url).c_str());
curl_easy_setopt(downloadManagerCurlObject, CURLOPT_USERAGENT, wstring_to_utf8(getUserAgent()).c_str());
curl_easy_setopt(downloadManagerCurlObject, CURLOPT_CAINFO, "cacert.pem");
curl_easy_setopt(downloadManagerCurlObject, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(downloadManagerCurlObject, CURLOPT_WRITEDATA, file);
CURLcode res = curl_easy_perform(downloadManagerCurlObject);
fclose(file);
}
}
downloadManagerJobs.erase(begin(downloadManagerJobs));
} else {
Sleep(500);
}
}
}
curl_easy_cleanup(downloadManagerCurlObject);
}
void drawAuthPage(HDC hdc, int w, int h) {
//Save a backup of the original GDI object
HGDIOBJ originalGDIObj = SelectObject(hdc, GetStockObject(DC_PEN));
//Draw the gray background
SelectObject(hdc, windowBGBrush);
SetDCPenColor(hdc, RGB(255,255,255));
SetBkColor(hdc, mainGrayColor);
SelectObject(hdc, authTokenPromptFont);
COLORREF originalTextColor = SetTextColor(hdc, RGB(255, 255, 255));
int centerW = w >> 1;
int centerH = h >> 1;
int authTextPromptX = centerW - 210;
int authTextPromptY = centerH - 150;
ExtTextOut(hdc, authTextPromptX, authTextPromptY, NULL, NULL, L"Please provide an authorization token", 37, NULL);
int authTokenBoxX = centerW - (AUTH_TOKEN_FIELD_WIDTH / 2);
int authTokenBoxY = authTextPromptY + 50;
RoundRectWidthHeight(hdc, authTokenBoxX - 7, authTokenBoxY - 8, AUTH_TOKEN_FIELD_WIDTH + 16, 36, 8, 8);
SetWindowPos(authTokenBox, HWND_TOPMOST, authTokenBoxX, authTokenBoxY, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
ShowWindow(authTokenBox, SW_SHOW);
SetWindowPos(loginBtn, HWND_TOPMOST, authTokenBoxX - 7 + (AUTH_TOKEN_FIELD_WIDTH - 85), authTokenBoxY + 40, 100, 36, SWP_NOSIZE | SWP_NOZORDER);
SetWindowPos(offlineBtn, HWND_TOPMOST, authTokenBoxX - 7 + (AUTH_TOKEN_FIELD_WIDTH - 85) - 135, authTokenBoxY + 40, 125, 36, SWP_NOSIZE | SWP_NOZORDER);
//Print the instructions for finding the auth token
SelectObject(hdc, smallInfoFont);
SetTextColor(hdc, RGB(255,255,255));
int textX = authTokenBoxX - 7;
int textY = authTokenBoxY + 100;
ExtTextOut(hdc, textX, textY, NULL, NULL, L"To find your authorization token (Chrome/Opera/Discord app),", 60, NULL);
textY += 20;
ExtTextOut(hdc, textX, textY, NULL, NULL, L"1. Sign in to Discord if you haven't already", 44, NULL);
textY += 20;
ExtTextOut(hdc, textX, textY, NULL, NULL, L"2. Press Ctrl+Shift+I", 21, NULL);
textY += 20;
ExtTextOut(hdc, authTokenBoxX - 7, textY, NULL, NULL, L"3. Open the Network tab and click \"XHR\"", 39, NULL);
textY += 20;
ExtTextOut(hdc, authTokenBoxX - 7, textY, NULL, NULL, L"4. Click any entry under \"Name\" and open the \"Headers\" tab on the right", 71, NULL);
textY += 20;
ExtTextOut(hdc, authTokenBoxX - 7, textY, NULL, NULL, L"5. Scroll down to the \"authorization\" entry under \"Request Headers\"", 67, NULL);
textY += 20;
ExtTextOut(hdc, authTokenBoxX - 7, textY, NULL, NULL, L"6. Copy and paste the random characters into the field above", 60, NULL);
SelectObject(hdc, originalGDIObj);
}
CURL *curl;
void drawMainPage(HDC hdc, int w, int h) {
//Save a backup of the original GDI object
HGDIOBJ originalGDIObj = SelectObject(hdc, GetStockObject(DC_PEN));
//Draw the gray background
SelectObject(hdc, windowBGBrush);
SetDCPenColor(hdc, RGB(255,255,255));
SetBkColor(hdc, mainGrayColor);
SelectObject(hdc, authTokenPromptFont);
COLORREF originalTextColor = SetTextColor(hdc, RGB(255, 255, 255));
//The main page has 4 sections from left to right: server icon list, left sidebar, content area, and right sidebar
//The server icon list width is 72 px + 15 px for the scrollbar
//The left sidebar width is 240 px + 15 px for the scrollbar
//The right sidebar is 240 px when viewing a channel and 420 px in the Friends list
//The content area which takes up the remaining space
contentAreaWidth = w - (72 + 15 + 240 + 15);
if (sublocation == Friends) {
contentAreaWidth -= 420;
} else if ((sublocation == Channel || sublocation == GroupDM) && config.showUserList) {
contentAreaWidth -= 240;
}
SelectObject(hdc, originalGDIObj);
}
//Copied from user 毕晓峰 on StackOverflow
//https://stackoverflow.com/a/35644947
// convert UTF-8 string to wstring
std::wstring utf8_to_wstring(const std::string& str)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.from_bytes(str);
}
// convert wstring to UTF-8 string
std::string wstring_to_utf8(const std::wstring& str)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
return myconv.to_bytes(str);
}
bool fileExists(LPCWSTR filename) {
DWORD attr = GetFileAttributes(filename);
return ((attr != INVALID_FILE_ATTRIBUTES) && !(attr & FILE_ATTRIBUTE_DIRECTORY));
}
bool folderExists(LPCWSTR foldername) {
DWORD attr = GetFileAttributes(foldername);
return ((attr != INVALID_FILE_ATTRIBUTES) && (attr & FILE_ATTRIBUTE_DIRECTORY));
}
bool loadOrCreateConfig() {
TCHAR szPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath))) {
MessageBox(NULL, L"Error: could not call SHGetFolderPath for the local appdata folder.", L"Error", MB_OK | MB_ICONERROR);
return false;
}
localAppDataPath = wstring(szPath);
if (localAppDataPath.at(localAppDataPath.length() - 1) != '\\') localAppDataPath += L"\\";
localAppDataPath += L"Talk32\\";
config.dataDir = localAppDataPath;
configFilePath = localAppDataPath + L"\\config.json";
bool shouldCreateConfigFile = true;
if (folderExists(localAppDataPath.c_str())) {
//The data folder already exists
shouldCreateConfigFile = !fileExists(configFilePath.c_str());
} else {
//The data folder doesn't exist yet
if (!SUCCEEDED(CreateDirectory(localAppDataPath.c_str(), NULL))) {
wstring error_msg = L"Error: could not create data directory at ";
error_msg += localAppDataPath;
MessageBox(NULL, error_msg.c_str(), L"Error", MB_OK | MB_ICONERROR);
return false;
}
}
if (shouldCreateConfigFile) {
ofstream configFile(configFilePath.c_str(), ios::binary);
if (!configFile) {
wstring error_msg = L"Error: could not create config file at ";
error_msg += configFilePath;
MessageBox(NULL, error_msg.c_str(), L"Error", MB_OK | MB_ICONERROR);
return false;
}
char c[2] = {'{', '}'};
configFile.write(c, 2);
configFile.close();
} else {
//Load the config file
ifstream configFile(configFilePath.c_str(), ios::binary);
if (!configFile) {
wstring error_msg = L"Error: could not load config file at ";
error_msg += configFilePath;
MessageBox(NULL, error_msg.c_str(), L"Error", MB_OK | MB_ICONERROR);
return false;
}
string configJsonStr((istreambuf_iterator<char>(configFile)), istreambuf_iterator<char>());
Document configDocument;
configDocument.Parse(configJsonStr.c_str());
if (configDocument.HasParseError()) {
wstring error_msg = L"Error parsing config file (at position ";
long long offset = (unsigned)configDocument.GetErrorOffset();
error_msg += to_wstring(offset);
error_msg += L"): ";
error_msg += utf8_to_wstring(GetParseError_En(configDocument.GetParseError()));
MessageBox(NULL, error_msg.c_str(), L"", MB_OK);
return true;
}
if (!configDocument.IsObject()) {
MessageBox(NULL, L"Error parsing config file: root element must be an object.", L"", MB_OK);
return true;
}
//Get the config options from the JSON document
//token (string)
rapidjson::Value::ConstMemberIterator iter = configDocument.FindMember("token");
if (iter != configDocument.MemberEnd()) {
config.authToken = utf8_to_wstring(configDocument["token"].GetString());
}
//showUserList (boolean)
iter = configDocument.FindMember("showUserList");
if (iter != configDocument.MemberEnd()) {
config.showUserList = configDocument["showUserList"].GetBool();
}
//round_server_icons (boolean)
iter = configDocument.FindMember("round_server_icons");
if (iter != configDocument.MemberEnd()) {
config.roundServerIcons = configDocument["round_server_icons"].GetBool();
}
//round_user_avatars (boolean)
iter = configDocument.FindMember("round_user_avatars");
if (iter != configDocument.MemberEnd()) {
config.roundUserAvatars = configDocument["round_user_avatars"].GetBool();
}
//Window position (array of x,y,w,h)
iter = configDocument.FindMember("window_pos");
if (iter != configDocument.MemberEnd() && configDocument["window_pos"].IsArray()) {
Value& positionArray = configDocument["window_pos"];
long long arraySize = positionArray.Size();
if (arraySize >= 1) config.windowX = configDocument["window_pos"][0].GetUint64();
if (arraySize >= 2) config.windowY = configDocument["window_pos"][1].GetUint64();
if (arraySize >= 3) config.windowWidth = configDocument["window_pos"][2].GetUint64();
if (arraySize >= 4) config.windowHeight = configDocument["window_pos"][3].GetUint64();
//Validate the window size so it can't go below the minimum
if (config.windowWidth < MINIMUM_WINDOW_WIDTH) config.windowWidth = MINIMUM_WINDOW_WIDTH;
if (config.windowHeight < MINIMUM_WINDOW_HEIGHT) config.windowHeight = MINIMUM_WINDOW_HEIGHT;
}
configFile.close();
//Logging servers
iter = configDocument.FindMember("logging_servers");
if (iter != configDocument.MemberEnd() && configDocument["logging_servers"].IsArray()) {
Value& loggingServerArray = configDocument["logging_servers"];
long long arraySize = loggingServerArray.Size();
for (int i = 0; i < arraySize; i++) {
LoggingServer ls;
ls.id = configDocument["logging_servers"][i]["id"].GetUint64();
ls.name = utf8_to_wstring(configDocument["logging_servers"][i]["name"].GetString());
string loggingServerFilename = configDocument["logging_servers"][i]["filename"].GetString();
ls.filename = utf8_to_wstring(loggingServerFilename);
string loggingServerAssetFolder = "";
if (configDocument["logging_servers"][i].FindMember("assets") != configDocument["logging_servers"][i].MemberEnd() && configDocument["logging_servers"][i]["assets"].IsString()) loggingServerAssetFolder = configDocument["logging_servers"][i]["assets"].GetString();
ls.assetFolder = utf8_to_wstring(loggingServerAssetFolder);
if (ls.assetFolder.at(ls.assetFolder.size() - 1) != L'\\') ls.assetFolder += L"\\";
wstring avatarsFolder = utf8_to_wstring(loggingServerAssetFolder) + L"avatars";
if (!folderExists(avatarsFolder.c_str())) {
if (!SUCCEEDED(CreateDirectory(avatarsFolder.c_str(), NULL))) {
wstring error_msg = L"Error: could not create avatars directory at ";
error_msg += avatarsFolder;
MessageBox(NULL, error_msg.c_str(), L"Error", MB_OK | MB_ICONERROR);
}
}
int rc = sqlite3_open(loggingServerFilename.c_str(), &ls.db);
if (rc) {
cout << endl << "Error while opening database: " << sqlite3_errmsg(ls.db);
} else {
initializeTables(ls.db);
}
//cout << endl << ls.id << ", " << wstring_to_utf8(ls.name) << ", " << wstring_to_utf8(ls.filename);
config.loggingServers.push_back(ls);
}
}
}
return true;
}
void saveConfig() {
return;
TCHAR szPath[MAX_PATH];
if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, szPath))) {
MessageBox(NULL, L"Error: could not call SHGetFolderPath for the local appdata folder.", L"Error", MB_OK | MB_ICONERROR);
return;
}
localAppDataPath = wstring(szPath);
if (localAppDataPath.at(localAppDataPath.length() - 1) != '\\') localAppDataPath += L"\\";
localAppDataPath += L"Talk32\\";
configFilePath = localAppDataPath + L"\\config.json";
GenericDocument<UTF16<> > d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
d.AddMember(L"token", StringRef(config.authToken), allocator);
d.AddMember(L"showUserList", config.showUserList, allocator);
d.AddMember(L"round_server_icons", config.roundServerIcons, allocator);
d.AddMember(L"round_user_avatars", config.roundUserAvatars, allocator);
RECT r;
if (GetWindowRect(hwndMainWin, &r)) {
config.windowX = r.left;
config.windowY = r.top;
config.windowWidth = r.right - r.left;
config.windowHeight = r.bottom - r.top;
}
GenericValue<UTF16<> > windowPos(kArrayType);
Value::AllocatorType allocator2;
windowPos.PushBack(config.windowX, allocator2);
windowPos.PushBack(config.windowY, allocator2);
windowPos.PushBack(config.windowWidth, allocator2);
windowPos.PushBack(config.windowHeight, allocator2);
d.AddMember(L"window_pos", windowPos, allocator2);
GenericValue<UTF16<> > loggingServers(kArrayType);
for (auto ls = begin(config.loggingServers); ls != end(config.loggingServers); ++ls) {
GenericDocument<UTF16<> > loggingServer;
loggingServer.SetObject();
Document::AllocatorType& allocator3 = loggingServer.GetAllocator();
loggingServer.AddMember(L"id", ls->id, allocator3);
loggingServer.AddMember(L"name", StringRef(ls->name), allocator3);
loggingServer.AddMember(L"filename", StringRef(ls->filename), allocator3);
loggingServers.PushBack(loggingServer, allocator3);
}
d.AddMember(L"logging_servers", loggingServers, allocator);
StringBuffer strbuf;
rapidjson::Writer< StringBuffer, UTF16<> > writer(strbuf);
//rapidjson::PrettyWriter< PrettyWriter, UTF16<> >(writer);
d.Accept(writer);
string json = strbuf.GetString();
ofstream configFile(configFilePath.c_str(), ios::binary);
if (!configFile) {
wstring error_msg = L"Error: could not open config file for writing at ";
error_msg += configFilePath;
MessageBox(NULL, error_msg.c_str(), L"Error", MB_OK | MB_ICONERROR);
return;
}
configFile.write(json.c_str(), json.length());
configFile.close();
}
curl_socket_t sock;
curl_socket_t my_opensocketfunc(void *clientp, curlsocktype purpose, struct curl_sockaddr *address){
return sock=socket(address->family, address->socktype, address->protocol);
}
ofstream logFile;
int heartbeat_interval = 30000;
bool shouldStopHeartbeats = false;
bool APIIsLoggedIn = false;
uintptr_t heartbeatThreadHandle = NULL;
string resume_gateway_url = "wss://gateway.discord.gg/?v=10&encoding=json";
string session_id;
uint64_t latestDiscordSequenceNumber = 0;
char* websocketFragment = NULL;
unsigned long websocketFragmentSize = 0;
unsigned long websocketFragmentCurrentIdx = 0;
unsigned long receivedWebsocketFramesWithinFragment = 0;
bool heartbeatThreadIsActive = false;
static size_t websocketCallback(void *data, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
std::string str = "Received WebSocket data (";
str += std::to_string((long long)realsize);
str += " bytes): ";
str += string((char*)data, realsize);
logFile << endl << str;
curl_ws_frame* frameInfo = curl_ws_meta(curl);
//cout << endl << "flags=" << frameInfo->flags << ", offset=" << frameInfo->offset << " (actual offset " << websocketFragmentCurrentIdx << "), bytesleft=" << frameInfo->bytesleft;
if (receivedWebsocketFramesWithinFragment == 0) {
free(websocketFragment);
websocketFragment = (char*)malloc(realsize + frameInfo->bytesleft);
websocketFragmentSize = realsize + frameInfo->bytesleft;
//cout << endl << "WebSocket fragment size: " << websocketFragmentSize;
}
memcpy(websocketFragment + websocketFragmentCurrentIdx, data, realsize);
//cout << endl << "Copied " << realsize << " bytes to offset " << websocketFragmentCurrentIdx;
if (frameInfo->bytesleft > 0) {
//This is a partial fragment so we have to just add it to the existing data
receivedWebsocketFramesWithinFragment++;
websocketFragmentCurrentIdx += realsize;
return realsize;
}
Document responseJSON;
logFile << endl << "About to parse JSON data: " << string((char*)websocketFragment, websocketFragmentSize);
//For some reason, Discord sometimes sends invalid JSON data with multiple objects like this: {}{}
int objectStart = 0;
int objectEnd = 0;
int curlyBrackets = 0;
while (objectStart < websocketFragmentSize) {
for (int i = objectStart; i < websocketFragmentSize; i++) {
if (websocketFragment[i] == '{') {
curlyBrackets++;
} else if (websocketFragment[i] == '}') {
curlyBrackets--;
}
if (curlyBrackets == 0) {
objectEnd = i;
logFile << endl << "curlyBrackets is 0 at index " << i;
break;
}
}
responseJSON.Parse(string((char*)websocketFragment + objectStart, (objectEnd - objectStart) + 1/*websocketFragmentSize*/).c_str());
if (((objectEnd - objectStart) + 1) < 8192) {
cout << endl << "JSON object: " << string((char*)websocketFragment + objectStart, (objectEnd - objectStart) + 1/*websocketFragmentSize*/);
}
logFile << endl << "JSON object: " << string((char*)websocketFragment + objectStart, (objectEnd - objectStart) + 1);
if (responseJSON.HasParseError()) {
/*wstring error_msg = L"Error parsing config file (at position ";
long long offset = (unsigned)responseJSON.GetErrorOffset();
error_msg += to_wstring(offset);
error_msg += L"): ";
error_msg += utf8_to_wstring(GetParseError_En(responseJSON.GetParseError()));*/
cout << endl << "Error while parsing WebSocket data";
return realsize;
}
if (!responseJSON.IsObject()) {
cout << endl << "Error parsing WebSocket data: root element must be an object";
return realsize;
}
rapidjson::Value::ConstMemberIterator iter = responseJSON.FindMember("op");
if (iter == responseJSON.MemberEnd()) {
cout << endl << "Could not find \"op\" element";
return realsize;
}
int op = responseJSON["op"].GetInt();
cout << endl << "op=" << op;
if (op >= 0 && op <= 11) cout << " (" << opcodes[op] << ")";
string t = "";
if (iter != responseJSON.MemberEnd()) {
switch(op) {
case 0: //Dispatch
{
//This includes things like READY and MESSAGE_CREATE
t = responseJSON["t"].GetString();
if (responseJSON["s"].IsUint64()) latestDiscordSequenceNumber = responseJSON["s"].GetUint64();
if (t.compare("READY") == 0) {
//Save "resume_gateway_url" and "session_id" so we can resume if we get disconnected
APIIsLoggedIn = true;
resume_gateway_url = responseJSON["d"]["resume_gateway_url"].GetString();
session_id = responseJSON["d"]["session_id"].GetString();
cout << endl << "resume_gateway_url=" << resume_gateway_url;
cout << endl << "session_id=" << session_id;
wstring currentTimestamp = unixTimestampToHumanReadableDate(GetSystemTimeAsUnixTime());
//Load the servers and channels
if (responseJSON["d"]["guilds"].IsArray()) {
//Clear the channel list
//Lock the data model so we the UI thread doesn't try to draw it
EnterCriticalSection(&globalServerListDataCS);
//cout << endl << "Entered the critical section";
globalLeftSidebarData->dataModel.clear();
Value& guildsArray = responseJSON["d"]["guilds"];
long long guildsArraySize = guildsArray.Size();
ServerListItem server;
ChannelGroup cg;
ChannelGroup defaultCG;
ChannelItem c;
cg.IsExpanded = true;
cg.IsCategory = true;
cg.collapseUnread = false;
defaultCG.IsExpanded = true;
defaultCG.IsCategory = true;
defaultCG.collapseUnread = false;
defaultCG.name = "Text Channels";
c.unread = false;
c.locked = false;
c.hideVoiceChannelMembers = false;
c.notificationSetting = 0;
uint64_t categoryID;
int channelType;
int channelsArraySize;
//Iterate over servers
for (int h = 0; h < guildsArraySize; h++) {
Value& guildObject = guildsArray[h];
server.id = stoull(guildObject["id"].GetString());
server.name = guildObject["name"].GetString();
server.unread = false;
string icon = "";
if (!guildObject["icon"].IsNull()) {
icon = guildObject["icon"].GetString();
server.hbmIcon = new Gdiplus::Bitmap(wstring(localAppDataPath + L"cache\\server_icons\\" + utf8_to_wstring(icon) + L".png").c_str(), false);
} else {
server.hbmIcon = new Gdiplus::Bitmap(wstring(localAppDataPath + L"cache\\server_icons\\null.png").c_str(), false);;
}
addServerToLog(server.id, server.name, icon, wstring_to_utf8(currentTimestamp));
channelsArraySize = guildObject["channels"].Size();
cg.channels.clear();
//Iterate over the channel objects to get the categories
for (int i = 0; i < channelsArraySize; i++) {
//Skip objects that aren't categories
channelType = guildObject["channels"][i]["type"].GetInt();
//Add channels with no category to a default category
if ((channelType == 0 /* GUILD_TEXT */ || channelType == 2 /* GUILD_VOICE */) && guildObject["channels"][i].FindMember("parent_id") == guildObject["channels"][i].MemberEnd()) {
c.id = stoull(guildObject["channels"][i]["id"].GetString(), NULL, 10);
c.name = guildObject["channels"][i]["name"].GetString();
c.topic = (guildObject["channels"][i].FindMember("topic") != guildObject["channels"][i].MemberEnd() && !guildObject["channels"][i]["topic"].IsNull()) ? guildObject["channels"][i]["topic"].GetString() : string("");
c.voiceChannel = (channelType == 2);
defaultCG.channels.push_back(c);
addChannelToLog(server.id, c.id, c.name, 0, c.topic, channelType, wstring_to_utf8(currentTimestamp));
continue;
}
if (guildObject["channels"][i]["type"].GetInt() != 4) continue;
categoryID = stoull(guildObject["channels"][i]["id"].GetString());
cg.id = categoryID;
cg.name = guildObject["channels"][i]["name"].GetString();
//Iterate over the channel objects to get the channels
for (int j = 0; j < channelsArraySize; j++) {
channelType = guildObject["channels"][j]["type"].GetInt();
if ((guildObject["channels"][j].FindMember("parent_id") == guildObject["channels"][j].MemberEnd() || !guildObject["channels"][j]["parent_id"].IsString() || stoull(guildObject["channels"][j]["parent_id"].GetString(), NULL, 10) != categoryID) || (channelType != 0 /* GUILD_TEXT */ && channelType != 2 /* GUILD_VOICE */)) continue;
c.id = stoull(guildObject["channels"][j]["id"].GetString(), NULL, 10);
c.name = guildObject["channels"][j]["name"].GetString();
c.topic = (guildObject["channels"][j].FindMember("topic") != guildObject["channels"][j].MemberEnd() && !guildObject["channels"][j]["topic"].IsNull()) ? guildObject["channels"][j]["topic"].GetString() : string("");
c.voiceChannel = (channelType == 2);
cg.channels.push_back(c);
addChannelToLog(server.id, c.id, c.name, categoryID, c.topic, channelType, wstring_to_utf8(currentTimestamp));
} //for (int j = 0; j < channelsArraySize; j++) {
server.dataModel.push_back(cg);
addCategoryToLog(server.id, cg.id, cg.name, wstring_to_utf8(currentTimestamp));
cg.channels.clear();
} //for (int i = 0; i < channelsArraySize; i++) {
if (!defaultCG.channels.empty()) server.dataModel.push_back(defaultCG);
globalServerListData->dataModel.push_back(server);
defaultCG.channels.clear();
server.dataModel.clear();
}
//Unlock the data model
LeaveCriticalSection(&globalServerListDataCS);
}
} else if (t.compare("MESSAGE_CREATE") == 0) {
//cout << endl << "MESSAGE_CREATE: \"" << responseJSON["d"]["content"].GetString() << "\"";
uint64_t serverID = (responseJSON["d"].FindMember("guild_id") != responseJSON["d"].MemberEnd() && responseJSON["d"]["guild_id"].IsString() ? stoull(responseJSON["d"]["guild_id"].GetString()) : -1);
uint64_t channelID = stoull(responseJSON["d"]["channel_id"].GetString());
//Save the message to a database if the user is logging the server it's from
addMessageToLog(&responseJSON["d"]);
if (channelID == selectedChannel) {
//Add the message to the current data model if the channel is selected
addMessageToDataModel(serverID, channelID, stoull(responseJSON["d"]["id"].GetString()), stoull(responseJSON["d"]["author"]["id"].GetString()), responseJSON["d"]["content"].GetString());
} else {
//If the message is for a channel that isn't selected, then we should just mark it as unread
//The message will be loaded anyway with the POST request when the user clicks it
markChannelAsUnread(serverID, channelID);
}
//recalculateTotalMessageHeight(true);
} else if (t.compare("MESSAGE_DELETE") == 0) {
markMessageAsDeletedInLog(&responseJSON["d"]);
uint64_t serverID = (responseJSON["d"].FindMember("guild_id") != responseJSON["d"].MemberEnd() && responseJSON["d"]["guild_id"].IsString() ? stoull(responseJSON["d"]["guild_id"].GetString()) : -1);
deleteMessageFromDataModel(serverID, stoull(responseJSON["d"]["channel_id"].GetString()), stoull(responseJSON["d"]["id"].GetString()));
} else if (t.compare("MESSAGE_UPDATE") == 0) {
uint64_t serverID = (responseJSON["d"].FindMember("guild_id") != responseJSON["d"].MemberEnd() && responseJSON["d"]["guild_id"].IsString() ? stoull(responseJSON["d"]["guild_id"].GetString()) : -1);
uint64_t channelID = stoull(responseJSON["d"]["channel_id"].GetString());
//Save the message to a database if the user is logging the server it's from
addMessageToLog(&responseJSON["d"]);
//recalculateTotalMessageHeight(true);
}
/*InvalidateRect(hwndLeftSidebar, NULL, TRUE);
InvalidateRect(hwndContentArea, NULL, TRUE);*/
}
break;
case 1: //Heartbeat
{
//If Discord requested a heartbeat then we need to send one
size_t sent;
EnterCriticalSection(&discordGatewayCurlObjectCS);
string heartbeatObject = "{\"op\":1,\"d\":" + (latestDiscordSequenceNumber >= 0 ? to_string(latestDiscordSequenceNumber) : string("null")) + "}";
try { curl_ws_send(curl, heartbeatObject.c_str(), heartbeatObject.length(), &sent, 4096, CURLWS_TEXT); } catch (...) {}
LeaveCriticalSection(&discordGatewayCurlObjectCS);
}
break;
case 7: //Reconnect
{
//We need to reconnect
size_t sent;
cout << endl << "Sending op 1000 to close the connection";
EnterCriticalSection(&discordGatewayCurlObjectCS);
string json = "{\"op\":1000,\"d\":" + (latestDiscordSequenceNumber >= 0 ? to_string(latestDiscordSequenceNumber) : string("null")) + "}";
try { curl_ws_send(curl, json.c_str(), json.length(), &sent, 4096, CURLWS_TEXT); } catch (...) {}
LeaveCriticalSection(&discordGatewayCurlObjectCS);
cout << endl << "Sent op 1000";
//Stop the heartbeat thread
shouldStopHeartbeats = true;
cout << endl << "Waiting for the heartbeat thread to stop";
while (heartbeatThreadIsActive) {}
cout << endl << "Heartbeat thread stopped";
/*shouldStopHeartbeats = false;
heartbeatThreadHandle = _beginthread(heartbeatThread, 0, NULL);*/
return CURL_WRITEFUNC_ERROR;
}
break;