-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
514 lines (435 loc) · 20.2 KB
/
Copy pathscript.js
File metadata and controls
514 lines (435 loc) · 20.2 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
function initializeLocalStorage() {
// Start with a clean copy of the default data
const db = { ...DEFAULT_DATA };
const sampleUserProfile = {
name: 'Llama',
pw: 'llamaPassword',
is_author: true,
is_admin: true,
private_snippet: 'I am Llama, the author!',
web_site: 'https://llamawa.re',
color: 'purple',
snippets: []
};
// Add the Llama profile to our temporary object
db['llamaware'] = sampleUserProfile;
// Save the combined database to storage
localStorage.setItem('_db', JSON.stringify(db));
// Set the initial session for the auto-login
const sampleCookie = {
uid: 'llamaware',
is_admin: true,
is_author: true
};
localStorage.setItem('_cookie', JSON.stringify(sampleCookie));
localStorage.setItem('_profile', JSON.stringify(sampleUserProfile));
}
// Function to get a special value based on the variable name
function getSpecialValue(varName) {
const specials = {
_key: null, // This will be set during iteration context
_this: null, // This will also be set during iteration context
_db: JSON.parse(localStorage.getItem('_db')),
_cookie: JSON.parse(localStorage.getItem('_cookie')),
_profile: JSON.parse(localStorage.getItem('_profile')),
};
return specials[varName];
}
async function loadTemplate(templateFile, templateParams = {}) {
try {
const response = await fetch(templateFile);
if (!response.ok) {
throw new Error('Failed to load template');
}
const template = await response.text();
// ALWAYS keep _profile as the logged-in user, and map URL parameters to _params.
const specials = {
_db: getSpecialValue('_db'),
_cookie: getSpecialValue('_cookie'),
_profile: getSpecialValue('_profile'),
_params: templateParams, // <-- Allows template to correctly access '*uid'
};
// Render and inject template into content div
const renderedTemplate = await expandTemplate(template, specials, templateParams);
document.getElementById('content').innerHTML = renderedTemplate;
setupAllSnippetsListener();
} catch (error) {
console.error('Error loading GTL template:', error);
document.getElementById('content').textContent = 'Error loading template.';
}
}
// Initialize local storage with sample data (run this once, or check if data exists)
if (!localStorage.getItem('_db')) {
initializeLocalStorage();
}
// Event listener for links that load templates
document.addEventListener('click', async function(event) { // Add async here
const target = event.target.closest('a'); // Get the closest anchor element
if (!target) return; // Exit if it's not a link
const id = target.getAttribute('id'); // Get the id of the clicked link
try {
// Check if the id matches various sections
if (id === 'login') {
await loadTemplate('login.gtl'); // Load the login template
setupLoginButtonListener();
} else if (id === 'newaccount') {
await loadTemplate('newaccount.gtl'); // Load the signup template
setupNewAccountButtonListener(); // Setup listener for signup
} else if (id === 'home') {
await loadTemplate('home.gtl'); // Load the home template
setupAllSnippetsListener();
} else if (id === 'snippets') {
await loadTemplate('snippets.gtl', {}); // Load the snippets template
} else if (id === 'newsnippet') {
await loadTemplate('newsnippet.gtl'); // Load the new snippet template
setupSubmitSnippetListener();
} else if (id === 'upload') {
await loadTemplate('upload.gtl'); // Load the upload template
setupUploadButtonListener();
} else if (id === 'manage') {
await loadTemplate('manage.gtl'); // Load the manage template
setupServerActionListeners();
} else if (id === 'editprofile') {
await loadTemplate('editprofile.gtl'); // Load the edit profile template
setupUpdateProfileButtonListener();
} else if (id === 'logout') {
localStorage.removeItem('_cookie'); // Clear the stored cookie data
localStorage.removeItem('_profile');
await loadTemplate('home.gtl'); // Load the logout template
setupAllSnippetsListener();
}
// If the id doesn't match, it will just act as normal
} catch (error) {
console.error('Error loading template:', error); // Handle any errors
}
});
function setupAllSnippetsListener() {
const allSnippetLinks = document.querySelectorAll('.all-snippets');
//console.log('All Snippet Links:', allSnippetLinks); // Debug log
allSnippetLinks.forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault();
const userId = this.getAttribute('data-user-id');
//console.log('User ID:', userId); // Debug log
loadUserProfile(userId);
});
});
}
async function loadUserProfile(userId) {
// 1. Get the current logged-in user ID from the cookie
const cookie = JSON.parse(localStorage.getItem('_cookie'));
const currentUserId = cookie ? cookie.uid : null;
const storedDb = JSON.parse(localStorage.getItem('_db'));
const userProfile = storedDb[userId];
if (userProfile) {
// 2. Check if the profile we are loading belongs to the logged-in user
if (userId === currentUserId) {
// If it's us, load snippets with NO uid parameter.
// This triggers [[if:!uid]] in the template, showing the [X] button.
await loadTemplate('snippets.gtl', {});
} else {
// If it's someone else, pass the uid parameter.
// This triggers [[if:uid]], hiding the [X] button.
await loadTemplate('snippets.gtl', { uid: userId });
}
} else {
console.error('User profile not found for ID:', userId);
}
}
// Function to setup event listeners for server actions
function setupServerActionListeners() {
const resetButton = document.getElementById('reset');
if (resetButton) {
resetButton.addEventListener('click', function(event) {
event.preventDefault();
resetLocalData();
});
}
const quitButton = document.getElementById('quitserver');
if (quitButton) {
quitButton.addEventListener('click', function(event) {
event.preventDefault();
quitServer();
});
}
// Intercept the Edit Profile form specifically found in manage.gtl
const forms = document.querySelectorAll('form');
forms.forEach(form => {
const action = form.getAttribute('action') || '';
// Capture any form whose action mimics the target URL
if (action.includes('editprofile')) {
form.addEventListener('submit', async function(event) {
event.preventDefault(); // Stop normal form submission from reloading page
const uidInput = form.querySelector('input[name="uid"]');
if (uidInput && uidInput.value) {
await loadTemplate('editprofile.gtl', { uid: uidInput.value });
// Pass the target uid to securely edit the targeted user
setupUpdateProfileButtonListener(uidInput.value);
}
});
}
});
}
// Function to reset local data
function resetLocalData() {
localStorage.clear(); // Clear all local storage data
initializeLocalStorage();
alert('Server reset to default values...'); // Notify the user
}
// Function to quit server and display message
function quitServer() {
// Set a flag in local storage indicating the server has been quit
localStorage.setItem('serverStatus', 'quit');
// Clear the content of the page
document.body.innerHTML = 'Server quit.'; // Display server quit message
// Optionally, you could add a reload or navigation prevention logic here
// For example, disable any links/buttons or prevent loading any new templates
}
// Function to check server status and prevent loading if server is quit
function checkServerStatus() {
const serverStatus = localStorage.getItem('serverStatus');
if (serverStatus === 'quit') {
return false; // Indicate that loading should not proceed
}
return true; // Indicate that loading can proceed
}
// Call this function before any template load or page initialization
function initializePage() {
if (!checkServerStatus()) {
document.title = "Problem loading page";
let link = document.querySelector("link[rel~='icon']");
const minimalistIcon = `
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'>
<circle cx='50' cy='50' r='44' fill='none' stroke='white' stroke-width='8' />
<rect x='45' y='46' width='10' height='30' rx='1' fill='white' />
<circle cx='50' cy='30' r='7' fill='white' />
</svg>`;
link.href = "data:image/svg+xml," + encodeURIComponent(minimalistIcon);
return; // Stop execution if the server is quit
}
// Normal page initialization code goes here
loadTemplate('home.gtl');
//setupAllSnippetsListener();
}
// Setup event listener for the login button
function setupLoginButtonListener() {
const loginButton = document.getElementById('login-button');
if (loginButton) {
loginButton.addEventListener('click', function() {
const loginForm = document.getElementById('login-form');
const username = loginForm.uid.value; // Get username value
const password = loginForm.pw.value; // Get password value
fakeLogin(username, password); // Call the fake login function
});
}
}
function setupUploadButtonListener() {
const uploadButton = document.getElementById('upload-button');
if (uploadButton) {
uploadButton.addEventListener('click', function() {
// 1. Find the file input element
const fileInput = document.querySelector('input[name="upload_file"]');
// 2. Check if a file was actually selected
if (fileInput && fileInput.files.length > 0) {
const file = fileInput.files[0];
// 3. Create a temporary local URL for that file
// This creates a string like: blob:http://localhost:8080/3f2a...
const localUrl = URL.createObjectURL(file);
// 4. Load the template passing the local URL and the filename
loadTemplate('upload2.gtl', {
url: localUrl,
filename: file.name
});
} else {
alert("Please select a file first!");
}
});
}
}
// Setup event listener for the "Create account" button
function setupNewAccountButtonListener() {
const newAccountButton = document.getElementById('new-account');
if (newAccountButton) {
newAccountButton.addEventListener('click', function() {
const uidInput = document.getElementById('uid');
const pwInput = document.getElementById('pw');
const username = uidInput.value.trim();
const password = pwInput.value.trim();
if (!username || !password) {
alert("Please enter both a username and a password.");
return;
}
// FIX: Read the current DB from storage first, don't use the global _db
const storedDb = JSON.parse(localStorage.getItem('_db')) || { ...DEFAULT_DATA };
if (storedDb[username]) {
alert("User already exists!");
return;
}
const newUser = {
name: username,
pw: password,
is_author: true,
is_admin: false,
private_snippet: 'This is a private snippet.',
web_site: 'https://example.com/',
color: getRandomColor(), // <--- Now it's random!
snippets: []
};
// Update the local object
storedDb[username] = newUser;
// Save the updated database back to storage
localStorage.setItem('_db', JSON.stringify(storedDb));
// Log the user in
const newSession = {
uid: username,
is_admin: false,
is_author: true
};
localStorage.setItem('_cookie', JSON.stringify(newSession));
localStorage.setItem('_profile', JSON.stringify(newUser));
loadTemplate('home.gtl');
});
}
}
function setupUpdateProfileButtonListener(targetUid = null) {
const updateButton = document.getElementById('update-profile');
if (updateButton) {
updateButton.addEventListener('click', function(event) {
event.preventDefault(); // Prevents form submission refresh
const form = document.getElementById('profile-form');
const cookie = JSON.parse(localStorage.getItem('_cookie'));
// Determine which user to update: specific targetUid or default to ourselves
let currentUser = targetUid;
if (!currentUser && form.uid && form.uid.value) {
currentUser = form.uid.value; // Checks if a hidden field provided it
}
if (!currentUser) {
currentUser = cookie.uid;
}
const storedDb = JSON.parse(localStorage.getItem('_db'));
const profileData = storedDb[currentUser];
if (!profileData) {
alert('User not found!');
return;
}
// Read variables, provide defaults if they don't apply
const username = form.name ? form.name.value : profileData.name;
const oldPassword = form.oldpw ? form.oldpw.value : '';
const newPassword = form.pw ? form.pw.value : '';
const icon = form.icon ? form.icon.value : (profileData.icon || '');
const homepage = form.web_site ? form.web_site.value : profileData.web_site;
const color = form.color ? form.color.value : profileData.color;
const privateSnippet = form.private_snippet ? form.private_snippet.value : profileData.private_snippet;
// Only require old password validation if the user is editing their own profile
if (currentUser === cookie.uid && oldPassword && oldPassword !== profileData.pw) {
alert('Incorrect old password. Please try again.');
return;
}
// Update profile
profileData.name = username;
profileData.icon = icon;
profileData.web_site = homepage;
profileData.color = color;
profileData.private_snippet = privateSnippet;
if (newPassword) {
profileData.pw = newPassword;
}
// Save back to local storage (simulating database save)
storedDb[currentUser] = profileData;
localStorage.setItem('_db', JSON.stringify(storedDb));
// ONLY modify local `_profile` cache if the user modified their own data
if (currentUser === cookie.uid) {
localStorage.setItem('_profile', JSON.stringify(profileData));
}
loadTemplate('home.gtl');
});
}
}
function setupSubmitSnippetListener() {
const submitButton = document.getElementById('submit-snippet');
if (submitButton) {
submitButton.addEventListener('click', function() {
console.log("Submit button clicked"); // Debug log
const snippetInput = document.getElementById('snippet-input');
const newSnippet = snippetInput.value.trim(); // Get and trim the snippet
console.log("New Snippet:", newSnippet); // Debug log
if (newSnippet) {
const cookie = JSON.parse(localStorage.getItem('_cookie'));
const currentUser = cookie.uid; // Get the uid from cookie
const storedDb = JSON.parse(localStorage.getItem('_db')); // Parse the stored DB
const profileData = storedDb[currentUser]; // Get profile data for the current user
if (profileData) {
profileData.snippets.unshift(newSnippet); // Add the new snippet
localStorage.setItem('_db', JSON.stringify(storedDb)); // Save updated db back to local storage
localStorage.setItem('_profile', JSON.stringify(profileData));
snippetInput.value = ''; // Clear the input after submission
console.log("Snippet added successfully!"); // Debug log
loadTemplate('home.gtl'); // Redirect to home page or refresh as needed
} else {
console.error('Profile data not found for user:', currentUser);
}
} else {
alert('Please enter a snippet before submitting.'); // Optional: notify user about empty input
}
});
}
}
// Fake login function to be called when the button is clicked
function fakeLogin(username, password) {
// Always fetch the latest DB from storage
const storedDb = JSON.parse(localStorage.getItem('_db'));
if (!storedDb) {
console.error("Database not found in localStorage!");
return;
}
const userProfile = storedDb[username];
// Check password
if (userProfile && userProfile.pw === password) {
const userCookie = {
uid: username,
is_admin: userProfile.is_admin,
is_author: userProfile.is_author
};
localStorage.setItem('_cookie', JSON.stringify(userCookie));
localStorage.setItem('_profile', JSON.stringify(userProfile));
loadTemplate('home.gtl');
console.log('Login successful! User:', userCookie);
} else {
// Failed login - show an error message
//alert('Login failed. Please check your username and password.');
console.log('Login failed for user:', username);
}
}
// Function to delete a snippet from the user's profile
function deleteSnippet(index) {
// Retrieve the cookie from local storage and parse it
const cookie = JSON.parse(localStorage.getItem('_cookie'));
const currentUser = cookie.uid; // Get the uid from cookie
const storedDb = JSON.parse(localStorage.getItem('_db')); // Parse the stored DB
const profileData = storedDb[currentUser]; // Get profile data for the current user
if (profileData) {
// Remove the snippet at the specified index
if (index >= 0 && index < profileData.snippets.length) {
profileData.snippets.splice(index, 1); // Remove snippet at the index
localStorage.setItem('_db', JSON.stringify(storedDb)); // Save updated db back to local storage
localStorage.setItem('_profile', JSON.stringify(profileData));
console.log("Snippet deleted successfully!"); // Debug log
// Optionally, refresh the snippet list to reflect changes
loadTemplate('snippets.gtl'); // Reload the snippets page
} else {
console.error('Invalid index for snippet deletion:', index);
}
} else {
console.error('Profile data not found for user:', currentUser);
}
}
function getRandomColor() {
const colors = [
'red', 'blue', 'green', 'purple', 'orange',
'deeppink', 'teal', 'brown', 'darkmagenta',
'midnightblue', 'crimson', 'forestgreen', 'darkslategrey'
];
// Pick a random index from the array
const randomIndex = Math.floor(Math.random() * colors.length);
return colors[randomIndex];
}