-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
463 lines (413 loc) · 14.3 KB
/
Copy pathrenderer.js
File metadata and controls
463 lines (413 loc) · 14.3 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
// renderer.js - UI logic for the Electron app and web app
let selectedGuildId = null;
let selectedChannelId = null;
let currentBotId = null;
// Check if running in Electron or web
const isElectron = typeof window.electronAPI !== 'undefined';
// API wrapper for Electron and web
const api = {
async getGuilds() {
if (isElectron) {
return window.electronAPI.getGuilds();
} else {
const response = await fetch('/api/guilds');
return response.json();
}
},
async getChannels(guildId) {
if (isElectron) {
return window.electronAPI.getChannels(guildId);
} else {
const response = await fetch(`/api/channels/${guildId}`);
return response.json();
}
},
async sendMessage(channelId, message) {
if (isElectron) {
return window.electronAPI.sendMessage(channelId, message);
} else {
const response = await fetch('/api/send-message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ channelId, message })
});
const result = await response.json();
return result.success;
}
},
async getLogs() {
if (isElectron) {
return window.electronAPI.getLogs();
} else {
const response = await fetch('/api/logs');
return response.json();
}
},
async getBots() {
if (isElectron) {
return window.electronAPI.getBots();
} else {
const response = await fetch('/api/bots');
return response.json();
}
},
async switchBot(botId) {
if (isElectron) {
return window.electronAPI.switchBot(botId);
} else {
const response = await fetch('/api/switch-bot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ botId })
});
return response.json();
}
},
async reconnectBot() {
if (isElectron) {
return window.electronAPI.reconnectBot();
} else {
const response = await fetch('/api/reconnect', { method: 'POST' });
return response.json();
}
},
async saveBotConfig(token, name) {
if (isElectron) {
return window.electronAPI.saveBotConfig(token, name);
} else {
const response = await fetch('/api/save-bot-config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, name })
});
return response.json();
}
},
async getStoredTokens() {
if (isElectron) {
return window.electronAPI.getStoredTokens();
} else {
const response = await fetch('/api/stored-tokens');
return response.json();
}
},
async clearAllData() {
if (isElectron) {
return window.electronAPI.clearAllData();
} else {
const response = await fetch('/api/clear-data', { method: 'POST' });
return response.json();
}
},
async startDiscordOAuth() {
if (isElectron) {
return window.electronAPI.startDiscordOAuth();
} else {
const response = await fetch('/api/oauth/start');
const data = await response.json();
// Open OAuth URL in popup or new window
window.open(data.url, 'discord-oauth', 'width=500,height=700');
}
},
async getOAuthStatus() {
if (isElectron) {
// For Electron, we'll implement this later
return { authenticated: false, user: null };
} else {
const response = await fetch('/api/oauth/status');
return response.json();
}
},
async logoutOAuth() {
if (isElectron) {
// For Electron, we'll implement this later
return true;
} else {
const response = await fetch('/api/oauth/logout', { method: 'POST' });
return response.json();
}
}
};
// DOM elements
const botSelect = document.getElementById('bot-select');
const reconnectBtn = document.getElementById('reconnect-btn');
const guildsContainer = document.getElementById('guilds');
const channelsContainer = document.getElementById('channels');
const messageInput = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
const chatMessages = document.getElementById('chat-messages');
const logsContainer = document.getElementById('logs');
// Settings modal elements
const settingsBtn = document.getElementById('settings-btn');
const settingsModal = document.getElementById('settings-modal');
const closeSettings = document.getElementById('close-settings');
const botTokenInput = document.getElementById('bot-token');
const botNameInput = document.getElementById('bot-name');
const saveBotConfigBtn = document.getElementById('save-bot-config');
const discordOauthBtn = document.getElementById('discord-oauth-btn');
const oauthStatus = document.getElementById('oauth-status');
const oauthText = document.getElementById('oauth-text');
const clearDataBtn = document.getElementById('clear-data-btn');
// Initialize the app
async function init() {
await loadBots();
await loadGuilds();
startLogUpdates();
}
// Load available bots
async function loadBots() {
try {
const bots = await api.getBots();
botSelect.innerHTML = '<option value="">Select Bot</option>';
bots.forEach(bot => {
const option = document.createElement('option');
option.value = bot.id;
option.textContent = bot.name;
botSelect.appendChild(option);
});
} catch (error) {
console.error('Error loading bots:', error);
}
}
// Load guilds (servers)
async function loadGuilds() {
try {
const guilds = await api.getGuilds();
guildsContainer.innerHTML = '';
guilds.forEach(guild => {
const guildElement = document.createElement('div');
guildElement.className = 'guild-item';
guildElement.textContent = guild.name;
guildElement.dataset.guildId = guild.id;
guildElement.addEventListener('click', () => selectGuild(guild.id));
guildsContainer.appendChild(guildElement);
});
} catch (error) {
console.error('Error loading guilds:', error);
}
}
// Select a guild and load its channels
async function selectGuild(guildId) {
selectedGuildId = guildId;
selectedChannelId = null;
// Update UI
document.querySelectorAll('.guild-item').forEach(item => {
item.classList.remove('selected');
});
document.querySelector(`[data-guild-id="${guildId}"]`).classList.add('selected');
// Load channels
try {
const channels = await api.getChannels(guildId);
channelsContainer.innerHTML = '';
channels.forEach(channel => {
const channelElement = document.createElement('div');
channelElement.className = 'channel-item';
channelElement.textContent = `#${channel.name}`;
channelElement.dataset.channelId = channel.id;
channelElement.addEventListener('click', () => selectChannel(channel.id));
channelsContainer.appendChild(channelElement);
});
} catch (error) {
console.error('Error loading channels:', error);
}
}
// Select a channel
function selectChannel(channelId) {
selectedChannelId = channelId;
// Update UI
document.querySelectorAll('.channel-item').forEach(item => {
item.classList.remove('selected');
});
document.querySelector(`[data-channel-id="${channelId}"]`).classList.add('selected');
// Clear chat messages and show channel selected
chatMessages.innerHTML = `
<div class="welcome-message">
<p>Channel selected! You can now send messages.</p>
</div>
`;
}
// Send a message
async function sendMessage() {
const message = messageInput.value.trim();
if (!message || !selectedChannelId) return;
try {
const success = await api.sendMessage(selectedChannelId, message);
if (success) {
messageInput.value = '';
// Add message to chat (optional, since bot events will be logged)
addChatMessage('You', message);
}
} catch (error) {
console.error('Error sending message:', error);
}
}
// Add a message to the chat display
function addChatMessage(author, content) {
const messageElement = document.createElement('div');
messageElement.className = 'chat-message';
messageElement.innerHTML = `
<strong>${author}:</strong> ${content}
`;
chatMessages.appendChild(messageElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Update logs display
async function updateLogs() {
try {
const logs = await api.getLogs();
logsContainer.innerHTML = '';
logs.forEach(log => {
const logElement = document.createElement('div');
logElement.className = 'log-entry';
if (log.includes('error') || log.includes('Error')) {
logElement.classList.add('error');
} else if (log.includes('ready') || log.includes('sent')) {
logElement.classList.add('success');
}
logElement.textContent = log;
logsContainer.appendChild(logElement);
});
logsContainer.scrollTop = logsContainer.scrollHeight;
} catch (error) {
console.error('Error updating logs:', error);
}
}
// Start periodic log updates
function startLogUpdates() {
updateLogs();
setInterval(updateLogs, 1000); // Update every second
}
// Event listeners
botSelect.addEventListener('change', async (e) => {
const botId = e.target.value;
if (botId) {
currentBotId = botId;
await api.switchBot(botId);
await loadGuilds();
}
});
reconnectBtn.addEventListener('click', async () => {
await api.reconnectBot();
});
sendBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
// Register service worker for PWA
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('public/sw.js')
.then(registration => {
console.log('ServiceWorker registered');
})
.catch(error => {
console.log('ServiceWorker registration failed');
});
});
}
// Settings modal functions
function openSettingsModal() {
settingsModal.classList.add('show');
loadStoredTokens();
checkOAuthStatus();
}
function closeSettingsModal() {
settingsModal.classList.remove('show');
}
async function loadStoredTokens() {
try {
const tokens = await api.getStoredTokens();
// Populate the form with stored data (but don't show the token)
if (tokens.length > 0) {
const latestToken = tokens[tokens.length - 1];
botNameInput.value = latestToken.name || '';
// Don't populate token input for security
}
} catch (error) {
console.error('Error loading stored tokens:', error);
}
}
async function saveBotConfig() {
const token = botTokenInput.value.trim();
const name = botNameInput.value.trim() || 'My Bot';
if (!token) {
alert('Please enter a bot token');
return;
}
try {
const success = await api.saveBotConfig(token, name);
if (success) {
alert('Bot configuration saved successfully!');
botTokenInput.value = '';
botNameInput.value = '';
closeSettingsModal();
await loadBots(); // Refresh bot list
} else {
alert('Failed to save bot configuration');
}
} catch (error) {
console.error('Error saving bot config:', error);
alert('Error saving bot configuration');
}
}
async function startDiscordOAuth() {
try {
await api.startDiscordOAuth();
// For web version, this will redirect
} catch (error) {
console.error('Error starting OAuth:', error);
}
}
async function checkOAuthStatus() {
try {
const status = await api.getOAuthStatus();
const oauthUserInfo = document.getElementById('oauth-user-info');
const userName = document.getElementById('user-name');
const logoutBtn = document.getElementById('logout-oauth-btn');
if (status.authenticated && status.user) {
oauthStatus.classList.add('connected');
oauthText.textContent = 'Connected to Discord';
userName.textContent = `${status.user.username}#${status.user.discriminator}`;
oauthUserInfo.style.display = 'block';
logoutBtn.style.display = 'inline-block';
} else {
oauthStatus.classList.remove('connected');
oauthText.textContent = 'Not connected';
oauthUserInfo.style.display = 'none';
logoutBtn.style.display = 'none';
}
} catch (error) {
console.error('Error checking OAuth status:', error);
oauthStatus.classList.remove('connected');
oauthText.textContent = 'Not connected';
document.getElementById('oauth-user-info').style.display = 'none';
}
}
async function logoutOAuth() {
try {
await api.logoutOAuth();
await checkOAuthStatus();
} catch (error) {
console.error('Error logging out:', error);
}
}
// Settings modal event listeners
settingsBtn.addEventListener('click', openSettingsModal);
closeSettings.addEventListener('click', closeSettingsModal);
settingsModal.addEventListener('click', (e) => {
if (e.target === settingsModal) {
closeSettingsModal();
}
});
saveBotConfigBtn.addEventListener('click', saveBotConfig);
discordOauthBtn.addEventListener('click', startDiscordOAuth);
clearDataBtn.addEventListener('click', clearAllData);
// OAuth logout button
const logoutOauthBtn = document.getElementById('logout-oauth-btn');
if (logoutOauthBtn) {
logoutOauthBtn.addEventListener('click', logoutOAuth);
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', init);