Spaces:
Running
Running
File size: 12,361 Bytes
e9a6464 |
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 |
// DOM Elements
const adminMenu = document.querySelector('.admin-menu');
const tabContents = document.querySelectorAll('.tab-content');
const logoutBtn = document.getElementById('logout-btn');
const sectionTitle = document.getElementById('section-title');
// OpenRouter API Configuration
let openRouterConfig = {
apiKey: localStorage.getItem('openRouterApiKey') || '',
siteUrl: localStorage.getItem('openRouterSiteUrl') || window.location.origin,
siteName: localStorage.getItem('openRouterSiteName') || 'Muhafiz AI Chat'
};
// Model Settings
let modelSettings = {
selectedModel: localStorage.getItem('selectedModel') || 'openai/gpt-3.5-turbo',
temperature: parseFloat(localStorage.getItem('temperature')) || 0.7,
maxTokens: parseInt(localStorage.getItem('maxTokens')) || 2048,
streamResponse: localStorage.getItem('streamResponse') === 'true'
};
// Initialize admin panel
function initAdminPanel() {
// Check authentication
if (localStorage.getItem('adminLoggedIn') !== 'true') {
window.location.href = 'login.html';
return;
}
// Add event listeners
adminMenu.addEventListener('click', handleMenuClick);
logoutBtn.addEventListener('click', handleLogout);
// Load saved settings
loadSettings();
// Set up form change tracking
setupChangeTracking();
}
// Handle menu item clicks
function handleMenuClick(e) {
const menuItem = e.target.closest('li');
if (!menuItem || menuItem.id === 'logout-btn') return;
// Update active menu item
document.querySelectorAll('.admin-menu li').forEach(item => {
item.classList.remove('active');
});
menuItem.classList.add('active');
// Show corresponding tab content
const tabId = menuItem.getAttribute('data-tab');
tabContents.forEach(tab => {
tab.classList.remove('active');
if (tab.id === tabId) {
tab.classList.add('active');
}
});
// Update section title
sectionTitle.textContent = menuItem.textContent.trim();
}
// Handle logout
function handleLogout() {
if (hasUnsavedChanges()) {
if (!confirm('You have unsaved changes. Are you sure you want to logout?')) {
return;
}
}
// Clear admin session
localStorage.removeItem('adminLoggedIn');
// Redirect to login page
window.location.href = 'login.html';
}
// Track unsaved changes
let hasUnsavedChanges = () => false;
// Set up change tracking
function setupChangeTracking() {
const formElements = document.querySelectorAll('input, select, textarea');
let initialValues = new Map();
formElements.forEach(element => {
initialValues.set(element, element.value);
element.addEventListener('change', () => {
const hasChanges = Array.from(formElements).some(el =>
initialValues.get(el) !== el.value
);
hasUnsavedChanges = () => hasChanges;
});
});
}
// Load saved settings
function loadSettings() {
const savedConfig = localStorage.getItem('chatConfig');
if (savedConfig) {
const config = JSON.parse(savedConfig);
// Apply saved settings to form elements
Object.entries(config).forEach(([key, value]) => {
const element = document.getElementById(key);
if (element) {
element.value = value;
}
});
}
}
// Save settings
function saveSettings() {
// OpenRouter API Configuration
openRouterConfig = {
apiKey: document.getElementById('openRouterApiKey').value,
siteUrl: document.getElementById('openRouterSiteUrl').value,
siteName: document.getElementById('openRouterSiteName').value
};
// Model Settings
modelSettings = {
selectedModel: document.getElementById('modelSelect').value,
temperature: parseFloat(document.getElementById('temperature').value),
maxTokens: parseInt(document.getElementById('maxTokens').value),
streamResponse: document.getElementById('streamResponse').checked
};
// Save to localStorage
Object.entries(openRouterConfig).forEach(([key, value]) => {
localStorage.setItem(`openRouter${key.charAt(0).toUpperCase() + key.slice(1)}`, value);
});
Object.entries(modelSettings).forEach(([key, value]) => {
localStorage.setItem(key, value);
});
showNotification('Settings saved successfully!', 'success');
}
// Show notification
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.classList.add('notification', `notification-${type}`);
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('notification-hide');
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', initAdminPanel);
// Handle beforeunload
window.addEventListener('beforeunload', (e) => {
if (hasUnsavedChanges()) {
e.preventDefault();
e.returnValue = '';
}
});
// Initialize form values
function initializeFormValues() {
// OpenRouter API Configuration
document.getElementById('openRouterApiKey').value = openRouterConfig.apiKey;
document.getElementById('openRouterSiteUrl').value = openRouterConfig.siteUrl;
document.getElementById('openRouterSiteName').value = openRouterConfig.siteName;
// Model Settings
document.getElementById('modelSelect').value = modelSettings.selectedModel;
document.getElementById('temperature').value = modelSettings.temperature;
document.getElementById('temperatureValue').textContent = modelSettings.temperature;
document.getElementById('maxTokens').value = modelSettings.maxTokens;
document.getElementById('streamResponse').checked = modelSettings.streamResponse;
}
// Copy to clipboard function
function copyToClipboard(elementId) {
const element = document.getElementById(elementId);
navigator.clipboard.writeText(element.value).then(() => {
showNotification('Copied to clipboard!', 'success');
}).catch(err => {
showNotification('Failed to copy text', 'error');
});
}
// Test model function
async function testModel() {
const testButton = document.getElementById('testModel');
const originalText = testButton.textContent;
testButton.disabled = true;
testButton.textContent = 'Testing...';
try {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${openRouterConfig.apiKey}`,
'HTTP-Referer': openRouterConfig.siteUrl,
'X-Title': openRouterConfig.siteName,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: modelSettings.selectedModel,
messages: [
{
role: 'user',
content: 'Say "Hello! I am working correctly!"'
}
],
temperature: modelSettings.temperature,
max_tokens: modelSettings.maxTokens,
stream: false
})
});
const data = await response.json();
if (!response.ok) {
console.error('OpenRouter API Error:', data);
throw new Error(data.error?.message || `HTTP error! status: ${response.status}`);
}
showNotification('Model test successful! Response: ' + data.choices[0].message.content, 'success');
} catch (error) {
console.error('Model test failed:', error);
showNotification('Model test failed: ' + error.message, 'error');
} finally {
testButton.disabled = false;
testButton.textContent = originalText;
}
}
// Update temperature value display
document.getElementById('temperature')?.addEventListener('input', (e) => {
document.getElementById('temperatureValue').textContent = e.target.value;
});
// Test API Response
async function testApiResponse() {
const testButton = document.getElementById('testApiBtn');
const testMessage = document.getElementById('testMessage');
const testResponse = document.getElementById('testResponse');
const testError = document.getElementById('testError');
const responseContainer = document.querySelector('.test-response-container');
// Validate inputs
if (!openRouterConfig.apiKey) {
showNotification('Please enter your API key first', 'error');
return;
}
// Update button state
testButton.classList.add('loading');
testButton.disabled = true;
const originalText = testButton.innerHTML;
testButton.innerHTML = '<i class="fas fa-spinner"></i> Testing...';
// Clear previous results
testResponse.textContent = '';
testError.textContent = '';
responseContainer.style.display = 'none';
try {
console.log('Testing API with configuration:', {
model: modelSettings.selectedModel,
siteUrl: openRouterConfig.siteUrl,
siteName: openRouterConfig.siteName
});
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${openRouterConfig.apiKey}`,
'HTTP-Referer': openRouterConfig.siteUrl,
'X-Title': openRouterConfig.siteName,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: modelSettings.selectedModel,
messages: [
{
role: 'user',
content: testMessage.value || 'Hello! Can you hear me?'
}
],
temperature: modelSettings.temperature,
max_tokens: modelSettings.maxTokens,
stream: false
})
});
const data = await response.json();
if (!response.ok) {
console.error('OpenRouter API Error:', data);
throw new Error(data.error?.message || `HTTP error! status: ${response.status}`);
}
// Display the full response for debugging
responseContainer.style.display = 'block';
testResponse.textContent = JSON.stringify(data, null, 2);
// Show success notification
showNotification('API test successful!', 'success');
} catch (error) {
console.error('API Test Error:', error);
responseContainer.style.display = 'block';
testError.textContent = `Error: ${error.message}`;
showNotification('API test failed. Check the error details below.', 'error');
} finally {
// Reset button state
testButton.classList.remove('loading');
testButton.disabled = false;
testButton.innerHTML = originalText;
}
}
// Initialize form values when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
initializeFormValues();
// Add event listeners for copy buttons
document.querySelectorAll('.copy-btn').forEach(button => {
button.addEventListener('click', (e) => {
const inputId = e.target.closest('.input-with-copy').querySelector('input').id;
copyToClipboard(inputId);
});
});
// Add event listener for test model button
document.getElementById('testModel')?.addEventListener('click', testModel);
// Add test API button handler
document.getElementById('testApiBtn')?.addEventListener('click', testApiResponse);
// Add form submit handler
document.getElementById('modelSettingsForm')?.addEventListener('submit', (e) => {
e.preventDefault();
saveSettings();
});
}); |