Repository navigation
Expand file tree
/
Copy pathTwitchNotify.c
More file actions
1492 lines (1304 loc) · 44.4 KB
/
Copy pathTwitchNotify.c
File metadata and controls
1492 lines (1304 loc) · 44.4 KB
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
#if defined(__GNUC__)
// NOTE(bk): Needed for gcc. msvc seems to set these values based off the current OS.
# define NTDDI_VERSION 0x06010000 // Windows 7 though technically could support Vista
# define WINVER 0x061
# define _WIN32_WINNT 0x061
# define _WIN32_DCOM
#elif defined(_MSC_VER)
# pragma warning (disable : 4204 4711 4710 4820)
# pragma warning (push, 0)
#endif
#include <windows.h>
#include <DbgHelp.h>
#include <shlwapi.h>
#include <strsafe.h>
#include <shlobj.h>
#include <wininet.h>
#include <wincodec.h>
#if defined(__GNUC__)
# pragma GCC diagnostic push
// TODO(bk): Do I need multiple push/pop?
// TODO(bk): I should see about fixing the warnings and submitting a push request.
# pragma GCC diagnostic ignored "-Wtype-limits"
# pragma GCC diagnostic ignored "-Wsign-compare"
#endif
#include "jsmn.c" // https://github.com/zserge/jsmn
#include "jsmn_iterator.c" // https://github.com/zserge/jsmn/pull/69
#if defined(_MSC_VER)
# pragma warning(pop)
#elif defined(__GNUC__)
# pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
#define NORETURN_FUNCTION __declspec(noreturn)
#else
#define NORETURN_FUNCTION __attribute__((noreturn))
#endif
// TODO
// automatic check for updates https://api.github.com/repos/mmozeiko/TwitchNotify/git/refs/heads/master
#ifdef _DEBUG
#define Assert(cond) do \
{ \
if (!(cond)) \
{ \
__debugbreak(); \
} \
} while (0)
#else
#define Assert(cond) ((void)(cond))
#endif
#define WM_TWITCH_NOTIFY_COMMAND (WM_USER + 1)
#define WM_TWITCH_NOTIFY_ALREADY_RUNNING (WM_USER + 2)
#define WM_TWITCH_NOTIFY_REMOVE_USERS (WM_USER + 3)
#define WM_TWITCH_NOTIFY_ADD_USER (WM_USER + 4)
#define WM_TWITCH_NOTIFY_START_UPDATE (WM_USER + 5)
#define WM_TWITCH_NOTIFY_USER_ONLINE (WM_USER + 6)
#define WM_TWITCH_NOTIFY_END_UPDATE (WM_USER + 7)
#define WM_TWITCH_NOTIFY_UPDATE_ERROR (WM_USER + 8)
#define CMD_OPEN_HOMEPAGE 1
#define CMD_USE_LIVESTREAMER 2
#define CMD_EDIT_LIVESTREAMERRC 3
#define CMD_USE_MPV_YDL 4
#define CMD_YDL_FORMAT_SOURCE 5
#define CMD_YDL_FORMAT_HIGH 6
#define CMD_YDL_FORMAT_MEDIUM 7
#define CMD_YDL_FORMAT_LOW 8
#define CMD_YDL_FORMAT_MOBILE 9
#define CMD_TOGGLE_ACTIVE 10
#define CMD_EDIT_CONFIG_FILE 11
#define CMD_QUIT 255
#define TWITCH_NOTIFY_CONFIG L"TwitchNotify.txt"
#define TWITCH_NOTIFY_TITLE L"Twitch Notify"
#define MAX_USER_COUNT 100 // max user count that can be requested in one Twitch API call
#define MAX_USER_NAME_LENGTH 256
#define MAX_GAME_NAME_LENGTH 128
#define MAX_WINDOWS_ICON_SIZE 256
#define MAX_DOWNLOAD_SIZE (1024 * 1024) // 1 MiB
#define CHECK_USERS_TIMER_INTERVAL 60 // seconds
#define RELOAD_CONFIG_TIMER_DELAY 100 // msec
#define SKIP_ERRORS_TIMER_INTERVAL (CHECK_USERS_TIMER_INTERVAL / 2)
#define UPDATE_USERS_TIMER_ID 1
#define RELOAD_CONFIG_TIMER_ID 2
#define SKIP_ERRORS_TIMER_ID 3
#define MAX_ICON_CACHE_AGE (60*60*24*7) // 1 week
struct User
{
WCHAR name[MAX_USER_NAME_LENGTH];
WCHAR game[MAX_GAME_NAME_LENGTH];
int online;
};
struct UserStatusOnline
{
WCHAR user[MAX_USER_NAME_LENGTH];
WCHAR game[MAX_GAME_NAME_LENGTH];
HICON icon;
};
static struct User gUsers[MAX_USER_COUNT];
static int gUserCount;
static int gUseMpvYdl;
static int gYdlFormat;
static int gUseLivestreamer;
static int gActive;
static int gLastPopupUserIndex = -1;
static BOOL gHideErrors;
static HANDLE gHeap;
static HICON gTwitchNotifyIcon;
static HWND gWindow;
static HINTERNET gInternet;
static IWICImagingFactory* gWicFactory;
static HANDLE gUpdateEvent;
static HANDLE gConfigEvent;
static WCHAR gExeFolder[MAX_PATH + 1];
static UINT WM_TASKBARCREATED;
#if defined(_MSC_VER)
# pragma function ("memset")
void* memset(void* dst, int value, size_t count)
{
__stosb((BYTE*)dst, (BYTE)value, count);
return dst;
}
#endif
static void ShowNotification(LPWSTR message, LPWSTR title, DWORD flags, HICON icon)
{
NOTIFYICONDATAW data =
{
.cbSize = sizeof(data),
.hWnd = gWindow,
.uFlags = NIF_INFO,
.dwInfoFlags = flags | (icon ? NIIF_LARGE_ICON : 0),
.hBalloonIcon = icon,
};
StrCpyNW(data.szInfo, message, _countof(data.szInfo));
StrCpyNW(data.szInfoTitle, title ? title : TWITCH_NOTIFY_TITLE, _countof(data.szInfoTitle));
BOOL ret = Shell_NotifyIconW(NIM_MODIFY, &data);
Assert(ret);
}
static void ShowUserOnlineNotification(struct UserStatusOnline* status)
{
WCHAR title[1024];
wnsprintfW(title, _countof(title), L"'%s' just went live!", status->user);
WCHAR message[1024];
if (status->game[0] == 0)
{
StrCpyNW(message, L"Playing unknown game", _countof(message));
}
else
{
wnsprintfW(message, _countof(message), L"Playing '%s'", status->game);
}
ShowNotification(message, title, NIIF_USER, status->icon ? status->icon : gTwitchNotifyIcon);
}
static void OpenTwitchUser(int index)
{
if (index < 0 || index >= gUserCount)
{
return;
}
WCHAR args[400];
wnsprintfW(args, _countof(args), L"https://www.twitch.tv/%s", gUsers[index].name);
if (gUsers[index].online)
{
if (gUseLivestreamer)
{
StrCatBuffW(args, L" --http-header Client-ID=jzkbprff40iqj646a697cyrvl0zt2m6", _countof(args));
ShellExecuteW(NULL, L"open", L"livestreamer.exe", args, NULL, SW_HIDE);
return;
}
else if (gUseMpvYdl)
{
static const WCHAR* formats[] = { L"Source", L"High", L"Medium", L"Low", L"Mobile" };
StrCatBuffW(args, L" --ytdl-format ", _countof(args));
StrCatBuffW(args, formats[gYdlFormat], _countof(args));
ShellExecuteW(NULL, L"open", L"mpv.exe", args, NULL, SW_HIDE);
return;
}
}
ShellExecuteW(NULL, L"open", args, NULL, NULL, SW_SHOWNORMAL);
}
static void ToggleActive(HWND window)
{
if (gActive)
{
KillTimer(window, UPDATE_USERS_TIMER_ID);
for (int i = 0; i < gUserCount; i++)
{
gUsers[i].>
}
}
else
{
UINT_PTR timer = SetTimer(window, UPDATE_USERS_TIMER_ID, CHECK_USERS_TIMER_INTERVAL * 1000, NULL);
Assert(timer);
SetEvent(gUpdateEvent);
}
gActive = !gActive;
}
static int IsLivestreamerInPath(void)
{
WCHAR livestreamer[MAX_PATH];
return FindExecutableW(L"livestreamer.exe", NULL, livestreamer) > (HINSTANCE)32;
}
static void ToggleLivestreamer(void)
{
gUseLivestreamer = !gUseLivestreamer;
if (gUseLivestreamer)
{
if (IsLivestreamerInPath())
{
gUseMpvYdl = 0;
}
else
{
MessageBoxW(NULL, L"Cannot find 'livestreamer.exe' in PATH!",
TWITCH_NOTIFY_TITLE, MB_ICONEXCLAMATION);
gUseLivestreamer = 0;
}
}
}
static int IsMpvAndYdlInPath(void)
{
WCHAR path[MAX_PATH];
return FindExecutableW(L"mpv.exe", NULL, path) > (HINSTANCE)32
&& FindExecutableW(L"youtube-dl.exe", NULL, path) > (HINSTANCE)32;
}
static void ToggleMpvYdl(void)
{
gUseMpvYdl = !gUseMpvYdl;
if (gUseMpvYdl)
{
if (IsMpvAndYdlInPath())
{
gUseLivestreamer = 0;
}
else
{
MessageBoxW(NULL, L"Cannot find 'mpv.exe' and 'youtube-dl.exe' in PATH!",
TWITCH_NOTIFY_TITLE, MB_ICONEXCLAMATION);
gUseMpvYdl = 0;
}
}
}
static void EditLivestreamerConfig(void)
{
WCHAR path[MAX_PATH];
HRESULT hr = SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path);
Assert(SUCCEEDED(hr));
PathAppendW(path, L"livestreamer");
if (!PathIsDirectoryW(path) && !CreateDirectoryW(path, NULL))
{
MessageBoxW(NULL, L"Cannot create livestreamer configuration directory!",
TWITCH_NOTIFY_TITLE, MB_ICONERROR);
}
PathAppendW(path, L"livestreamerrc");
ShellExecuteW(NULL, L"open", L"notepad.exe", path, NULL, SW_SHOWNORMAL);
}
static void EditConfigFile(void)
{
WCHAR path[MAX_PATH];
StrCpyNW(path, gExeFolder, _countof(path));
PathAppendW(path, TWITCH_NOTIFY_CONFIG);
ShellExecuteW(NULL, L"open", L"notepad.exe", path, NULL, SW_SHOWNORMAL);
}
static void AddTrayIcon(HWND window)
{
NOTIFYICONDATAW data =
{
.cbSize = sizeof(data),
.hWnd = window,
.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP,
.uCallbackMessage = WM_TWITCH_NOTIFY_COMMAND,
.hIcon = gTwitchNotifyIcon,
};
Assert(data.hIcon);
StrCpyNW(data.szTip, TWITCH_NOTIFY_TITLE, _countof(data.szTip));
BOOL ret = Shell_NotifyIconW(NIM_ADD, &data);
Assert(ret);
}
static void OpenHomePage(void)
{
ShellExecuteW(NULL, L"open", L"https://github.com/mmozeiko/TwitchNotify/", NULL, NULL, SW_SHOWNORMAL);
}
static LRESULT CALLBACK WindowProc(HWND window, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_CREATE:
{
WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated");
Assert(WM_TASKBARCREATED);
AddTrayIcon(window);
ToggleActive(window);
SetEvent(gConfigEvent);
return 0;
}
case WM_DESTROY:
{
NOTIFYICONDATAW data =
{
.cbSize = sizeof(data),
.hWnd = window,
};
BOOL ret = Shell_NotifyIconW(NIM_DELETE, &data);
Assert(ret);
PostQuitMessage(0);
return 0;
}
case WM_POWERBROADCAST:
{
if (wparam == PBT_APMRESUMEAUTOMATIC)
{
if (gActive)
{
gHideErrors = TRUE;
SetTimer(window, SKIP_ERRORS_TIMER_ID, SKIP_ERRORS_TIMER_INTERVAL * 1000, NULL);
ToggleActive(window);
ToggleActive(window);
}
}
return 0;
}
case WM_TWITCH_NOTIFY_COMMAND:
{
if (lparam == WM_RBUTTONUP)
{
HMENU mpvYdl = CreatePopupMenu();
Assert(mpvYdl);
AppendMenuW(mpvYdl, gYdlFormat == 0 ? MF_CHECKED : MF_UNCHECKED, CMD_YDL_FORMAT_SOURCE, L"Source");
AppendMenuW(mpvYdl, gYdlFormat == 1 ? MF_CHECKED : MF_UNCHECKED, CMD_YDL_FORMAT_HIGH, L"High (1280x720)");
AppendMenuW(mpvYdl, gYdlFormat == 2 ? MF_CHECKED : MF_UNCHECKED, CMD_YDL_FORMAT_MEDIUM, L"Medium (852x480)");
AppendMenuW(mpvYdl, gYdlFormat == 3 ? MF_CHECKED : MF_UNCHECKED, CMD_YDL_FORMAT_LOW, L"Low (640x360)");
AppendMenuW(mpvYdl, gYdlFormat == 4 ? MF_CHECKED : MF_UNCHECKED, CMD_YDL_FORMAT_MOBILE, L"Mobile (400x226)");
HMENU settings = CreatePopupMenu();
Assert(settings);
AppendMenuW(settings, gUseLivestreamer ? MF_CHECKED : MF_UNCHECKED, CMD_USE_LIVESTREAMER, L"Use livestreamer");
AppendMenuW(settings, gUseLivestreamer ? MF_STRING : MF_GRAYED, CMD_EDIT_LIVESTREAMERRC, L"Edit livestreamerrc file");
AppendMenuW(settings, MF_SEPARATOR, 0, NULL);
AppendMenuW(settings, gUseMpvYdl ? MF_CHECKED : MF_UNCHECKED, CMD_USE_MPV_YDL, L"Use mpv && youtube-dl");
AppendMenuW(settings, (gUseMpvYdl ? 0 : MF_GRAYED) | MF_POPUP, (UINT_PTR)mpvYdl, L"youtube-dl format");
HMENU users = CreatePopupMenu();
Assert(users);
for (int i = 0; i < gUserCount; i++)
{
struct User user = gUsers[i];
if (user.online)
{
// TODO(bk): Play around with the size of the buffer. If the game
// length is the max length, the menu will expand for the
// full length. It looks weird. Is this what is wanted?
WCHAR game[MAX_GAME_NAME_LENGTH];
int result;
if (user.game[0] == '\0')
{
result = SUCCEEDED(StringCbCopyW(game, _countof(game),
L" Playing unknown game")) ? 1 : 0;
}
else
{
result = wnsprintfW(game, _countof(game),
L" Playing: %s", user.game);
}
Assert(result > 0 && result < MAX_GAME_NAME_LENGTH);
AppendMenuW(users, MF_CHECKED, (i + 1) << 8, user.name);
if (result)
{
AppendMenuW(users, MF_GRAYED, 0, game);
}
}
else
{
AppendMenuW(users, MF_STRING, (i + 1) << 8, user.name);
}
}
HMENU menu = CreatePopupMenu();
Assert(menu);
#ifdef TWITCH_NOTIFY_VERSION
AppendMenuW(menu, MF_STRING, CMD_OPEN_HOMEPAGE, L"Twitch Notify (" TWITCH_NOTIFY_VERSION ")");
#else
AppendMenuW(menu, MF_STRING, CMD_OPEN_HOMEPAGE, L"Twitch Notify");
#endif
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(menu, gActive ? MF_CHECKED : MF_UNCHECKED, CMD_TOGGLE_ACTIVE, L"Active");
AppendMenuW(menu, MF_POPUP, (UINT_PTR)settings, L"Settings");
AppendMenuW(menu, MF_STRING, CMD_EDIT_CONFIG_FILE, L"Modify user list");
if (gUserCount == 0)
{
AppendMenuW(menu, MF_GRAYED, 0, L"No users found");
}
else
{
AppendMenuW(menu, MF_POPUP, (UINT_PTR)users, L"Users");
}
AppendMenuW(menu, MF_SEPARATOR, 0, NULL);
AppendMenuW(menu, MF_STRING, CMD_QUIT, L"Exit");
POINT mouse;
GetCursorPos(&mouse);
SetForegroundWindow(window);
int cmd = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY, mouse.x, mouse.y, 0, window, NULL);
switch (cmd)
{
case CMD_OPEN_HOMEPAGE:
OpenHomePage();
break;
case CMD_TOGGLE_ACTIVE:
ToggleActive(window);
break;
case CMD_USE_LIVESTREAMER:
ToggleLivestreamer();
break;
case CMD_EDIT_LIVESTREAMERRC:
EditLivestreamerConfig();
break;
case CMD_USE_MPV_YDL:
ToggleMpvYdl();
break;
case CMD_YDL_FORMAT_SOURCE:
case CMD_YDL_FORMAT_HIGH:
case CMD_YDL_FORMAT_MEDIUM:
case CMD_YDL_FORMAT_LOW:
case CMD_YDL_FORMAT_MOBILE:
gYdlFormat = cmd - CMD_YDL_FORMAT_SOURCE;
break;
case CMD_EDIT_CONFIG_FILE:
EditConfigFile();
break;
case CMD_QUIT:
DestroyWindow(window);
break;
default:
OpenTwitchUser((cmd >> 8) - 1);
break;
}
DestroyMenu(menu);
DestroyMenu(users);
DestroyMenu(settings);
DestroyMenu(mpvYdl);
}
else if (lparam == NIN_BALLOONUSERCLICK)
{
if (gLastPopupUserIndex != -1)
{
OpenTwitchUser(gLastPopupUserIndex);
gLastPopupUserIndex = -1;
}
}
else if (lparam == WM_LBUTTONDBLCLK)
{
OpenHomePage();
}
break;
}
case WM_TWITCH_NOTIFY_REMOVE_USERS:
{
gUserCount = 0;
return 0;
}
case WM_TWITCH_NOTIFY_ADD_USER:
{
if (gUserCount < (int)_countof(gUsers))
{
struct User* user = gUsers + gUserCount++;
StrCpyNW(user->name, (PCWSTR)wparam, _countof(user->name));
user->>
}
return 0;
}
case WM_TWITCH_NOTIFY_START_UPDATE:
{
for (int i = 0; i < gUserCount; i++)
{
gUsers[i].>
}
return 0;
}
case WM_TWITCH_NOTIFY_USER_ONLINE:
{
struct UserStatusOnline* status = (void*)wparam;
for (int i = 0; i < gUserCount; i++)
{
struct User* user = gUsers + i;
if (StrCmpW(user->name, status->user) == 0)
{
if (user-> 0)
{
gLastPopupUserIndex = i;
ShowUserOnlineNotification(status);
}
StringCbCopyW(user->game, _countof(user->game), status->game);
user->>
break;
}
}
if (status->icon)
{
DestroyIcon(status->icon);
}
return 0;
}
case WM_TWITCH_NOTIFY_END_UPDATE:
{
for (int i = 0; i < gUserCount; i++)
{
// -1 means user was online, now is offline
// 0 means user was and now is offline
// +1 means user now is online
gUsers[i]. > 0;
}
return 0;
}
case WM_TWITCH_NOTIFY_UPDATE_ERROR:
{
gLastPopupUserIndex = -1;
ShowNotification((LPWSTR)wparam, (LPWSTR)lparam, NIIF_ERROR, NULL);
return 0;
}
case WM_TWITCH_NOTIFY_ALREADY_RUNNING:
{
gLastPopupUserIndex = -1;
ShowNotification(TWITCH_NOTIFY_TITLE L" is already running!", NULL, NIIF_INFO, NULL);
return 0;
}
case WM_TIMER:
{
if (wparam == UPDATE_USERS_TIMER_ID)
{
SetEvent(gUpdateEvent);
}
else if (wparam == RELOAD_CONFIG_TIMER_ID)
{
SetEvent(gConfigEvent);
KillTimer(window, RELOAD_CONFIG_TIMER_ID);
}
else if (wparam == SKIP_ERRORS_TIMER_ID)
{
gHideErrors = FALSE;
KillTimer(window, SKIP_ERRORS_TIMER_ID);
}
return 0;
}
default:
if (WM_TASKBARCREATED && msg == WM_TASKBARCREATED)
{
AddTrayIcon(window);
return 0;
}
break;
}
return DefWindowProcW(window, msg, wparam, lparam);
}
static int DownloadURL(WCHAR* url, WCHAR* headers, char* data, DWORD* dataLength)
{
DWORD flags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_KEEP_CONNECTION |
INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE;
HINTERNET connection = InternetOpenUrlW(gInternet, url, headers, (DWORD)-1, flags, 0);
if (!connection)
{
return 0;
}
DWORD downloaded = 0;
DWORD available = *dataLength;
int result = 1;
for (;;)
{
DWORD read;
if (InternetReadFile(connection, data + downloaded, available, &read))
{
if (read == 0)
{
break;
}
downloaded += read;
}
else
{
result = read == 0;
break;
}
}
InternetCloseHandle(connection);
*dataLength = downloaded;
return result;
}
// http://www.isthe.com/chongo/tech/comp/fnv/
static UINT64 GetFnv1Hash(BYTE* bytes, size_t size)
{
UINT64 hash = 14695981039346656037ULL;
for (size_t i = 0; i < size; i++)
{
hash *= 1099511628211ULL;
hash ^= bytes[i];
}
return hash;
}
static int GetUserIconCachePath(WCHAR* path, DWORD size, UINT64 hash)
{
DWORD length = GetTempPathW(size, path);
if (length)
{
wnsprintfW(path + length, size - length, L"%016I64x.ico", hash);
return 1;
}
return 0;
}
static void SaveIconToCache(UINT64 hash, UINT width, UINT height, BYTE* pixels)
{
WCHAR path[MAX_PATH];
if (!GetUserIconCachePath(path, _countof(path), hash))
{
return;
}
DWORD size = width * height * 4;
struct ICONDIR
{
WORD idReserved;
WORD idType;
WORD idCount;
} dir = {
.idType = 1,
.idCount = 1,
};
struct ICONDIRENTRY
{
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
DWORD dwImageOffset;
} entry = {
.bWidth = (BYTE)(width == MAX_WINDOWS_ICON_SIZE ? 0 : width),
.bHeight = (BYTE)(height == MAX_WINDOWS_ICON_SIZE ? 0 : height),
.wPlanes = 1,
.wBitCount = 32,
.dwBytesInRes = sizeof(BITMAPINFOHEADER) + size + size/32,
.dwImageOffset = sizeof(dir) + sizeof(entry),
};
BITMAPINFOHEADER bmp =
{
.biSize = sizeof(bmp),
.biWidth = width,
.biHeight = 2 * height,
.biPlanes = 1,
.biBitCount = 32,
.biSizeImage = size + size / 32,
};
for (UINT y = 0; y < height / 2; y++)
{
DWORD* row0 = (DWORD*)(pixels + y * width * 4);
DWORD* row1 = (DWORD*)(pixels + (height - 1 - y) * width * 4);
for (UINT x = 0; x < width; x++)
{
DWORD tmp = *row0;
*row0++ = *row1;
*row1++ = tmp;
}
}
HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (file != INVALID_HANDLE_VALUE)
{
DWORD written;
WriteFile(file, &dir, sizeof(dir), &written, NULL);
WriteFile(file, &entry, sizeof(entry), &written, NULL);
WriteFile(file, &bmp, sizeof(bmp), &written, NULL);
WriteFile(file, pixels, size, &written, NULL);
SetFilePointer(file, size / 32, NULL, FILE_CURRENT); // and-mask, 1bpp
SetEndOfFile(file);
CloseHandle(file);
}
}
static HICON DecodeIconAndSaveToCache(UINT64 hash, void* data, DWORD length)
{
if (!gWicFactory)
{
return NULL;
}
IStream* stream = SHCreateMemStream(data, length);
if (!stream)
{
return NULL;
}
HICON icon = NULL;
HRESULT hr;
IWICBitmapDecoder* decoder;
hr = IWICImagingFactory_CreateDecoderFromStream(gWicFactory, stream, NULL, WICDecodeMetadataCacheOnDemand,
&decoder);
if (SUCCEEDED(hr))
{
IWICBitmapFrameDecode* frame;
hr = IWICBitmapDecoder_GetFrame(decoder, 0, &frame);
if (SUCCEEDED(hr))
{
IWICFormatConverter* bitmap;
hr = IWICImagingFactory_CreateFormatConverter(gWicFactory, &bitmap);
if (SUCCEEDED(hr))
{
hr = IWICFormatConverter_Initialize(bitmap, (IWICBitmapSource*)frame,
&GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, NULL, 0., WICBitmapPaletteTypeCustom);
if (SUCCEEDED(hr))
{
UINT w, h;
if (SUCCEEDED(IWICBitmapFrameDecode_GetSize(bitmap, &w, &h)))
{
IWICBitmapSource* source = NULL;
if (w > MAX_WINDOWS_ICON_SIZE || h > MAX_WINDOWS_ICON_SIZE)
{
if (w > MAX_WINDOWS_ICON_SIZE)
{
h = h * MAX_WINDOWS_ICON_SIZE / w;
w = MAX_WINDOWS_ICON_SIZE;
}
if (h > MAX_WINDOWS_ICON_SIZE)
{
h = MAX_WINDOWS_ICON_SIZE;
w = w * MAX_WINDOWS_ICON_SIZE / h;
}
IWICBitmapScaler* scaler;
hr = IWICImagingFactory_CreateBitmapScaler(gWicFactory, &scaler);
if (SUCCEEDED(hr))
{
hr = IWICBitmapScaler_Initialize(scaler, (IWICBitmapSource*)bitmap, w, h,
WICBitmapInterpolationModeCubic);
if (SUCCEEDED(hr))
{
hr = IWICBitmapScaler_QueryInterface(scaler, &IID_IWICBitmapSource, (void**)&source);
}
IWICBitmapScaler_Release(scaler);
}
}
else
{
hr = IWICBitmapScaler_QueryInterface(bitmap, &IID_IWICBitmapSource, (void**)&source);
}
if (SUCCEEDED(hr))
{
Assert(source);
Assert(w <= MAX_WINDOWS_ICON_SIZE && h <= MAX_WINDOWS_ICON_SIZE);
DWORD stride = w * 4;
DWORD size = w * h * 4;
BYTE pixels[MAX_WINDOWS_ICON_SIZE * MAX_WINDOWS_ICON_SIZE * 4];
if (SUCCEEDED(IWICBitmapFrameDecode_CopyPixels(source, NULL, stride, size, pixels)))
{
icon = CreateIcon(NULL, w, h, 1, 32, NULL, pixels);
SaveIconToCache(hash, w, h, pixels);
}
IWICBitmapSource_Release(source);
}
}
}
IWICFormatConverter_Release(bitmap);
}
IWICBitmapFrameDecode_Release(frame);
}
IWICBitmapFrameDecode_Release(decoder);
}
IStream_Release(stream);
return icon;
}
static HICON LoadUserIconFromCache(UINT64 hash)
{
WCHAR path[MAX_PATH];
if (!GetUserIconCachePath(path, _countof(path), hash))
{
return NULL;
}
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(path, GetFileExInfoStandard, &data))
{
UINT64 lastWrite = (((UINT64)data.ftLastWriteTime.dwHighDateTime) << 32) +
data.ftLastWriteTime.dwLowDateTime;
FILETIME nowTime;
GetSystemTimeAsFileTime(&nowTime);
UINT64 now = (((UINT64)nowTime.dwHighDateTime) << 32) + nowTime.dwLowDateTime;
UINT64 expires = lastWrite + (UINT64)MAX_ICON_CACHE_AGE * 10 * 1000 * 1000;
if (expires < now)
{
return NULL;
}
return LoadImageW(NULL, path, IMAGE_ICON, 0, 0, LR_LOADFROMFILE);
}
return NULL;
}
static HICON GetUserIcon(WCHAR* url, int urlLength, char* downloadBuffer)
{
UINT64 hash = GetFnv1Hash((BYTE*)url, urlLength * sizeof(WCHAR));
HICON icon = LoadUserIconFromCache(hash);
if (icon)
{
return icon;
}
DWORD dataLength = MAX_DOWNLOAD_SIZE;
if (DownloadURL(url, NULL, downloadBuffer, &dataLength))
{
icon = DecodeIconAndSaveToCache(hash, downloadBuffer, dataLength);
}
return icon;
}
static int jsoneq(const char* json, jsmntok_t* token, const char* str)
{
if (token->type != JSMN_STRING)
{
return 0;
}
const char* ptr = json + token->start;
int length = token->end - token->start;
while (*str)
{
if (length == 0 || *ptr++ != *str++)
{
return 0;
}
length--;
}
return length == 0;
}
static int ConvertJsonStringToW(char* src, int length, WCHAR* dst, int dstLength)
{
char* read = src;
char* write = src;
while (length --> 0)
{
char ch = *read++;
if (ch == '\\')
{
if (length == 0)
{
break;
}
ch = *read++;
--length;
if (ch == '"') *write++ = L'"';
else if (ch == '\\') *write++ = L'\\';
else if (ch == '/') *write++ = L'/';
else if (ch == 'b') *write++ = L'\b';
else if (ch == 'f') *write++ = L'\f';
else if (ch == 'n') *write++ = L'\n';
else if (ch == 'r') *write++ = L'\r';
else if (ch == 't') *write++ = L'\t';
else if (ch == 'u')
{
if (length < 4)
{
break;
}
int value;
char tmp = read[4];
read[-2] = '0';
read[-1] = 'x';
read[4] = 0;
BOOL ok = StrToIntEx(read - 2, STIF_SUPPORT_HEX, &value);
Assert(ok);
read[4] = tmp;
read += 4;
length -= 4;
if (value >= 0xd800 && value <= 0xdfff)
{
if (length < 6 || read[0] != '\\' || read[1] != 'u')
{
break;
}
int value2;
tmp = read[6];
read[0] = '0';
read[1] = 'x';
read[6] = 0;
ok = StrToIntEx(read, STIF_SUPPORT_HEX, &value2);
Assert(ok);
read[6] = tmp;
read += 6;
length -= 6;
if (value2 < 0xdc00 || value2 >= 0xdfff)
{
break;
}
value = ((value - 0xd800) << 10) + (value2 - 0xdc00) + 0x10000;
}
You can’t perform that action at this time.