-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
599 lines (519 loc) · 22.5 KB
/
script.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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
const config = {
baseUrl: wpData.baseUrl, // This will be dynamically set to the WordPress base URL,
siteTitle: wpData.siteTitle,
siteDescription: wpData.siteDescription,
currentTheme: wpData.currentTheme,
memoryUsage: wpData.memoryUsage,
serverSoftware: wpData.serverSoftware,
ipAddress: wpData.ipAddress,
requestTime: wpData.requestTime,
};
const history = document.getElementById('history');
// Terminal Service
const terminalService = {
print: (message, promptSymbol = true) => {
const prompt = promptSymbol ? '$ ' : '';
history.innerHTML += `<div class="command-output">${prompt}${message}</div>`;
},
printError: (errorMessage) => {
history.innerHTML += `<div class="command-output error">${errorMessage}</div>`;
},
appendCommandInput: () => {
// Remove existing command input line if it exists
const existingCommandLine = history.querySelector('#commandInput');
if (existingCommandLine) {
existingCommandLine.parentElement.remove();
}
// Add the new command input field to the bottom of the history
history.innerHTML += `<div class="command-line">$ <input type="text" id="commandInput" placeholder=""></div>`;
const commandInput = document.getElementById('commandInput');
commandInput.focus();
// Event listener for the commandInput
commandInput.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
let command = this.value.trim();
commandService.execute(command);
}
});
},
};
// API Service
const apiService = {
getTotalPosts: async () => {
try {
const response = await fetch(`${config.baseUrl}/wp-json/wp/v2/posts?per_page=1`);
return response.headers.get('X-WP-Total');
} catch (error) {
console.error('Error fetching total posts:', error);
return 'Unavailable';
}
},
getTotalCategories: async () => {
try {
const response = await fetch(`${config.baseUrl}/wp-json/wp/v2/categories?per_page=1`);
return response.headers.get('X-WP-Total');
} catch (error) {
console.error('Error fetching total categories:', error);
return 'Unavailable';
}
},
getCategories: async () => {
try {
const response = await fetch(`${config.baseUrl}/wp-json/wp/v2/categories`);
if (!response.ok) {
throw new Error(`Failed to fetch categories: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching categories:', error);
throw error; // You can choose to throw the error for better error handling
}
},
fetchPostsByPage: async (page = 1, perPage = 10) => {
try {
const response = await fetch(
`${config.baseUrl}/wp-json/wp/v2/posts?page=${page}&per_page=${perPage}&_embed`
);
if (!response.ok) {
throw new Error(`Failed to fetch posts: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching posts:', error);
throw error; // You can choose to throw the error for better error handling
}
},
fetchPostsByCategory: async (categoryId) => {
try {
const response = await fetch(
`${config.baseUrl}/wp-json/wp/v2/posts?categories=${categoryId}&_embed`
);
if (!response.ok) {
throw new Error(`Failed to fetch posts by category: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching posts by category:', error);
throw error; // You can choose to throw the error for better error handling
}
},
fetchCategoriesBySlug: async (slug) => {
try {
const response = await fetch(
`${config.baseUrl}/wp-json/wp/v2/categories?slug=${slug}`
);
if (!response.ok) {
throw new Error(`Failed to fetch categories by slug: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching categories by slug:', error);
throw error; // You can choose to throw the error for better error handling
}
},
fetchPost: async (postId) => {
try {
const response = await fetch(
`${config.baseUrl}/wp-json/wp/v2/posts/${postId}?_embed`
);
if (!response.ok) {
throw new Error(`Failed to fetch post: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching post:', error);
throw error; // You can choose to throw the error for better error handling
}
},
fetchPostsBySearch: async (query, page = 1, perPage = 10) => {
try {
// First, fetch the total number of search results to calculate the total pages
const totalResultsResponse = await fetch(
`${config.baseUrl}/wp-json/wp/v2/posts?per_page=1&search=${encodeURIComponent(
query
)}`
);
const totalResults = parseInt(
totalResultsResponse.headers.get('X-WP-Total')
);
const totalPages = Math.ceil(totalResults / perPage);
// Check if the requested page exceeds the total pages
if (page > totalPages) {
throw new Error(
`Page ${page} does not exist. Total pages: ${totalPages}.`
);
}
const response = await fetch(
`${config.baseUrl}/wp-json/wp/v2/posts?page=${page}&per_page=${perPage}&search=${encodeURIComponent(
query
)}&_embed`
);
if (!response.ok) {
throw new Error(`Failed to fetch posts: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching posts:', error);
throw error; // You can choose to throw the error for better error handling
}
},
getTotalSearchResults: async (query) => {
try {
// Make a request to the WordPress REST API to retrieve the total number of search results for the given query
const response = await fetch(`${config.baseUrl}/wp-json/wp/v2/posts?search=${query}`);
const headers = response.headers;
const totalResults = parseInt(headers.get('X-WP-Total'));
if (isNaN(totalResults)) {
throw new Error('Invalid total results count');
}
return totalResults;
} catch (error) {
console.error('Error fetching total search results:', error);
return 0; // Return 0 in case of an error
}
},
};
// Command Service
const commandService = {
execute: async (command) => {
terminalService.print(command);
let commandParts = command.split(' ');
let mainCommand = commandParts[0];
let arguments = commandParts.slice(1);
let page = 1;
let perPage = 10;
try {
switch (mainCommand) {
case 'ls':
page = parseInt(arguments[0]) || 1;
perPage = parseInt(arguments[1]) || 10;
await listPosts(page, perPage);
break;
case 'cat':
await viewPost(arguments[0]);
break;
case 'search':
page = parseInt(arguments[0]) || 1;
perPage = parseInt(arguments[1]) || 10;
await searchPosts(arguments[0], page, perPage);
break;
case 'categories':
await fetchCategories();
break;
case 'posts':
await listPostsByCategory(arguments[0]);
break;
case 'help':
await getHelp();
break;
default:
terminalService.printError('Command not recognized');
}
} catch (error) {
terminalService.printError('An error occurred while executing the command.');
} finally {
await terminalService.appendCommandInput();
history.scrollTop = history.scrollHeight;
}
},
};
// URL Service
const urlService = {
getCurrentPathname: () => {
const url = window.location.href;
const urlObj = new URL(url);
return urlObj.pathname;
},
getCategoryNameFromPathname: (pathname) => {
if (pathname.startsWith('/category/')) {
let categoryName = pathname.split('/category/')[1];
if (categoryName.endsWith('/')) {
categoryName = categoryName.slice(0, -1);
}
return categoryName;
}
return null;
},
getPostSlugFromPathname: (pathname) => {
if (pathname !== '/' && !pathname.startsWith('/category/')) {
let postSlug = pathname.slice(1); // Remove the leading '/'
if (postSlug.endsWith('/')) {
postSlug = postSlug.slice(0, -1);
}
return postSlug;
}
return null;
},
};
// Service for generating social media share links
const shareService = {
generateShareLinks: (url, title) => {
const twitterShareUrl = `https://twitter.com/intent/tweet?url=${url}&text=${title}`;
const facebookShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
const linkedInShareUrl = `https://www.linkedin.com/shareArticle?mini=true&url=${url}&title=${title}`;
return `<span class="shared-links"><span class="text-orange">Share on</span>
<a href="${twitterShareUrl}" target="_blank" class="terminal-link">Twitter</a> |
<a href="${facebookShareUrl}" target="_blank" class="terminal-link">Facebook</a> |
<a href="${linkedInShareUrl}" target="_blank" class="terminal-link">LinkedIn</a></span>
`;
},
};
// Service for error handling
const errorService = {
printError: (message) => {
// Implement logic to display error messages
},
};
document.addEventListener('DOMContentLoaded', (event) => {
welcomeScreen();
});
async function welcomeScreen() {
const title = await printTitle();
await commandService.execute('help');
await autoExecuteCommandFromURL();
}
// Refactored autoExecuteCommandFromURL using services
async function autoExecuteCommandFromURL() {
const pathname = urlService.getCurrentPathname();
const categoryName = urlService.getCategoryNameFromPathname(pathname);
const postSlug = urlService.getPostSlugFromPathname(pathname);
if (categoryName) {
const categoryId = await getCategoryIDByName(categoryName);
await commandService.execute(`posts ${categoryId}`);
} else if (postSlug) {
const postId = await getPostIDBySlug(postSlug);
await commandService.execute(`cat ${postId}`);
} else {
await commandService.execute('ls');
}
}
async function getPostIDBySlug(slug) {
try {
let response = await fetch(`/wp-json/wp/v2/posts?slug=${slug}`);
let posts = await response.json();
if (posts.length > 0) {
return posts[0].id; // Assuming the first post is the one we want
} else {
throw new Error('Post not found');
}
} catch (error) {
console.error('Error fetching post ID:', error);
return null;
}
}
async function printTitle() {
try {
const totalPosts = await apiService.getTotalPosts();
const totalCategories = await apiService.getTotalCategories();
const domain = new URL(config.baseUrl).hostname;
const emailAddress = `hello@${domain}`;
terminalService.print(`Welcome to ${config.siteTitle} - ${config.siteDescription}`);
terminalService.print(`* For more information, email: ${emailAddress}`);
terminalService.print(``);
terminalService.print(`System information as of ${new Date().toLocaleString()}`);
terminalService.print(``);
terminalService.print(`
<table class="no-spacing">
<tr>
<td>$ System software:</td>
<td>${config.serverSoftware}</td>
<td>Total Articles:</td>
<td>${totalPosts}</td>
</tr>
<tr>
<td>$ Request Time:</td>
<td>${config.requestTime}</td>
<td>Total Categories:</td>
<td>${totalCategories}</td>
</tr>
<tr>
<td>$ Memory usage:</td>
<td>${config.memoryUsage}</td>
<td>IP address:</td>
<td>${config.ipAddress}</td>
</tr>
</table>
`);
terminalService.print(`Current theme: ${config.currentTheme} `);
terminalService.print(``);
} catch (error) {
errorService.printError('Error fetching data');
}
}
async function getHelp() {
let helpText = `
<div class="help-text">
<strong>Available Commands:</strong>
<ul>
<li><strong>ls [page] [per_page]</strong> - Lists all articles. Usage: <code>ls</code> for default, <code>ls 2</code> for page 2, <code>ls 2 5</code> for page 2 with 5 posts per page.</li>
<li><strong>cat [post-id or title]</strong> - Displays a specific article by its ID or title. Usage: <code>cat 123</code> or <code>cat example-post-title</code></li>
<li><strong>search [query] [page] [per_page]</strong> - Searches articles with the given query. Usage: <code>search keyword</code> for default, <code>search keyword 2</code> for page 2, <code>search keyword 2 5</code> for page 2 with 5 posts per page</li>
<li><strong>categories</strong> - Lists all categories. Usage: <code>categories</code></li>
<li><strong>posts [category-id]</strong> - Lists all articles in a specific category. Usage: <code>posts 5</code> (where 5 is the category ID)</li>
<li><strong>help</strong> - Displays this help message. Usage: <code>help</code></li>
</ul>
</div>
`;
terminalService.print(`${helpText}`, false);
}
async function listPosts(page = 1, perPage = 10) {
try {
// First, fetch the total number of posts to calculate the total pages
const totalPosts = await apiService.getTotalPosts();
let totalPages = Math.ceil(totalPosts / perPage);
// Check if the requested page exceeds the total pages
if (page > totalPages) {
errorService.printError(`Page ${page} does not exist. Total pages: ${totalPages}.`);
return;
}
const posts = await apiService.fetchPostsByPage(page, perPage);
// Generate and display output
const output = posts.map(post => {
const date = new Date(post.date).toLocaleDateString();
const postUrl = `${config.baseUrl}/${post.slug}`; // Adjust based on your site's URL structure
const postTitle = encodeURIComponent(post.title.rendered);
// Generate social media share links
const socialMediaLinks = shareService.generateShareLinks(postUrl, postTitle);
return `ID: ${post.id} | <span class="clickable-post" onclick="commandService.execute('cat ${post.id}')">${post.title.rendered}</span> | Date: ${date} | ${socialMediaLinks}`;
}).join('<br>');
terminalService.print(output, false);
// Pagination controls
terminalService.print('<div class="pagination-controls">', false);
if (page > 1) {
terminalService.print(`<button class="terminal-button" onclick="commandService.execute(('ls ${parseInt(page) - 1} ${perPage}')">Previous Page</button>`, false);
}
if (page < totalPages) {
terminalService.print(`<button class="terminal-button" onclick="commandService.execute(('ls ${parseInt(page) + 1} ${perPage}')">Next Page</button>`, false);
}
terminalService.print('</div>', false);
} catch (error) {
errorService.printError('Error fetching posts');
}
}
async function viewPost(identifier) {
try {
const post = await apiService.fetchPost(identifier);
if (!post || post.length === 0) {
errorService.printError('Post not found');
return;
}
let content = `<h2>${post.title.rendered}</h2>`;
// Check if the post has a featured image
if (post._embedded && post._embedded['wp:featuredmedia'] && post._embedded['wp:featuredmedia'][0]) {
const imageUrl = post._embedded['wp:featuredmedia'][0].source_url;
content += `<img src="${imageUrl}" alt="${post.title.rendered}" onclick="openImagePopup('${imageUrl}')">`;
}
content += `${post.content.rendered}`;
terminalService.print(content, false);
const postUrl = `${config.baseUrl}/${post.slug}`; // Adjust based on your site's URL structure
const postTitle = encodeURIComponent(post.title.rendered);
terminalService.print(shareService.generateShareLinks(postUrl, postTitle), false);
} catch (error) {
errorService.printError('Error fetching post');
}
}
async function fetchCategories() {
try {
const categories = await apiService.getCategories();
displayCategories(categories);
} catch (error) {
errorService.printError('Error fetching categories');
}
}
function displayCategories(categories) {
const output = categories.map(category => {
const categoryUrl = `${config.baseUrl}/${category.slug}`; // Adjust based on your site's URL structure
const categoryTitle = encodeURIComponent(category.name);
// Generate social media share links
const socialMediaLinks = shareService.generateShareLinks(categoryUrl, categoryTitle);
return `ID: ${category.id} | <span class="clickable-post" onclick="commandService.execute('posts ${category.id}')">${category.name}</span> | <span>${socialMediaLinks}</span>`;
}).join('<br>');
terminalService.print(output);
}
async function listPostsByCategory(categoryId) {
try {
const posts = await apiService.fetchPostsByCategory(categoryId);
const output = posts.map(post => {
const date = new Date(post.date).toLocaleDateString();
return `ID: ${post.id} | <span class="clickable-post" onclick="commandService.execute('cat ${post.id}')">${post.title.rendered}</span> | Date: ${date}`;
}).join('<br>');
terminalService.print(output);
} catch (error) {
errorService.printError(`Error fetching posts for category ${categoryId}`);
}
}
async function getCategoryIDByName(categoryName) {
try {
const categories = await apiService.fetchCategoriesBySlug(categoryName);
if (categories.length > 0) {
return categories[0].id; // Assuming the first category is the one we want
} else {
throw new Error('Category not found');
}
} catch (error) {
errorService.printError('Error fetching category ID:', error);
return null;
}
}
async function searchPosts(query, page = 1, perPage = 10) {
try {
// Fetch the total number of search results to calculate total pages
const totalResults = await apiService.getTotalSearchResults(query);
const totalPages = Math.ceil(totalResults / perPage);
if (totalPages === 0) {
terminalService.print(`No results found for "${query}"`);
return;
}
// Check if the requested page exceeds the total pages
if (page > totalPages) {
errorService.printError(`Page ${page} does not exist. Total pages: ${totalPages}.`);
return;
}
// Fetch search results for the specified page
const searchResults = await apiService.fetchPostsBySearch(query, page, perPage);
// Generate and display output
const output = searchResults.map(post => {
const date = new Date(post.date).toLocaleDateString();
const postUrl = `${config.baseUrl}/${post.slug}`; // Adjust based on your site's URL structure
const postTitle = encodeURIComponent(post.title.rendered);
// Generate social media share links
const socialMediaLinks = shareService.generateShareLinks(postUrl, postTitle);
return `ID: ${post.id} | <span class="clickable-post" onclick="commandService.execute('cat ${post.id}')">${post.title.rendered}</span> | Date: ${date} | ${socialMediaLinks}`;
}).join('<br>');
terminalService.print(output);
// Pagination controls
terminalService.print('<div class="pagination-controls">', false);
if (page > 1) {
terminalService.print(`<button class="terminal-button" onclick="commandService.execute('search ${query} ${parseInt(page) - 1} ${perPage}')">Previous Page</button>`, false);
}
if (page < totalPages) {
terminalService.print(`<button class="terminal-button" onclick="commandService.execute('search ${query} ${parseInt(page) + 1} ${perPage}')">Next Page</button>`, false);
}
terminalService.print('</div>', false);
} catch (error) {
errorService.printError('Error fetching search results');
}
}
function openImagePopup(imageUrl) {
const popup = document.createElement('div');
popup.style.position = 'fixed';
popup.style.top = '0';
popup.style.left = '0';
popup.style.width = '100%';
popup.style.height = '100%';
popup.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
popup.style.display = 'flex';
popup.style.justifyContent = 'center';
popup.style.alignItems = 'center';
popup.style.zIndex = '1000';
const img = document.createElement('img');
img.src = imageUrl;
img.style.maxWidth = '90%';
img.style.maxHeight = '90%';
img.style.margin = 'auto';
popup.appendChild(img);
popup.addEventListener('click', function() {
document.body.removeChild(popup);
});
document.body.appendChild(popup);
}