-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
1530 lines (1527 loc) · 77.9 KB
/
server.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
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
import http from "node:http";
import url from "url";
import fs from "fs";
import path from "path";
import os from "os";
import {Ollama} from "ollama";
import formidable from "formidable";
import mime from "mime";
import {v4 as uuidv4} from 'uuid';
import crypto from 'crypto';
import bcrypt from 'bcrypt';
import moment from 'moment';
import zipper from 'zip-local';
import { exec } from 'child_process';
import tesseract from "node-tesseract-ocr";
import { fromPath } from "pdf2pic";
import pdf from 'pdf-page-counter';
import { config, validateConfig, setConfig } from './config/env.js';
validateConfig();
const server = http.createServer((req, res)=>{
const baseDir=config.baseDir;
const saltRounds=10;
let body = '';
let r={error:'',data:''}
let url=new URL("http://"+os.hostname()+":3000/"+req.url);
let s=url.searchParams;
const uploadMaxFileSize=9000*1024*1024; // 9gb
//
if(req.url.split('/')[1]==='authenticate') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let passcode=payload.passcode;
let hashedPasscode=JSON.parse(fs.readFileSync(baseDir+'/p.json'))['p'];
bcrypt.compare(passcode,hashedPasscode,(err,result)=>{
if(result) {
if(!fs.existsSync(baseDir+'/t.json')) fs.writeFileSync(baseDir+'/t.json','[]');
let tokens=JSON.parse(fs.readFileSync(baseDir+'/t.json'));
let t=crypto.createHash('sha256').update(Math.random().toString()).digest('hex');
tokens.push({id:uuidv4(),t:t,timestamp:moment().unix(),alive:1});
fs.writeFileSync(baseDir+'/t.json',JSON.stringify(tokens));
r.data=t;
}
else {
r.error='Wrong passcode.';
}
res.writeHead(200,{'Content-Type':'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
else {
let tokens=JSON.parse(fs.readFileSync(baseDir+'/t.json'));
if((req.headers['public-token'] && tokens.findIndex(x=>x.t===req.headers['public-token'])>-1) || (s.get('publicToken') && tokens.findIndex(x=>x.t===s.get('publicToken'))>-1)) {
const host=config.host;
const modelV=config.modelV;
const embedModel=config.embedModel;
//
const chatDir=baseDir+'/chat';
const filesDir=baseDir+'/files';
const tempDir=baseDir+'/temp';
const embeddingsDir=baseDir+'/embeddings';
const settingsDir=baseDir+'/settings';
const firmwareDir=baseDir+'/firmware';
const logsDir=baseDir+'/logs';
const appsDir=baseDir+'/apps';
//
const ollama=new Ollama({host:'http://'+host+':11434'});
//
//
if(!fs.existsSync(baseDir)) fs.mkdirSync(baseDir);
//
// chat
if(!fs.existsSync(chatDir)) fs.mkdirSync(chatDir);
if(!fs.existsSync(chatDir+'/chats.json') || fs.readFileSync(chatDir+'/chats.json')==='') fs.writeFile(chatDir+'/chats.json','[]',()=>{});
if(!fs.existsSync(chatDir+'/personalities.json') || fs.readFileSync(chatDir+'/personalities.json')==='') fs.writeFile(chatDir+'/personalities.json',JSON.stringify([{id:"default",name:"PERSYS","active":1,"system":"Your name is Persys and you are a virtual personal assistant. Be brief in your answers."}]),()=>{});
//
// main files dir
if(!fs.existsSync(filesDir)) fs.mkdirSync(filesDir);
//
// temp dir for zip downloads and pdf conversions
if(!fs.existsSync(tempDir)) fs.mkdirSync(tempDir);
//
// embeddings dir
if(!fs.existsSync(embeddingsDir)) fs.mkdirSync(embeddingsDir);
if(!fs.existsSync(embeddingsDir+'/embeddings.json') || fs.readFileSync(embeddingsDir+'/embeddings.json')==='') fs.writeFileSync(embeddingsDir+'/embeddings.json','[]');
//
// settings dir
if(!fs.existsSync(settingsDir)) fs.mkdirSync(settingsDir);
if(!fs.existsSync(settingsDir+'/settings.json') || fs.readFileSync(settingsDir+'/settings.json')==='') fs.writeFileSync(settingsDir+'/settings.json',JSON.stringify({wallpapers:[{name:'default_wallpaper.jpg',active:1,default:1}]}));
if(!fs.existsSync(settingsDir+'/wallpapers')) fs.mkdirSync(settingsDir+'/wallpapers');
if(!fs.existsSync(settingsDir+'/wallpapers/default_wallpaper.jpg')) fs.copyFileSync('default_wallpaper.jpg',settingsDir+'/wallpapers/default_wallpaper.jpg');
//
// firmware update dir
if(!fs.existsSync(firmwareDir)) fs.mkdirSync(firmwareDir);
// logs dir
if(!fs.existsSync(logsDir)) fs.mkdirSync(logsDir);
//
// apps dir
if(!fs.existsSync(appsDir)) fs.mkdirSync(appsDir);
if(!fs.existsSync(appsDir+'/todo.json') || fs.readFileSync(appsDir+'/todo.json')==='') fs.writeFile(appsDir+'/todo.json','[]',()=>{});
if(!fs.existsSync(appsDir+'/cardclip.json') || fs.readFileSync(appsDir+'/cardclip.json')==='') fs.writeFile(appsDir+'/cardclip.json',JSON.stringify([{id:'default',firstName:'Persys Support',lastName:'', phone:'', email:'[email protected]',thumb:false}]),()=>{});
if(!fs.existsSync(appsDir+'/cardclip')) fs.mkdirSync(appsDir+'/cardclip');
if(!fs.existsSync(appsDir+'/paper')) fs.mkdirSync(appsDir+'/paper');
//
//
//
if(req.url.split('/')[1]==='sessions') {
if(req.url.split('/')[2]==='logout') {
let tokens=JSON.parse(fs.readFileSync(baseDir+'/t.json'));
tokens.splice(tokens.findIndex(x=>x.id===req.headers['public-token']),1);
fs.writeFile(baseDir+'/t.json',JSON.stringify(tokens),(err) => {
if(!err) {
r.data='deleted';
}
else {
r.error='Could not log out.';
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
}
else if(req.url.split('/')[2]==='all') {
let tokens=JSON.parse(fs.readFileSync(baseDir+'/t.json'));
for(let i=0;i<tokens.length;i++) {
if(req.headers['public-token']===tokens[i].t) tokens[i].current=true;
tokens[i].t='';
}
r.data=tokens;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
else if(req.url.split('/')[2]==='delete') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let tokens=JSON.parse(fs.readFileSync(baseDir+'/t.json'));
tokens.splice(tokens.findIndex(x=>x.id===payload.id),1);
fs.writeFile(baseDir+'/t.json',JSON.stringify(tokens),(err) => {
if(!err) {
r.data='deleted';
}
else {
r.error='Could not delete session.';
}
res.writeHead(200,{'Content-Type':'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
}
//
// about
if(req.url.split('/')[1]==='about') {
r.data={
deviceName:config.deviceName,
serialNumber:config.serialNumber,
firmwareVersion:config.firmwareVersion
};
res.writeHead(200,{'Content-Type':'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
//
// file system endpoints
else if(req.url.split('/')[1]==='files') {
if(req.url.split('/')[2]==='get') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
fs.readdir(filesDir+payload.path, (err, files) => {
let filesPacket=[];
files.forEach((fileItem,i)=>{
fs.stat(filesDir+'/'+payload.path+'/'+fileItem,(err,stats)=>{
filesPacket.push({name:fileItem,isDirectory:stats.isDirectory(),mime:mime.getType(filesDir+'/'+payload.path+'/'+fileItem)});
if(i===files.length-1) {
if(!err) r.data=filesPacket;
else r.error=err;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
});
});
});
});
}
else if(req.url.split('/')[2]==='upload') {
let form=formidable({maxFileSize:uploadMaxFileSize});
form.parse(req, (err, fields, files)=>{
let fileContent=fs.readFileSync(files.file[0].filepath);
fs.writeFile(filesDir+'/'+fields.path+'/'+fields.fileName,fileContent,(err)=>{
if(!err) {
r.data='uploaded';
}
else {
r.error=err;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
else if(req.url.split('/')[2]==='new-folder') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
if(!fs.existsSync(filesDir+payload.path+'/'+payload.folderName)){
fs.mkdirSync(filesDir+payload.path+'/'+payload.folderName);
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='created';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else if(req.url.split('/')[2]==='rename') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
if(fs.existsSync(filesDir+payload.path+'/'+payload.file.name)) {
fs.rename(filesDir+payload.path+'/'+payload.file.name,filesDir+payload.path+'/'+payload.newName,(err)=>{
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='renamed';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Error renaming object';
res.write(JSON.stringify(r));
return res.end();
}
});
}
});
}
else if(req.url.split('/')[2]==='delete') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
if(fs.existsSync(filesDir+payload.path+'/'+payload.file.name)){
if(payload.file.isDirectory) {
fs.rmdir(filesDir+payload.path+'/'+payload.file.name,(err)=>{
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='deleted';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Error deleting folder';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else {
fs.unlink(filesDir+payload.path+'/'+payload.file.name,(err)=>{
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='deleted';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Error deleting file';
res.write(JSON.stringify(r));
return res.end();
}
});
}
}
});
}
else if(req.url.split('/')[2]==='plaintext') {
req.on('data',(chunk)=>{
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
if(fs.existsSync(filesDir+payload.path+'/'+payload.file.name)){
fs.readFile(filesDir+payload.path+'/'+payload.file.name,(err,content)=>{
let buff=new Buffer(content);
r.data=btoa(buff.toString());
res.writeHead(200,{'Content-Type':'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
}
});
}
else if(req.url.split('/')[2]==='list-objects') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let indexed=[];
function walk(dir) {
let items=fs.readdirSync(dir);
if(items && items.length>0) {
items.forEach((item)=>{
let stats=fs.statSync(path.join(dir,item));
if(stats.isDirectory()) walk(path.join(dir,item));
else {
let filePath=path.join(dir,item);
if(payload.type.indexOf(path.extname(item).toLowerCase())>-1) indexed.push({name:item,mime:mime.getType(filePath),path:filePath});
}
});
}
}
walk(filesDir);
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=indexed;
res.write(JSON.stringify(r));
return res.end();
});
}
else if(req.url.split('/')[2]==='stream') {
let fileName=decodeURIComponent(s.get('fileName'))
let basePath=decodeURIComponent(s.get('path'));
let fullPath=decodeURIComponent(s.get('fullPath'));
let srcPath;
if(s.get('fullPath')) srcPath=fullPath;
else srcPath=filesDir+basePath+'/'+fileName;
let buffer=fs.readFileSync(srcPath);
let stats=fs.statSync(srcPath);
res.writeHead(200,{
'Content-Type':mime.getType(srcPath),
'Content-Length':stats.size,
});
res.write(buffer);
return res.end();
}
else if(req.url.split('/')[2]==='download') {
let fileName=decodeURIComponent(s.get('fileName'))
let basePath=decodeURIComponent(s.get('path'));
let fullPath=decodeURIComponent(s.get('fullPath'));
let srcPath;
if(s.get('fullPath')) srcPath=fullPath;
else srcPath=filesDir+basePath+'/'+fileName;
let stats=fs.statSync(srcPath);
if(stats.isDirectory()) {
zipper.zip(srcPath,(error,zipped)=>{
if(!error) {
zipped.compress();
zipped.save(tempDir+'/'+fileName+'.zip',(error)=>{
if(!error) {
let buffer=fs.readFileSync(tempDir+'/'+fileName+'.zip');
res.writeHead(200,{
'Content-Type':mime.getType(tempDir+'/'+fileName+'.zip'),
"Content-Disposition":"attachment;filename="+fileName+'.zip',
'Content-Length':buffer.length,
});
res.write(buffer);
return res.end();
}
});
}
});
}
else {
let buffer=fs.readFileSync(srcPath);
res.writeHead(200,{
'Content-Type':mime.getType(srcPath),
"Content-Disposition":"attachment;filename="+fileName,
'Content-Length':buffer.length,
});
res.write(buffer);
return res.end();
}
}
}
//
// chat endpoints
else if(req.url.split('/')[1]==='chat') {
if(req.url.split('/')[2]==='get') {
fs.readFile(chatDir+'/chats.json', (err, content) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=JSON.parse(content);
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Chats not found. Create a new one.';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else if(req.url.split('/')[2]==='create') {
let chats=JSON.parse(fs.readFileSync(chatDir+'/chats.json'));
let session={id:uuidv4(),name:'Untitled Chat',active:1};
chats.push(session);
fs.writeFileSync(chatDir+'/session_'+session.id+'.json','[]');
fs.writeFile(chatDir+'/chats.json',JSON.stringify(chats),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='created';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not create chat session.';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else if(req.url.split('/')[2]==='activate') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let chats=JSON.parse(fs.readFileSync(chatDir+'/chats.json'));
for(let i=0;i<chats.length;i++) {
chats[i].active=0;
}
chats[chats.findIndex(x=>x.id===payload.id)].active=1;
fs.writeFile(chatDir+'/chats.json', JSON.stringify(chats),(err) => {
if(!err) r.data='activated';
else r.error='Could not activate chat session.';
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
else if(req.url.split('/')[2]==='history') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
fs.readFile(chatDir+'/session_'+payload.id+'.json', (err, content) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=JSON.parse(content);
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Chat history not found.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='save') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
fs.writeFile(chatDir+'/session_'+payload.id+'.json',JSON.stringify(payload.history), (err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='saved';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Chat history could not be saved.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='rename') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let chats=JSON.parse(fs.readFileSync(chatDir+'/chats.json'));
chats[chats.findIndex(x=>x.id===payload.id)].name=payload.name;
fs.writeFile(chatDir+'/chats.json', JSON.stringify(chats),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='reamed';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not rename chat session.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='delete') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let chats=JSON.parse(fs.readFileSync(chatDir+'/chats.json'));
chats.splice(chats.findIndex(x=>x.id===payload.id),1);
fs.writeFile(chatDir+'/chats.json', JSON.stringify(chats),(err) => {
if(!err) {
fs.unlinkSync(chatDir+'/session_'+payload.id+'.json');
r.data='deleted';
}
else {
r.error='Could not delete chat session.';
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
}
else if(req.url.split('/')[1]==='personalities') {
if(req.url.split('/')[2]==='get') {
fs.readFile(chatDir+'/personalities.json', (err, content) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=JSON.parse(content);
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not access personalities.';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else if(req.url.split('/')[2]==='create') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let personalities=JSON.parse(fs.readFileSync(chatDir+'/personalities.json'));
personalities.push({id:uuidv4(),name:payload.name,active:1,system:payload.system});
let modelfile=`
FROM `+modelV+`
SYSTEM "`+payload.system+`"
`;
ollama.create({model:modelV,modelfile:modelfile});
fs.writeFile(chatDir+'/personalities.json', JSON.stringify(personalities),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='created';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not create AI personality.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='activate') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let personalities=JSON.parse(fs.readFileSync(chatDir+'/personalities.json'));
for(let i=0;i<personalities.length;i++) {
personalities[i].active=0;
}
let pIndex=personalities.findIndex(x=>x.id===payload.id);
personalities[pIndex].active=1;
let modelfile=`
FROM `+modelV+`
SYSTEM "`+personalities[pIndex].system+`"
`;
ollama.create({model:modelV,modelfile:modelfile});
fs.writeFile(chatDir+'/personalities.json', JSON.stringify(personalities),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='activated';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not activate AI personality.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='update') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let personalities=JSON.parse(fs.readFileSync(chatDir+'/personalities.json'));
if(payload.id==='default') {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Default personality cannot be updated.';
res.write(JSON.stringify(r));
return res.end();
}
let pIndex=personalities.findIndex(x=>x.id===payload.id);
personalities[pIndex].name=payload.name;
personalities[pIndex].system=payload.system;
fs.writeFile(chatDir+'/personalities.json', JSON.stringify(personalities),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='created';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not update AI personality.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='delete') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
if(payload.id==='default') {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Default personality cannot be deleted.';
res.write(JSON.stringify(r));
return res.end();
}
let personalities=JSON.parse(fs.readFileSync(chatDir+'/personalities.json'));
personalities.splice(personalities.findIndex(x=>x.id===payload.id),1);
fs.writeFile(chatDir+'/personalities.json', JSON.stringify(personalities),(err) => {
if(!err) {
res.writeHead(200, {'Content-Type': 'application/json'});
r.data='deleted';
res.write(JSON.stringify(r));
return res.end();
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Could not delete AI personality.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
}
//
// embeddings endpoint
else if(req.url.split('/')[1]==='embeddings') {
if(req.url.split('/')[2]==='create') {
req.on('data',(chunk)=>{
body+=chunk;
});
req.on('end',()=>{
let payload=JSON.parse(body);
let settings=JSON.parse(fs.readFileSync(embeddingsDir+'/embeddings.json'));
if((settings.findIndex(x=>x.name===payload.name)>-1 && settings[settings.findIndex(x=>x.name===payload.name)].md5!==crypto.createHash('md5').update(JSON.stringify(payload.content)).digest('hex')) || settings.findIndex(x=>x.name===payload.name)===-1){
async function embed() {
let vector={data:[],prompt:''};
for(let i=0;i<payload.content.length;i++) {
let v=await ollama.embeddings({model:embedModel,prompt:payload.content[i]});
vector.data.push({vector:v.embedding,document:payload.content[i]});
}
return vector;
}
embed().then(result =>{
fs.writeFileSync(embeddingsDir+'/'+payload.name+'.embedding',JSON.stringify(result));
if(settings.findIndex(x=>x.name===payload.name)>-1) {
settings[settings.findIndex(x=>x.name===payload.name)].active=1;
settings[settings.findIndex(x=>x.name===payload.name)].md5=crypto.createHash('md5').update(JSON.stringify(payload.content)).digest('hex');
}
else settings.push({name:payload.name,active:1,md5:crypto.createHash('md5').update(JSON.stringify(payload.content)).digest('hex')});
fs.writeFileSync(embeddingsDir+'/embeddings.json',JSON.stringify(settings));
res.writeHead(200,{'Content-Type': 'application/json'});
r.data='embedded';
res.write(JSON.stringify(r));
return res.end();
});
}
else {
res.writeHead(200,{'Content-Type': 'application/json'});
r.data='already embedded';
res.write(JSON.stringify(r));
return res.end();
}
});
}
else if(req.url.split('/')[2]==='rag') {
req.on('data',(chunk)=>{
body+=chunk;
});
req.on('end',()=>{
let payload=JSON.parse(body);
let settings=JSON.parse(fs.readFileSync(embeddingsDir+'/embeddings.json'));
let emPath=embeddingsDir+'/'+payload.name+'.embedding';
if(fs.existsSync(emPath)) {
let embeddedFile=JSON.parse(fs.readFileSync(emPath));
embeddedFile.prompt=payload.input;
for(let i=0;i<settings.length;i++) {
settings[i].active=0;
}
settings[settings.findIndex(x=>x.name===payload.name)].active=1;
fs.writeFileSync(embeddingsDir+'/embeddings.json',JSON.stringify(settings));
//
fs.writeFile(emPath,JSON.stringify(embeddedFile),(err)=>{
if(!err) {
r.data='Saved';
}
else {
r.error='Could not save prompt.';
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
}
else {
r.error='Embedding does not exist.';
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
});
}
}
//
// models
else if(req.url.split('/')[1]==='models') {
if(req.url.split('/')[2]==='ps') {
async function ps() {
return await ollama.ps();
}
ps().then(models=>{
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=models.models;
res.write(JSON.stringify(r));
return res.end();
});
}
else if(req.url.split('/')[2]==='list') {
async function list() {
return await ollama.list();
}
list().then(models=>{
res.writeHead(200, {'Content-Type': 'application/json'});
r.data=models.models;
res.write(JSON.stringify(r));
return res.end();
});
}
else if(req.url.split('/')[2]==='stop') {
req.on('data',(chunk)=>{
body+=chunk;
});
req.on('end',()=>{
let payload=JSON.parse(body);
//exec('ollama stop '+payload.name);
res.writeHead(200,{'Content-Type': 'application/json'});
r.data='stopped';
res.write(JSON.stringify(r));
return res.end();
});
}
else if(req.url.split('/')[2]==='create') {
req.on('data',(chunk)=>{
body+=chunk;
});
req.on('end',()=>{
let payload=JSON.parse(body);
let personalities=JSON.parse(fs.readFileSync(chatDir+'/personalities.json'));
let activePersonality=personalities[personalities.findIndex(x=>x.active===1)];
let modelfile=`
FROM `+payload.name+`
SYSTEM "`+activePersonality.system+`"
`;
async function create() {
await ollama.create({model:payload.name,modelfile:modelfile});
if(payload.details.family==='llama') await ollama.generate({model:payload.name,prompt:'.'});
}
create()
.then(()=>{
if(payload.details.family==='llama') {
setConfig({modelV: payload.name});
r.data='started';
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
else {
r.data='started';
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
})
.catch((err)=>{
r.data=err;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
}
//
// settings
else if(req.url.split('/')[1]==='settings') {
if(req.url.split('/')[2]==='update-passcode') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let currentPasscode=payload.currentPasscode;
let newPasscode=payload.newPasscode;
let passcodeFile=JSON.parse(fs.readFileSync(baseDir+'/p.json'));
let hashedPasscode=passcodeFile['p'];
bcrypt.compare(currentPasscode,hashedPasscode,(err,result)=>{
if(result) {
bcrypt.hash(newPasscode,saltRounds,(err,hash)=>{
passcodeFile.p=hash;
fs.writeFile(baseDir+'/p.json',JSON.stringify(passcodeFile),(err)=>{
if(!err) {
r.data='updated';
}
else {
r.error='Could not update passcode.';
}
res.writeHead(200,{'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
else {
res.writeHead(200, {'Content-Type': 'application/json'});
r.error='Current passcode is wrong.';
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='upload-firmware') {
let form=formidable();
form.parse(req, (err,fields,files)=>{
bcrypt.compare(fields.passcode[0],JSON.parse(fs.readFileSync(baseDir+'/p.json'))['p'],(err,result)=>{
if(result) {
let fileContent=fs.readFileSync(files.file[0].filepath);
fs.writeFile(firmwareDir+'/persys-pkg.zip',fileContent,(err)=>{
if(!err) {
exec('sh update.sh',(err,stdout,stderr)=>{
if(!stderr) r.data=stdout;
else r.error=stderr;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
}
else {
r.error=err;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
});
}
else {
r.error='Passcode is incorrect';
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
});
});
}
else if(req.url.split('/')[2]==='restart-services') {
exec('sh restart.sh',(err,stdout,stderr)=>{
r.data='restarted';
res.writeHead(200,{'Content-Type':'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
}
}
else if(req.url.split('/')[1]==='wallpapers') {
if(req.url.split('/')[2]==='current') {
let settings=JSON.parse(fs.readFileSync(settingsDir+'/settings.json'));
let activeWallpaper=settings.wallpapers[settings.wallpapers.findIndex(x=>x.active===1)].name;
let buffer=fs.readFileSync(settingsDir+'/wallpapers/'+activeWallpaper);
res.writeHead(200, {
'Content-Type':mime.getType(settingsDir+'/'+activeWallpaper),
"Content-Disposition": "attachment;filename="+activeWallpaper,
'Content-Length': buffer.length,
});
res.write(buffer);
return res.end();
}
else if(req.url.split('/')[2]==='get') {
let fileName=decodeURIComponent(s.get('fileName'))
let buffer=fs.readFileSync(settingsDir+'/wallpapers/'+fileName);
res.writeHead(200, {
'Content-Type':mime.getType(settingsDir+'/wallpapers/'+fileName),
"Content-Disposition": "attachment;filename="+settingsDir+'/wallpapers/'+fileName,
'Content-Length': buffer.length,
});
res.write(buffer);
return res.end();
}
else if(req.url.split('/')[2]==='list') {
let settings=JSON.parse(fs.readFileSync(settingsDir+'/settings.json'));
r.data=settings.wallpapers;
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
}
else if(req.url.split('/')[2]==='upload') {
let settings=JSON.parse(fs.readFileSync(settingsDir+'/settings.json'));
//
let form=formidable();
form.parse(req, (err,fields,files)=>{
let fileContent=fs.readFileSync(files.file[0].filepath);
fs.writeFile(settingsDir+'/wallpapers/'+fields.fileName[0],fileContent,(err)=>{
if(!err) {
for(let i=0;i<settings.wallpapers.length;i++) {
settings.wallpapers[i].active=0;
}
settings.wallpapers.push({name:fields.fileName[0],active:1,default:0});
fs.writeFileSync(settingsDir+'/settings.json',JSON.stringify(settings));
r.data='uploaded';
}
else {
r.error=err;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(r));
return res.end();
});
});
}
else if(req.url.split('/')[2]==='activate') {
req.on('data', (chunk) => {
body+=chunk;
});
req.on('end', () => {
let payload=JSON.parse(body);
let settings=JSON.parse(fs.readFileSync(settingsDir+'/settings.json'));
for(let i=0;i<settings.wallpapers.length;i++) {
settings.wallpapers[i].active=0;
}
settings.wallpapers[settings.wallpapers.findIndex(x=>x.name===payload.name)].active=1;
fs.writeFile(settingsDir+'/settings.json', JSON.stringify(settings),(err) => {
if(!err) {
r.data='activated';
}
else {
r.error='Could not activate wallpaper.';
}