-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathschedules.js
374 lines (343 loc) · 14.2 KB
/
schedules.js
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
/**
@typedef {Object} Schedule
@property {string} id
@property {string} name
@property {string} description
@property {string} ownerUuid
@property {number} partyId
@property {string} game
@property {boolean} recurring
@property {boolean} official
@property {number} interval
@property {string} intervalType
@property {string} datetime
@property {string} systemName
@property {number} followerCount
@property {boolean} playerLiked
@property {string} ownerName
@property {number} ownerRank
@property {string} ownerString
@property {string} ownerSystemName
@property {string} discord
@property {string} youtube
@property {string} twitch
@property {string} niconico
@property {string} openrec
@property {string} bilibili
*/
let escapeHtml;
{
const elm = document.createElement('div');
escapeHtml = text => {
elm.innerText = text;
return elm.innerText;
};
}
/** Events starting in 15 minutes or less are considered "ongoing". */
const ONGOING_SCHEDULES_THRESHOLD = 15 * 60 * 1000;
const YEAR = 366 * 24 * 60 * 60 * 1000;
const platformAuthorities = Object.freeze({
discord: 'discord.com',
youtube: 'youtube.com',
twitch: 'twitch.tv',
niconico: 'nicovideo.jp',
openrec: 'openrec.tv',
bilibili: 'bilibili.com',
});
let editingScheduleId;
function sanitizeLink(platform, link, pathOnly = false) {
try {
let parsed = new URL(link, 'https://' + platformAuthorities[platform]);
let parsedHostname = parsed.hostname.replace('www.', '');
if (parsedHostname !== platformAuthorities[platform]) return null;
parsed.hostname = platformAuthorities[platform];
parsed.protocol = 'https:';
return pathOnly ? parsed.href.substring(parsed.origin.length + 1) : parsed;
} catch (err) {
console.warn(link, 'is not a valid link');
return null;
}
}
function formatScheduleFormValue(field, raw) {
if (field === 'datetime') {
try {
let parsed = new Date(raw);
parsed = +parsed - parsed.getTimezoneOffset() * 60 * 1000;
return new Date(parsed).toISOString().slice(0, 23);
} catch {
return raw;
}
}
return raw;
}
/** @param {Schedule} schedule */
function addScheduleItem(schedule) {
/** @type {HTMLElement} */
const template = document.getElementById('scheduleTemplate').content.firstElementChild.cloneNode(true);
const isMod = playerData && playerData.rank > 0;
let parsedDatetime;
try {
if (schedule.datetime)
parsedDatetime = new Date(schedule.datetime);
} catch {}
for (const slot of template.querySelectorAll('[data-role]')) {
switch (slot.dataset.role) {
case 'name':
slot.append(schedule.name);
break;
case 'partyIcon':
slot.classList.toggle('hidden', !schedule.partyId);
break;
case 'edit':
if (!isMod && (!playerData?.uuid || playerData.uuid !== schedule.ownerUuid)) break;
slot.classList.remove('hidden');
if (schedule.game !== gameId) {
slot.classList.add('toggled');
addTooltip(slot, localizedMessages.schedules.wrongEditGame.replace('{GAME}', localizedMessages.games[schedule.game]));
} else
slot.addEventListener('click', () => openScheduleEditModal(schedule));
break;
case 'cancel':
if (!isMod && (!playerData?.uuid || playerData.uuid !== schedule.ownerUuid)) break;
slot.classList.remove('hidden');
slot.addEventListener('click', () => {
showConfirmModal(localizedMessages.schedules.confirmCancel, () => {
apiFetch(`schedule?command=cancel&scheduleId=${schedule.id}`)
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
openSchedulesModal();
}, err => console.error(err));
});
});
break;
case 'description':
const descriptionContents = document.createElement('span');
descriptionContents.classList.add('messageContents', 'themeText');
let msg = parseMessageTextForMarkdown(escapeHtml(schedule.description));
if (msg.includes('{{')) {
// Special syntax: leads to yume.wiki
msg = msg.replace(/{{l:(.+?)}}/g, (_, descriptor) => {
const [href, altText] = descriptor.split(',', 2);
const a = document.createElement('a');
a.target = '_blank';
a.href = `https://yume.wiki/${schedule.game}/${href}`;
a.innerText = altText || href;
return a.outerHTML;
});
}
populateMessageNodes(msg, descriptionContents, true);
wrapMessageEmojis(descriptionContents);
slot.appendChild(descriptionContents);
break;
case 'follow':
if (!playerData?.uuid) break;
slot.classList.toggle('fillIcon', !!schedule.playerLiked);
slot.addEventListener('click', function () {
apiFetch(`schedule?command=follow&value=${!schedule.playerLiked}&scheduleId=${schedule.id}`)
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.text();
})
.then(likeCount => {
schedule.playerLiked = !schedule.playerLiked;
this.classList.toggle('fillIcon', schedule.playerLiked);
const elm = this.parentElement.querySelector('[data-role="followerCount"]');
if (elm)
elm.innerText = likeCount;
}, err => console.error(err));
});
break;
case 'links':
const links = [];
for (const platform in platformAuthorities)
if (schedule[platform]) {
const a = document.createElement('a');
a.target = '_blank';
a.href = sanitizeLink(platform, schedule[platform])?.href || 'javascript:void(0)';
a.innerText = localizedMessages.schedules.platforms[platform];
links.push(a.outerHTML);
}
slot.innerHTML = links.join(' | ');
break;
case 'organizer':
const playerNameHtml = getPlayerName({ name: schedule.ownerName, systemName: schedule.ownerSystemName || 'null', rank: schedule.ownerRank, account: true, badge: schedule.ownerString || 'null' }, false, true, true);
slot.innerHTML = localizedMessages.schedules.organizer.replace('{NAME}', playerNameHtml);
break;
case 'datetime':
if (parsedDatetime) {
const locale = globalConfig.lang === 'en' ? [] : globalConfig.lang;
slot.innerText = parsedDatetime.toLocaleString(locale, { "dateStyle": "short", "timeStyle": "short" });
addTooltip(slot, parsedDatetime.toLocaleString(locale, { weekday: 'long' }));
}
break;
case 'followerCount':
slot.innerText = schedule.followerCount;
break;
default:
console.warn(`Unknown schedule slot "${slot.dataset.role}"`);
break;
}
}
if (schedule.systemName && schedule.game) {
let theme = schedule.systemName;
if (!allGameUiThemes[schedule.game].includes(theme))
theme = getDefaultUiTheme(schedule.game);
initUiThemeContainerStyles(theme, schedule.game, false, () => {
initUiThemeFontStyles(theme, schedule.game, 0, false);
theme = theme.replace(/'|\s$/g, "").replace(/ /g, "_");
applyThemeStyles(template, theme, schedule.game);
});
}
updateThemedContainer(template);
fastdom.mutate(() => {
if (parsedDatetime && +parsedDatetime - +new Date <= ONGOING_SCHEDULES_THRESHOLD)
document.getElementById('ongoingSchedules').appendChild(template);
else if (schedule.partyId && schedule.partyId === joinedPartyId)
document.getElementById('partySchedules').appendChild(template);
else if (schedule.official)
document.getElementById('officialSchedules').appendChild(template);
else
document.getElementById('futureSchedules').appendChild(template);
});
}
function openSchedulesModal() {
const schedulesModal = document.getElementById('schedulesModal');
addLoader(schedulesModal);
for (const elm of document.querySelectorAll('.scheduleContainer'))
elm.replaceChildren();
document.getElementById('createSchedule').classList.toggle('hidden', !playerData?.account);
openModal('schedulesModal');
return apiFetch('schedule?command=list')
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.json();
})
.then(
/** @param {Schedule[]} schedules */
schedules => {
if (!schedules)
schedules = [];
schedules.sort((a, z) => a.datetime.localeCompare(z.datetime));
for (const schedule of schedules)
if (!schedule.partyId || schedule.partyId === joinedPartyId)
addScheduleItem(schedule);
document.getElementById('emptySchedules').classList.toggle('hidden', !!schedules.length);
},
err => console.error(err)
).finally(_ => removeLoader(schedulesModal));
}
/** @param {Partial<Schedule>} schedule */
function openScheduleEditModal(schedule = {}) {
const isMod = playerData && playerData.rank > 0;
if (!isMod && schedule.ownerUuid && schedule.ownerUuid !== playerData?.uuid) return;
editingScheduleId = schedule.id;
/** @type {HTMLFormElement} */
const form = document.getElementById('scheduleForm');
for (const input of form.querySelectorAll('[name]')) {
input.value = formatScheduleFormValue(input.name, schedule[input.name] || '');
if (input.name === 'datetime') {
let min = new Date();
min.setHours(0, 0);
const max = new Date(min.valueOf() + YEAR);
input.setAttribute('min', min.toISOString().slice(0, 16));
input.setAttribute('max', max.toISOString().slice(0, 16));
}
}
document.getElementById('eventRecurring').classList.toggle('toggled', !!schedule.recurring);
document.getElementById('eventOfficial').classList.toggle('toggled', !!schedule.official);
document.getElementById('eventOfficialRow').classList.toggle('hidden', !isMod);
document.getElementById('resetOrganizer').classList.remove('toggled');
document.getElementById('resetOrganizerRow').classList.toggle('hidden', !isMod || !schedule.id);
form.interval.toggleAttribute('required', !!schedule.recurring);
form.intervalType.toggleAttribute('required', !!schedule.recurring);
document.getElementById('eventInterval').classList.toggle('hidden', !schedule.recurring);
document.getElementById('restrictPartyRow').classList.toggle('hidden', !joinedPartyCache || joinedPartyCache.ownerUuid !== playerData?.uuid);
document.getElementById('restrictParty').classList.toggle('toggled', !!schedule.partyId);
let scheduleSystemName = schedule.systemName;
if (!scheduleSystemName)
scheduleSystemName = config.uiTheme === 'auto' ? systemName : config.uiTheme;
setScheduleTheme(scheduleSystemName);
openModal('scheduleEditModal', scheduleSystemName, 'schedulesModal');
updateYnomojiContainerPos(false, document.getElementById('editScheduleDescription'));
}
document.getElementById('schedulesButton').addEventListener('click', () => openSchedulesModal());
{
let toggleButton = elm => {
const enabled = !elm.classList.contains('toggled');
elm.classList.toggle('toggled', enabled);
return enabled;
};
document.getElementById('eventRecurring').addEventListener('click', function () {
const enabled = toggleButton(this);
document.getElementById('eventInterval').classList.toggle('hidden', !enabled);
const form = document.getElementById('scheduleForm');
form.interval.toggleAttribute('required', enabled);
form.intervalType.toggleAttribute('required', enabled);
});
for (const elmid of ['eventOfficial', 'restrictParty', 'resetOrganizer'])
document.getElementById(elmid).addEventListener('click', function () { toggleButton(this); });
}
document.getElementById('scheduleForm').addEventListener('submit', function editSchedule() {
if (!playerData?.account) return;
const form = document.getElementById('scheduleForm');
const schedule = Object.fromEntries(new FormData(form).entries());
if (editingScheduleId)
schedule.id = editingScheduleId;
schedule.recurring = document.getElementById('eventRecurring').classList.contains('toggled');
schedule.datetime = new Date(schedule.datetime).toISOString();
schedule.systemName = document.getElementById('scheduleThemeButton').nextElementSibling.value;
schedule.game = gameId;
schedule.official = document.getElementById('eventOfficial').classList.contains('toggled');
schedule.ownerUuid = playerData.uuid;
if (editingScheduleId && playerData.rank > 0 && !document.getElementById('resetOrganizer').classList.contains('toggled'))
schedule.ownerUuid = '';
if (joinedPartyCache?.ownerUuid && joinedPartyCache.ownerUuid === playerData?.uuid) {
const partyOnly = document.getElementById('restrictParty').classList.contains('toggled');
if (partyOnly) {
schedule.partyId = joinedPartyId;
schedule.systemName = joinedPartyCache.systemName;
} else
delete schedule.partyId;
}
apiFetch(`schedule?command=update&${new URLSearchParams(schedule).toString()}`)
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.text();
})
.then(() => {
closeModal();
openSchedulesModal();
}, err => console.error(err));
return false;
});
document.getElementById('cancelSchedule').addEventListener('click', function () {
if (!editingScheduleId) {
openSchedulesModal();
return;
}
showConfirmModal(localizedMessages.schedules.confirmCancel, () => {
apiFetch(`schedule?command=cancel&scheduleId=${editingScheduleId}`)
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
openSchedulesModal();
}, err => console.error(err));
});
});
document.getElementById('scheduleThemeButton').addEventListener('click', function () {
openModal('uiThemesModal', this.nextElementSibling.value, 'scheduleEditModal');
});
for (const platformInput of document.querySelectorAll('input[data-platform]')) {
platformInput.addEventListener('change', function () {
const sanitized = sanitizeLink(platformInput.name, this.value, true);
if (sanitized !== null) {
this.value = sanitized;
this.setCustomValidity('');
} else
this.setCustomValidity(localizedMessages.schedules.invalidPlatformLink);
});
}