-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
287 lines (232 loc) · 8.18 KB
/
Copy pathscript.js
File metadata and controls
287 lines (232 loc) · 8.18 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
const channelEl = document.getElementById("channel");
const counterEl = document.getElementById("counter");
const scoreEl = document.getElementById("score");
const timeEL = document.getElementById("time");
const infoTextEl = document.getElementById("info-text");
const mainEl = document.getElementById("main");
const btnEl = document.getElementById("start-button");
let timer = null;
let animationTimer = null;
let started = false;
let timerValue = 60;
let users = [];
let movieList = [];
let movieTitleCache = {};
const channel = new URLSearchParams(document.location.search).get("channel");
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
});
document.addEventListener('DOMContentLoaded', function() {
particlesJS.load('particles-js', './particlesjs-config.json', function() {
console.log('callback - particles.js config loaded');
});
});
initChannel();
function initChannel() {
if (channel) {
channelEl.innerHTML = `
Нажмите на кнопку, чтобы начать голование в чате twitch-канала
«${channel}».<br>Или измените название канала в URL-адресе.
`;
btnEl.disabled = false;
ComfyJS.Init(channel);
} else {
channelEl.innerHTML = `
Не указан twitch канал! К текущей ссылке добавьте «?channel=название_канала»
`;
}
}
function start() {
if (started) {
stop();
return;
}
if (channelEl) {
channelEl.style.display = "none";
}
mainEl.style.visibility = "visible";
btnEl.innerText = "СТОП";
btnEl.style.backgroundColor = "rgb(129, 93, 93)";
infoTextEl.innerHTML = `Голосование в чате «${channel}»!<br>
Напишите ID фильма с сайта «Кинопоиск»<br>`;
started = true;
timer = setInterval(onTimer, 1000);
timerToTime();
}
function stop() {
try { clearInterval(timer); } catch {}
btnEl.innerText = "СТАРТ";
btnEl.style.backgroundColor = "rgb(93, 129, 93)";
infoTextEl.innerHTML = "Голосование окончено!";
btnEl.disabled = true;
timeEL.style.display = "none";
if (users.length > 0) {
if (movieList.length === 1) {
showWinner(movieList[0]);
} else {
startAnimation();
}
} else {
scoreEl.innerHTML = "Никто не проголосовал x_x";
}
started = false;
}
async function messageHandler(user, message) {
if (!started) {
return;
}
if (users.includes(user)) {
return;
}
const cleanMessage = message.trim();
if (/^[\d\s]+$/.test(cleanMessage)) {
const movieId = cleanMessage;
const movieTitle = await fetchMovieTitle(movieId);
if (!movieTitle) {
return;
}
movieList.push(movieId);
showNewVote(user, movieTitle);
users.push(user);
counterEl.innerText = users.length;
}
}
function showNewVote(user, movieTitle) {
let el = document.createElement("div");
el.className = "new-vote";
el.innerText = `${user} предложил фильм: ${movieTitle}`;
let y = Math.floor(Math.random() * (window.innerHeight / 3 * 2)) + 100;
let x = Math.floor(Math.random() * (window.innerWidth / 3 * 2)) + 80;
el.style.top = `${y}px`;
el.style.left = `${x}px`;
document.body.appendChild(el);
setTimeout(() => {
document.body.removeChild(el);
}, 1500);
}
/**
* Показывает быструю анимацию с названиями фильмов, поочередно отображая их.
**/
async function startAnimation() {
let counter = 0;
const uniqueMovieIds = [...new Set(movieList)];
const titles = await Promise.all(uniqueMovieIds.map(fetchMovieTitle));
// Создаем контейнер для анимации
let animationContainer = document.createElement("div");
animationContainer.style.position = "absolute";
animationContainer.style.top = "50%";
animationContainer.style.left = "50%";
animationContainer.style.transform = "translate(-50%, -50%)";
animationContainer.style.whiteSpace = "nowrap";
animationContainer.style.fontSize = "60pt";
animationContainer.style.fontWeight = "bold";
animationContainer.style.display = "flex";
animationContainer.style.justifyContent = "center";
animationContainer.style.alignItems = "center";
animationContainer.style.userSelect = "none";
document.body.appendChild(animationContainer);
// Начальное отображение первого фильма
let el = document.createElement("span");
el.className = "movie-item";
el.innerText = truncateTitle(titles[0]);
animationContainer.appendChild(el);
let interval = setInterval(() => {
el.innerText = truncateTitle(titles[counter % titles.length]);
counter++;
}, 100);
// Ожидаем 5 секунд, чтобы завершить анимацию, и показываем победителя
setTimeout(() => {
clearInterval(interval);
showWinner();
}, 5000);
// Убираем контейнер после окончания анимации
setTimeout(() => {
document.body.removeChild(animationContainer);
}, 5000);
}
/**
* Возвращает ID победившего фильма, учитывая количество голосов.
* Чем больше голосов у фильма, тем выше шанс его выбора.
**/
function getWeightedWinner() {
const counts = {};
for (const movie of movieList) {
counts[movie] = (counts[movie] || 0) + 1;
}
const weightedList = [];
for (const [movie, count] of Object.entries(counts)) {
for (let i = 0; i < count; i++) {
weightedList.push(movie);
}
}
const winner = weightedList[Math.floor(Math.random() * weightedList.length)];
return winner;
}
/**
* Показывает победителя голосования.
**/
async function showWinner() {
let winnerId = getWeightedWinner();
let winnerTitle = await fetchMovieTitle(winnerId);
let winnerEl = document.getElementById('winner');
winnerEl.innerHTML = `EZ для «<b>${truncateTitle(winnerTitle)}</b>»`;
winnerEl.style.display = "block";
const nyanCat = document.getElementById('nyan-cat').classList.add('animate');
nyanCat.style.display = 'block';
nyanCat.style.left = '0';
let position = 0;
const interval = setInterval(() => {
position += 5;
nyanCat.style.left = position + 'px';
if (position > window.innerWidth) {
clearInterval(interval);
nyanCat.style.display = 'none';
}
}, 16);
}
function onTimer() {
timerValue -= 1;
if (timerValue > 0) {
timerToTime();
} else {
stop();
}
}
function timerToTime() {
let minutes = Math.floor(timerValue / 60);
let seconds = timerValue % 60;
minutes = minutes.toString().padStart(2, "0");
seconds = seconds.toString().padStart(2, "0");
let text = `${minutes}:${seconds}`;
timeEL.innerText = text;
}
function truncateTitle(title, maxLength = 30) {
return title.length > maxLength ? title.slice(0, maxLength - 3) + "..." : title;
}
/**
* Функция для получения названия фильма по его ID
* с помощью «Kinopoisk API Unofficial».
**/
async function fetchMovieTitle(id) {
if (movieTitleCache[id]) {
return movieTitleCache[id];
}
try {
const res = await fetch(`https://kinopoiskapiunofficial.tech/api/v2.2/films/${id}`, {
method: "GET",
headers: {
"X-API-KEY": "0b5e9b54-b226-4f62-a12b-d48a095e7f38",
"Content-Type": "application/json",
}
});
if (res.status === 404) {
return null;
}
const data = await res.json();
const title = data?.nameRu || `${id}`;
movieTitleCache[id] = title;
return title;
} catch (e) {
return `${id}`;
}
}