1
0

fs.html 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. <html>
  2. <head>
  3. <title>File Manager</title>
  4. <meta charset="UTF-8">
  5. <meta name="zoraxy.csrf.Token" content="{{.csrfToken}}">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
  7. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" />
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
  11. <link rel="stylesheet" href="fs.css">
  12. <script src="../script/utils.js"></script>
  13. <script>
  14. </script>
  15. <style>
  16. body{
  17. background-color: white;
  18. }
  19. #uploadProgressBar{
  20. position: fixed;
  21. bottom: 0;
  22. left: 0;
  23. width: 100%;
  24. }
  25. .fileOprBtn.disabled{
  26. opacity: 0.5;
  27. user-select: none;
  28. pointer-events: none;
  29. }
  30. </style>
  31. </head>
  32. <body class="whiteTheme">
  33. <div id="navibar" class="navibar">
  34. <!-- File Opr Group-->
  35. <button class="fileOprBtn" title="Open" onclick="openViaButton(event);"><img class="opricon" src="img/opr/open.svg"><p class="oprtxt" locale="fileopr/Open">Open</p></button>
  36. <button id="copyButton" class="fileOprBtn" title="Copy" onclick="copy();"><img class="opricon" src="img/opr/copy.svg"><p class="oprtxt" locale="fileopr/Copy">Copy</p></button>
  37. <button id="pasteButton" class="fileOprBtn" title="Paste" onclick="paste();"><img class="opricon" src="img/opr/paste.svg"><p class="oprtxt" locale="fileopr/Paste">Paste</p></button>
  38. <div class="fileoprGroupDivider" style="display: inline-block; vertical-align: top;">
  39. <button class="fileoprSmallBtn" title="Refresh" onclick="refresh();"><i class="green refresh icon"></i> <span locale="fileopr/Refresh">Refresh</span></button><br>
  40. <button class="fileoprSmallBtn" title="Cut" onclick="cut();"><i class="blue cut icon"></i> <span locale="fileopr/Cut">Cut</span></button><br>
  41. <button class="fileoprSmallBtn" title="Rename" onclick="rename();"><i class="teal i cursor icon"></i> <span locale="fileopr/Rename">Rename</span></button>
  42. </div>
  43. <button class="fileOprBtn" title="Upload" onclick="upload(); "><img class="opricon" src="img/opr/upload.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/Upload">Upload</p></button>
  44. <button class="fileOprBtn" title="Download" onclick="downloadFile(); "><img class="opricon" src="img/opr/download.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/Download">Download</p></button>
  45. <div class="fileoprGroupDivider" style="display: inline-block; vertical-align: top;"></div>
  46. <div class="fileoprGroupDivider" style="display: inline-block; vertical-align: top;">
  47. <button class="fileoprSmallBtn" title="New File" onclick="newFile();"><i style="color: #c7c7c7 !important;" class="file outline icon"></i> <span locale="fileopr/New File">New File</span></button><br>
  48. <button class="fileoprSmallBtn" title="New Folder" onclick="newFolder();"><i style="color: #ffe79e !important;" class="yellow folder icon"></i> <span locale="fileopr/New Folder">New Folder</span></button><br>
  49. <button class="fileoprSmallBtn" title="Delete" onclick="deleteFile();"><i class="red times icon"></i> <span locale="fileopr/Delete">Delete</span></button><br>
  50. </div>
  51. <br>
  52. <!-- Directoy navigations -->
  53. <div class="addressBar">
  54. <button id="prevDir" class="navibarBtn" onclick="prevDir();" title="Back"><i class="left arrow icon"></i></button>
  55. <button id="ppbtn" class="navibarBtn" onclick="parentDir();" title="Parent Folder"><i class="up arrow icon"></i></button>
  56. <div id="pathDisplayField" class="ui breadcrumb addressText pathDisplay desktopOnly" >
  57. </div>
  58. <button id="togglePropertiesViewBtn" style="margin-left: 0.4em;" class="ui icon tiny button videmode propbar" title="Show Properties" onclick="togglePropertiesView(this);"><i class="columns icon"></i></button>
  59. </div>
  60. <div class="msgbox" style="z-index:999; display:none; padding-bottom: 1em;">
  61. <i class="checkmark icon showicon"></i> <span style="word-break: break-all;">No Message</span>
  62. <div class="closeMsgButton" onclick="$(this).parent().stop().slideUp('fast');"><i class="caret down icon"></i></div>
  63. </div>
  64. </div>
  65. <div id="mainWindow">
  66. <div id="folderView" style="height: 100%;">
  67. <div id="folderList" class="fileviewList">
  68. </div>
  69. <div id="fileList" class="fileviewList">
  70. </div>
  71. <br>
  72. </div>
  73. <div id="propertiesView" class="small">
  74. <h3 class="ui header" style="margin-top: 0.4em;">
  75. <span class="filename" style="word-break: break-all;" locale="sidebar/default/nofileselected">No File Selected</span>
  76. <div class="sub header vpath" style="word-break: break-all;" locale="sidebar/default/instruction">Select a file to view file properties</div>
  77. </h3>
  78. <table class="ui very basic table">
  79. <tbody class="propertiesTable">
  80. </tbody>
  81. </table>
  82. </div>
  83. <div id="uploadProgressBar">
  84. <div class="ui small indicating progress" style="margin-bottom: 0px !important; border-radius: 0 !important;">
  85. <div class="bar" style="background-color: #92cfe7 !important; min-width: 0; border-radius: 0 !important;">
  86. <div class="progress"></div>
  87. </div>
  88. <div class="label">Uploading Files</div>
  89. </div>
  90. </div>
  91. </div>
  92. <script>
  93. let currentPath = "/";
  94. let listDirInitTime = 0;
  95. let propertiesView = true;
  96. //Uploads
  97. let uploadPendingFiles = [];
  98. let currentlyUploading = false;
  99. //File operations
  100. let cutMode = false;
  101. let cutPendingFilepath = [];
  102. let copyPendingFiles = [];
  103. //History
  104. let dirHistory = [];
  105. $(window).on("resize", function(){
  106. updateElementSize();
  107. })
  108. $(document).ready(function(){
  109. if (window.location.hash.length > 1){
  110. let previousPath = window.location.hash.substr(1);
  111. listDir(previousPath);
  112. }else{
  113. listDir("/");
  114. }
  115. //Add drop events to file view
  116. var folderView = document.getElementById('folderView');
  117. // Add event listeners for dragover and drop events
  118. folderView.addEventListener('dragover', handleDragOver, false);
  119. folderView.addEventListener('drop', handleFileDrop, false);
  120. });
  121. // Event handler for dragover event
  122. function handleDragOver(event) {
  123. event.preventDefault();
  124. event.stopPropagation();
  125. }
  126. function handleFileDrop(event) {
  127. event.preventDefault();
  128. event.stopPropagation();
  129. // Get the File object from the dataTransfer object
  130. var files = event.dataTransfer.files;
  131. //Push the files into queue
  132. for (var i = 0; i < files.length; i++) {
  133. if (files[i].name.indexOf(".") < 0){
  134. msgbox("Folder upload is not supported", false);
  135. if (files.length == 1){
  136. return;
  137. }
  138. continue;
  139. }
  140. let pathToUpload = currentPath;
  141. uploadPendingFiles.push({
  142. "file": files[i],
  143. "dir": pathToUpload
  144. });
  145. }
  146. //Upload the first file
  147. msgbox("File Upload Started")
  148. if (!currentlyUploading){
  149. uploadFileQueue();
  150. }
  151. }
  152. function uploadFileQueue(){
  153. if (uploadPendingFiles.length > 0){
  154. currentlyUploading = true;
  155. let nextFileToUpload = uploadPendingFiles.pop();
  156. handleFile(nextFileToUpload.file, nextFileToUpload.dir, function(){
  157. msgbox(nextFileToUpload.file.name + " uploaded");
  158. setTimeout(function(){
  159. uploadFileQueue();
  160. }, 300);
  161. });
  162. }else{
  163. msgbox("Upload Queue Completed");
  164. currentlyUploading = false;
  165. }
  166. }
  167. function deleteFile(){
  168. if ($(".fileObject.selected").length == 0){
  169. return;
  170. }
  171. if (confirm("Confirm removing " + $(".fileObject.selected").length + " files?")){
  172. let counter = $(".fileObject.selected").length;
  173. $(".fileObject.selected").each(function(){
  174. let thisFilepath = $(this).attr("filepath");
  175. $.cjax({
  176. url: "/api/fs/del?target=" + thisFilepath,
  177. method: "POST",
  178. success: function(data){
  179. if (data.error != undefined){
  180. msgbox(data.error, false);
  181. }else{
  182. counter--;
  183. if (counter == 0){
  184. //All removed
  185. msgbox("File(s) Removed");
  186. refresh();
  187. }
  188. }
  189. }
  190. })
  191. });
  192. }
  193. }
  194. //Check if a extension is code file, remember to trim the first dot
  195. function isCodeFiles(ext){
  196. if (ext == "html" || ext == "htm"|| ext == "css"|| ext == "js"|| ext == "json"){
  197. return true;
  198. }
  199. return false;
  200. }
  201. function openViaButton(evt){
  202. if ($(".fileObject.selected").length == 0){
  203. return;
  204. }
  205. let editableCodeFiles = [];
  206. $(".fileObject.selected").each(function(){
  207. let ftype = $(this).attr('type');
  208. let filepath = $(this).attr("filepath");
  209. let filename = $(this).attr("filename");
  210. if (ftype != "folder"){
  211. let ext = filepath.split(".").pop();
  212. openthis($(this), evt);
  213. }
  214. });
  215. }
  216. function refresh(){
  217. listDir(currentPath);
  218. }
  219. function updatePathDisplay(){
  220. $("#pathDisplayField").empty();
  221. $("#pathDisplayField").append(`<div class="section selectable" onclick="jumpToDir('/');"><i class="folder icon"></i> Zoraxy</div><div class="divider">:/</div>`);
  222. let pathSegments = currentPath;
  223. if (pathSegments.startsWith("/")){
  224. pathSegments = pathSegments.substr(1);
  225. }
  226. if (pathSegments.endsWith("/")){
  227. pathSegments = pathSegments.substr(0, pathSegments.length - 1);
  228. }
  229. pathSegments = pathSegments.split("/");
  230. let htmlSegments = [];
  231. let accumulativeDir = "/";
  232. pathSegments.forEach(function(segment){
  233. accumulativeDir = accumulativeDir + segment + "/"
  234. htmlSegments.push(`<div class="section selectable" onclick="jumpToDir('${accumulativeDir}');">${segment}</div>`);
  235. });
  236. $("#pathDisplayField").append(htmlSegments.join(`<div class="divider">/</div>`));
  237. }
  238. function cut(){
  239. if ($(".fileObject.selected").length == 0){
  240. msgbox("No file selected", false);
  241. return;
  242. }
  243. cutMode = true;
  244. cutPendingFilepath = [];
  245. $(".fileObject.selected").each(function(){
  246. cutPendingFilepath.push({
  247. filename: $(this).attr("filename"),
  248. filepath: $(this).attr("filepath")
  249. });
  250. });
  251. msgbox("File Ready to Paste");
  252. }
  253. function downloadFile(){
  254. let selectedFiles = [];
  255. let filenames = [];
  256. let containsDir = false;
  257. $(".fileObject.selected").each(function(){
  258. if ($(this).attr("type") == "folder"){
  259. containsDir = true;
  260. }
  261. });
  262. if (containsDir){
  263. msgbox("Folder download is not supported", false);
  264. return;
  265. };
  266. if ($(".fileObject.selected").length > 0){
  267. $(".fileObject.selected").each(function(){
  268. selectedFiles.push($(this).attr("filepath"));
  269. filenames.push($(this).attr("filename"))
  270. });
  271. }
  272. if (selectedFiles.length == 1){
  273. //Only one file
  274. //window.open("/api/fs/download?file=" + selectedFiles[0]);
  275. var file_path = "/api/fs/download?file=" + selectedFiles[0];
  276. var a = document.createElement('A');
  277. a.href = file_path;
  278. a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
  279. document.body.appendChild(a);
  280. a.click();
  281. document.body.removeChild(a);
  282. }else{
  283. let urls = [];
  284. selectedFiles.forEach(function(thisFilepath){
  285. urls.push("/api/fs/download?file=" + thisFilepath);
  286. });
  287. msgbox("Zipping might take a few minutes...");
  288. compressFileToZip(urls, filenames);
  289. }
  290. }
  291. function compressFileToZip(urls, filenames) {
  292. var zip = new JSZip();
  293. // Create a function to fetch each image and add it to the zip
  294. var addFileToZip = function (url, filename) {
  295. return new Promise(function (resolve, reject) {
  296. var xhr = new XMLHttpRequest();
  297. xhr.open('GET', url);
  298. xhr.responseType = 'blob';
  299. xhr.onload = function () {
  300. if (xhr.status === 200) {
  301. zip.file(filename, xhr.response);
  302. resolve();
  303. } else {
  304. reject(Error('Failed to fetch file: ' + url));
  305. }
  306. };
  307. xhr.onerror = function () {
  308. reject(Error('Error fetching file: ' + url));
  309. };
  310. xhr.send();
  311. });
  312. };
  313. // Iterate over each image URL and add it to the zip
  314. var promises = urls.map(function (url, index) {
  315. var filename = filenames[index];
  316. return addFileToZip(url, filename);
  317. });
  318. // When all promises are resolved, generate the zip file
  319. Promise.all(promises).then(function () {
  320. zip.generateAsync({ type: 'blob' }).then(function (content) {
  321. // Save the zip file or do something with it
  322. msgbox("Download Zip Created");
  323. saveAs(content, 'dl_' + Math.floor(Date.now() / 1000) +'.zip');
  324. });
  325. }).catch(function (error) {
  326. console.error(error);
  327. });
  328. }
  329. function saveAs(blob, filename) {
  330. if (navigator.msSaveBlob) {
  331. // For IE and Edge browsers
  332. navigator.msSaveBlob(blob, filename);
  333. } else {
  334. // For other browsers
  335. var link = document.createElement('a');
  336. link.href = URL.createObjectURL(blob);
  337. link.download = filename;
  338. link.style.display = 'none';
  339. document.body.appendChild(link);
  340. link.click();
  341. document.body.removeChild(link);
  342. }
  343. }
  344. //Jump to new directory via path input field
  345. function jumpToDir(newDir){
  346. if (newDir == currentPath){
  347. return;
  348. }
  349. listDir(newDir);
  350. }
  351. function prevDir(){
  352. if (dirHistory.length > 0){
  353. let pathToGo = dirHistory.pop();
  354. if (pathToGo == currentPath && dirHistory.length > 0){
  355. //pop again
  356. pathToGo = dirHistory.pop();
  357. listDir(pathToGo);
  358. return;
  359. }
  360. listDir(pathToGo, false);
  361. }
  362. }
  363. function listDir(path, recordHistory = true){
  364. if (path.length > 0 && path.substr(0, 1) != "/"){
  365. path = "/" + path;
  366. }
  367. if (!path.endsWith("/")){
  368. path = path + "/";
  369. }
  370. //Update the current path
  371. currentPath = path;
  372. if (recordHistory && currentPath != dirHistory[dirHistory.length - 1]){
  373. dirHistory.push(currentPath);
  374. }
  375. window.location.hash = currentPath;
  376. updatePathDisplay();
  377. listDirInitTime = Date.now();
  378. let validationTimestamp = listDirInitTime;
  379. $("#folderList").html(`<div class="fileObject item" style="pointer-events: none;">
  380. <span style="display:inline-block !important;word-break: break-all; width:100%;" class="normal object">
  381. <i class="loading spinner icon" style="margin-right:12px; color:#grey;"></i> <span class="filename">Loading</span>
  382. </span>
  383. </div>`);
  384. $("#fileList").html("");
  385. $.ajax({
  386. url: "/api/fs/list?dir=" + path,
  387. success: function(data){
  388. if (validationTimestamp != listDirInitTime){
  389. //Another refresh is in progress. Skip render.
  390. return;
  391. }
  392. $("#folderList").html("");
  393. if (data.error != undefined){
  394. $("#folderList").append(`<div class="ui segment">
  395. <div class="ui header themed">
  396. <i class="remove icon" style="display: inline-block;"></i> <span>Error Opening Folder</span>
  397. <div class="sub header" style="margin-top:12px;">Server return the following error message: <br><code>${data.error.toUpperCase()}</code><br>
  398. ${new Date().toLocaleString()}</div>
  399. </div>
  400. </div>`);
  401. msgbox(data.error, false);
  402. }else{
  403. data.forEach(function(filedata){
  404. let isDir = filedata.isDir;
  405. let filename = filedata.filename;
  406. let filesize = filedata.size;
  407. if (isDir){
  408. $("#folderList").append(`<div class="fileObject item" draggable="true" filename="${filename}" filepath="${path + filename}" ondblclick="openthis(this,event);" type="folder">
  409. <span style="display:inline-block !important;word-break: break-all; width:100%;" class="normal object">
  410. <i class="folder icon" style="margin-right:12px; color:#eab54e;"></i> <span class="filename">${filename}</span>
  411. </span>
  412. </div>`);
  413. }else{
  414. let extension = "." + filename.split(".").pop();
  415. let fileIcon = getFileIcon(extension);
  416. $("#fileList").append(`<div class="fileObject item" draggable="true" filename="${filename}" filepath="${path + filename}" ondblclick="openthis(this,event);" type="file">
  417. <span style="display:inline-block !important;word-break: break-all; width:100%;" class="normal object">
  418. <i class="${fileIcon} icon" style="margin-right:12px; color:grey;"></i> <span class="filename">${filename} (${humanFileSize(filesize)})</span>
  419. </span>
  420. </div>`);
  421. }
  422. });
  423. }
  424. $(".fileObject").off("click").on("click", function(e){
  425. if (!e.ctrlKey) {
  426. $(".fileObject.selected").removeClass("selected");
  427. getFileProperties( $(this).attr("filepath"));
  428. let fileType = $(this).attr('type');
  429. if (fileType == "folder"){
  430. $("#propertiesView").find(".preview").find("img").attr("src", "img/folder.svg");
  431. }else{
  432. $("#propertiesView").find(".preview").find("img").attr("src", "img/file.svg");
  433. }
  434. }
  435. $(this).addClass("selected");
  436. });
  437. sortFileList();
  438. }
  439. });
  440. }
  441. function openthis(target, event){
  442. let isDir = ($(target).attr("type") == "folder");
  443. if (isDir){
  444. let targetPath = $(target).attr("filepath");
  445. listDir(targetPath);
  446. }else{
  447. let ext = $(target).attr("filepath").split(".").pop();
  448. window.open("/api/fs/download?file=" + $(target).attr("filepath") + "&preview=true");
  449. }
  450. }
  451. function isFilenameValid(filename) {
  452. // Split the filename into the name and extension parts
  453. var name = filename.slice(0, filename.lastIndexOf('.'));
  454. var extension = filename.slice(filename.lastIndexOf('.') + 1);
  455. // Check if the name and extension lengths are within the limits
  456. if (name.length <= 8 && extension.length <= 3) {
  457. return true;
  458. } else {
  459. return false;
  460. }
  461. }
  462. function newFile(){
  463. var fileName = window.prompt("Name for new file: ", "file.txt");
  464. if (fileName.indexOf("/") >= 0){
  465. //Contains /. Reject
  466. msgbox("File name cannot contain path seperator", false);
  467. return;
  468. }
  469. if (fileName.indexOf(".") == -1){
  470. msgbox("Missing file extension")
  471. return
  472. }
  473. let filenameOnly = fileName.split(".");
  474. let ext = filenameOnly.pop();
  475. filenameOnly = filenameOnly.join(".");
  476. //OK! Create the file
  477. const blob = new Blob(["\n"], { type: 'text/plain' });
  478. const file = new File([blob], fileName);
  479. handleFile(file, currentPath, function(){
  480. msgbox("New File Created");
  481. });
  482. }
  483. function newFolder(){
  484. var folderName = window.prompt("Name for new folder: ", "Folder");
  485. if (folderName.indexOf("/") >= 0){
  486. //Contains /. Reject
  487. msgbox("Folder name cannot contain path seperator", false);
  488. return;
  489. }
  490. $.cjax({
  491. url: "/api/fs/newFolder",
  492. method: "POST",
  493. data: {
  494. "path": currentPath + folderName,
  495. },
  496. success: function(data){
  497. if (data.error != undefined){
  498. msgbox(data.error, false);
  499. }else{
  500. msgbox("Folder Created");
  501. refresh();
  502. }
  503. }
  504. });
  505. }
  506. function rename(){
  507. if ($(".fileObject.selected").length > 1){
  508. //Too many objects
  509. }else if ($(".fileObject.selected").length == 1){
  510. var oldName = $(".fileObject.selected").attr("filename");
  511. var oldPath = $(".fileObject.selected").attr("filepath");
  512. var newName = window.prompt("Rename " + oldName + " to: ", oldName);
  513. if (newName.indexOf("/") >= 0){
  514. //Contains /. Reject
  515. msgbox("File name cannot contain path seperator", false);
  516. return;
  517. }
  518. if (newName && newName != oldName) {
  519. // User entered a new name, perform renaming logic here
  520. console.log(oldPath, currentPath + newName);
  521. $.cjax({
  522. url: "/api/fs/move",
  523. data: {
  524. "srcpath": oldPath,
  525. "destpath": currentPath + newName
  526. },
  527. method: "POST",
  528. success: function(data){
  529. if (data.error != undefined){
  530. msgbox(data.error, false);
  531. }else{
  532. msgbox("File renamed");
  533. refresh();
  534. }
  535. }
  536. })
  537. }
  538. }
  539. }
  540. function getFileIcon(extension) {
  541. const textExtensions = [".md", ".txt"];
  542. const codeExtensions = [".js", ".json", ".css", ".html", ".htm"];
  543. const musicExtensions = [".mp3", ".aac", ".ogg", ".wav"];
  544. const videoExtensions = [".mp4", ".m4v", ".webm"];
  545. const photoExtensions = [".png", ".gif", ".jpg", ".ico", ".svg"];
  546. if (textExtensions.includes(extension)) {
  547. return "file alternate outline";
  548. } else if (codeExtensions.includes(extension)) {
  549. return "black file code outline";
  550. } else if (musicExtensions.includes(extension)) {
  551. return "blue music";
  552. } else if (videoExtensions.includes(extension)) {
  553. return "red video";
  554. } else if (photoExtensions.includes(extension)) {
  555. return "green image outline";
  556. } else {
  557. return "file outline";
  558. }
  559. }
  560. function isPreviewable(ext){
  561. let previeableFiles = [".png", ".gif", ".jpg", ".ico", ".svg"];
  562. return previeableFiles.includes(ext);
  563. }
  564. function getFileProperties(filepath){
  565. $.get("/api/fs/properties?file=" + filepath, function(data){
  566. if (data.error != undefined){
  567. msgbox(data.error, false);
  568. return;
  569. }
  570. $("#propertiesView").find(".filename").text(data.filename);
  571. $("#propertiesView").find(".vpath").text(data.filepath);
  572. let propTable = $("#propertiesView").find(".propertiesTable");
  573. let styleOverwrite = `min-width: 4em;`;
  574. $(propTable).html("");
  575. $(propTable).append(`<tr>
  576. <td style="${styleOverwrite}">
  577. File Size
  578. </td>
  579. <td>
  580. ${bytesToSize(data.size)}
  581. </td>
  582. </tr><tr>
  583. <td style="${styleOverwrite}">
  584. Disk Path
  585. </td>
  586. <td style="word-break: break-all;">
  587. /www${data.filepath}
  588. </td>
  589. </tr><tr>
  590. <td style="${styleOverwrite}">
  591. Folder
  592. </td>
  593. <td style="word-break: break-all;">
  594. ${data.isDir?`<i class="ui green check icon"></i>`:`<i class="ui red times icon"></i>`}
  595. </td>
  596. </tr>`);
  597. if (data.isDir){
  598. $(propTable).append(`<tr>
  599. <td style="${styleOverwrite}">
  600. Files #
  601. </td>
  602. <td>
  603. ${data.fileCounts}
  604. </td>
  605. </tr><tr>
  606. <td style="${styleOverwrite}">
  607. Folders #
  608. </td>
  609. <td style="word-break: break-all;">
  610. ${data.folderCounts}
  611. </td>
  612. </tr>`);
  613. }
  614. })
  615. }
  616. function loadPreview(){
  617. let readyToLoadSrc = $("#propertiesView").find(".preview").find("img").attr("xsrc");
  618. if (readyToLoadSrc == undefined || readyToLoadSrc == "" ){
  619. }else{
  620. let ext = readyToLoadSrc.split(".").pop();
  621. $("#propertiesView").find(".preview").find("img").show();
  622. $("#propertiesView").find(".preview").find("audio").hide();
  623. $("#propertiesView").find(".preview").find("img").attr("src", readyToLoadSrc);
  624. }
  625. }
  626. function bytesToSize(bytes) {
  627. var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
  628. if (bytes == 0) return '0 Byte';
  629. var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  630. return Math.round(bytes / Math.pow(1024, i) * 100, 2) / 100 + ' ' + sizes[i];
  631. }
  632. function getParentDirectory(path) {
  633. // Remove any trailing slashes
  634. if (path.endsWith("/")){
  635. path = path.substr(0, path.length - 1);
  636. }
  637. // Find the last index of the slash character
  638. var lastIndex = path.lastIndexOf('/');
  639. // Extract the parent directory substring
  640. var parentDir = path.substring(0, lastIndex);
  641. return parentDir;
  642. }
  643. function parentDir(){
  644. if (currentPath.indexOf("/") >= 0 && currentPath != "/"){
  645. let parentPath = getParentDirectory(currentPath);
  646. listDir(parentPath);
  647. }else{
  648. //already top
  649. }
  650. }
  651. function humanFileSize(bytes, si=true, dp=1) {
  652. const thresh = si ? 1000 : 1024;
  653. if (Math.abs(bytes) < thresh) {
  654. return bytes + ' B';
  655. }
  656. const units = si
  657. ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  658. : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  659. let u = -1;
  660. const r = 10**dp;
  661. do {
  662. bytes /= thresh;
  663. ++u;
  664. } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);
  665. return bytes.toFixed(dp) + ' ' + units[u];
  666. }
  667. function updateElementSize(){
  668. $("#mainWindow").css("height", window.innerHeight - $("#navibar").height() + "px");
  669. }
  670. updateElementSize();
  671. function upload() {
  672. // Create a file input element
  673. var fileInput = $('<input>').attr('type', 'file');
  674. // Trigger the file selector dialog
  675. fileInput.trigger('click');
  676. // Handle the selected file using a callback event handler
  677. fileInput.change(function(e) {
  678. var file = e.target.files[0];
  679. if (currentlyUploading){
  680. //Already tasks uploading in the background. Add it to queue
  681. uploadPendingFiles.push({
  682. "file": file,
  683. "dir": currentPath
  684. });
  685. msgbox("File Added to Upload Queue");
  686. return;
  687. }
  688. // Pass the file object to the callback event handler
  689. msgbox("File Upload Started")
  690. handleFile(file, currentPath, function(){
  691. msgbox("Upload Completed");
  692. });
  693. });
  694. }
  695. function handleFile(file, dir=currentPath, callback=undefined) {
  696. // Perform actions with the selected file
  697. $("#pasteButton").addClass("disabled");
  698. console.log('Selected file:', file);
  699. var formdata = new FormData();
  700. formdata.append("file", file);
  701. var ajax = new XMLHttpRequest();
  702. ajax.upload.addEventListener("progress", progressHandler, false);
  703. ajax.addEventListener("load", function(event){
  704. let responseText = event.target.responseText;
  705. try{
  706. responseText = JSON.parse(responseText);
  707. if (responseText.error != undefined){
  708. alert(responseText.error);
  709. }
  710. }catch(ex){
  711. }
  712. completeHandler(event, dir==currentPath);
  713. $("#pasteButton").removeClass("disabled");
  714. if (callback != undefined){
  715. callback();
  716. }
  717. }, false); // doesnt appear to ever get called even upon success
  718. ajax.addEventListener("error", errorHandler, false);
  719. ajax.addEventListener("abort", abortHandler, false);
  720. ajax.open("POST", "/api/fs/upload?dir=" + dir);
  721. ajax.setRequestHeader("X-CSRF-Token", document.getElementsByTagName("meta")["zoraxy.csrf.Token"].getAttribute("content"));
  722. ajax.send(formdata);
  723. }
  724. function progressHandler(event) {
  725. //_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total; // event.total doesnt show accurate total file size
  726. var percent = (event.loaded / event.total) * 100;
  727. $("#uploadProgressBar").find(".bar").css("width", Math.round(percent) + "%");
  728. console.log("Uploaded " + event.loaded + " bytes => " + percent +"%");
  729. if (percent >= 100) {
  730. $("#uploadProgressBar").find(".bar").css("width", "100%");
  731. //_("status").innerHTML = "Please wait, writing file to filesystem";
  732. }
  733. }
  734. function completeHandler(event, requireRefresh=true) {
  735. $("#uploadProgressBar").find(".bar").css("width", "0%");
  736. if(requireRefresh){
  737. refresh();
  738. }
  739. }
  740. function errorHandler(event) {
  741. msgbox("Upload Failed", false);
  742. $("#pasteButton").removeClass("disabled");
  743. }
  744. function abortHandler(event) {
  745. msgbox("Upload Aborted", false);
  746. $("#pasteButton").removeClass("disabled");
  747. }
  748. function msgbox(message, succ=true){
  749. function capitalizeFirstLetter(string) {
  750. return string.charAt(0).toUpperCase() + string.slice(1);
  751. }
  752. message = capitalizeFirstLetter(message);
  753. if (succ){
  754. $(".msgbox").find(".showicon").attr("class", "green circle check icon showicon");
  755. }else{
  756. $(".msgbox").find(".showicon").attr("class", "red circle times icon showicon");
  757. }
  758. $(".msgbox").find("span").text(message);
  759. $(".msgbox").stop().finish().slideDown("fast").delay(3000).slideUp("fast");
  760. }
  761. //Copy file
  762. function copy(){
  763. if ($(".fileObject.selected").length == 0){
  764. //No file selected
  765. msgbox("No file selected", false);
  766. return;
  767. }
  768. let selectedFiles = [];
  769. $(".fileObject.selected").each(function(){
  770. let filepath = $(this).attr("filepath");
  771. selectedFiles.push(filepath);
  772. console.log(filepath);
  773. });
  774. copyPendingFiles = selectedFiles;
  775. cutMode = false;
  776. msgbox(`${selectedFiles.length} files ready to paste`, true)
  777. }
  778. function fileExistsInThisFolder(filename){
  779. let exists = false;
  780. $(".fileObject").each(function(){
  781. if ($(this).attr("filename") == filename){
  782. exists = true;
  783. }
  784. });
  785. return exists;
  786. }
  787. function paste(){
  788. if (cutMode){
  789. let remainingFilesCounter = cutPendingFilepath.length;
  790. console.log("Moving " , cutPendingFilepath);
  791. cutPendingFilepath.forEach(fileToPaste => {
  792. let filename = fileToPaste.filename;
  793. let filepath = fileToPaste.filepath;
  794. $.cjax({
  795. url: "/api/fs/move",
  796. data:{
  797. "srcpath": filepath,
  798. "destpath": currentPath + filename,
  799. },
  800. method: "POST",
  801. success: function(data){
  802. if (data.error != undefined){
  803. msgbox(data.error)
  804. }else{
  805. remainingFilesCounter--;
  806. if (remainingFilesCounter == 0){
  807. msgbox("File Move Completed");
  808. refresh();
  809. }
  810. }
  811. }
  812. })
  813. });
  814. }else{
  815. //Copy and Paste
  816. copyFirstItemInQueueUntilAllCopied();
  817. }
  818. }
  819. function copyFirstItemInQueueUntilAllCopied(){
  820. let file = copyPendingFiles.shift();
  821. let startingDir = currentPath;
  822. $.cjax({
  823. url: "/api/fs/copy",
  824. method: "POST",
  825. data: {
  826. "srcpath": file,
  827. "destpath": currentPath
  828. },
  829. success: function(data){
  830. if (data.error != undefined){
  831. msgbox(data.error, false);
  832. }else{
  833. if (copyPendingFiles.length > 0){
  834. //Contine to copy and paste the files
  835. copyFirstItemInQueueUntilAllCopied();
  836. if (startingDir == currentPath){
  837. refresh();
  838. }
  839. }else{
  840. //All copy operation done
  841. msgbox("Files copied");
  842. if (startingDir == currentPath){
  843. refresh();
  844. }
  845. }
  846. }
  847. }
  848. })
  849. }
  850. function sortFileList(){
  851. sortFileObjects("folderList");
  852. sortFileObjects("fileList");
  853. }
  854. function sortFileObjects(listSelector) {
  855. const fileObjects = document.querySelectorAll(`#${listSelector} .fileObject`)
  856. // Convert the NodeList to an array for sorting
  857. const fileObjectsArray = Array.from(fileObjects);
  858. // Sort the elements based on their text content
  859. fileObjectsArray.sort((a, b) => {
  860. const textA = a.querySelector('.filename').textContent.toLowerCase();
  861. const textB = b.querySelector('.filename').textContent.toLowerCase();
  862. return textA.localeCompare(textB);
  863. });
  864. // Reorder the elements in the DOM
  865. const fileList = document.getElementById(listSelector);
  866. fileObjectsArray.forEach((fileObject) => {
  867. fileList.appendChild(fileObject);
  868. });
  869. }
  870. function togglePropertiesView(object){
  871. propertiesView = !propertiesView;
  872. if (propertiesView){
  873. $("#propertiesView").show();
  874. $(object).addClass('active');
  875. localStorage.setItem("file_explorer/viewProperties", "true");
  876. if ($(".fileObject.selected").length >= 1){
  877. //Load the file properties
  878. let targetFile = getFileObjectFromFID(lastClickedFileID);
  879. if (targetFile == null){
  880. targetFile = $(".fileObject.selected")[0];
  881. }
  882. let filepath = $(targetFile).attr("filepath");
  883. loadFileProperties(filepath);
  884. }
  885. }else{
  886. $("#propertiesView").hide();
  887. $(object).removeClass('active');
  888. localStorage.setItem("file_explorer/viewProperties", "false");
  889. }
  890. }
  891. // Bind the onDeleteKeyPress() function to the document's keydown event
  892. $(document).on("keydown", function(evt){
  893. if (event.ctrlKey) {
  894. // Check for Ctrl key combinations
  895. if (event.keyCode == 67) {
  896. // Ctrl + C
  897. evt.preventDefault();
  898. copy();
  899. } else if (event.keyCode == 86) {
  900. // Ctrl + V
  901. evt.preventDefault();
  902. paste();
  903. } else if (event.keyCode == 88) {
  904. // Ctrl + X
  905. evt.preventDefault();
  906. cut();
  907. }
  908. } else {
  909. if (event.keyCode == 46) {
  910. //Delete
  911. evt.preventDefault();
  912. deleteFile();
  913. }else if (event.keyCode == 13){
  914. //Enter
  915. evt.preventDefault();
  916. $(".fileObject.selected").each(function(e){
  917. openthis($(this), e);
  918. });
  919. }
  920. }
  921. });
  922. </script>
  923. </body>
  924. </html>