-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_render.js
More file actions
1957 lines (1690 loc) · 56 KB
/
Copy pathapp_render.js
File metadata and controls
1957 lines (1690 loc) · 56 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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Elriel - A haunted terminal-based social network
// Render deployment version - completely removes SQLite dependency
// ==== RENDER SQLITE PREVENTION SYSTEM ====
// Overwrite the require function to prevent any SQLite module from loading
const originalRequire = module.require;
module.require = function(id) {
if (id === 'better-sqlite3' || id === 'sqlite3' || id.includes('sqlite')) {
console.error(`❌ BLOCKED IMPORT: Attempted to require SQLite module: ${id}`);
console.error('This is prevented in the Render deployment version.');
// Return a mock object instead of actually loading SQLite
return {
verbose: () => ({}),
Database: function() {
return {
prepare: () => ({
get: () => ({}),
all: () => ([]),
run: () => ({})
}),
close: () => {}
};
}
};
}
return originalRequire.apply(this, arguments);
};
// Also patch the global require function
const originalGlobalRequire = require;
global.require = function(id) {
if (id === 'better-sqlite3' || id === 'sqlite3' || id.includes('sqlite')) {
console.error(`❌ BLOCKED IMPORT: Attempted to require SQLite module: ${id}`);
console.error('This is prevented in the Render deployment version.');
// Return a mock object instead of actually loading SQLite
return {
verbose: () => ({}),
Database: function() {
return {
prepare: () => ({
get: () => ({}),
all: () => ([]),
run: () => ({})
}),
close: () => {}
};
}
};
}
return originalGlobalRequire.apply(this, arguments);
};
console.log('✅ Render SQLite Prevention System active - all SQLite imports will be mocked');
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require('path');
const multer = require('multer');
// IMPORTANT: This version is specifically for Render.com deployment
// It does NOT use any SQLite dependencies and should not import any modules that use SQLite
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
// Add a Render health check endpoint
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
// Configure Express for production behind proxy
app.set('trust proxy', 1);
// Configure middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Configure static file serving with multiple paths for better compatibility
const publicPath = path.join(__dirname, 'public');
console.log('Serving static files from primary path:', publicPath);
app.use(express.static(publicPath));
// Also serve files directly from the root for compatibility with some paths
app.use('/public', express.static(publicPath));
// Add logging and cache control for static assets
app.use((req, res, next) => {
// Log static asset requests
if (req.url.startsWith('/css/') || req.url.startsWith('/js/') || req.url.match(/\.(css|js|png|jpg|ico)$/)) {
console.log(`[STATIC ASSET] ${req.method} ${req.url} from ${publicPath}`);
}
// If the request is for a static asset
if (req.url.match(/\.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$/)) {
// Set cache headers
res.setHeader('Cache-Control', 'public, max-age=86400'); // 1 day
res.setHeader('Expires', new Date(Date.now() + 86400000).toUTCString());
}
next();
});
// Configure session
app.use(session({
secret: process.env.SESSION_SECRET || 'elriel_default_secret',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // Only secure in production
sameSite: 'lax',
maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
}
}));
// Configure file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
// Route to appropriate directory based on field name
if (file.fieldname === 'background' || file.fieldname === 'headerImage') {
cb(null, './public/uploads/backgrounds/');
} else if (file.fieldname === 'asset') {
cb(null, './public/uploads/assets/');
} else {
cb(null, './public/uploads/');
}
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
const ext = path.extname(file.originalname);
const prefix = file.fieldname === 'background' ? 'bg-' :
file.fieldname === 'headerImage' ? 'header-' :
file.fieldname === 'asset' ? 'asset-' : '';
cb(null, prefix + uniqueSuffix + ext);
}
});
const upload = multer({
storage,
limits: {
fileSize: 10 * 1024 * 1024 // 10MB limit
},
fileFilter: (req, file, cb) => {
// For profile images, accept only images
if (file.fieldname === 'background' || file.fieldname === 'headerImage') {
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed for backgrounds'), false);
}
}
// For assets, accept more file types
else if (file.fieldname === 'asset') {
const allowedTypes = [
'image/', 'text/', 'application/json', 'application/pdf',
'application/zip', 'application/x-zip-compressed',
'application/javascript', 'application/xml'
];
const isAllowed = allowedTypes.some(type => file.mimetype.startsWith(type));
if (isAllowed) {
cb(null, true);
} else {
cb(new Error('File type not allowed for assets'), false);
}
}
else {
cb(null, true);
}
}
});
// Create uploads directories if they don't exist
const fs = require('fs');
const uploadDirs = [
'./public/uploads',
'./public/uploads/backgrounds',
'./public/uploads/assets',
'./public/uploads/assets/thumbnails'
];
uploadDirs.forEach(dir => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
console.log(`Created upload directory: ${dir}`);
}
});
// Render health check endpoint
app.get('/health', (req, res) => {
res.status(200).send('OK');
});
// IMPORTANT: We do NOT import any routes files from the /routes directory here
// because those files might require better-sqlite3 directly or indirectly
// Instead, we define all routes directly in this file
// This ensures no SQLite dependencies are loaded
const staticRouter = express.Router();
// Basic home page
staticRouter.get('/', (req, res) => {
// Create mock data for the index page
const data = {
announcement: {
title: "Welcome to Elriel Network",
content: "This is a static demo version. Some features may be limited.",
created_at: new Date().toISOString()
},
recentActivity: [],
user: req.session.user || null
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'index.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(data));
res.send(html);
});
// Serve static views for demo
// Feed routes - Updated to use session-based data
staticRouter.get('/feed/bleedstream', (req, res) => {
try {
const { tag } = req.query;
const appData = initializeSessionData(req);
// Filter posts based on tag if provided
let posts = [...appData.posts];
if (tag) {
posts = posts.filter(post => post.tags && post.tags.includes(tag));
}
// Add some default posts if none exist
if (posts.length === 0 && !tag) {
const defaultPosts = [
{
id: 'default-1',
title: "Welcome to the Bleedstream",
content: "This is your personal feed. Create posts to see them here.",
username: "system_admin",
user_id: 'system',
created_at: new Date().toISOString(),
is_encrypted: 0,
tags: null,
glyph_id: null
},
{
id: 'default-2',
title: "Exploring the Digital Wasteland",
content: "The network expands. The signal grows stronger. Start posting to build your presence.",
username: "terminal_ghost",
user_id: 'system',
created_at: new Date(Date.now() - 86400000).toISOString(),
is_encrypted: 0,
tags: 'exploration,network',
glyph_id: null
}
];
posts = defaultPosts;
}
// Get all unique tags for filter dropdown
const allTags = new Set();
[...appData.posts].forEach(post => {
if (post.tags) {
post.tags.split(',').forEach(t => allTags.add(t.trim()));
}
});
const feedData = {
user: req.session.user || null,
posts: posts.slice(0, 50), // Limit to 50 posts
tags: Array.from(allTags),
currentTag: tag || null
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'feed', 'bleedstream.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(feedData));
res.send(html);
} catch (err) {
console.error('Error loading Bleedstream:', err);
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Redirect for compatibility with old links
staticRouter.get('/bleedstream', (req, res) => {
res.redirect('/feed/bleedstream');
});
// Glyph routes
staticRouter.get('/glyph/crucible', (req, res) => {
// Create mock glyph data
const glyphData = {
user: req.session.user || null,
glyphs: [
{
id: 1,
name: "Void Sigil",
creator: "system_admin",
created_at: new Date().toISOString()
},
{
id: 2,
name: "Digital Rune",
creator: "terminal_ghost",
created_at: new Date(Date.now() - 86400000).toISOString()
}
]
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'glyph', 'crucible.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(glyphData));
res.send(html);
});
// Redirect for compatibility with old links
staticRouter.get('/glyph-crucible', (req, res) => {
res.redirect('/glyph/crucible');
});
// Whisper routes
staticRouter.get('/whisper/board', (req, res) => {
try {
const appData = initializeSessionData(req);
// Initialize whispers if they don't exist
if (!appData.whispers) {
appData.whispers = [];
}
// Add default whispers if none exist
let whispers = [...appData.whispers];
if (whispers.length === 0) {
const defaultWhispers = [
{
id: 'whisper-1',
content: "The void listens. The network expands.",
user_id: 'system',
username: 'void_speaker',
created_at: new Date().toISOString()
},
{
id: 'whisper-2',
content: "Signals in the noise. Patterns in the static.",
user_id: 'system',
username: 'signal_hunter',
created_at: new Date(Date.now() - 86400000).toISOString()
}
];
whispers = defaultWhispers;
}
const whisperData = {
user: req.session.user || null,
whispers: whispers.slice(0, 50) // Limit to 50 whispers
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'whisper', 'board.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(whisperData));
res.send(html);
} catch (err) {
console.error('Error loading whisper board:', err);
res.set('Content-Type', 'text/html; charset=utf-8');
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Create whisper
staticRouter.post('/whisper/create', (req, res) => {
try {
if (!req.session.user) {
return res.status(401).json({
error: 'Authentication required',
message: 'Please log in to create whispers.'
});
}
const { content } = req.body;
if (!content) {
return res.status(400).json({
error: 'Invalid input',
message: 'Content is required.'
});
}
const appData = initializeSessionData(req);
if (!appData.whispers) {
appData.whispers = [];
}
const newWhisper = {
id: `whisper-${Date.now()}`,
content: content.slice(0, 500),
user_id: req.session.user.id,
username: req.session.user.username,
created_at: new Date().toISOString()
};
appData.whispers.unshift(newWhisper);
res.status(201).json({
success: true,
message: 'Whisper sent into the void',
whisperId: newWhisper.id
});
} catch (err) {
console.error('Whisper creation error:', err);
res.status(500).json({
error: 'System error',
message: 'Terminal connection unstable. Try again later.'
});
}
});
// Get whisper creation page
staticRouter.get('/whisper/new', (req, res) => {
try {
if (!req.session.user) {
return res.redirect('/auth/login');
}
const data = {
user: req.session.user
};
let html = fs.readFileSync(path.join(__dirname, 'views', 'whisper', 'new.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(data));
res.send(html);
} catch (err) {
console.error('Error loading whisper creation page:', err);
res.set('Content-Type', 'text/html; charset=utf-8');
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Redirect for compatibility with old links
staticRouter.get('/whisperboard', (req, res) => {
res.redirect('/whisper/board');
});
// Terminal/secrets routes
staticRouter.get('/terminal/numbpill', (req, res) => {
res.set('Content-Type', 'text/html; charset=utf-8');
res.sendFile(path.join(__dirname, 'views', 'secrets', 'numbpill.html'));
});
// Redirect for compatibility with old links
staticRouter.get('/numbpill', (req, res) => {
res.redirect('/terminal/numbpill');
});
staticRouter.get('/terminal/void', (req, res) => {
res.set('Content-Type', 'text/html; charset=utf-8');
res.sendFile(path.join(__dirname, 'views', 'secrets', 'void.html'));
});
// Profile routes
staticRouter.get('/profile', (req, res) => {
if (req.session.user) {
const appData = initializeSessionData(req);
// Get or create profile for this user
let profile = appData.profiles.get(req.session.user.id) || {
user_id: req.session.user.id,
status: 'New terminal connected',
custom_css: '',
custom_html: '',
theme_template: 'default',
blog_layout: 'feed',
district_id: 1,
background_image: null,
header_image: null,
widgets_data: null,
glyph_id: null,
glyph_3d: 0,
glyph_rotation_speed: 3,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
// Get user's glyph if set
let glyph = null;
if (profile.glyph_id) {
glyph = appData.glyphs.find(g => g.id == profile.glyph_id);
}
// Get user's posts
const posts = appData.posts.filter(p => p.user_id === req.session.user.id);
const profileData = {
user: req.session.user,
profile: profile,
glyph: glyph,
posts: posts
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'profile', 'view.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(profileData));
res.send(html);
} else {
res.redirect('/auth/login');
}
});
// Auth routes
staticRouter.get('/auth/login', (req, res) => {
const filePath = path.join(__dirname, 'views', 'auth', 'login.html');
console.log(`[LOGIN ROUTE] Requested login page. Path: ${filePath}`);
console.log(`[LOGIN ROUTE] File exists: ${fs.existsSync(filePath)}`);
res.set('Content-Type', 'text/html; charset=utf-8');
res.sendFile(filePath, (err) => {
if (err) {
console.error(`[LOGIN ROUTE] Error serving file: ${err}`);
res.status(err.status || 500).send('Failed to load login page');
} else {
console.log(`[LOGIN ROUTE] Login page sent successfully. Status: ${res.statusCode}`);
console.log(`[LOGIN ROUTE] Content-Type: ${res.get('Content-Type')}`);
}
});
});
staticRouter.get('/auth/register', (req, res) => {
res.set('Content-Type', 'text/html; charset=utf-8');
res.sendFile(path.join(__dirname, 'views', 'auth', 'register.html'));
});
// Handle login (mock version for demo)
staticRouter.post('/auth/login', (req, res) => {
const { username, password } = req.body;
// For demo purposes, accept any login
// In a real app, you would validate against a database
req.session.user = {
id: 1,
username: username,
isAdmin: false
};
res.json({
success: true,
message: 'Terminal access granted',
user: req.session.user
});
});
// Handle registration (mock version for demo)
staticRouter.post('/auth/register', (req, res) => {
const { username, email, password } = req.body;
// For demo purposes, accept any registration
// In a real app, you would store in a database
req.session.user = {
id: Math.floor(Math.random() * 1000) + 1,
username: username,
isAdmin: false
};
res.status(201).json({
success: true,
message: 'Terminal identity registered successfully',
user: req.session.user
});
});
// Handle logout
staticRouter.get('/auth/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
console.error('Logout error:', err);
return res.status(500).json({
error: 'System error',
message: 'Terminal disconnection failed. Try again.'
});
}
res.redirect('/');
});
});
// Redirect for compatibility with old links
staticRouter.get('/login', (req, res) => {
res.redirect('/auth/login');
});
staticRouter.get('/register', (req, res) => {
res.redirect('/auth/register');
});
// Additional redirects for common path issues
staticRouter.get('/bleedstream.html', (req, res) => {
res.redirect('/feed/bleedstream');
});
staticRouter.get('/glyph-crucible.html', (req, res) => {
res.redirect('/glyph/crucible');
});
staticRouter.get('/whisperboard.html', (req, res) => {
res.redirect('/whisper/board');
});
staticRouter.get('/numbpill.html', (req, res) => {
res.redirect('/terminal/numbpill');
});
staticRouter.get('/void', (req, res) => {
res.redirect('/terminal/void');
});
staticRouter.get('/secrets/numbpill', (req, res) => {
res.redirect('/terminal/numbpill');
});
staticRouter.get('/secrets/void', (req, res) => {
res.redirect('/terminal/void');
});
// Forum routes
staticRouter.get('/forum', (req, res) => {
res.redirect('/forum/scrapyard');
});
staticRouter.get('/forum/scrapyard', (req, res) => {
// Create mock forum data
const forumData = {
items: [
{
id: 1,
title: "Welcome to the Scrapyard",
content: "This is a demo post in the static version.",
username: "system_admin",
created_at: new Date().toISOString(),
comment_count: 2
},
{
id: 2,
title: "Digital Artifacts Collection",
content: "Share your findings from the digital wasteland.",
username: "terminal_ghost",
created_at: new Date(Date.now() - 86400000).toISOString(),
comment_count: 0
}
],
user: req.session.user || null
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'forum', 'scrapyard.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(forumData));
res.send(html);
});
// Forum topic view
staticRouter.get('/forum/topic/:id', (req, res) => {
const id = req.params.id;
// Create mock topic data
const topicData = {
topic: {
id: id,
title: id === "1" ? "Welcome to the Scrapyard" : "Digital Artifacts Collection",
content: "This is a demo topic in the static version.",
username: "system_admin",
created_at: new Date().toISOString(),
forum_title: "Scrapyard",
forum_slug: "scrapyard"
},
comments: [
{
id: 1,
content: "First comment on this topic.",
username: "terminal_ghost",
created_at: new Date(Date.now() - 3600000).toISOString()
}
],
user: req.session.user || null
};
// Inject data into the HTML
let html = fs.readFileSync(path.join(__dirname, 'views', 'forum', 'topic.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(topicData));
res.send(html);
});
// Session-based data storage for the static version
// This creates persistent data that survives across requests within the same session
const initializeSessionData = (req) => {
if (!req.session.appData) {
req.session.appData = {
profiles: new Map(),
posts: [],
glyphs: [],
districts: [
{ id: 1, name: 'Central Terminal', is_hidden: 0 },
{ id: 2, name: 'Digital Wasteland', is_hidden: 0 },
{ id: 3, name: 'Void District', is_hidden: 0 },
{ id: 4, name: 'Neon Sector', is_hidden: 0 }
],
nextPostId: 1,
nextGlyphId: 1
};
}
return req.session.appData;
};
// Profile update route
staticRouter.post('/profile/update', upload.fields([
{ name: 'background', maxCount: 1 },
{ name: 'headerImage', maxCount: 1 }
]), (req, res) => {
try {
if (!req.session.user) {
return res.status(401).json({
error: 'Authentication required',
message: 'Please log in to update your profile.'
});
}
const appData = initializeSessionData(req);
const { status, customCss, customHtml, themeTemplate, blogLayout, districtId, widgets } = req.body;
// Get or create profile for this user
let profile = appData.profiles.get(req.session.user.id) || {
user_id: req.session.user.id,
status: 'New terminal connected',
custom_css: '',
custom_html: '',
theme_template: 'default',
blog_layout: 'feed',
district_id: 1,
background_image: null,
header_image: null,
widgets_data: null,
glyph_id: null,
glyph_3d: 0,
glyph_rotation_speed: 3,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
// Update profile fields
if (status !== undefined) profile.status = status.slice(0, 100);
if (customCss !== undefined) profile.custom_css = customCss.slice(0, 10000);
if (customHtml !== undefined) profile.custom_html = customHtml.slice(0, 20000);
if (themeTemplate) profile.theme_template = themeTemplate;
if (blogLayout) profile.blog_layout = blogLayout;
if (districtId) profile.district_id = parseInt(districtId);
// Handle file uploads
if (req.files) {
if (req.files.background && req.files.background[0]) {
profile.background_image = '/uploads/backgrounds/' + req.files.background[0].filename;
}
if (req.files.headerImage && req.files.headerImage[0]) {
profile.header_image = '/uploads/backgrounds/' + req.files.headerImage[0].filename;
}
}
// Handle widgets
if (widgets) {
try {
const parsedWidgets = JSON.parse(widgets);
if (Array.isArray(parsedWidgets)) {
profile.widgets_data = widgets;
}
} catch (e) {
console.error('Error parsing widgets data:', e);
}
}
profile.updated_at = new Date().toISOString();
// Save profile back to session
appData.profiles.set(req.session.user.id, profile);
res.json({
success: true,
message: 'Terminal identity updated successfully'
});
} catch (err) {
console.error('Profile update error:', err);
res.status(500).json({
error: 'System error',
message: 'Terminal connection unstable. Try again later.'
});
}
});
// Profile edit page with proper data injection
staticRouter.get('/profile/edit', (req, res) => {
try {
if (!req.session.user) {
return res.redirect('/auth/login');
}
const appData = initializeSessionData(req);
let profile = appData.profiles.get(req.session.user.id) || {
user_id: req.session.user.id,
status: 'New terminal connected',
custom_css: '',
custom_html: '',
theme_template: 'default',
blog_layout: 'feed',
district_id: 1,
background_image: null,
header_image: null,
widgets_data: null,
glyph_id: null,
glyph_3d: 0,
glyph_rotation_speed: 3,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
// Get user's glyphs (mock data for now)
const userGlyphs = appData.glyphs.filter(g => g.user_id === req.session.user.id);
const data = {
profile,
glyph: profile.glyph_id ? userGlyphs.find(g => g.id === profile.glyph_id) : null,
userGlyphs,
districts: appData.districts,
user: req.session.user
};
let html = fs.readFileSync(path.join(__dirname, 'views', 'profile', 'edit.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(data));
res.send(html);
} catch (err) {
console.error('Error loading profile editor:', err);
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Feed post creation
staticRouter.get('/feed/new', (req, res) => {
try {
if (!req.session.user) {
return res.redirect('/auth/login');
}
const appData = initializeSessionData(req);
const userGlyphs = appData.glyphs.filter(g => g.user_id === req.session.user.id);
const data = {
glyphs: userGlyphs,
user: req.session.user
};
let html = fs.readFileSync(path.join(__dirname, 'views', 'feed', 'new-post.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(data));
res.send(html);
} catch (err) {
console.error('Error loading new post page:', err);
res.set('Content-Type', 'text/html; charset=utf-8');
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Create new post
staticRouter.post('/feed/create', (req, res) => {
try {
if (!req.session.user) {
return res.status(401).json({
error: 'Authentication required',
message: 'Please log in to create posts.'
});
}
const { title, content, tags, glyphId, isEncrypted } = req.body;
if (!title || !content) {
return res.status(400).json({
error: 'Invalid input',
message: 'Title and content are required.'
});
}
const appData = initializeSessionData(req);
// Generate encryption key if post is encrypted
let encryptionKey = null;
if (isEncrypted === '1' || isEncrypted === true) {
encryptionKey = require('crypto').randomBytes(16).toString('hex');
}
// Create new post
const newPost = {
id: appData.nextPostId++,
user_id: req.session.user.id,
username: req.session.user.username,
title,
content,
tags: tags || null,
is_encrypted: isEncrypted === '1' || isEncrypted === true ? 1 : 0,
encryption_key: encryptionKey,
glyph_id: glyphId || null,
created_at: new Date().toISOString()
};
appData.posts.unshift(newPost); // Add to beginning for latest first
const response = {
success: true,
message: 'Post successfully transmitted to the Bleedstream',
postId: newPost.id
};
if (encryptionKey) {
response.encryptionKey = encryptionKey;
response.message += '. Save your encryption key to access this post later.';
}
res.status(201).json(response);
} catch (err) {
console.error('Post creation error:', err);
res.status(500).json({
error: 'System error',
message: 'Terminal connection unstable. Try again later.'
});
}
});
// View specific post
staticRouter.get('/feed/post/:id', (req, res) => {
try {
const { id } = req.params;
const { key } = req.query;
const appData = initializeSessionData(req);
const post = appData.posts.find(p => p.id == id);
if (!post) {
return res.status(404).sendFile(path.join(__dirname, 'views', '404.html'));
}
// Check if post is encrypted and key is provided
if (post.is_encrypted === 1 && post.encryption_key !== key) {
let html = fs.readFileSync(path.join(__dirname, 'views', 'feed', 'encrypted-post.html'), 'utf8');
html = html.replace('__POST_ID__', id);
return res.send(html);
}
// Get user profile
const profile = appData.profiles.get(post.user_id) || {
user_id: post.user_id,
status: 'Terminal connected',
district_name: 'Unknown District'
};
const data = {
post,
profile,
user: req.session.user || null,
isOwner: req.session.user && req.session.user.id === post.user_id
};
let html = fs.readFileSync(path.join(__dirname, 'views', 'feed', 'view-post.html'), 'utf8');
html = html.replace('__DATA__', JSON.stringify(data));
res.send(html);
} catch (err) {
console.error('Error viewing post:', err);
res.set('Content-Type', 'text/html; charset=utf-8');
res.status(500).sendFile(path.join(__dirname, 'views', 'error.html'));
}
});
// Delete post
staticRouter.delete('/feed/post/:id', (req, res) => {
try {
if (!req.session.user) {
return res.status(401).json({
error: 'Authentication required',
message: 'Please log in to delete posts.'
});
}
const { id } = req.params;
const appData = initializeSessionData(req);
const postIndex = appData.posts.findIndex(p => p.id == id && p.user_id === req.session.user.id);