upload external files

This commit is contained in:
Davide Scaini
2026-03-30 13:06:20 +02:00
parent fa08988471
commit 0865159cca
3 changed files with 160 additions and 2 deletions
+1 -1
View File
@@ -625,7 +625,7 @@ Not yet implemented — see friends/federation items in the checklist below.
- [ ] Activity search / full-text filter in feed
- [ ] Map thumbnail in activity cards (SVG path from GeoJSON)
- [ ] GitHub Actions template for auto-publish
- [ ] **Ingestion: web file upload**`POST /api/upload` in edit server, drag-and-drop in nav
- [x] **Ingestion: web file upload**`POST /api/upload` in edit server, drag-and-drop in nav
- [ ] **Ingestion: `bincio import strava`** — OAuth2 + streams API, idempotent incremental sync
- [ ] **Ingestion: `bincio extract --watch`** — directory watcher for ongoing FIT sync
- [ ] **Ingestion: `bincio import garmin`** — garminconnect library or FIT folder sync
+66
View File
@@ -516,6 +516,72 @@ def _read_athlete_edits(data_dir: Path) -> dict:
return {}
_SUPPORTED_SUFFIXES = {".fit", ".gpx", ".tcx", ".fit.gz", ".gpx.gz", ".tcx.gz"}
def _file_suffix(name: str) -> str:
"""Return the effective suffix, including .gz double-extension."""
p = Path(name.lower())
if p.suffix == ".gz":
return p.stem.rsplit(".", 1)[-1].join([".", ".gz"]) if "." in p.stem else ".gz"
return p.suffix
@app.post("/api/upload")
async def upload_activity(file: UploadFile = File(...)) -> JSONResponse:
"""Accept a FIT/GPX/TCX file, extract it, update index.json, and re-merge."""
dd = _get_data_dir()
name = file.filename or "upload.fit"
suffix = _file_suffix(name)
if suffix not in _SUPPORTED_SUFFIXES:
raise HTTPException(400, f"Unsupported file type '{Path(name).suffix}'. Expected FIT, GPX, or TCX.")
staging = dd / "_uploads"
staging.mkdir(exist_ok=True)
staged = staging / name
staged.write_bytes(await file.read())
try:
from bincio.extract.metrics import compute
from bincio.extract.parsers.factory import parse_file
from bincio.extract.writer import build_summary, make_activity_id, write_activity, write_index
activity = parse_file(staged)
metrics = compute(activity)
activity_id = make_activity_id(activity)
existing_json = dd / "activities" / f"{activity_id}.json"
if existing_json.exists():
raise HTTPException(409, f"Activity already exists: {activity_id}")
write_activity(activity, metrics, dd, privacy="public", rdp_epsilon=0.0001)
summary = build_summary(activity, metrics, activity_id, "public")
# Read current index to preserve owner + existing summaries
index_path = dd / "index.json"
if index_path.exists():
index_data = json.loads(index_path.read_text(encoding="utf-8"))
else:
index_data = {"owner": {"handle": "unknown"}, "activities": []}
owner = index_data.get("owner", {})
existing = {s["id"]: s for s in index_data.get("activities", [])}
existing[activity_id] = summary
write_index(list(existing.values()), dd, owner)
from bincio.render.merge import merge_all
merge_all(dd)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(422, str(exc))
finally:
staged.unlink(missing_ok=True)
return JSONResponse({"ok": True, "id": activity_id})
@app.delete("/api/activity/{activity_id}/images/{filename}")
async def delete_image(activity_id: str, filename: str) -> JSONResponse:
dd = _get_data_dir()
+93 -1
View File
@@ -4,6 +4,7 @@ interface Props {
description?: string;
}
const { title = 'BincioActivity', description = 'Your personal activity stats' } = Astro.props;
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? '';
---
<!doctype html>
<html lang="en" data-theme="dark">
@@ -103,7 +104,15 @@ const { title = 'BincioActivity', description = 'Your personal activity stats' }
<a href="/stats/" class="text-sm text-zinc-400 hover:text-white transition-colors">Stats</a>
<a href="/athlete/" class="text-sm text-zinc-400 hover:text-white transition-colors">Athlete</a>
<div class="ml-auto">
<div class="ml-auto flex items-center gap-1">
{editUrl && (
<button
id="upload-btn"
class="text-zinc-400 hover:text-white transition-colors w-8 h-8 flex items-center justify-center rounded-md hover:bg-zinc-800 text-base"
aria-label="Upload activity"
title="Upload activity"
>↑</button>
)}
<button
id="theme-toggle"
class="text-zinc-400 hover:text-white transition-colors w-8 h-8 flex items-center justify-center rounded-md hover:bg-zinc-800 text-base"
@@ -112,6 +121,34 @@ const { title = 'BincioActivity', description = 'Your personal activity stats' }
</div>
</div>
</nav>
{editUrl && (
<!-- Upload modal -->
<div
id="upload-modal"
style="display:none"
class="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center"
role="dialog"
aria-modal="true"
aria-label="Upload activity"
>
<div class="bg-zinc-900 border border-zinc-800 rounded-xl p-6 w-full max-w-sm mx-4 shadow-2xl">
<div class="flex items-center justify-between mb-4">
<h2 class="font-semibold text-white text-sm">Upload activity</h2>
<button id="upload-close" class="text-zinc-500 hover:text-white transition-colors text-xl leading-none" aria-label="Close">×</button>
</div>
<div
id="upload-drop"
class="border-2 border-dashed border-zinc-700 rounded-lg p-8 text-center text-zinc-500 text-sm cursor-pointer hover:border-zinc-500 hover:text-zinc-300 transition-colors"
>
<div id="upload-label">Drop a FIT, GPX, or TCX file<br/>or click to browse</div>
<input id="upload-input" type="file" accept=".fit,.gpx,.tcx,.fit.gz,.gpx.gz,.tcx.gz" class="hidden" />
</div>
<p id="upload-status" class="mt-3 text-xs text-center" style="color: var(--text-5); min-height: 1.25rem"></p>
</div>
</div>
)}
<main class="max-w-7xl mx-auto px-4 py-6">
<slot />
</main>
@@ -135,5 +172,60 @@ const { title = 'BincioActivity', description = 'Your personal activity stats' }
applyTheme(next);
});
</script>
{editUrl && (
<script define:vars={{ editUrl }}>
const modal = document.getElementById('upload-modal');
const drop = document.getElementById('upload-drop');
const input = document.getElementById('upload-input');
const label = document.getElementById('upload-label');
const status = document.getElementById('upload-status');
const openBtn = document.getElementById('upload-btn');
const closeBtn = document.getElementById('upload-close');
function openModal() { modal.style.display = 'flex'; }
function closeModal() { modal.style.display = 'none'; label.innerHTML = 'Drop a FIT, GPX, or TCX file<br>or click to browse'; status.textContent = ''; status.style.color = ''; }
openBtn.addEventListener('click', openModal);
closeBtn.addEventListener('click', closeModal);
modal.addEventListener('click', e => { if (e.target === modal) closeModal(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape' && modal.style.display !== 'none') closeModal(); });
drop.addEventListener('click', () => input.click());
drop.addEventListener('dragover', e => { e.preventDefault(); drop.style.borderColor = 'var(--accent)'; drop.style.color = 'var(--text-primary)'; });
drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; drop.style.color = ''; });
drop.addEventListener('drop', e => {
e.preventDefault();
drop.style.borderColor = '';
drop.style.color = '';
if (e.dataTransfer?.files[0]) doUpload(e.dataTransfer.files[0]);
});
input.addEventListener('change', () => { if (input.files?.[0]) doUpload(input.files[0]); });
async function doUpload(file) {
label.textContent = file.name;
status.textContent = 'Uploading…';
status.style.color = 'var(--text-4)';
drop.style.pointerEvents = 'none';
const fd = new FormData();
fd.append('file', file);
try {
const r = await fetch(`${editUrl}/api/upload`, { method: 'POST', body: fd });
if (!r.ok) throw new Error(await r.text());
const d = await r.json();
status.textContent = 'Done! Opening activity…';
status.style.color = '#4ade80';
setTimeout(() => { window.location.href = `/activity/${d.id}/`; }, 600);
} catch (e) {
status.textContent = 'Error: ' + e.message;
status.style.color = '#f87171';
drop.style.pointerEvents = '';
input.value = '';
}
}
</script>
)}
</body>
</html>