Skip to content

Commit 8e8cff1

Browse files
committed
Custom listdir
1 parent 066bd45 commit 8e8cff1

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/HTTPServer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def do_GET(self):
9696
if SETTINGS.get("root") == "index":
9797
self.path = URL.path + 'index.html'
9898
else:
99-
return self.copyfile(self.list_directory(path), self.wfile)
99+
return self.copyfile(list_directory(path, URL.path), self.wfile)
100100
else:
101101
if not os.path.exists(path):
102102
self.path = URL.path + '.html'

src/utils.py

+50
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
import socket
33
import json
44
import tkinter as tk
5+
import io
6+
import urllib
57

68

79
def resource_path(relative_path):
@@ -31,6 +33,54 @@ def get_host(host=""):
3133
return "127.0.0.1"
3234
return host
3335

36+
def get_files_and_folders(path):
37+
files = []
38+
folders = []
39+
for item in os.listdir(path):
40+
full_path = os.path.join(path, item)
41+
if os.path.isdir(full_path):
42+
folders.append(item)
43+
elif os.path.isfile(full_path):
44+
files.append(item)
45+
return files, folders
46+
47+
def list_directory(path, urlpath):
48+
files, folders = get_files_and_folders(path)
49+
50+
folders_html = ""
51+
for folder in folders:
52+
folders_html += f"<li>📁<a href='{folder}/'>{folder}/</a></li>"
53+
54+
files_html = ""
55+
for file in files:
56+
folders_html += f"<li>🗎<a href='{file}'>{file}</a></li>"
57+
58+
nothing = "<p>¯\\_(ツ)_/¯</p>"
59+
html = f"""
60+
<!DOCTYPE html>
61+
<html>
62+
<head>
63+
<title>Directory listing</title>
64+
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
65+
<meta name='viewport' content='width=device-width'>
66+
</head>
67+
<body>
68+
<h2>{urllib.parse.unquote(urlpath)}</h2>
69+
<hr>
70+
<ul>
71+
{"<li><a href='../'>↩</a></li>" if urlpath != "/" else ""}
72+
{nothing if (not folders_html and not files_html) else ""}
73+
{folders_html}
74+
{files_html}
75+
</ul>
76+
</body>
77+
</html>
78+
"""
79+
f = io.BytesIO()
80+
f.write(bytes(html, 'utf-8'))
81+
f.seek(0)
82+
return f
83+
3484
class EntryWithPlaceholder(tk.Entry):
3585
def __init__(self, master, placeholder, color='grey'):
3686
super().__init__(master)

0 commit comments

Comments
 (0)