-
Notifications
You must be signed in to change notification settings - Fork 14
/
TwitchNotify.c
1708 lines (1471 loc) · 49.1 KB
/
TwitchNotify.c
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
#define INITGUID
#define COBJMACROS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlobj.h>
#include <shellapi.h>
#include <shlwapi.h>
#include <winhttp.h>
#include <stdbool.h>
#include <stdint.h>
#pragma comment (lib, "kernel32.lib")
#pragma comment (lib, "user32.lib")
#pragma comment (lib, "shell32.lib")
#pragma comment (lib, "shlwapi.lib")
#pragma comment (lib, "ole32.lib")
#pragma comment (lib, "winhttp.lib")
#ifdef _DEBUG
#define Assert(Cond) do { if (!(Cond)) __debugbreak(); } while (0)
#else
#define Assert(Cond) ((void)(Cond))
#endif
#define HR(hr) do { HRESULT _hr = (hr); Assert(SUCCEEDED(_hr)); } while (0)
#include "WindowsToast.h"
#include "WindowsJson.h"
// sent when tray icon is clicked
#define WM_TWITCH_NOTIFY_COMMAND (WM_USER + 1)
// sent from duplicate to original instance of application to show notification
#define WM_TWITCH_NOTIFY_ALREADY_RUNNING (WM_USER + 2)
// sent when websocket is connected or disconnected
// WParam contains HINTERNET handle for websocket, or NULL when disconnected
// LParam contains true if this is first time websocket connected
#define WM_TWITCH_NOTIFY_WEBSOCKET (WM_USER + 3)
// sent when websocked receives live status update for user
// WParam is UserId, LParam is true when user goes live, false when goes offline
#define WM_TWITCH_NOTIFY_USER_STATUS (WM_USER + 4)
// sent when websocket receives viewer count update
// WParam is UserId, LParam is viewer count
#define WM_TWITCH_NOTIFY_USER_VIEWER_COUNT (WM_USER + 5)
// sent when game/stream name is downloaded
// WParam is UserId, LParam is JsonObject for response (must release it)
#define WM_TWITCH_NOTIFY_USER_STREAM (WM_USER + 6)
// sent when initial user info is downloaded
// WParam is JsonObject for response (must release it)
#define WM_TWITCH_NOTIFY_USER_INFO (WM_USER + 7)
// sent when user stream status is downloaded
// WParam is JsonObject for response (must release it)
#define WM_TWITCH_NOTIFY_USER_STREAM_INFO (WM_USER + 8)
// sent when list of followed users is download
// WParam is JsonObject for response (must release it)
#define WM_TWITCH_NOTIFY_FOLLOWED_USERS (WM_USER + 9)
// command id's for popup menu items
#define CMD_OPEN_HOMEPAGE 10 // "Twitch Notify" item selected
#define CMD_USE_MPV 20 // "Use mpv" checkbox
#define CMD_QUALITY 30 // +N for Quality submenu items
#define CMD_EDIT_USERS 40 // "Edit List" in user submenu
#define CMD_DOWNLOAD_USERS 50 // "Download List" in user submenu
#define CMD_EXIT 60 // "Exit"
#define CMD_USER 70 // +N for one of users (indexed into State.Users[] array)
#define TWITCH_NOTIFY_NAME L"Twitch Notify"
#define TWITCH_NOTIFY_INI L"TwitchNotify.ini"
#define TWITCH_NOTIFY_APPID L"TwitchNotify.TwitchNotify" // CompanyName.ProductName
#define TWITCH_NOTIFY_HOMEPAGE L"https://github.com/mmozeiko/TwitchNotify/"
// Twitch oficially documented monitored user count is limited to 50
#define MAX_USER_COUNT 50
// just arbitrary limit for strings (most of them will be shorter anyway)
#define MAX_STRING_LENGTH 256
// downloaded user profile image files will be cached
// length in seconds, 1 week
#define MAX_IMAGE_CACHE_AGE (60*60*24*7)
// WM_TIMER id's
#define TIMER_RELOAD_USERS 1
#define TIMER_WEBSOCKET_PING 2
// how much to delay after .ini file notification is detected
#define TIMER_RELOAD_USERS_DELAY 100 // msec
// Twitch requires to send PING message over websocket at least once per 5 min
#define TIMER_WEBSOCKET_PING_INTERVAL (2*60*1000) // 2 min in msec
// youtube-dl quality names to use with mpv player
struct
{
LPCWSTR Name;
LPCSTR Format;
}
static const Quality[] =
{
{ L"Source", "best" },
{ L"1080p @ 60", "best[height<=?1080]/best" },
{ L"1080p", "best[height<=?1080][fps<=30]/best" },
{ L"720p @ 60", "best[height<=?720]/best" },
{ L"720p", "best[height<=?720][fps<=?30]/best" },
{ L"480p", "best[height<=?480]/best" },
{ L"360p", "best[height<=?360]/best" },
{ L"160p", "best[height<=?160]/best" },
};
// message sent when explorer.exe restarts, to restore tray icon
static uint32_t WM_TASKBARCREATED;
typedef struct
{
WCHAR Name[MAX_STRING_LENGTH]; // name from .ini file, used for Twitch URL
WCHAR DisplayName[MAX_STRING_LENGTH]; // display name user can customize
WCHAR ImagePath[MAX_PATH]; // path to downloaded profile image
// 0 when user id is not yet known (gql query executing)
// -1 when gql query did not return any user (invalid username)
// >0 for actual users
int UserId;
int ViewerCount;
bool IsLive;
// WindowsToast notification, keep it around to update it
void* Notification;
} User;
// global state of application
// members are modified & accessed only from main thread
// only exception is HWND Window - to post messages from background threads
struct
{
HICON Icon;
HICON IconDisconnected;
HWND Window;
WindowsToast Toast;
HINTERNET Session;
HINTERNET Websocket;
PTP_POOL ThreadPool;
// for loading & saving .ini file
WCHAR IniPath[MAX_PATH];
FILETIME LastIniWriteTime;
// global settings
int Quality;
bool UseMpv;
// user list
User Users[MAX_USER_COUNT];
int UserCount;
}
static State;
// http://www.isthe.com/chongo/tech/comp/fnv/
static uint64_t GetFnv1Hash(const void* Ptr, int Size)
{
const uint8_t* Bytes = Ptr;
uint64_t Hash = 14695981039346656037ULL;
for (int Index = 0; Index < Size; Index++)
{
Hash *= 1099511628211ULL;
Hash ^= Bytes[Index];
}
return Hash;
}
// system tray icon stuff
static void AddTrayIcon(HWND Window, HICON Icon)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP,
.uCallbackMessage = WM_TWITCH_NOTIFY_COMMAND,
.hIcon = Icon,
};
StrCpyNW(Data.szInfoTitle, TWITCH_NOTIFY_NAME, ARRAYSIZE(Data.szInfoTitle));
Assert(Shell_NotifyIconW(NIM_ADD, &Data));
}
static void RemoveTrayIcon(HWND Window)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
};
Assert(Shell_NotifyIconW(NIM_DELETE, &Data));
}
static void UpdateTrayIcon(HWND Window, HICON Icon)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
.uFlags = NIF_ICON,
.hIcon = Icon,
};
Assert(Shell_NotifyIconW(NIM_MODIFY, &Data));
}
// InfoType can be: NIIF_NONE, NIIF_INFO, NIIF_WARNING, NIIF_ERROR
static void ShowTrayMessage(HWND Window, DWORD InfoType, LPCWSTR Message)
{
NOTIFYICONDATAW Data =
{
.cbSize = sizeof(Data),
.hWnd = Window,
.uFlags = NIF_INFO,
.dwInfoFlags = InfoType,
.hIcon = State.Websocket ? State.Icon : State.IconDisconnected,
};
StrCpyNW(Data.szInfo, Message, ARRAYSIZE(Data.szInfo));
StrCpyNW(Data.szInfoTitle, TWITCH_NOTIFY_NAME, ARRAYSIZE(Data.szInfoTitle));
Assert(Shell_NotifyIconW(NIM_MODIFY, &Data));
}
static bool IsMpvInPath(void)
{
WCHAR mpv[MAX_PATH];
return FindExecutableW(L"mpv.exe", NULL, mpv) > (HINSTANCE)32;
}
static void OpenMpvUrl(LPCWSTR Url)
{
WCHAR Args[1024];
wsprintfW(Args, L"--profile=low-latency --ytdl-format=\"%S\" %s", Quality[State.Quality].Format, Url);
ShellExecuteW(NULL, L"open", L"mpv.exe", Args, NULL, SW_SHOWNORMAL);
}
static void GetTwitchIcon(LPWSTR ImagePath)
{
int TempLength = GetTempPathW(MAX_PATH, ImagePath);
Assert(TempLength);
wsprintfW(ImagePath + TempLength, L"twitch.png");
// if file does not exist
if (GetFileAttributesW(ImagePath) == INVALID_FILE_ATTRIBUTES)
{
// extract first icon image data from resources, it is a png file
HRSRC Resource = FindResourceW(NULL, MAKEINTRESOURCEW(1), MAKEINTRESOURCEW(3)); // 3=RT_ICON
if (Resource)
{
HGLOBAL Global = LoadResource(NULL, Resource);
if (Global)
{
int ResourceSize = SizeofResource(NULL, Resource);
LPVOID ResourceData = LockResource(Global);
if (ResourceData && ResourceSize)
{
HANDLE File = CreateFileW(ImagePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (File != INVALID_HANDLE_VALUE)
{
DWORD Written;
WriteFile(File, ResourceData, ResourceSize, &Written, NULL);
CloseHandle(File);
}
}
}
}
}
}
// showing & updating Windows Toast notification
static void ShowUserNotification(User* User)
{
WCHAR ImagePath[MAX_PATH];
if (GetFileAttributesW(User->ImagePath) == INVALID_FILE_ATTRIBUTES)
{
// unlikely, but in case image file is missing on disk, use generic Twitch image from our icon
GetTwitchIcon(ImagePath);
}
else
{
StrCpyW(ImagePath, User->ImagePath);
}
for (WCHAR* P = ImagePath; *P; P++)
{
if (*P == '\\') *P = '/';
}
WCHAR Xml[4096];
int XmlLength = 0;
// use long duration, because getting game & stream name often takes a while
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"<toast duration=\"long\"><visual><binding template=\"ToastGeneric\">"
L"<image placement=\"appLogoOverride\" src=\"file:///");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, ImagePath);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"\"/>"
L"<text hint-maxLines=\"3\">{user}</text>"
L"<text>{game}</text>"
L"<text>{stream}</text>"
L"</binding></visual><actions>");
if (IsMpvInPath())
{
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, L"<action content=\"Play\" arguments=\"Phttps://www.twitch.tv/");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, User->Name);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, L"\"/>");
}
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, L"<action content=\"Open Browser\" arguments=\"Ohttps://www.twitch.tv/");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, User->Name);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"\"/>"
L"</actions></toast>");
// initial user notification does not have game & stream title yet
// show "..." while it will be downloading in background
LPCWSTR Data[][2] =
{
{ L"user", User->DisplayName },
{ L"game", L"..." },
{ L"stream", L"" },
};
void* Notification = WindowsToast_Create(&State.Toast, Xml, XmlLength, Data, ARRAYSIZE(Data));
WindowsToast_Show(&State.Toast, Notification);
User->Notification = Notification;
}
// updates & releases user notification
static void UpdateUserNotification(User* User, LPCWSTR GameName, LPCWSTR StreamName)
{
if (User->Notification)
{
LPCWSTR Data[][2] =
{
{ L"game", GameName },
{ L"stream", StreamName },
};
WindowsToast_Update(&State.Toast, User->Notification, Data, ARRAYSIZE(Data));
WindowsToast_Release(&State.Toast, User->Notification);
User->Notification = NULL;
}
}
// websocket stuff that main thread sends to server
// don't care if WinHttpWebSocketSend fails, because that means websocket is
// disconnected, and it will reconnect in background anyway
static void WebsocketPing(void)
{
char Data[] = "{\"type\":\"PING\"}";
WinHttpWebSocketSend(State.Websocket, WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE, Data, ARRAYSIZE(Data) - 1);
}
static void WebsocketListenUser(int UserId, bool Listen)
{
if (State.Websocket)
{
char Data[1024];
int DataSize = wsprintfA(Data, "{\"type\":\"%s\",\"data\":{\"topics\":[\"video-playback-by-id.%d\"]}}", Listen ? "LISTEN" : "UNLISTEN", UserId);
WinHttpWebSocketSend(State.Websocket, WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE, Data, DataSize);
}
}
// gql query stuff, will be called from background threads
static int DoGqlQuery(char* Query, int QuerySize, char* Buffer, int BufferSize)
{
int ReadSize = 0;
HINTERNET Connection = WinHttpConnect(State.Session, L"gql.twitch.tv", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (Connection)
{
HINTERNET Request = WinHttpOpenRequest(Connection, L"POST", L"/gql", NULL, NULL, NULL, WINHTTP_FLAG_SECURE);
if (Request)
{
WCHAR Headers[] = L"Client-ID: kimne78kx3ncx6brgo4mv6wki5h1ko";
if (WinHttpSendRequest(Request, Headers, ARRAYSIZE(Headers) - 1, Query, QuerySize, QuerySize, 0) &&
WinHttpReceiveResponse(Request, NULL))
{
DWORD Status = 0;
DWORD StatusSize = sizeof(Status);
WinHttpQueryHeaders(
Request,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&Status,
&StatusSize,
WINHTTP_NO_HEADER_INDEX);
if (Status == HTTP_STATUS_OK)
{
while (ReadSize < BufferSize)
{
DWORD Read;
if (!WinHttpReadData(Request, Buffer + ReadSize, BufferSize - ReadSize, &Read) || Read == 0)
{
break;
}
ReadSize += Read;
}
}
}
WinHttpCloseHandle(Request);
}
WinHttpCloseHandle(Connection);
}
return ReadSize;
}
// gets "unique" path on disk to image - do this by hashing image URL
// image will be placed in %TEMP% folder
static void GetImagePath(LPWSTR ImagePath, LPCWSTR ImageUrl)
{
int ImageUrlLength = lstrlenW(ImageUrl);
uint64_t Hash = GetFnv1Hash(ImageUrl, ImageUrlLength * sizeof(WCHAR));
int TempLength = GetTempPathW(MAX_PATH, ImagePath);
Assert(TempLength);
LPWSTR Extension = StrRChrW(ImageUrl, ImageUrl + ImageUrlLength, L'.');
wsprintfW(ImagePath + TempLength, L"%016I64x%s", Hash, Extension);
}
// image downloading, happens in background thread
static void CALLBACK DownloadUserImageWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
LPWSTR ImageUrl = (LPWSTR)Context;
WCHAR ImagePath[MAX_PATH];
GetImagePath(ImagePath, ImageUrl);
WCHAR HostName[MAX_PATH];
WCHAR UrlPath[MAX_PATH];
URL_COMPONENTSW Url =
{
.dwStructSize = sizeof(Url),
.lpszHostName = HostName,
.lpszUrlPath = UrlPath,
.dwHostNameLength = ARRAYSIZE(HostName),
.dwUrlPathLength = ARRAYSIZE(UrlPath),
};
if (WinHttpCrackUrl(ImageUrl, 0, 0, &Url))
{
HINTERNET Connection = WinHttpConnect(State.Session, HostName, Url.nPort, 0);
if (Connection)
{
HINTERNET Request = WinHttpOpenRequest(
Connection, L"GET", UrlPath, NULL,
NULL, NULL, Url.nScheme == INTERNET_SCHEME_HTTPS ? WINHTTP_FLAG_SECURE : 0);
if (Request)
{
if (WinHttpSendRequest(Request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) &&
WinHttpReceiveResponse(Request, NULL))
{
DWORD Status = 0;
DWORD StatusSize = sizeof(Status);
WinHttpQueryHeaders(
Request,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&Status,
&StatusSize,
WINHTTP_NO_HEADER_INDEX);
if (Status == HTTP_STATUS_OK)
{
// there's a minor race condition when user notification can show up
// before image file has finished downloading, but this will almost
// never happen, and it is such a minor issue, so... meh
HANDLE File = CreateFileW(ImagePath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (File != INVALID_HANDLE_VALUE)
{
char Buffer[65536];
for (;;)
{
DWORD Read;
if (!WinHttpReadData(Request, Buffer, sizeof(Buffer), &Read) || Read == 0)
{
break;
}
DWORD Written;
WriteFile(File, Buffer, Read, &Written, NULL);
}
CloseHandle(File);
}
}
WinHttpCloseHandle(Request);
}
WinHttpCloseHandle(Connection);
}
}
}
LocalFree(ImageUrl);
CloseThreadpoolWork(Work);
}
// called on main thread, gets path to profile image, and downloads it when necessary
static void DownloadUserImage(LPWSTR ImagePath, LPCWSTR ImageUrl)
{
GetImagePath(ImagePath, ImageUrl);
WIN32_FILE_ATTRIBUTE_DATA Data;
if (GetFileAttributesExW(ImagePath, GetFileExInfoStandard, &Data))
{
// FILETIME is in 100nsec units
uint64_t LastWrite =
(((uint64_t)Data.ftLastWriteTime.dwHighDateTime) << 32) + Data.ftLastWriteTime.dwLowDateTime;
FILETIME NowTime;
GetSystemTimeAsFileTime(&NowTime);
uint64_t Now = (((uint64_t)NowTime.dwHighDateTime) << 32) + NowTime.dwLowDateTime;
uint64_t Expires = LastWrite + (uint64_t)MAX_IMAGE_CACHE_AGE * 10 * 1000 * 1000;
if (Now < Expires)
{
// ok image up to date
return;
}
}
// when image is not present or out of date, queue its download
TP_CALLBACK_ENVIRON Environ;
InitializeThreadpoolEnvironment(&Environ);
SetThreadpoolCallbackPool(&Environ, State.ThreadPool);
// NOTE: callback must LocalFree() passed context pointer
PTP_WORK Work = CreateThreadpoolWork(&DownloadUserImageWork, StrDupW(ImageUrl), &Environ);
Assert(Work);
SubmitThreadpoolWork(Work);
}
// gql query for getting initial user info (UserId & friends), happens in background thread
static void CALLBACK DownloadUserInfoWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
char* Query = (char*)Context;
char Buffer[65536];
int BufferSize = DoGqlQuery(Query, lstrlenA(Query), Buffer, sizeof(Buffer));
LocalFree(Query);
JsonObject* Json = JsonObject_Parse(Buffer, BufferSize);
PostMessageW(State.Window, WM_TWITCH_NOTIFY_USER_INFO, (WPARAM)Json, 0);
CloseThreadpoolWork(Work);
}
// reloads .ini file if need & updates State.User[] array, must be called from main thread
static void LoadUsers(void)
{
WIN32_FILE_ATTRIBUTE_DATA Data;
if (!GetFileAttributesExW(State.IniPath, GetFileExInfoStandard, &Data))
{
// .ini file deleted?
return;
}
if (CompareFileTime(&State.LastIniWriteTime, &Data.ftLastWriteTime) >= 0)
{
// .ini file is up to date
return;
}
State.LastIniWriteTime = Data.ftLastWriteTime;
WCHAR Users[32768]; // max size GetPrivateProfileSection() can return
Users[0] = 0;
GetPrivateProfileSectionW(L"users", Users, ARRAYSIZE(Users), State.IniPath);
WCHAR* Ptr = Users;
LPCWSTR NewUsers[MAX_USER_COUNT];
int NewCount = 0;
while (*Ptr != 0)
{
if (NewCount == MAX_USER_COUNT)
{
ShowTrayMessage(State.Window, NIIF_WARNING, L"More than 50 users is not supported");
break;
}
int PtrLength = lstrlenW(Ptr);
WCHAR* Name = Ptr;
StrTrimW(Name, L" \t");
if (Name[0])
{
NewUsers[NewCount++] = Name;
}
Ptr += PtrLength + 1;
}
// remember current user count
int OldCount = State.UserCount;
User OldUsers[MAX_USER_COUNT];
CopyMemory(OldUsers, State.Users, OldCount * sizeof(User));
// copy users back which have not changed
int UserCount = 0;
for (int OldIndex = 0; OldIndex < OldCount; OldIndex++)
{
for (int NewIndex = 0; NewIndex < NewCount; NewIndex++)
{
if (StrCmpW(OldUsers[OldIndex].Name, NewUsers[NewIndex]) == 0)
{
State.Users[UserCount++] = OldUsers[OldIndex];
NewUsers[NewIndex] = NULL;
OldUsers[OldIndex].Name[0] = 0;
break;
}
}
}
// unsubscribe from removed ones
for (int OldIndex = 0; OldIndex < OldCount; OldIndex++)
{
User* OldUser = &OldUsers[OldIndex];
if (OldUser->Name[0])
{
if (OldUser->UserId > 0)
{
// unsubscribe from websocket notifications
WebsocketListenUser(OldUser->UserId, false);
}
// in case notification game/stream title update was pending
// update it and release notification handle
UpdateUserNotification(OldUser, L"", L"");
}
}
WCHAR Query[4096];
int QuerySize = 0;
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"{\"query\":\"{users(logins:[");
LPCWSTR Delim = L"";
// add new users & prepare query to download their info - user id, display name, profile image, stream viewer count
for (int NewIndex = 0; NewIndex < NewCount; NewIndex++)
{
if (NewUsers[NewIndex])
{
User* User = &State.Users[UserCount++];
StrCpyNW(User->Name, NewUsers[NewIndex], MAX_STRING_LENGTH);
// this info is not known yet, will be downloaded in DownloadUserInfoWork callback
User->UserId = 0;
User->DisplayName[0] = 0;
// no notification is shown initially
User->Notification = NULL;
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, Delim);
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"\\\"");
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, NewUsers[NewIndex]);
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"\\\"");
Delim = L",";
}
}
State.UserCount = UserCount;
// allowed image widths: 28, 50, 70, 150, 300, 600
// use 70 because for 100% dpi scale the toast size is 48 pixels, for 200% it is 96
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"]){id,displayName,profileImageURL(width:70),stream{viewersCount}}}\"}");
char QueryBytes[4096];
QuerySize = WideCharToMultiByte(CP_UTF8, 0, Query, QuerySize, QueryBytes, ARRAYSIZE(QueryBytes), NULL, NULL);
QueryBytes[QuerySize] = 0;
// queue gql query to background
TP_CALLBACK_ENVIRON Environ;
InitializeThreadpoolEnvironment(&Environ);
SetThreadpoolCallbackPool(&Environ, State.ThreadPool);
// NOTE: callback must LocalFree() passed context pointer
PTP_WORK Work = CreateThreadpoolWork(&DownloadUserInfoWork, StrDupA(QueryBytes), &Environ);
Assert(Work);
SubmitThreadpoolWork(Work);
}
// gql query for getting list of followed usernames, happens in background thread
static void CALLBACK DownloadFollowedUsersWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
char* Query = (char*)Context;
char Buffer[65536];
int BufferSize = DoGqlQuery(Query, lstrlenA(Query), Buffer, sizeof(Buffer));
LocalFree(Query);
JsonObject* Json = JsonObject_Parse(Buffer, BufferSize);
PostMessageW(State.Window, WM_TWITCH_NOTIFY_FOLLOWED_USERS, (WPARAM)Json, 0);
CloseThreadpoolWork(Work);
}
// starts download of list of followed users
static void DownloadFollowedUsers(void)
{
WCHAR username[MAX_STRING_LENGTH];
if (!GetPrivateProfileStringW(L"twitch", L"username", L"", username, ARRAYSIZE(username), State.IniPath) || username[0] == 0)
{
WCHAR ImagePath[MAX_PATH];
GetTwitchIcon(ImagePath);
WCHAR Xml[4096];
int XmlLength = 0;
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength,
L"<toast><visual><binding template=\"ToastGeneric\">"
L"<image placement=\"appLogoOverride\" src=\"file:///");
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, ImagePath);
XmlLength = StrCatChainW(Xml, ARRAYSIZE(Xml), XmlLength, L"\"/>"
L"<text>Username not set</text>"
L"<text>Cannot download followed users!</text>"
L"<text>Edit .ini file to set username?</text>"
L"</binding></visual><actions>"
L"<action content=\"Yes\" arguments=\"E\"/>"
L"<action content=\"No\" arguments=\"N\"/>"
L"</actions></toast>");
WindowsToast_ShowSimple(&State.Toast, Xml, XmlLength, NULL, 0);
return;
}
char QueryBytes[1024];
wsprintfA(QueryBytes, "{\"query\":\"# query:\\n{user(login:\\\"%S\\\"){follows(first:%u){edges{node{login}}}}}\"}", username, MAX_USER_COUNT);
// queue gql query to background
TP_CALLBACK_ENVIRON Environ;
InitializeThreadpoolEnvironment(&Environ);
SetThreadpoolCallbackPool(&Environ, State.ThreadPool);
// NOTE: callback must LocalFree() passed context pointer
PTP_WORK Work = CreateThreadpoolWork(&DownloadFollowedUsersWork, StrDupA(QueryBytes), &Environ);
Assert(Work);
SubmitThreadpoolWork(Work);
}
// gql query for getting user game/stream title, happens in background thread
static void DownloadUserStreamCommon(int UserId)
{
char Query[1024];
int QuerySize = wsprintfA(Query, "{\"query\":\"{users(ids:[%d]){stream{title,game{displayName}}}}\"}", UserId);
char Buffer[4096];
int BufferSize = DoGqlQuery(Query, QuerySize, Buffer, sizeof(Buffer));
JsonObject* Json = BufferSize ? JsonObject_Parse(Buffer, BufferSize) : NULL;
PostMessageW(State.Window, WM_TWITCH_NOTIFY_USER_STREAM, UserId, (LPARAM)Json);
}
static void CALLBACK DownloadUserStreamWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
int UserId = PtrToInt(Context);
DownloadUserStreamCommon(UserId);
CloseThreadpoolWork(Work);
}
static void CALLBACK DownloadUserStreamTimer(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer)
{
int UserId = PtrToInt(Context);
DownloadUserStreamCommon(UserId);
CloseThreadpoolTimer(Timer);
}
// issues gql query for getting user game/stream title, must be called from main thread
// Delay is extra time to delay before actual download, in msec
static void DownloadUserStream(int UserId, int Delay)
{
TP_CALLBACK_ENVIRON Environ;
InitializeThreadpoolEnvironment(&Environ);
SetThreadpoolCallbackPool(&Environ, State.ThreadPool);
if (Delay == 0)
{
PTP_WORK Work = CreateThreadpoolWork(&DownloadUserStreamWork, IntToPtr(UserId), &Environ);
Assert(Work);
SubmitThreadpoolWork(Work);
}
else
{
PTP_TIMER Timer = CreateThreadpoolTimer(&DownloadUserStreamTimer, IntToPtr(UserId), &Environ);
Assert(Timer);
// negative timer value means relative time
LARGE_INTEGER Time = { .QuadPart = -Delay * 10000LL }; // in 100 nsec units
FILETIME DueTime =
{
.dwLowDateTime = Time.LowPart,
.dwHighDateTime = Time.HighPart,
};
SetThreadpoolTimer(Timer, &DueTime, 0, 0);
}
}
static void ShowTrayMenu(HWND Window)
{
bool MpvFound = IsMpvInPath();
WCHAR username[MAX_STRING_LENGTH];
bool CanUpdateUsers = GetPrivateProfileStringW(L"twitch", L"username", L"", username, ARRAYSIZE(username), State.IniPath) && username[0];
HMENU QualityMenu = CreatePopupMenu();
Assert(QualityMenu);
for (int Index = 0; Index < ARRAYSIZE(Quality); Index++)
{
UINT Flags = State.Quality == Index ? MF_CHECKED : MF_UNCHECKED;
AppendMenuW(QualityMenu, Flags, CMD_QUALITY + Index, Quality[Index].Name);
}
HMENU Menu = CreatePopupMenu();
Assert(Menu);
AppendMenuW(Menu, MF_STRING, CMD_OPEN_HOMEPAGE, L"Twitch Notify");
AppendMenuW(Menu, MF_SEPARATOR, 0, NULL);
for (int Index = 0; Index < State.UserCount; Index++)
{
User* User = &State.Users[Index];
if (User->UserId > 0)
{
LPCWSTR Name = User->DisplayName[0] ? User->DisplayName : User->Name;
if (User->IsLive)
{
WCHAR Caption[1024];
wsprintfW(Caption, L"%s\t%d", Name, User->ViewerCount);
AppendMenuW(Menu, MF_CHECKED, CMD_USER + Index, Caption);
}
else
{
AppendMenuW(Menu, MF_STRING, CMD_USER + Index, Name);
}
}
else // unknown user
{
AppendMenuW(Menu, MF_GRAYED, 0, User->Name);
}
}
if (State.UserCount == 0)
{
AppendMenuW(Menu, MF_GRAYED, 0, L"No users");
}
AppendMenuW(Menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(Menu, MF_STRING | (CanUpdateUsers ? 0 : MF_GRAYED), CMD_DOWNLOAD_USERS, L"Download User List");
AppendMenuW(Menu, MF_STRING, CMD_EDIT_USERS, L"Edit User List");
AppendMenuW(Menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(Menu, (State.UseMpv ? MF_CHECKED : MF_STRING) | (MpvFound ? 0 : MF_GRAYED), CMD_USE_MPV, L"mpv Playback");
AppendMenuW(Menu, MF_POPUP | (MpvFound ? 0 : MF_GRAYED), (UINT_PTR)QualityMenu, L"mpv Quality");
AppendMenuW(Menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(Menu, MF_STRING, CMD_EXIT, L"Exit");
POINT Mouse;
GetCursorPos(&Mouse);
SetForegroundWindow(Window);
int Command = TrackPopupMenu(Menu, TPM_RETURNCMD | TPM_NONOTIFY, Mouse.x, Mouse.y, 0, Window, NULL);
if (Command == CMD_OPEN_HOMEPAGE)
{
ShellExecuteW(NULL, L"open", TWITCH_NOTIFY_HOMEPAGE, NULL, NULL, SW_SHOWNORMAL);
}
else if (Command == CMD_USE_MPV)
{
State.UseMpv = !State.UseMpv;
}
else if (Command >= CMD_QUALITY && Command < CMD_QUALITY + ARRAYSIZE(Quality))
{
State.Quality = Command - CMD_QUALITY;
}
else if (Command == CMD_EDIT_USERS)
{
ShellExecuteW(NULL, L"edit", State.IniPath, NULL, NULL, SW_SHOWNORMAL);
}
else if (Command == CMD_DOWNLOAD_USERS)
{
DownloadFollowedUsers();
}
else if (Command == CMD_EXIT)
{
DestroyWindow(Window);
}
else if (Command >= CMD_USER && Command < CMD_USER + State.UserCount)
{
User* User = &State.Users[Command - CMD_USER];
WCHAR Url[1024];
wsprintfW(Url, L"https://www.twitch.tv/%s", User->Name);
if (State.UseMpv && IsMpvInPath() && User->IsLive)
{
// use mpv only if mpv is selected, it is available in path, and user is live
OpenMpvUrl(Url);
}
else
{
// otherwise open browser url
ShellExecuteW(NULL, L"open", Url, NULL, NULL, SW_SHOWNORMAL);
}
}
DestroyMenu(Menu);
DestroyMenu(QualityMenu);
}
static void CALLBACK DownloadUserStreamInfoWork(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK Work)
{
char* Query = (char*)Context;
char Buffer[65536];
int BufferSize = DoGqlQuery(Query, lstrlenA(Query), Buffer, sizeof(Buffer));
LocalFree(Query);
JsonObject* Json = JsonObject_Parse(Buffer, BufferSize);
PostMessageW(State.Window, WM_TWITCH_NOTIFY_USER_STREAM_INFO, (WPARAM)Json, 0);
CloseThreadpoolWork(Work);
}
static void OnWebsocketConnected(HINTERNET Websocket, BOOL FirstConnection)
{
State.Websocket = Websocket;
UpdateTrayIcon(State.Window, Websocket ? State.Icon : State.IconDisconnected);
if (Websocket)
{
// if websocket is connected, start timer for sending PING messages
SetTimer(State.Window, TIMER_WEBSOCKET_PING, TIMER_WEBSOCKET_PING_INTERVAL, NULL);
// subscribe to all users with valid UserId
for (int Index = 0; Index < State.UserCount; Index++)
{
User* User = &State.Users[Index];
if (User->UserId > 0)
{
WebsocketListenUser(User->UserId, true);
}
}
// query if users streams are online
// don't need to do that on first connection, because that is done as part of .ini file load
if (!FirstConnection)
{
WCHAR Query[4096];
int QuerySize = 0;
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"{\"query\":\"{users(logins:[");
LPCWSTR Delim = L"";
for (int Index = 0; Index < State.UserCount; Index++)
{
User* User = &State.Users[Index];
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, Delim);
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"\\\"");
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, User->Name);
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"\\\"");
Delim = L",";
}
QuerySize = StrCatChainW(Query, ARRAYSIZE(Query), QuerySize, L"]){id,stream{viewersCount}}}\"}");
char QueryBytes[4096];
QuerySize = WideCharToMultiByte(CP_UTF8, 0, Query, QuerySize, QueryBytes, ARRAYSIZE(QueryBytes), NULL, NULL);
QueryBytes[QuerySize] = 0;
// queue gql query to background