-
Notifications
You must be signed in to change notification settings - Fork 1
/
PiZeroWebSerialConsole_anyHostName.html
1170 lines (1095 loc) · 35.6 KB
/
PiZeroWebSerialConsole_anyHostName.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Web Serial(Read)</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/css/xterm.css" />
<script src="https://unpkg.com/[email protected]/lib/xterm.js"></script>
</head>
<style>
.filelistdiv {
overflow-x: hidden;
width: 180px;
height: 300px;
/* margin: 0 auto; */
padding: 0;
/* box-sizing: border-box;
display: flex; */
}
.filelist {
width: 180px;
margin: 0;
padding: 0;
}
.filelist li {
position: relative;
width: 180px;
height: 20px;
white-space: nowrap;
}
.filelist > li {
border-bottom: none;
}
.filelist li:last-child {
border-bottom: none;
}
.filelist li:hover > ul > li {
border-bottom: none;
}
.filelist li > ul > li:last-child {
border-bottom: none;
}
.filelist li span {
/* layer-1 */
display: block;
width: 180px;
height: 20px;
color: #fff;
font-size: 14px;
line-height: 1.4;
padding: 0 3px;
background: #356;
border-bottom: 1px solid #eee;
box-sizing: border-box;
text-decoration: none;
}
.filelist > li:hover > span {
/*layer-1 sel*/
color: orange;
background: #46f;
cursor: pointer;
}
.filelist > li:hover > span > label {
/*layer-1 label sel*/
cursor: pointer;
}
.filelist > li li:hover > span {
/*layer-2 sel*/
color: #611;
background: #d4f;
cursor: pointer;
}
.filelist li:hover > ul > li {
/*layer-2*/
overflow: visible;
top: -20px;
left: 40px;
height: 20px;
z-index: 2;
}
.filelist li ul li {
overflow: hidden;
height: 0;
/* left: 110px; */
list-style: none;
}
.filelist li ul li span {
/*layer-2*/
background: #93d;
width: 100px;
}
.filelist li:hover ul li ul li:hover > span {
/*layer-3 sel*/
color: #22a;
background: #d01;
z-index: 3;
}
.filelist li:hover > ul > li:hover > ul > li {
left: 10px;
}
.filelist li ul li ul li span {
/*layer-3*/
background: #622;
width: 50px;
}
</style>
<style type="text/css">
#fileListTable {
/* overflow:auto; */
width: 200px;
height: 420px;
margin: 0px;
padding: 0px;
border: 0px;
background-color: #f9f9f9;
color: #000;
font-size: 10px;
}
input {
font-size: 9px;
}
button {
font-size: 12px;
}
table {
table-layout: fixed;
}
.fileListNameTd {
width: 100px;
}
.fileListBtnTd {
width: 50px;
}
</style>
<script>
/**
PiZeroWebSerialConsole Web App.
This is an application that allows a web browser to interact with the
Raspberry Pi Zero via its USB OTG Serial, regardless of the IP settings.
================================================================================
Programmed by Satoru Takagi
Copyright 2021 by Satoru Takagi All Rights Reserved
================================================================================
License: (GPL v3)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
However, if you want to use the contents of this repository for CHIRIMEN
community's projects, you can also choose the MIT license.
So, this is a limited dual license for the CHIRIMEN community.
================================================================================
History
2021/09/02 Initial Release
================================================================================
**/
var port;
var currentDir = ""; // cdコマンドを打つたびに更新されるグローバル変数
var currentDirFiles = {};
async function startConnection() {
// Web Serial APIでRasoberry PiのUSB OTG Serialをつなぐ
try {
port = await navigator.serial.requestPort();
await port.open({ baudRate: 115200 });
serialConnecting = true;
startTermLoop();
term.writeln("<<CONNECTED>>");
} catch (error) {
console.log("Error: Open");
console.log(error);
}
}
var serialConnecting;
async function terminateConnection() {
serialConnecting = false;
portWrite(" ");
await sleep("10");
await port.close();
term.writeln("\r\n<<CONNETCTION CLOSED>>");
}
async function startTermLoop() {
try {
while (port.readable && serialConnecting) {
const reader = port.readable.getReader();
try {
waitForSerialIn.inputValue = "";
while (serialConnecting) {
if (waitForSerialIn.inputValue.endsWith("\n")) {
//waitForSerialIn.inputValue ="";
}
const { value, done } = await reader.read();
if (done) {
console.log("Canceled");
break;
}
waitForSerialIn.inputValue =
waitForSerialIn.inputValue +
new TextDecoder("utf-8").decode(value);
//console.log(waitForSerialIn.inputValue.replace("\n","[RET]\n"));
// console.log(waitForSerialIn.RegExp,waitForSerialIn.inputValue.match(waitForSerialIn.RegExp));
if (
waitForSerialIn.RegExp &&
waitForSerialIn.CBF &&
waitForSerialIn.inputValue.match(waitForSerialIn.RegExp) != null
) {
waitForSerialIn.CBF(
removeControlChars(waitForSerialIn.inputValue)
);
clearTimeout(waitForSerialIn.TimeOutID);
waitForSerialIn.RegExp = null;
waitForSerialIn.CBF = null;
waitForSerialIn.TimeOutID = null;
waitForSerialIn.inputValue = "";
}
if (value) {
term.writeUtf8(value);
}
}
console.log("exit termLoop");
} catch (error) {
console.log("Error: Read");
console.log(error);
} finally {
reader.releaseLock();
}
}
} catch (error) {
console.log("Error: Open");
console.log(error);
}
}
function removeControlChars(str) {
// https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
return str.replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
""
);
}
var term;
var writer;
//var waitForSerialInRegExp, waitForSerialInCBF,waitForSerialInTimeOutID;
const waitForSerialIn = {
RegExp: null,
CBF: null,
TimeOutID: null,
inputValue: "",
};
var lang = "en";
const encoder = new TextEncoder();
onload = function () {
if (navigator.language == "ja") {
lang = navigator.language;
}
term = new Terminal.Terminal();
term.open(document.getElementById("terminal"));
term.onData(function (data) {
//console.log(data);
//term.writeUtf8(encoder.encode(data));
if (port) {
writer = port.writable.getWriter();
writer.write(encoder.encode(data));
writer.releaseLock();
}
});
};
// シリアルに単に書き出すだけの関数
function portWrite(data) {
writer = port.writable.getWriter();
writer.write(encoder.encode(data));
writer.releaseLock();
}
function portWriteln(data) {
portWrite(data + "\n");
}
// 書き出して、指定した文字列の返却を待つ非同期関数
function portWriteWaitfor(writeData, waitForRegExp, timeOutMsOptional) {
if (waitForRegExp == null) {
throw "waitForRegExp is not.";
}
if (waitForSerialIn.RegExp != null) {
console.warn("Now traansmitting skip");
return;
}
if (typeof waitForRegExp == "string") {
waitForRegExp = new RegExp(waitForRegExp);
//console.log("RE:",waitForRegExp);
}
if (!timeOutMsOptional) {
timeOutMsOptional = 30_000;
}
return new Promise(function (cbf, failCbf) {
waitForSerialIn.inputValue = "";
waitForSerialIn.RegExp = waitForRegExp;
waitForSerialIn.CBF = cbf;
waitForSerialIn.TimeOutCBF = function () {
console.warn("fail wait for:", waitForSerialIn.inputValue);
waitForSerialIn.inputValue = "";
waitForSerialIn.CBF = null;
waitForSerialIn.Str = null;
waitForSerialIn.RegExp = null;
if (failCbf) {
failCbf();
}
};
waitForSerialIn.TimeOutID = setTimeout(
waitForSerialIn.TimeOutCBF,
timeOutMsOptional
);
//console.log("portWrite:",writeData," cond:",waitForRegExp);
portWrite(writeData);
});
}
async function portWritelnWaitfor(
writeData,
waitForRegExp,
timeOutMsOptional
) {
var ret = await portWriteWaitfor(
writeData + "\n",
waitForRegExp,
timeOutMsOptional
);
return ret;
}
var ctrlc = "\x03"; // end of text
var ctrld = "\x04"; // end of transmission
const sleep = (msec) => new Promise((resolve) => setTimeout(resolve, msec));
function arrayBufferToBase64(buffer) {
var binary = "";
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
function getOutputLines(str) {
var lines = str.split("\n");
var ans = [];
for (var i = 0; i < lines.length; i++) {
ans.push(lines[i].trim());
}
return ans;
}
// アプリ的関数
//var cmdPrompt = "pi@raspberrypi:"; // ホームは"pi@raspberrypi:~\\$"
var cmdPrompt = new RegExp("pi@[a-z0-9\-]+:");
var loginId = "pi";
var loginPassword = "raspberry";
async function autoLogInPiZero(noRetry) {
// ログイン処理
var ret;
await startConnection();
await sleep(100);
// await portWriteWaitfor(ctrlc,".");
//console.log("ctrlc-> ret:",ret);
var hasResp;
term.write("Waiting prompt");
while (!hasResp) {
try {
portWrite(ctrlc);
ret = await portWriteWaitfor("\n", ":", 1000);
hasResp = true;
} catch (e) {
console.log("retry resp");
term.write(".");
await sleep(1000);
}
}
console.log("enter-> ret:", ret);
if (ret.indexOf("pi@") >= 0) {
console.log("already logged in");
//return;
} else if (ret.indexOf("login:") >= 0) {
var ret = await portWriteWaitfor(loginId + "\n", "Password:");
ret = await portWriteWaitfor(loginPassword + "\n", "\\$", 40000);
} else if (!noRetry) {
await autoLogInPiZero(true);
} else {
console.error("login fail...");
return;
}
document.getElementById("terminal").focus();
console.log("success");
await sleep(300);
await portWritelnWaitfor(" HISTCONTROL=ignoreboth", cmdPrompt); // 頭にスペースを付けたコマンド&連続したコマンドはhistoryに残さないようにする
if (lang == "ja") {
await portWritelnWaitfor(
" sudo timedatectl set-timezone Asia/Tokyo",
cmdPrompt
);
}
await sleep(100);
var date = new Date();
var dateCmd =
" sudo date " +
pad2(date.getMonth() + 1) +
pad2(date.getDate()) +
pad2(date.getHours()) +
pad2(date.getMinutes()) +
date.getFullYear() +
"." +
pad2(date.getSeconds());
await portWritelnWaitfor(dateCmd, cmdPrompt);
await pwd();
await sleep(100);
await cdHome();
connectBtn.style.display = "none";
cmdBtns.style.display = "";
}
function pad2(inp) {
return ("0" + inp).slice(-2);
}
async function closeConnection() {
await terminateConnection();
connectBtn.style.display = "";
cmdBtns.style.display = "none";
}
var currentAbsDir;
async function pwd() {
var ret = getOutputLines(await portWritelnWaitfor(" pwd", cmdPrompt));
console.log(ret);
currentAbsDir = ret[1].trim();
currentDir = getDirFromPrompt(ret[2]);
showCurrentDir();
return currentDir;
}
async function lsal() {
/** 表示結果からファイルに関する付帯情報を得るための正規表現 */
const capturingRegex =
/^(?<attr>\S+)\s+(?<hlinks>\S+)\s+(?<group>\S+)\s+(?<user>\S+)\s+(?<size>\S+)\s+(?<month>\S+)\s+(?<date>\S+)\s+(?<time>\S+)\s+(?<name>.+)$/;
var ret = await portWritelnWaitfor(
" ls -al --quoting-style=c",
cmdPrompt
);
ret = getOutputLines(ret);
var ans = [];
var prompt = ret[ret.length - 1].trim();
for (var i = 2; i < ret.length - 1; i++) {
const match = capturingRegex.exec(ret[i]);
const isDir = match?.groups.attr[0] === "d";
const fileInfo = {
dir: isDir,
...match?.groups,
};
try {
// TODO: C Quoting の解釈を JSON.parse によって代替しているため \v など一部トークンの解釈に失敗しうる
fileInfo.name = JSON.parse(fileInfo.name ?? JSON.stringify(""));
} catch {
fileInfo.name = "";
}
ans.push(fileInfo);
}
return { files: ans, prompt: prompt };
}
async function rm(fileName) {
// フルパスの場合はどうするか・・
var ret = getOutputLines(
await portWritelnWaitfor(` rm -- ${escapePath(fileName)}`, cmdPrompt)
);
console.log(ret);
}
async function mv(fromPath, toPath, bySudo) {
// フルパスの場合はどうするか・・
var sudoHead = "";
if (bySudo) {
sudoHead = "sudo ";
}
var ret = getOutputLines(
await portWritelnWaitfor(
` ${sudoHead} mv -- ${escapePath(fromPath)} ${escapePath(toPath)}`,
cmdPrompt
)
);
console.log(ret);
}
async function cp(fromPath, toPath, bySudo) {
// フルパスの場合はどうするか・・
var sudoHead = "";
if (bySudo) {
sudoHead = "sudo ";
}
var ret = getOutputLines(
await portWritelnWaitfor(
` ${sudoHead} cp -- ${escapePath(fromPath)} ${escapePath(toPath)}`,
cmdPrompt
)
);
console.log(ret);
}
async function remveAndList(fileName) {
var ret = await rm(fileName);
console.log("rm:", ret);
ret = await showDir();
console.log("ls:", ret);
currentDir = getDirFromPrompt(ret);
showCurrentDir();
}
function str2arrayBuffer_old(str) {
// textDecoder使わないタイプ・・
return new Promise(function (callback) {
// https://qiita.com/ukyo/items/1626defd020b2157e6bf
var fr = new FileReader();
fr.onloadend = function () {
callback(fr.result);
};
fr.readAsArrayBuffer(new Blob([str]));
});
}
function str2arrayBuffer(str) {
return new TextEncoder("utf-8").encode(str);
}
function arrayBuffer2str(buf) {
return new TextDecoder("utf-8").decode(buf);
}
async function saveFile(buffer, fileName) {
if (transferFileObj.transferring) {
console.warn("NOW File Transferring exit.");
return;
}
var base64 = arrayBufferToBase64(buffer);
//var ua = new Uint8Array(buffer);
// https://pisuke-code.com/js-soln-of-maximum-call-stack/
//var uas = String.fromCharCode.apply(null, new Uint8Array(buffer));
//console.log(ua);
//var base64String = window.btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
//console.log(base64String);
console.log(fileName);
//var base64 = base64String = btoa(String.fromCharCode(...new Uint8Array(buffer)));
//console.log(base64);
if (progress) {
progress.insertAdjacentHTML(
"afterbegin",
"<span id='progressText'></span><input id='haltButton' type='button' onclick='haltTransferFile()' value='キャンセル' />"
);
}
transferFileObj.transferring = true;
portWrite(ctrlc); // フォアグランドアプリ動作中のものを止める努力をした方が良さそう2021/11/02
await sleep(100);
await portWriteWaitfor(` base64 -d > ${escapePath(fileName)}\n`, "\n");
for (var i = 0; i <= Math.floor(base64.length / lineLength); i++) {
if (transferFileObj.halt == true) {
transferFileObj.halt = false;
break;
}
var line = base64.substring(i * lineLength, (i + 1) * lineLength);
await portWriteWaitfor(line + "\n", "\n");
await sleep(1);
if (progress) {
progressText.innerText =
Math.floor((100 * i) / Math.floor(base64.length / lineLength)) +
"% completed";
}
}
progress.innerText = "";
//portWrite(base64);
await sleep(50);
portWrite(ctrld);
await sleep(10);
portWriteln("");
await sleep(10);
portWriteWaitfor("\n", "\\$");
await sleep(10);
transferFileObj.transferring = false;
}
var lineLength = 512;
async function uploadFile(event) {
// base64を使って任意のファイルを登録する感じ
// https://qiita.com/gyarasu/items/a8009ea76a561cf80b06
// https://qiita.com/allein-s/items/13d0e2fc0896df83b234
// https://qiita.com/kareharide/items/93f0257ee5c31e239e63
console.log("uploadFile:", event.target.files[0]);
var file = event.target.files[0];
var fileInputElement = event.target;
const fr = new FileReader();
fr.onload = async function (e) {
var buffer = e.target.result;
await saveFile(buffer, file.name);
fileInputElement.value = "";
await sleep(200);
await showDir();
};
fr.readAsArrayBuffer(file);
}
async function wifiScan() {
var ret = getOutputLines(
await portWritelnWaitfor(" sudo iwlist wlan0 scan", cmdPrompt)
);
const wifiInfos = [];
var wifiInfo = {};
var first = true;
for (var i = 1; i < ret.length - 1; i++) {
var row = ret[i].split(/:/);
//console.log(row,ret[i].indexOf("Cell"));
if (ret[i].indexOf("Cell") >= 0 && ret[i].indexOf("Address") > 0) {
row = ret[i].split(/\s+/);
if (!first) {
wifiInfos.push(wifiInfo);
} else {
first = false;
}
//console.log("NEW",row);
wifiInfo = { address: row[4] };
} else if (ret[i].indexOf("ESSID:") >= 0) {
wifiInfo.essid = row[1].trim().replaceAll('"', "");
} else if (ret[i].indexOf("IEEE 802.11") >= 0) {
wifiInfo.spec = row[1].trim();
} else if (ret[i].indexOf("Quality") >= 0) {
wifiInfo.quality = ret[i].trim();
} else if (ret[i].indexOf("Group Cipher") >= 0) {
wifiInfo.spec += "," + row[1].trim();
} else if (ret[i].indexOf("Pairwise Ciphers") >= 0) {
wifiInfo.spec += "," + row[1].trim();
} else if (ret[i].indexOf("Authentication Suites") >= 0) {
wifiInfo.spec += row[1].trim();
} else if (ret[i].indexOf("Frequency:") >= 0) {
wifiInfo.frequency = row[1].trim();
} else if (ret[i].indexOf("Channel:") >= 0) {
wifiInfo.channel = row[1].trim();
}
}
wifiInfos.push(wifiInfo);
return { rawData: ret, wifiInfos: wifiInfos };
}
async function WiFiPanel() {
var win = window.open(
"WiFiPanel.html",
"wifiPanelWindow",
"height=600,width=800"
);
}
function CHIRIMENPanel() {
var win = window.open(
"chirimenPanel.html",
"chirimenPanel",
"height=650,width=800"
);
}
FileManagerMessage = {
ja: {
move: "移動",
view: "表示",
edit: "編集",
delete: "削除",
do: "実行",
},
en: {
move: "move",
view: "view",
edit: "edit",
delete: "delete",
do: "do",
},
};
async function showDir() {
//await pwd();
removeChildren(fileListTable);
var lsFiles = await lsal();
var files = lsFiles.files;
currentDirFiles = files;
//console.log(files);
var ul = document.createElement("ul");
ul.setAttribute("class", "filelist");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
var fname = files[i].name;
var fsize = Number(files[i].size);
var fnSpan = document.createElement("span");
//fnSpan.innerText=fname;
var fsizeS = fsize;
if (fsizeS > 1024 * 1024) {
fsizeS = Math.floor((10 * fsizeS) / (1024 * 1024)) / 10 + "M";
} else if (fsizeS > 1024) {
fsizeS = Math.floor((10 * fsizeS) / 1024) / 10 + "K";
}
fnSpan.innerHTML =
"<label title='" +
fname +
" : " +
fsizeS +
"bytes'>" +
fname +
"</label>";
li.appendChild(fnSpan);
ul.appendChild(li);
var actUl = document.createElement("ul");
if (files[i].dir) {
var cdLi = document.createElement("li");
var cdSpan = document.createElement("span");
cdSpan.innerText = FileManagerMessage[lang].move;
cdSpan.addEventListener(
"click",
(function (fname) {
return function () {
cd(fname);
};
})(fname)
);
cdLi.appendChild(cdSpan);
actUl.appendChild(cdLi);
} else {
var viewLi = document.createElement("li");
var viewSpan = document.createElement("span");
viewSpan.innerText = FileManagerMessage[lang].view;
viewSpan.addEventListener(
"click",
(function (fname, fsize, editFlg) {
return function () {
showFile(fname, fsize, editFlg);
};
})(fname, fsize, false)
);
viewLi.appendChild(viewSpan);
actUl.appendChild(viewLi);
var editLi = document.createElement("li");
var editSpan = document.createElement("span");
editSpan.innerText = FileManagerMessage[lang].edit;
editSpan.addEventListener(
"click",
(function (fname, fsize, editFlg) {
return function () {
showFile(fname, fsize, editFlg);
};
})(fname, fsize, true)
);
editLi.appendChild(editSpan);
actUl.appendChild(editLi);
var delLi = document.createElement("li");
var delSpan = document.createElement("span");
delSpan.innerText = FileManagerMessage[lang].delete;
delLi.appendChild(delSpan);
actUl.appendChild(delLi);
var delCfUl = document.createElement("ul");
var delCfNgLi = document.createElement("li");
var delCfNgSpan = document.createElement("span");
delCfNgSpan.innerText = "-";
delCfNgLi.appendChild(delCfNgSpan);
delCfUl.appendChild(delCfNgLi);
var delCfOkLi = document.createElement("li");
var delCfOkSpan = document.createElement("span");
delCfOkSpan.innerText = FileManagerMessage[lang].do;
delCfOkSpan.addEventListener(
"click",
(function (fname) {
return function () {
remveAndList(fname);
};
})(fname)
);
delCfOkLi.appendChild(delCfOkSpan);
delCfUl.appendChild(delCfOkLi);
delLi.appendChild(delCfUl);
}
li.appendChild(actUl);
//li.innerHTML="<span>"+fname+"</span>";
}
for (var i = 0; i < 3; i++) {
var li = document.createElement("li");
ul.appendChild(li);
}
fileListTable.appendChild(ul);
return lsFiles.prompt;
}
async function cd(dir) {
var ret = await portWritelnWaitfor(
` cd -- ${escapePath(dir)}`,
cmdPrompt
);
ret = await showDir();
//console.log(ret);
currentDir = getDirFromPrompt(ret);
showCurrentDir();
return currentDir;
}
function getDirFromPrompt(promptStr) {
var ret = promptStr
.trim()
.substring(promptStr.lastIndexOf(":") + 1, promptStr.lastIndexOf("$"));
//console.log("getDirFromPrompt:",promptStr," parse:",ret," caller:",getDirFromPrompt.caller);
return ret;
}
async function cdHome() {
await cd("");
}
function removeChildren(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
textFileExtensions = [
".txt",
".sh",
".csv",
".tsv",
".js",
".conf",
".mjs",
".md",
".yml",
".xml",
".html",
".htm",
".json",
".py",
".php",
];
function isTextFile(path) {
var fname = path.substring(path.lastIndexOf("/"));
var ans = true;
var f_ext = fname.substring(fname.lastIndexOf("."));
var f_name = fname.substring(0, fname.lastIndexOf("."));
if (f_name == "") {
ans = true;
} else if (textFileExtensions.indexOf(f_ext) == -1) {
ans = false;
}
return ans;
}
async function getFileSmall(path) {
// 短いファイルでないとフロー制御できてなくて破綻する? obsoluted
var ret = await portWritelnWaitfor(
` base64 -- ${escapePath(path)}`,
"\r\n" + cmdPrompt
);
ret = getOutputLines(ret);
var ans = "";
for (var i = 1; i < ret.length - 1; i++) {
ans += ret[i];
}
ans = base64ToArrayBuffer(ans);
if (isTextFile(path)) {
var txtString = new TextDecoder().decode(new Uint8Array(ans));
return txtString;
} else {
return ans;
}
}
var transferFileObj = {};
async function getFile(path, size) {
// 大きいファイルでも、取りこぼしなく取得可能なgetFileを開発
// moreを使って段階的に取得可能なものを作った。途中でキャンセルすることも可能なはず
// sizeは取得予定ファイルの参考情報(なくても良い)
if (transferFileObj.transferring) {
console.warn("NOW File Transferring exit.");
return;
}
transferFileObj.transferring = true;
var totalLines = -1;
if (size) {
totalLines = Math.floor(((4 / 3) * size) / 76);
}
if (progress) {
progress.insertAdjacentHTML(
"afterbegin",
"<span id='progressText'></span><input id='haltButton' type='button' onclick='haltTransferFile()' value='キャンセル' />"
);
}
var ans = "";
portWrite(ctrlc); // こちらもフォアグランドアプリ動作中のものを止める努力をした方が良さそう2021/11/17
await sleep(100);
var ret = await portWritelnWaitfor(
` base64 -- ${escapePath(path)} | sed '$a ENDLINE--More--' | if [ 12 -le $(cat /etc/debian_version | cut -d. -f1) ]; then more --exit-on-eof -50; else more -50; fi`,
"; fi"
);
//console.log(ret);
ret = await portWriteWaitfor("", "--More--");
//console.log(ret);
var lines = 0;
while (true) {
var rets = getOutputLines(ret);
//console.log(rets,rets[rets.length-1]);
for (var i = 0; i < rets.length; i++) {
if (rets[i].indexOf("--More--") >= 0) {
break;
}
ans += rets[i];
++lines;
}
if (ret.indexOf("ENDLINE") >= 0) {
break;
}
if (transferFileObj.halt == true) {
await portWritelnWaitfor("q", cmdPrompt);
break;
}
if (totalLines > 0 && progress) {
progressText.innerText =
"Loading: " + Math.floor((100 * lines) / totalLines) + "%";
}
await sleep(5);
ret = await portWriteWaitfor(" ", "--More--");
}
transferFileObj.transferring = false;
progress.innerText = "";
if (transferFileObj.halt == true) {
transferFileObj.halt = false;
return null;
}
console.log(ans.length);
ans = base64ToArrayBuffer(ans);
console.log(ans);
if (isTextFile(path)) {
var txtString = new TextDecoder().decode(new Uint8Array(ans)); // arrayBuffer to string
return txtString;
} else {
return ans;
}
}
function haltTransferFile() {
// getFileを途中でキャンセルする
if (transferFileObj.transferring) {
transferFileObj.halt = true;
}
}
function existFile(fileName) {
for (var fl of currentDirFiles) {
if (fileName == fl.name) {
return true;
}