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.

81 lines
2.5 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
from sanic import Sanic, HTTPResponse
5 years ago
from sanic.request import Request
from sanic.response import text, html, file_stream, redirect
from sanic.exceptions import NotFound, MethodNotAllowed
3 years ago
from sanic_cors import CORS
from sanic_ext import Extend
7 years ago
5 years ago
from utils import get_j2env, get_sort_icon, get_sort_link, resolve_path, list_dir
7 years ago
DEBUG = Path('.debug').exists()
7 years ago
app = Sanic('autoindex', strict_slashes=True)
Extend(app)
3 years ago
cors = CORS(app)
5 years ago
app.static('/~static/', '~static/', use_content_range=True, stream_large_files=True)
j2env = get_j2env(DEBUG)
7 years ago
@app.get(r'/<path:.*/?>')
5 years ago
async def index(request: Request, path=''):
path = path.replace('%20', ' ')
5 years ago
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():
stream = await file_stream(resolved_path)
if request.method == 'HEAD':
stream.headers['Content-Length'] = resolved_path.stat().st_size
return HTTPResponse(
'', status=200, headers=stream.headers, content_type=stream.content_type
)
return stream
5 years ago
1 year ago
raise NotFound('Path was not found')
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)