You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

5 years ago
import os
import socket
5 years ago
from os import environ
5 years ago
from pathlib import Path
7 years ago
5 years ago
from sanic import Sanic
from sanic.request import Request
from sanic.response import text, html, file_stream, redirect
from sanic.exceptions import abort
7 years ago
5 years ago
from utils import get_j2env, get_sort_icon, get_sort_link, resolve_path, list_dir
7 years ago
5 years ago
DEBUG = environ.get('ENV', '').upper() != 'PRODUCTION'
7 years ago
3 years ago
app = Sanic('autoindex')
5 years ago
app.static('/~static/', '~static/', use_content_range=True, stream_large_files=True)
j2env = get_j2env(DEBUG)
7 years ago
5 years ago
async def index(request: Request, path=''):
domain = request.host
query = f'?{request.query_string}' if request.query_string else ''
7 years ago
try:
5 years ago
resolved_path, resolved_query = resolve_path(domain, path)
7 years ago
except ValueError:
5 years ago
return text('GTFO', 400)
if resolved_path.is_dir():
7 years ago
if path and path[-1] != '/':
return redirect(f'/{path}/')
5 years ago
hidden = request.args.get('hidden') is not None
sort = request.args.get('sort', 'name')
7 years ago
if sort not in ['name', '-name', 'size', '-size', 'created', '-created']:
sort = 'name'
5 years ago
return html(j2env.get_template('filelist.tpl').render(
lst=list_dir(resolved_path, sort, hidden, root=not resolved_query),
get_sort_icon=get_sort_icon,
get_sort_link=get_sort_link,
sort=sort,
hidden=hidden,
path=resolved_query,
query=query,
))
elif resolved_path.is_file():
return await file_stream(resolved_path)
abort(404, 'Path was not found')
7 years ago
3 years ago
app.get('/')(index)
app.get('/<path:path>')(index)
7 years ago
if __name__ == '__main__':
5 years ago
if DEBUG:
app.run(host='localhost', port=8080, debug=True, auto_reload=True)
else:
5 years ago
socket_address = Path('/tmp/drop.sock')
try:
socket_address.unlink()
except OSError:
if socket_address.exists():
raise
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
5 years ago
sock.bind(str(socket_address))
5 years ago
socket_address.chmod(0o666)
app.run(sock=sock, workers=2)