67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
import os
|
|
import markdown
|
|
import secrets
|
|
from flask import current_app
|
|
from werkzeug.utils import secure_filename
|
|
import json
|
|
|
|
def get_uri_map_path():
|
|
"""Get the path to the URI mapping file"""
|
|
return os.path.join(current_app.config['UPLOAD_FOLDER'], 'uri_map.json')
|
|
|
|
def load_uri_map():
|
|
"""Load the URI mapping from file"""
|
|
map_path = get_uri_map_path()
|
|
if os.path.exists(map_path):
|
|
with open(map_path, 'r') as f:
|
|
return json.load(f)
|
|
return {}
|
|
|
|
def save_uri_map(uri_map):
|
|
"""Save the URI mapping to file"""
|
|
with open(get_uri_map_path(), 'w') as f:
|
|
json.dump(uri_map, f, indent=2)
|
|
|
|
def generate_unique_uri():
|
|
"""Generate a unique URI for a file"""
|
|
uri_map = load_uri_map()
|
|
while True:
|
|
uri = secrets.token_urlsafe(6) # Generate a short random string
|
|
if uri not in uri_map:
|
|
return uri
|
|
|
|
def save_file(file, custom_uri=None):
|
|
"""Save the uploaded file to the upload folder and assign a URI"""
|
|
# Secure the filename first
|
|
filename = secure_filename(file.filename)
|
|
|
|
# Generate or use custom URI
|
|
uri = custom_uri if custom_uri else generate_unique_uri()
|
|
|
|
# Save the file with its original name
|
|
filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
|
|
file.save(filepath)
|
|
|
|
# Update the URI map
|
|
uri_map = load_uri_map()
|
|
uri_map[uri] = {
|
|
'filename': filename,
|
|
'path': filepath
|
|
}
|
|
save_uri_map(uri_map)
|
|
|
|
return uri, filename
|
|
|
|
def get_file_by_uri(uri):
|
|
"""Get file info by URI"""
|
|
uri_map = load_uri_map()
|
|
if uri in uri_map:
|
|
return uri_map[uri]
|
|
return None
|
|
|
|
def read_markdown_file(filepath):
|
|
"""Read and convert markdown file to HTML"""
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
md_content = f.read()
|
|
html_content = markdown.markdown(md_content, extensions=['tables', 'fenced_code'])
|
|
return html_content
|