allow to edit files

This commit is contained in:
2026-04-01 19:45:22 +02:00
parent 0681bd398c
commit eeda177182
6 changed files with 370 additions and 62 deletions
+12 -3
View File
@@ -36,7 +36,7 @@ class ConvexDB(ConvexDbBase):
"uploaded_at": int(x['uploaded_at']), "uploaded_at": int(x['uploaded_at']),
} for x in data ] } for x in data ]
async def add_file(self, file_name:str, file_size:str, note:str, content_type:str, expires_at:datetime, storage_id:str, user_id:str): async def add_file(self, file_name:str, file_size:str, note:str, content_type:str, expires_at:datetime|None, storage_id:str, user_id:str):
args = { args = {
'file_name': file_name, 'file_size': file_size, 'content_type': content_type, 'file_name': file_name, 'file_size': file_size, 'content_type': content_type,
'note': note, 'note': note,
@@ -51,10 +51,19 @@ class ConvexDB(ConvexDbBase):
) )
return data return data
async def update_file(self, file_id:str, file_name:str, note:str, expires_at:datetime, user_id:str): async def update_file(self, file_id:str, file_name:str, note:str, expires_at:datetime|None, user_id:str):
args = {
'file_id': file_id,
'file_name': file_name,
'note': note,
'user_id': user_id
}
if expires_at:
args['expires_at'] = expires_at.isoformat()
await self.run_mutation( await self.run_mutation(
name='files:updateFile', name='files:updateFile',
args={ 'file_id': file_id, 'file_name': file_name, 'note': note, 'expires_at': expires_at.isoformat(), 'user_id': user_id } args=args,
) )
async def delete_file(self, file_id:str, user_id:str): async def delete_file(self, file_id:str, user_id:str):
+32
View File
@@ -0,0 +1,32 @@
from datetime import datetime, timedelta, timezone
from typing import Optional
import re
PRESET_H = re.compile(r"^(\d+)h$")
PRESET_D = re.compile(r"^(\d+)d$")
def parse_expires(value: str | None) -> datetime | None:
"""Parse expiration presets or ISO datetime."""
if not value or value == "never":
return None
value = value.strip()
if not value:
return None
if m := PRESET_H.match(value):
return datetime.now(timezone.utc) + timedelta(hours=int(m.group(1)))
if m := PRESET_D.match(value):
return datetime.now(timezone.utc) + timedelta(days=int(m.group(1)))
try:
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
except Exception:
return None
def ensure_utc(dt:datetime):
"""Ensure a timezone-aware UTC datetime or None."""
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
+27
View File
@@ -0,0 +1,27 @@
from datetime import datetime, timezone
def iso_stamp_filename(prefix: str, ext: str) -> str:
"""Generate timestamped filename, e.g. pasted-2025-10-23T121212Z.png"""
ts = datetime.now(timezone.utc).isoformat()
ts = ts.replace(":", "").split(".")[0]
if ts.endswith("+00:00"):
ts = ts.replace("+00:00", "Z")
return f"{prefix}-{ts}.{ext}"
def format_size(num_bytes: int) -> str:
"""Return a human-readable file size (e.g., '2.3 MB', '10 Bytes')."""
if num_bytes < 1024:
return f"{num_bytes} Byte{'s' if num_bytes != 1 else ''}"
units = ["KB", "MB", "GB", "TB", "PB", "EB"]
size = float(num_bytes)
for unit in units:
size /= 1024.0
if size < 1024.0 or unit == units[-1]:
# 1 decimal place; drop trailing .0 (optional)
val = f"{size:.1f}"
if val.endswith(".0"):
val = val[:-2]
return f"{val} {unit}"
return f"{num_bytes} Bytes" # fallback
+86 -7
View File
@@ -2,10 +2,27 @@ from my_modules.decoratory.header import login_required, feature_flag_required
from my_modules.functions import get_ip from my_modules.functions import get_ip
from my_modules.app.setup import LIMITER from my_modules.app.setup import LIMITER
from my_modules.app.logger import logger from my_modules.app.logger import logger
from my_modules.expiry import parse_expires
from quart import Blueprint, request, session, Response, send_file, render_template, abort, current_app from quart import (
Blueprint,
request,
session,
Response,
send_file,
render_template,
abort,
current_app,
jsonify,
)
side_main_bp = Blueprint('side_main', __name__) side_main_bp = Blueprint("side_main", __name__)
def find_file(files: list[dict], file_id: str):
for file_data in files:
if file_data.get("file_id") == file_id:
return file_data
return None
@side_main_bp.route('/') @side_main_bp.route('/')
@LIMITER.limit("10 per minute;50 per hour") @LIMITER.limit("10 per minute;50 per hour")
@@ -36,15 +53,77 @@ async def files_list(user):
@login_required @login_required
@feature_flag_required("nanoshare_files-info", fallback=False, status_code=404) @feature_flag_required("nanoshare_files-info", fallback=False, status_code=404)
async def file_info(file_id, user): async def file_info(file_id, user):
files_data = await current_app.convex.get_files(user_id=user['sub']) files_data = await current_app.convex.get_files(user_id=user["sub"])
return await render_template("views/webpage/files/info.htm", files=files_data) file_data = find_file(files_data, file_id)
if not file_data:
abort(404)
@side_main_bp.route('/files/<path:file_id>/edit') access_data = await current_app.convex.get_file_access(file_id=file_id) or []
share_url = request.url_root.rstrip("/") + f"/-{file_id}"
return await render_template(
"views/webpage/files/info.htm",
file=file_data,
accesses=access_data,
share_url=share_url,
)
@side_main_bp.route("/files/<path:file_id>/edit")
@login_required @login_required
@feature_flag_required("nanoshare_files-edit", fallback=False, status_code=404) @feature_flag_required("nanoshare_files-edit", fallback=False, status_code=404)
async def file_edit(file_id, user): async def file_edit(file_id, user):
files_data = await current_app.convex.get_files(user_id=user['sub']) files_data = await current_app.convex.get_files(user_id=user["sub"])
return await render_template("views/webpage/files/edit.htm", files=files_data) file_data = find_file(files_data, file_id)
if not file_data:
abort(404)
share_url = request.url_root.rstrip("/") + f"/-{file_id}"
return await render_template(
"views/webpage/files/edit.htm", file=file_data, share_url=share_url
)
@side_main_bp.post("/api/files/<path:file_id>/edit")
@login_required
@feature_flag_required("nanoshare_files-edit", fallback=False, status_code=404)
async def file_edit_api(file_id, user):
files_data = await current_app.convex.get_files(user_id=user["sub"])
if not find_file(files_data, file_id):
return jsonify({"ok": False, "error": "File not found"}), 404
payload = await request.get_json(silent=True)
if payload is None:
payload = await request.form
file_name = str(payload.get("file_name", "")).strip()
note = str(payload.get("note", "")).strip()
expires_raw = str(payload.get("expires", "")).strip()
if not file_name:
return jsonify({"ok": False, "error": "Filename is required"}), 400
expires_at = parse_expires(expires_raw)
if expires_raw and expires_raw != "never" and expires_at is None:
return jsonify({"ok": False, "error": "Invalid expiration value"}), 400
await current_app.convex.update_file(
file_id=file_id,
file_name=file_name,
note=note,
expires_at=expires_at,
user_id=user["sub"],
)
return jsonify({"ok": True})
@side_main_bp.post("/api/files/<path:file_id>/delete")
@login_required
@feature_flag_required("nanoshare_files-edit", fallback=False, status_code=404)
async def file_delete_api(file_id, user):
files_data = await current_app.convex.get_files(user_id=user["sub"])
if not find_file(files_data, file_id):
return jsonify({"ok": False, "error": "File not found"}), 404
await current_app.convex.delete_file(file_id=file_id, user_id=user["sub"])
return jsonify({"ok": True})
@side_main_bp.route("/-<file_id>") @side_main_bp.route("/-<file_id>")
@LIMITER.limit("10 per minute;500 per hour;") @LIMITER.limit("10 per minute;500 per hour;")
+3 -52
View File
@@ -1,55 +1,14 @@
from my_modules.decoratory.header import login_required from my_modules.decoratory.header import login_required
from my_modules.expiry import parse_expires, ensure_utc
from my_modules.file_meta import iso_stamp_filename, format_size
from quart import Blueprint, request, jsonify, current_app from quart import Blueprint, request, jsonify, current_app
from datetime import datetime, timedelta, timezone import asyncio
import aiofiles, asyncio, re
upload_bp = Blueprint("upload_bp", __name__) upload_bp = Blueprint("upload_bp", __name__)
# --- Helpers ----------------------------------------------------- # --- Helpers -----------------------------------------------------
PRESET_H = re.compile(r"^(\d+)h$")
PRESET_D = re.compile(r"^(\d+)d$")
def iso_stamp_filename(prefix: str, ext: str) -> str:
"""Generate timestamped filename, e.g. pasted-2025-10-23T121212Z.png"""
ts = datetime.now(timezone.utc).isoformat()
ts = ts.replace(":", "").split(".")[0]
if ts.endswith("+00:00"):
ts = ts.replace("+00:00", "Z")
return f"{prefix}-{ts}.{ext}"
def parse_expires(value: str | None) -> datetime | None:
"""Parse expiration presets or ISO datetime."""
if not value:
return None
value = value.strip()
if m := PRESET_H.match(value):
return datetime.now(timezone.utc) + timedelta(hours=int(m.group(1)))
if m := PRESET_D.match(value):
return datetime.now(timezone.utc) + timedelta(days=int(m.group(1)))
try:
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
except Exception:
return None
def format_size(num_bytes: int) -> str:
"""Return a human-readable file size (e.g., '2.3 MB', '10 Bytes')."""
if num_bytes < 1024:
return f"{num_bytes} Byte{'s' if num_bytes != 1 else ''}"
units = ["KB", "MB", "GB", "TB", "PB", "EB"]
size = float(num_bytes)
for unit in units:
size /= 1024.0
if size < 1024.0 or unit == units[-1]:
# 1 decimal place; drop trailing .0 (optional)
val = f"{size:.1f}"
if val.endswith(".0"):
val = val[:-2]
return f"{val} {unit}"
return f"{num_bytes} Bytes" # fallback
async def read_all(uploaded) -> bytes: async def read_all(uploaded) -> bytes:
"""Read all bytes from an uploaded file, handling sync or async .read().""" """Read all bytes from an uploaded file, handling sync or async .read()."""
reader = getattr(uploaded, "read", None) reader = getattr(uploaded, "read", None)
@@ -63,14 +22,6 @@ async def read_all(uploaded) -> bytes:
return await data return await data
return data return data
def ensure_utc(dt:datetime):
"""Ensure a timezone-aware UTC datetime or None."""
if dt is None:
return None
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
# --- Routes ------------------------------------------------------ # --- Routes ------------------------------------------------------
@upload_bp.post("/api/upload") @upload_bp.post("/api/upload")
+210
View File
@@ -0,0 +1,210 @@
{% extends "base.htm" %}
{% block title %}NanoShare - Edit file{% endblock %}
{% block meta %}
<meta name="description" content="NanoShare file editing page.">
<meta name="robots" content="noindex, nofollow" />
{% endblock %}
{% block head %}
<style>
.file-edit-page { margin: clamp(16px, 3vw, 32px) auto; }
.info-line { margin-top: 12px; color: var(--muted); font-size: .95rem; }
.save-row { margin-top: 18px; display: flex; justify-content: space-evenly; align-items: center; gap: 10px; flex-wrap: wrap; }
.status-row { margin-top: 8px; text-align: center; }
.status { color: var(--muted); font-size: .92rem; }
.status.ok { color: #8ee28e; }
.status.err { color: #f08f8f; }
.btn-danger { border-color: #8f3b3b; color: #ffd4d4; }
.btn-danger:hover { background: #4d1f1f; }
.meta-table-wrap { margin-top: 10px; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
.meta-table { width: 100%; border-collapse: collapse; }
.meta-table th, .meta-table td { padding: 10px 12px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
.meta-table tr:last-child th, .meta-table tr:last-child td { border-bottom: 0; }
.meta-table th { width: 160px; color: var(--muted); font-weight: 700; }
.danger-zone { margin-top: 20px; border: 1px solid #6a2c2c; border-radius: 12px; padding: 12px; background: rgba(120, 32, 32, 0.14); }
.danger-zone h2 { margin: 0 0 6px; font-size: 1rem; }
.danger-zone p { margin: 0 0 10px; color: var(--muted); font-size: .92rem; }
</style>
{% endblock %}
{% block content %}
<main class="file-edit-page">
<section class="card" aria-labelledby="edit-title">
<h1 id="edit-title" class="page-title">Edit file</h1>
<p class="subtle">Update filename, note and expiration date.</p>
<div class="meta-table-wrap" role="region" aria-label="File metadata">
<table class="meta-table">
<tbody>
<tr>
<th scope="row">URL</th>
<td><a href="{{ share_url }}">{{ share_url }}</a></td>
</tr>
<tr>
<th scope="row">File ID</th>
<td><code>{{ file.file_id }}</code></td>
</tr>
<tr>
<th scope="row">Uploaded at</th>
<td><time class="local-time" data-ts="{{ file.uploaded_at }}"></time></td>
</tr>
<tr>
<th scope="row">File size</th>
<td><span class="badge">{{ file.file_size }}</span></td>
</tr>
</tbody>
</table>
</div>
<div class="field">
<label for="fileName" class="label">Filename</label>
<input id="fileName" class="input" type="text" maxlength="255" value="{{ file.file_name }}" />
</div>
<div class="field">
<label for="note" class="label">Note</label>
<input id="note" class="input" type="text" maxlength="500" value="{{ file.note or '' }}" />
</div>
<div class="row">
<div class="field">
<label for="expiresMode" class="label">Expiration</label>
<select id="expiresMode" class="select">
<option value="1h">1 hour</option>
<option value="24h">24 hours</option>
<option value="7d">7 days</option>
<option value="30d">30 days</option>
<option value="never">Never</option>
<option value="custom">Custom date</option>
</select>
</div>
<div class="field" id="customWrap" style="display:none;">
<label for="customExpire" class="label">Custom expiration</label>
<input type="datetime-local" id="customExpire" class="datetime" />
</div>
</div>
<div class="save-row">
<button id="saveBtn" class="btn" type="button">Save changes</button>
<a class="btn btn-ghost" href="{{ url_for('side_main.file_info', file_id=file.file_id) }}">View info</a>
<a class="btn btn-ghost" href="{{ url_for('side_main.files_list') }}">Back to files</a>
</div>
<div class="status-row"><span id="status" class="status"></span></div>
<section class="danger-zone" aria-labelledby="danger-title">
<h2 id="danger-title">Danger zone</h2>
<p>Deleting a file is permanent and cannot be undone.</p>
<button id="deleteBtn" class="btn btn-ghost btn-danger" type="button">Delete file</button>
</section>
</section>
</main>
<script>
const fileId = '{{ file.file_id }}';
const initialExpires = '{{ file.expires_at }}';
const expiresMode = document.getElementById('expiresMode');
const customWrap = document.getElementById('customWrap');
const customExpire = document.getElementById('customExpire');
const statusEl = document.getElementById('status');
function formatDate(value) {
if (!value) return 'Never';
const date = new Date(Number.parseInt(String(value), 10));
if (Number.isNaN(date.getTime())) return 'Invalid date';
return date.toLocaleString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false,
});
}
function toLocalInputValue(timestampMs) {
const d = new Date(Number.parseInt(String(timestampMs), 10));
if (Number.isNaN(d.getTime())) return '';
const local = new Date(d.getTime() - d.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16);
}
function setStatus(msg, type) {
statusEl.textContent = msg;
statusEl.className = 'status';
if (type) statusEl.classList.add(type);
}
function syncExpireUI() {
customWrap.style.display = expiresMode.value === 'custom' ? 'block' : 'none';
}
if (initialExpires) {
expiresMode.value = 'custom';
customExpire.value = toLocalInputValue(initialExpires);
} else {
expiresMode.value = 'never';
}
syncExpireUI();
expiresMode.addEventListener('change', syncExpireUI);
document.querySelectorAll('time.local-time').forEach((el) => {
el.textContent = formatDate(el.dataset.ts || '');
});
document.getElementById('saveBtn').addEventListener('click', async () => {
const fileName = document.getElementById('fileName').value.trim();
const note = document.getElementById('note').value.trim();
if (!fileName) {
setStatus('Filename is required.', 'err');
return;
}
let expires = expiresMode.value;
if (expiresMode.value === 'custom') {
if (!customExpire.value) {
setStatus('Pick a custom date.', 'err');
return;
}
expires = new Date(customExpire.value).toISOString();
}
setStatus('Saving...');
try {
const response = await fetch(`/api/files/${encodeURIComponent(fileId)}/edit`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_name: fileName, note, expires }),
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || 'Could not update file');
}
setStatus('Saved.', 'ok');
} catch (error) {
setStatus(error.message || 'Could not update file.', 'err');
}
});
document.getElementById('deleteBtn').addEventListener('click', async () => {
const ok = window.confirm('Delete this file? This cannot be undone.');
if (!ok) return;
setStatus('Deleting...');
try {
const response = await fetch(`/api/files/${encodeURIComponent(fileId)}/delete`, {
method: 'POST',
});
const data = await response.json();
if (!response.ok || !data.ok) {
throw new Error(data.error || 'Could not delete file');
}
window.location.href = '{{ url_for("side_main.files_list") }}';
} catch (error) {
setStatus(error.message || 'Could not delete file.', 'err');
}
});
</script>
{% endblock %}