forked from steveseguin/social_stream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgiveaway.html
More file actions
1826 lines (1562 loc) · 79.8 KB
/
Copy pathgiveaway.html
File metadata and controls
1826 lines (1562 loc) · 79.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Giveaway Wheel</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
animation: {
'spin-slow': 'spin 3s linear infinite',
'spin-fast': 'spin 0.5s linear infinite',
'bounce-gentle': 'bounce 2s infinite',
'pulse-slow': 'pulse 3s infinite',
'wheel-spin': 'wheel-spin 4s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards',
},
keyframes: {
'wheel-spin': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(1800deg)' }
}
},
colors: {
'wheel-primary': '#667eea',
'wheel-secondary': '#764ba2',
}
}
}
}
</script>
<style>
/* Modern wheel styles with material design */
#wheel-canvas {
border: none;
border-radius: 50%;
background: transparent;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
filter: drop-shadow(0 8px 32px rgba(0, 0, 0, 0.15));
}
#wheel-canvas:hover {
filter: drop-shadow(0 12px 40px rgba(0, 0, 0, 0.2));
transform: scale(1.02);
}
.wheel-container {
position: relative;
display: inline-block;
}
.wheel-glow {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
border-radius: 50%;
background: radial-gradient(circle, rgba(103, 126, 234, 0.1) 0%, transparent 70%);
animation: pulse 3s ease-in-out infinite;
pointer-events: none;
}
@keyframes pulse {
0%, 100% { opacity: 0.5; transform: translate(-50%, -50%) scale(1); }
50% { opacity: 0.8; transform: translate(-50%, -50%) scale(1.05); }
}
.spinning {
animation: none !important;
}
.winner-announcement {
animation: winnerPop 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
@keyframes winnerPop {
0% { transform: scale(0.8); opacity: 0; }
50% { transform: scale(1.1); }
100% { transform: scale(1); opacity: 1; }
}
/* Legacy pointer and center (hidden since we draw them on canvas now) */
.wheel-pointer {
display: none;
}
.wheel-center {
display: none;
}
/* Minimal custom styles for elements that can't be easily replicated with Tailwind */
.confetti {
position: fixed;
width: 10px;
height: 10px;
background: #f94144;
z-index: 1000;
pointer-events: none;
}
/* OBS Mode Styles */
.obs-mode {
background: transparent !important;
padding: 0 !important;
}
.obs-mode .container {
background: transparent;
box-shadow: none;
}
.obs-mode h1 {
display: none;
}
.obs-mode .controls {
display: none;
}
.obs-mode .entrants-list {
display: none;
}
@media (max-width: 768px) {
.wheel-container {
width: 300px;
height: 300px;
}
h1 {
font-size: 2em;
}
.input-group {
flex-direction: column;
}
input[type="text"] {
min-width: 250px;
}
}
</style>
</head>
<body class="min-h-screen bg-gradient-to-br from-wheel-primary via-purple-600 to-wheel-secondary flex flex-col items-center justify-center text-white font-sans">
<div class="text-center max-w-4xl w-full px-6 py-8">
<h1 class="text-5xl md:text-6xl font-bold mb-8 text-transparent bg-clip-text bg-gradient-to-r from-yellow-400 via-pink-500 to-purple-600 drop-shadow-lg animate-pulse-slow">
🎯 Giveaway Wheel
</h1>
<div class="wheel-container relative w-96 h-96 md:w-[400px] md:h-[400px] mx-auto my-8 flex items-center justify-center group">
<div class="wheel-glow"></div>
<canvas id="wheel-canvas" class="rounded-full transition-transform duration-100 ease-out" width="400" height="400"></canvas>
</div>
<div class="hidden bg-gradient-to-r from-yellow-400 via-yellow-500 to-amber-500 text-gray-900 p-6 rounded-2xl my-6 text-2xl font-bold shadow-2xl border-4 border-yellow-300 animate-bounce-gentle" id="winner-display"></div>
<div class="space-y-6 mt-8">
<div class="bg-white/10 backdrop-blur-md p-6 rounded-2xl border border-white/20 shadow-xl">
<h3 class="text-2xl font-bold mb-4 text-center">🔑 Entry Keyword</h3>
<div class="text-2xl text-yellow-400 font-bold text-center my-4">
Current Keyword: <span class="bg-yellow-400 text-gray-900 px-3 py-1 rounded-lg" id="current-keyword">ENTER</span>
</div>
<div class="text-sm text-gray-300 text-center mb-4">
Viewers type this keyword in chat to enter the giveaway
</div>
<div class="flex flex-col sm:flex-row gap-3 items-center justify-center mb-4">
<input type="text" id="keyword-input" placeholder="Enter new keyword..."
class="px-4 py-3 rounded-lg border-2 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 text-gray-900 font-medium min-w-0 flex-1">
<button onclick="setKeyword()"
class="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
Set Keyword
</button>
</div>
<button onclick="openOBSWidget()"
class="w-full px-6 py-3 bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
📺 Open OBS Widget
</button>
</div>
<div class="flex flex-col sm:flex-row gap-3 items-center justify-center">
<input type="text" id="entrant-name" placeholder="Enter participant name"
class="px-4 py-3 rounded-lg border-2 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 text-gray-900 font-medium min-w-0 flex-1">
<select id="platform-select"
class="px-4 py-3 rounded-lg border-2 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all duration-200 text-gray-900 font-medium">
<option value="twitch">Twitch</option>
<option value="youtube">YouTube</option>
<option value="facebook">Facebook</option>
<option value="instagram">Instagram</option>
<option value="tiktok">TikTok</option>
<option value="discord">Discord</option>
<option value="kick">Kick</option>
</select>
<button onclick="addEntrant()"
class="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
Add Participant
</button>
</div>
<div class="flex flex-wrap gap-3 items-center justify-center">
<button onclick="spinWheel()" id="spin-btn"
class="px-8 py-4 bg-gradient-to-r from-red-500 via-pink-500 to-red-600 hover:from-red-600 hover:via-pink-600 hover:to-red-700 text-white font-bold rounded-xl transition-all duration-200 transform hover:scale-110 hover:shadow-2xl text-lg motion-safe:hover:animate-pulse">
🎯 Spin the Wheel!
</button>
<button onclick="clearEntrants()"
class="px-6 py-3 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
Clear All
</button>
<button onclick="addTestData()"
class="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
Add Test Data
</button>
<button onclick="clearAllEntries()"
class="px-6 py-3 bg-gradient-to-r from-red-600 to-red-700 hover:from-red-700 hover:to-red-800 text-white font-bold rounded-lg transition-all duration-200 transform hover:scale-105 hover:shadow-lg">
🗑️ Clear All Entries
</button>
</div>
</div>
<div class="bg-white/10 backdrop-blur-md p-6 rounded-2xl border border-white/20 shadow-xl mt-8">
<h3 class="text-2xl font-bold mb-4 text-center">
Participants (<span class="text-yellow-400" id="entrant-count">0</span>)
</h3>
<div id="entrants-container" class="space-y-2 max-h-64 overflow-y-auto scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent"></div>
</div>
</div>
<script>
// 🐛 DEBUGGING VARIABLES
let messageCount = 0;
let debugStartTime = new Date();
console.log('🎯 GIVEAWAY PAGE LOADED');
console.log('⏰ Load time:', debugStartTime.toISOString());
console.log('🌐 Page URL:', window.location.href);
console.log('📱 User Agent:', navigator.userAgent);
console.log('🔧 Console debugging enabled');
// Global state
let entrants = {};
let isSpinning = false;
let isOBSMode = false;
let currentKeyword = 'ENTER';
let currentRotation = 0; // Track wheel rotation in radians (same as OBS widget)
// Social Stream WebRTC integration
let iframe = null;
let roomID = "test";
let password = "false";
// Get session ID and password from URL parameters
console.log('🔍 PARSING URL PARAMETERS...');
const urlParams = new URLSearchParams(window.location.search);
console.log('📋 All URL params:', Array.from(urlParams.entries()));
if (urlParams.has("session")) {
roomID = urlParams.get("session");
console.log('✅ Found session parameter:', roomID);
} else if (urlParams.has("s")) {
roomID = urlParams.get("s");
console.log('✅ Found s parameter:', roomID);
} else if (urlParams.has("id")) {
roomID = urlParams.get("id");
console.log('✅ Found id parameter:', roomID);
} else {
console.log('❌ No session parameter found! Using default:', roomID);
console.log('💡 Add ?session=YOUR_SESSION_ID to the URL to connect');
}
if (urlParams.has("password")) {
password = urlParams.get("password") || "false";
console.log('🔑 Found password parameter:', password);
} else {
console.log('🔓 No password parameter found, using default:', password);
}
console.log('🎯 Final connection parameters:');
console.log(' 📋 Room ID:', roomID);
console.log(' 🔑 Password:', password);
// Platform icon cache
let platformIconCache = {};
// WebRTC iframe setup for Social Stream integration
function setupWebRTCConnection() {
console.log('🚀 Setting up WebRTC connection for giveaway...');
console.log('📋 Session ID:', roomID);
console.log('🔑 Password:', password);
// Always set up local communication channel first
setupLocalCommunication();
if (!roomID || roomID === "test") {
console.log("⚠️ Using test session - WebRTC will use local communication only");
return;
}
console.log('🔧🔧🔧 CREATING WEBRTC IFRAME 🔧🔧🔧');
console.log('📋 Session ID (roomID):', roomID);
console.log('🔐 Password:', password);
// Create hidden iframe for WebRTC connection (same pattern as dock.html)
iframe = document.createElement('iframe');
iframe.style.width = "0px";
iframe.style.height = "0px";
iframe.style.position = "fixed";
iframe.style.left = "-100px";
iframe.style.top = "-100px";
iframe.id = "frame1";
iframe.allow = "midi;geolocation;microphone;"; // microphone needed for Safari WebRTC P2P connections
console.log('🖼️ Iframe element created with ID:', iframe.id);
// Connect as a view-only client to receive chat messages (same as sampleoverlay.html pattern)
iframe.src = "https://vdo.socialstream.ninja/?ln&salt=vdo.ninja&password="+password+"&push&label=dock&vd=0&ad=0&novideo&noaudio&autostart&cleanoutput&room="+roomID;
console.log('🔗🔗🔗 IFRAME CONNECTION URL 🔗🔗🔗');
console.log('📍 Full URL:', iframe.src);
console.log('🏠 Base URL: https://vdo.socialstream.ninja/');
console.log('🎯 Room parameter: room=' + roomID);
console.log('🔐 Password parameter: password=' + password);
console.log('🏷️ Label parameter: label=giveaway');
console.log('⚙️ Other parameters: ln&salt=vdo.ninja&push&vd=0&ad=0&novideo&noaudio&autostart&cleanoutput');
document.body.appendChild(iframe);
console.log('✅ Iframe added to document body');
// Add iframe load event listener
iframe.onload = function() {
console.log('🎉 IFRAME LOADED SUCCESSFULLY!');
console.log('📍 Iframe contentWindow:', iframe.contentWindow);
};
iframe.onerror = function(error) {
console.log('❌ IFRAME LOAD ERROR:', error);
};
// Set up message listener for WebRTC data (same simple pattern as sampleoverlay.html)
window.addEventListener("message", function (e) {
console.log('🔥🔥🔥 RAW MESSAGE RECEIVED FROM IFRAME 🔥🔥🔥');
console.log('📨 Full event object:', e);
console.log('📦 Event data:', e.data);
console.log('🌐 Event origin:', e.origin);
console.log('📍 Event source:', e.source);
console.log('🖼️ Iframe source check:', e.source === iframe.contentWindow);
console.log('⏰ Timestamp:', new Date().toISOString());
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
if (e.source != iframe.contentWindow) {
console.log('❌ REJECTED: Message not from our iframe');
return;
} // reject messages send from other iframes
console.log('✅ MESSAGE SOURCE VERIFIED - Processing...');
if (e.data.dataReceived && e.data.dataReceived.overlayNinja) {
console.log('🎉 FOUND CHAT MESSAGE via WebRTC! (sampleoverlay pattern)');
console.log('💬 Chat data:', e.data.dataReceived.overlayNinja);
processGiveawayMessage(e.data.dataReceived.overlayNinja);
} else {
console.log('❓ UNKNOWN MESSAGE FORMAT - NOT PROCESSING');
console.log('🔍 Data type:', typeof e.data);
console.log('🔍 Data keys:', e.data ? Object.keys(e.data) : 'No data object');
console.log('🔍 Raw data:', JSON.stringify(e.data, null, 2));
}
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
});
console.log(`🎯 Giveaway connected to Social Stream WebRTC with session: ${roomID}`);
}
// Local communication setup for when WebRTC session is not available
function setupLocalCommunication() {
// Use BroadcastChannel API for local communication between tabs
if (typeof BroadcastChannel !== 'undefined') {
const channel = new BroadcastChannel('giveaway_' + roomID);
channel.addEventListener('message', function(event) {
console.log('📥 Received local broadcast:', event.data);
handleLocalMessage(event.data);
});
// Store channel for broadcasting
window.giveawayChannel = channel;
console.log('📡 Local communication channel established');
} else {
// Fallback to localStorage for older browsers
console.log('📡 Using localStorage fallback for local communication');
window.addEventListener('storage', function(e) {
if (e.key === 'giveaway_broadcast_' + roomID) {
try {
const data = JSON.parse(e.newValue);
handleLocalMessage(data);
} catch (error) {
console.error('Error processing localStorage message:', error);
}
}
});
}
}
// Handle messages from local communication
function handleLocalMessage(data) {
if (data.action === 'giveaway_update') {
handleGiveawayUpdate(data.data);
} else if (data.action === 'keyword_update') {
handleKeywordUpdate(data.keyword);
} else if (data.action === 'spin_update') {
handleSpinUpdate(data.data);
} else if (data.action === 'winner_update') {
handleWinnerUpdate(data.data);
}
}
// WebSocket fallback implementation (same pattern as dock.html)
var conCon = 1;
var socketserver = false;
var serverURL = urlParams.has("localserver") ? "ws://127.0.0.1:3000" : "wss://io.socialstream.ninja/api";
var reconnectionTimeout = null;
function setupSocket() {
// Clear any existing reconnection timeout
if (reconnectionTimeout) {
clearTimeout(reconnectionTimeout);
reconnectionTimeout = null;
}
if (socketserver) {
socketserver.onclose = null;
socketserver.close();
socketserver = null;
}
socketserver = new WebSocket(serverURL);
socketserver.onclose = function () {
reconnectionTimeout = setTimeout(function () {
conCon += 1;
setupSocket();
}, 100 * conCon);
};
socketserver.onopen = function () {
conCon = 1;
// Use channel 5 for giveaway communication (out: 5, in: 6)
socketserver.send(JSON.stringify({ join: roomID.split(",")[0], out: 5, in: 6 }));
console.log("Giveaway WebSocket: output channel: 5, input channel: 6");
};
socketserver.onerror = function (error) {
console.error("WebSocket error:", error);
socketserver.close();
};
socketserver.addEventListener("message", function (event) {
if (event.data) {
try {
var data = JSON.parse(event.data);
// Handle giveaway-specific messages
if (data.action === 'giveaway_update') {
handleGiveawayUpdate(data.data);
} else if (data.action === 'keyword_update') {
handleKeywordUpdate(data.keyword);
} else if (data.action === 'spin_update') {
handleSpinUpdate(data.data);
} else if (data.action === 'winner_update') {
handleWinnerUpdate(data.data);
} else if (data.chatname || data.chatmessage) {
processGiveawayMessage(data);
}
} catch (e) {
console.error("Error processing WebSocket message:", e);
}
}
});
}
// Enable WebSocket if server parameter is provided
if (urlParams.has("server")) {
serverURL = urlParams.get("server") || serverURL;
setupSocket();
}
// WebSocket fallback debugging function
function testWebSocketConnection() {
console.log('🔄 TESTING WEBSOCKET FALLBACK...');
const wsUrl = `wss://api.socialstream.ninja/ws?session=${roomID}&password=${password}`;
console.log('🔗 WebSocket URL:', wsUrl);
try {
const ws = new WebSocket(wsUrl);
ws.onopen = function() {
console.log('✅ WebSocket connection opened successfully!');
console.log('📡 This means the session ID is valid');
};
ws.onmessage = function(event) {
console.log('📨 WebSocket message received:', event.data);
try {
const data = JSON.parse(event.data);
console.log('📊 Parsed WebSocket data:', data);
if (data.chatname && data.chatmessage) {
console.log('🎯 FOUND CHAT DATA VIA WEBSOCKET:');
console.log(' - chatname:', data.chatname);
console.log(' - chatmessage:', data.chatmessage);
}
} catch (e) {
console.log('❌ Failed to parse WebSocket data:', e);
}
};
ws.onerror = function(error) {
console.log('❌ WebSocket error:', error);
};
ws.onclose = function(event) {
console.log('🔌 WebSocket closed:', event.code, event.reason);
};
// Close after 30 seconds
setTimeout(() => {
if (ws.readyState === WebSocket.OPEN) {
console.log('🔌 Closing WebSocket test connection');
ws.close();
}
}, 30000);
} catch (error) {
console.log('❌ Failed to create WebSocket:', error);
}
}
// Add WebSocket test button to page for manual testing
function addWebSocketTestButton() {
const button = document.createElement('button');
button.textContent = '🔄 Test WebSocket';
button.style.position = 'fixed';
button.style.top = '10px';
button.style.left = '10px';
button.style.zIndex = '9999';
button.style.padding = '10px';
button.style.backgroundColor = '#2196F3';
button.style.color = 'white';
button.style.border = 'none';
button.style.borderRadius = '5px';
button.style.cursor = 'pointer';
button.onclick = testWebSocketConnection;
document.body.appendChild(button);
console.log('🔘 Added WebSocket test button to page');
}
// Process incoming chat messages for giveaway entries
function processGiveawayMessage(data) {
console.log("🚀🚀🚀 PROCESS GIVEAWAY MESSAGE CALLED 🚀🚀🚀");
console.log("⏰ Timestamp:", new Date().toISOString());
console.log("📦 Input data:", data);
console.log("🔍 RAW DATA TYPE:", typeof data);
console.log("🔍 RAW DATA STRUCTURE:", JSON.stringify(data, null, 2));
// Comprehensive data analysis
console.log("🔍 DETAILED DATA BREAKDOWN:");
console.log(" - chatname:", data.chatname || "❌ NOT FOUND");
console.log(" - chatmessage:", data.chatmessage || "❌ NOT FOUND");
console.log(" - type:", data.type || "❌ NOT FOUND");
console.log(" - All data keys:", Object.keys(data));
console.log(" - Data length:", Object.keys(data).length);
// Check for nested structures
if (data.data) {
console.log("🔍 NESTED DATA FOUND:");
console.log(" - data.data:", data.data);
console.log(" - data.data keys:", Object.keys(data.data || {}));
}
// Check for alternative field names
console.log("🔍 ALTERNATIVE FIELD CHECK:");
console.log(" - username:", data.username || "❌ NOT FOUND");
console.log(" - user:", data.user || "❌ NOT FOUND");
console.log(" - name:", data.name || "❌ NOT FOUND");
console.log(" - message:", data.message || "❌ NOT FOUND");
console.log(" - text:", data.text || "❌ NOT FOUND");
console.log(" - content:", data.content || "❌ NOT FOUND");
// Show a visual indicator that a message was received
const indicator = document.createElement('div');
indicator.textContent = '📨 Message received';
indicator.style.position = 'fixed';
indicator.style.top = '10px';
indicator.style.right = '10px';
indicator.style.backgroundColor = '#4CAF50';
indicator.style.color = 'white';
indicator.style.padding = '10px';
indicator.style.borderRadius = '5px';
indicator.style.zIndex = '9999';
document.body.appendChild(indicator);
// Remove the indicator after 2 seconds
setTimeout(() => {
indicator.style.opacity = '0';
indicator.style.transition = 'opacity 0.5s';
setTimeout(() => indicator.remove(), 500);
}, 2000);
// Use same validation logic as sampleoverlay.html - more permissive
if (!data.chatname && !data.chatmessage && !data.hasDonation && !data.donation && !data.contentimg) {
console.log("No valid message data found:", data);
return;
}
// Show warning if missing expected fields but continue processing
if (!data.chatname || !data.chatmessage) {
console.log("⚠️ Warning - missing some fields:", {
chatname: data.chatname,
chatmessage: data.chatmessage,
type: data.type
});
// Show warning indicator but don't return
const warningIndicator = document.createElement('div');
warningIndicator.textContent = '⚠️ Partial data: ' +
(!data.chatname ? 'no chatname ' : '') +
(!data.chatmessage ? 'no chatmessage ' : '');
warningIndicator.style.position = 'fixed';
warningIndicator.style.top = '60px';
warningIndicator.style.right = '10px';
warningIndicator.style.backgroundColor = '#FF9800';
warningIndicator.style.color = 'white';
warningIndicator.style.padding = '10px';
warningIndicator.style.borderRadius = '5px';
warningIndicator.style.zIndex = '9999';
document.body.appendChild(warningIndicator);
// Remove the warning indicator after 2 seconds
setTimeout(() => {
warningIndicator.style.opacity = '0';
warningIndicator.style.transition = 'opacity 0.5s';
setTimeout(() => warningIndicator.remove(), 500);
}, 2000);
}
// Handle missing chatname or chatmessage gracefully
const chatname = data.chatname || 'Unknown User';
const chatmessage = data.chatmessage || '';
const platform = data.type || 'unknown';
console.log(`Processing message from ${chatname} (${platform}): "${chatmessage}"`);
// Only check keyword if we have a message
if (chatmessage) {
// Check if message contains the current keyword
const message = chatmessage.toLowerCase().trim();
const keyword = currentKeyword.toLowerCase();
console.log(`Checking if "${message}" contains keyword "${keyword}"`);
if (message.includes(keyword)) {
console.log("Keyword match found!");
// Add user to giveaway
const entrantId = `${chatname}_${platform}`;
// Prevent duplicate entries
if (!entrants[entrantId]) {
entrants[entrantId] = {
name: chatname,
platform: platform,
timestamp: Date.now(),
originalMessage: chatmessage
};
console.log(`✅ New giveaway entry added: ${chatname} from ${platform}`);
updateDisplay();
saveState();
// Show success indicator
const successIndicator = document.createElement('div');
successIndicator.textContent = '✅ Added entry: ' + chatname;
successIndicator.style.position = 'fixed';
successIndicator.style.top = '160px';
successIndicator.style.right = '10px';
successIndicator.style.backgroundColor = '#2196F3';
successIndicator.style.color = 'white';
successIndicator.style.padding = '10px';
successIndicator.style.borderRadius = '5px';
successIndicator.style.zIndex = '9999';
document.body.appendChild(successIndicator);
// Remove the success indicator after 3 seconds
setTimeout(() => {
successIndicator.style.opacity = '0';
successIndicator.style.transition = 'opacity 0.5s';
setTimeout(() => successIndicator.remove(), 500);
}, 3000);
} else {
console.log(`❌ Duplicate entry prevented: ${data.chatname} from ${data.type}`);
// Show duplicate entry indicator
const dupIndicator = document.createElement('div');
dupIndicator.textContent = '🔄 Duplicate entry: ' + data.chatname;
dupIndicator.style.position = 'fixed';
dupIndicator.style.top = '110px';
dupIndicator.style.right = '10px';
dupIndicator.style.backgroundColor = '#FF9800';
dupIndicator.style.color = 'white';
dupIndicator.style.padding = '10px';
dupIndicator.style.borderRadius = '5px';
dupIndicator.style.zIndex = '9999';
document.body.appendChild(dupIndicator);
// Remove the duplicate indicator after 2 seconds
setTimeout(() => {
dupIndicator.style.opacity = '0';
dupIndicator.style.transition = 'opacity 0.5s';
setTimeout(() => dupIndicator.remove(), 500);
}, 2000);
}
} else {
console.log(`❌ No keyword match: "${message}" does not contain "${keyword}"`);
}
} else {
console.log("No message content to check for keyword");
}
}
// Check for OBS mode
if (urlParams.get('obs') === 'true') {
isOBSMode = true;
document.body.classList.add('obs-mode');
}
// Platform colors
function getPlatformColor(platform, index) {
const platformColors = {
'twitch': '#9146ff',
'youtube': '#ff0000',
'facebook': '#1877f2',
'instagram': '#e4405f',
'tiktok': '#000000',
'discord': '#5865f2',
'kick': '#53fc18'
};
return platformColors[platform?.toLowerCase()] || `hsl(${index * 137.5 % 360}, 70%, 60%)`;
}
// Preload platform icons
function preloadPlatformIcons(entrants, callback) {
const entrantsList = Object.values(entrants);
const uniquePlatforms = [...new Set(entrantsList.map(e => e.platform).filter(p => p))];
let loadedCount = 0;
const totalCount = uniquePlatforms.length;
if (totalCount === 0) {
callback();
return;
}
uniquePlatforms.forEach(platform => {
if (platformIconCache[platform]) {
loadedCount++;
if (loadedCount === totalCount) callback();
return;
}
const img = new Image();
img.onload = function() {
platformIconCache[platform] = img;
loadedCount++;
if (loadedCount === totalCount) callback();
};
img.onerror = function() {
platformIconCache[platform] = null;
loadedCount++;
if (loadedCount === totalCount) callback();
};
img.src = `./sources/images/${platform.toLowerCase()}.png`;
});
}
// Draw wheel function
function drawWheel(canvas, entrants) {
if (!canvas || !entrants) {
return;
}
// Ensure canvas size matches its container
const container = canvas.parentElement;
if (container) {
const containerRect = container.getBoundingClientRect();
if (containerRect.width > 0 && containerRect.height > 0) {
canvas.width = Math.min(containerRect.width, containerRect.height);
canvas.height = canvas.width;
}
}
// Preload platform icons first, then draw
preloadPlatformIcons(entrants, function() {
drawWheelWithIcons(canvas, entrants);
});
}
function drawWheelWithIcons(canvas, entrants) {
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(centerX, centerY) - 20;
const entrantsList = Object.values(entrants);
const segmentAngle = (2 * Math.PI) / entrantsList.length;
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw outer shadow for depth
ctx.save();
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
ctx.shadowBlur = 20;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 8;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.restore();
if (entrantsList.length === 0) {
// Draw modern empty wheel
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
// Modern gradient background
const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius);
gradient.addColorStop(0, '#f8f9fa');
gradient.addColorStop(1, '#e9ecef');
ctx.fillStyle = gradient;
ctx.fill();
// Modern border
ctx.strokeStyle = '#dee2e6';
ctx.lineWidth = 3;
ctx.stroke();
// Modern typography
ctx.fillStyle = '#6c757d';
ctx.font = '600 24px "Segoe UI", system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('Add participants to spin!', centerX, centerY);
return;
}
// Apply current rotation to wheel content (same as OBS widget)
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(currentRotation);
ctx.translate(-centerX, -centerY);
// Draw wheel segments with modern material design
entrantsList.forEach((entrant, index) => {
const startAngle = index * segmentAngle;
const endAngle = (index + 1) * segmentAngle;
// Get modern platform-specific color
const segmentColor = getModernPlatformColor(entrant.platform, index);
// Draw segment with gradient
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
// Create radial gradient for depth
const midAngle = startAngle + segmentAngle / 2;
const gradientX = centerX + Math.cos(midAngle) * radius * 0.3;
const gradientY = centerY + Math.sin(midAngle) * radius * 0.3;
const gradient = ctx.createRadialGradient(gradientX, gradientY, 0, centerX, centerY, radius);
gradient.addColorStop(0, segmentColor.light);
gradient.addColorStop(0.7, segmentColor.main);
gradient.addColorStop(1, segmentColor.dark);
ctx.fillStyle = gradient;
ctx.fill();
// Modern border with subtle shadow
ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
ctx.lineWidth = 3;
ctx.stroke();
// Add inner shadow for depth
ctx.save();
ctx.clip();
ctx.shadowColor = 'rgba(0, 0, 0, 0.2)';
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 2;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius - 2, startAngle, endAngle);
ctx.closePath();
ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)';
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
// Draw modern text and platform badge
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(startAngle + segmentAngle / 2);
// Position elements with modern spacing
const textRadius = radius - 60; // More space for modern design
const textX = textRadius;
const maxTextWidth = radius * 0.5;
// Modern typography with better contrast
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#ffffff';
ctx.font = '600 20px "Segoe UI", system-ui, -apple-system, sans-serif';
// Modern text shadow for depth
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 6;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 2;
const userName = entrant.name || 'Anonymous';
// Smart text truncation
let displayText = userName;
if (ctx.measureText(displayText).width > maxTextWidth) {
while (ctx.measureText(displayText + '...').width > maxTextWidth && displayText.length > 1) {
displayText = displayText.slice(0, -1);
}
displayText += '...';
}
// Draw username with modern styling
ctx.fillText(displayText, textX, -15);
// Draw modern platform icon
if (entrant.platform) {
const platformIcon = platformIconCache[entrant.platform];
if (platformIcon) {
// Modern icon design with material elevation
const iconSize = 28;
const iconX = textX - iconSize/2;
const iconY = 10;
// Draw modern icon background with elevation
ctx.save();
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 4;
ctx.beginPath();
ctx.arc(textX, iconY + iconSize/2, iconSize/2 + 6, 0, 2 * Math.PI);
ctx.fillStyle = '#ffffff';
ctx.fill();
ctx.restore();
// Draw subtle border
ctx.beginPath();
ctx.arc(textX, iconY + iconSize/2, iconSize/2 + 6, 0, 2 * Math.PI);
ctx.strokeStyle = 'rgba(0, 0, 0, 0.1)';
ctx.lineWidth = 1;
ctx.stroke();
// Draw platform icon
ctx.drawImage(platformIcon, iconX, iconY, iconSize, iconSize);
} else {
// Modern text badge design
const platformText = entrant.platform.substring(0, 3).toUpperCase();
ctx.font = '600 12px "Segoe UI", system-ui, sans-serif';
// Modern badge with material design
const badgeWidth = 40;
const badgeHeight = 24;
const badgeX = textX - badgeWidth/2;
const badgeY = 8;
// Badge shadow
ctx.save();
ctx.shadowColor = 'rgba(0, 0, 0, 0.3)';
ctx.shadowBlur = 6;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 3;
// Badge background with rounded corners effect
ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
ctx.fillRect(badgeX, badgeY, badgeWidth, badgeHeight);
ctx.restore();
// Badge border
ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
ctx.lineWidth = 1;
ctx.strokeRect(badgeX, badgeY, badgeWidth, badgeHeight);