-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroutes.py
More file actions
711 lines (608 loc) · 24.7 KB
/
Copy pathroutes.py
File metadata and controls
711 lines (608 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
"""
REST API / Interface REST FastAPI
EN: HTTP interface consumed by the Flutter app for all data operations.
Runs on port 8766 alongside the WebDAV server (port 8765).
FR: Interface HTTP consommée par l'app Flutter pour toutes les opérations.
Tourne sur le port 8766 en parallèle du serveur WebDAV (port 8765).
Routes:
GET /health → server status / statut du serveur
GET /notebooks → list notebooks / liste des carnets
POST /notebooks → create notebook / créer un carnet
GET /notebooks/{id} → notebook detail / détails d'un carnet
PUT /notebooks/{id} → update notebook / modifier un carnet
DELETE /notebooks/{id} → supprimer un carnet
GET /notes → liste des notes (filtrable)
POST /notes → créer une note
GET /notes/{id} → détails d'une note (avec pages)
PUT /notes/{id} → modifier une note
DELETE /notes/{id} → suppression logique
POST /notes/{id}/restore → restaurer depuis la corbeille
POST /notes/{id}/duplicate → dupliquer une note
GET /notes/{id}/pages/{num} → récupérer une page
PUT /notes/{id}/pages/{num}/ink → sauvegarder les strokes d'une page
PUT /notes/{id}/pages/{num}/text → sauvegarder le contenu texte
POST /sync/trigger → déclencher une sync WebDAV
GET /sync/status → état de la dernière sync
POST /export/markdown → export propre vers un dossier (Obsidian)
GET /stats → statistiques globales
GET /search?q=... → recherche par titre
"""
from __future__ import annotations
import json
import logging
import os
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from nexanote.models.note import (
InkStroke, Note, Notebook, NoteType, Page, Point, SyncStatus
)
from nexanote.storage.file_store import FileNoteStore
from nexanote.sync.client import NexaNoteSyncEngine, SyncConfig, SyncReport
logger = logging.getLogger("nexanote.api")
# ---------------------------------------------------------------------------
# Schémas Pydantic (validation + sérialisation)
# ---------------------------------------------------------------------------
class PointSchema(BaseModel):
x: float
y: float
pressure: float = 0.5
ts: int = 0
class StrokeSchema(BaseModel):
id: str
color: str = "#000000"
width: float = 2.0
tool: str = "pen"
points: list[PointSchema]
created_at: Optional[str] = None
class PageSchema(BaseModel):
page_number: int
template: str = "blank"
width_px: float = 1404.0
height_px: float = 1872.0
typed_content: str = ""
strokes: list[StrokeSchema] = Field(default_factory=list)
updated_at: Optional[str] = None
class NoteCreateSchema(BaseModel):
title: str = "Sans titre"
note_type: str = "typed"
notebook_id: Optional[str] = None
tags: list[str] = Field(default_factory=list)
template: str = "blank"
class NoteUpdateSchema(BaseModel):
title: Optional[str] = None
tags: Optional[list[str]] = None
is_pinned: Optional[bool] = None
notebook_id: Optional[str] = None
class NoteSchema(BaseModel):
id: str
title: str
note_type: str
notebook_id: Optional[str]
tags: list[str]
is_pinned: bool
is_archived: bool
is_deleted: bool
sync_status: str
page_count: int
created_at: str
updated_at: str
pages: Optional[list[PageSchema]] = None
class NotebookCreateSchema(BaseModel):
name: str = "Nouveau carnet"
description: str = ""
color: str = "#6366f1"
icon: str = "notebook"
parent_id: Optional[str] = None
class NotebookUpdateSchema(BaseModel):
name: Optional[str] = None
description: Optional[str] = None
color: Optional[str] = None
icon: Optional[str] = None
class NotebookSchema(BaseModel):
id: str
name: str
description: str
color: str
icon: str
parent_id: Optional[str]
is_archived: bool
sync_status: str
created_at: str
updated_at: str
class InkUpdateSchema(BaseModel):
strokes: list[StrokeSchema]
class TextUpdateSchema(BaseModel):
typed_content: str
class SyncConfigSchema(BaseModel):
server_url: str
username: str = "nexanote"
password: str = "nexanote"
conflict_strategy: str = "merge_strokes"
class SyncReportSchema(BaseModel):
success: bool
notes_pulled: int
notes_pushed: int
conflicts_resolved: int
errors: list[str]
duration_seconds: float
summary: str
# Diagnostics — additive, default-valued so existing clients are unaffected.
notes_ignored_legacy: int = 0
dry_run: bool = False
conflicts: list[dict] = Field(default_factory=list)
warnings: list[str] = Field(default_factory=list)
plan: dict = Field(default_factory=dict)
class ExportRequestSchema(BaseModel):
target_dir: Optional[str] = None
include_archived: bool = False
class ExportReportSchema(BaseModel):
target_dir: str
exported: int
files: list[str]
# ---------------------------------------------------------------------------
# Sérialiseurs
# ---------------------------------------------------------------------------
def _notebook_to_schema(nb: Notebook) -> NotebookSchema:
return NotebookSchema(
id=nb.id,
name=nb.name,
description=nb.description,
color=nb.color,
icon=nb.icon,
parent_id=nb.parent_id,
is_archived=nb.is_archived,
sync_status=nb.sync_status.value,
created_at=nb.created_at.isoformat(),
updated_at=nb.updated_at.isoformat(),
)
def _note_to_schema(note: Note, include_pages: bool = False) -> NoteSchema:
pages = None
if include_pages:
pages = [_page_to_schema(p) for p in note.pages]
return NoteSchema(
id=note.id,
title=note.title,
note_type=note.note_type.value,
notebook_id=note.notebook_id,
tags=note.tags,
is_pinned=note.is_pinned,
is_archived=note.is_archived,
is_deleted=note.is_deleted,
sync_status=note.sync_status.value,
page_count=note.page_count(),
created_at=note.created_at.isoformat(),
updated_at=note.updated_at.isoformat(),
pages=pages,
)
def _page_to_schema(page: Page) -> PageSchema:
return PageSchema(
page_number=page.page_number,
template=page.template,
width_px=page.width_px,
height_px=page.height_px,
typed_content=page.typed_content,
updated_at=page.updated_at.isoformat(),
strokes=[
StrokeSchema(
id=s.id,
color=s.color,
width=s.width,
tool=s.tool,
created_at=s.created_at.isoformat(),
points=[
PointSchema(x=p.x, y=p.y, pressure=p.pressure, ts=p.timestamp_ms)
for p in s.points
],
)
for s in page.strokes
],
)
# ---------------------------------------------------------------------------
# App FastAPI
# ---------------------------------------------------------------------------
def create_app(db: FileNoteStore) -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("NexaNote API démarrée")
yield
db.close()
logger.info("NexaNote API arrêtée")
app = FastAPI(
title="NexaNote API",
description="API REST pour l'app NexaNote",
version="1.0.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# EN: Non-sensitive sync fields that are safe to write to disk.
# Password is intentionally excluded — never persisted in plain text.
# FR: Champs de sync non-sensibles sûrs à écrire sur disque.
# Le mot de passe est exclu intentionnellement — jamais écrit en clair.
_PERSIST_FIELDS = {"server_url", "username", "conflict_strategy"}
_last_sync_report: dict = {}
_sync_config: dict = {}
_sync_config_path = db.data_dir / "sync_config.json"
def _save_sync_config_to_disk() -> None:
"""
EN: Persist non-sensitive sync fields to disk.
File permissions are set to 0o600 (owner read/write only).
Password is never written — user must re-enter it after a restart.
FR: Persiste les champs non-sensibles sur disque.
Permissions du fichier : 0o600 (lecture/écriture propriétaire uniquement).
Le mot de passe n'est jamais écrit — l'utilisateur doit le re-saisir après redémarrage.
"""
safe = {k: v for k, v in _sync_config.items() if k in _PERSIST_FIELDS}
try:
_sync_config_path.write_text(json.dumps(safe, indent=2))
os.chmod(_sync_config_path, 0o600)
except OSError as exc:
logger.warning(f"Could not persist sync config: {exc}")
if _sync_config_path.exists():
try:
_sync_config.update(json.loads(_sync_config_path.read_text()))
logger.info(f"Sync config loaded from {_sync_config_path}")
except (OSError, json.JSONDecodeError, ValueError) as exc:
logger.warning(f"Could not load sync config: {exc}")
# ------------------------------------------------------------------
# Health
# ------------------------------------------------------------------
@app.get("/health")
def health():
stats = db.get_stats()
return {
"status": "ok",
"version": "1.0.0",
"storage": "file",
"stats": stats,
"timestamp": datetime.now(timezone.utc).isoformat(),
}
# ------------------------------------------------------------------
# Notebooks
# ------------------------------------------------------------------
@app.get("/notebooks", response_model=list[NotebookSchema])
def list_notebooks(include_archived: bool = False):
return [
_notebook_to_schema(nb)
for nb in db.list_notebooks(include_archived=include_archived)
]
@app.post("/notebooks", response_model=NotebookSchema, status_code=201)
def create_notebook(data: NotebookCreateSchema):
nb = Notebook(
name=data.name,
description=data.description,
color=data.color,
icon=data.icon,
parent_id=data.parent_id,
)
db.save_notebook(nb)
logger.info(f"Carnet créé : {nb.name}")
return _notebook_to_schema(nb)
@app.get("/notebooks/{notebook_id}", response_model=NotebookSchema)
def get_notebook(notebook_id: str):
nb = db.get_notebook(notebook_id)
if not nb:
raise HTTPException(404, f"Carnet {notebook_id} introuvable")
return _notebook_to_schema(nb)
@app.put("/notebooks/{notebook_id}", response_model=NotebookSchema)
def update_notebook(notebook_id: str, data: NotebookUpdateSchema):
nb = db.get_notebook(notebook_id)
if not nb:
raise HTTPException(404, f"Carnet {notebook_id} introuvable")
if data.name is not None:
nb.name = data.name
if data.description is not None:
nb.description = data.description
if data.color is not None:
nb.color = data.color
if data.icon is not None:
nb.icon = data.icon
nb.touch()
db.save_notebook(nb)
return _notebook_to_schema(nb)
@app.delete("/notebooks/{notebook_id}", status_code=204)
def delete_notebook(notebook_id: str):
nb = db.get_notebook(notebook_id)
if not nb:
raise HTTPException(404, f"Carnet {notebook_id} introuvable")
db.delete_notebook(notebook_id)
# ------------------------------------------------------------------
# Notes
# ------------------------------------------------------------------
@app.get("/notes", response_model=list[NoteSchema])
def list_notes(
notebook_id: Optional[str] = None,
include_deleted: bool = False,
include_archived: bool = False,
search: Optional[str] = Query(None, alias="q"),
):
notes = db.list_notes(
notebook_id=notebook_id,
include_deleted=include_deleted,
include_archived=include_archived,
search_title=search,
)
return [_note_to_schema(n) for n in notes]
@app.post("/notes", response_model=NoteSchema, status_code=201)
def create_note(data: NoteCreateSchema):
if data.notebook_id:
nb = db.get_notebook(data.notebook_id)
if not nb:
raise HTTPException(404, f"Carnet {data.notebook_id} introuvable")
note = Note(
title=data.title,
note_type=NoteType(data.note_type),
notebook_id=data.notebook_id,
tags=data.tags,
)
note.add_page(template=data.template)
db.save_note(note)
logger.info(f"Note créée : {note.title}")
return _note_to_schema(note)
@app.get("/notes/{note_id}", response_model=NoteSchema)
def get_note(note_id: str, pages: bool = True):
note = db.get_note(note_id, load_pages=pages)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
return _note_to_schema(note, include_pages=pages)
@app.put("/notes/{note_id}", response_model=NoteSchema)
def update_note(note_id: str, data: NoteUpdateSchema):
note = db.get_note(note_id, load_pages=False)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
if data.title is not None:
note.title = data.title
if data.tags is not None:
note.tags = data.tags
if data.is_pinned is not None:
note.is_pinned = data.is_pinned
if data.notebook_id is not None:
note.notebook_id = data.notebook_id
note.touch()
db.save_note(note, save_pages=False)
return _note_to_schema(note)
@app.delete("/notes/{note_id}", status_code=204)
def delete_note(note_id: str):
note = db.get_note(note_id, load_pages=False)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
note.soft_delete()
db.save_note(note, save_pages=False)
@app.post("/notes/{note_id}/restore", response_model=NoteSchema)
def restore_note(note_id: str):
note = db.get_note(note_id, load_pages=False)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
note.restore()
db.save_note(note, save_pages=False)
return _note_to_schema(note)
@app.post("/notes/{note_id}/duplicate", response_model=NoteSchema, status_code=201)
def duplicate_note(note_id: str):
import copy
note = db.get_note(note_id, load_pages=True)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
dupe = copy.deepcopy(note)
# Nouveau ID et titre pour la copie
from nexanote.models.note import _new_id, _now
dupe.id = _new_id()
dupe.title = f"{note.title} (copie)"
dupe.sync_status = SyncStatus.LOCAL_ONLY
dupe.created_at = _now()
dupe.updated_at = _now()
# Réinitialiser les IDs de pages
for page in dupe.pages:
page.id = _new_id()
page.note_id = dupe.id
db.save_note(dupe)
logger.info(f"Note dupliquée : {dupe.title}")
return _note_to_schema(dupe)
# ------------------------------------------------------------------
# Pages — encre et texte
# ------------------------------------------------------------------
@app.get("/notes/{note_id}/pages/{page_num}", response_model=PageSchema)
def get_page(note_id: str, page_num: int):
note = db.get_note(note_id, load_pages=True)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
page = note.get_page(page_num)
if not page:
raise HTTPException(404, f"Page {page_num} introuvable dans la note {note_id}")
return _page_to_schema(page)
@app.put("/notes/{note_id}/pages/{page_num}/ink", response_model=PageSchema)
def update_ink(note_id: str, page_num: int, data: InkUpdateSchema):
"""Remplace tous les strokes d'une page — appelé après chaque session d'écriture."""
note = db.get_note(note_id, load_pages=True)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
page = note.get_page(page_num)
if not page:
raise HTTPException(404, f"Page {page_num} introuvable")
new_strokes = []
for s in data.strokes:
points = [
Point(x=p.x, y=p.y, pressure=p.pressure, timestamp_ms=p.ts)
for p in s.points
]
stroke = InkStroke(
id=s.id,
color=s.color,
width=s.width,
tool=s.tool,
points=points,
)
new_strokes.append(stroke)
page.strokes = new_strokes
page.touch()
note.touch()
db.save_page(page)
db.save_note(note, save_pages=False)
return _page_to_schema(page)
@app.put("/notes/{note_id}/pages/{page_num}/text", response_model=PageSchema)
def update_text(note_id: str, page_num: int, data: TextUpdateSchema):
"""Met à jour le contenu texte/markdown d'une page."""
note = db.get_note(note_id, load_pages=True)
if not note:
raise HTTPException(404, f"Note {note_id} introuvable")
page = note.get_page(page_num)
if not page:
raise HTTPException(404, f"Page {page_num} introuvable")
page.typed_content = data.typed_content
page.touch()
note.touch()
db.save_page(page)
db.save_note(note, save_pages=False)
return _page_to_schema(page)
# ------------------------------------------------------------------
# Sync
# ------------------------------------------------------------------
@app.post("/sync/configure")
def configure_sync(config: SyncConfigSchema):
"""
EN: Save WebDAV connection settings in memory and persist safe fields to disk.
The password is kept in memory only and is never written to disk.
FR: Sauvegarde les paramètres WebDAV en mémoire et persiste les champs
sûrs sur disque. Le mot de passe reste en mémoire uniquement.
"""
_sync_config.update(config.model_dump())
_save_sync_config_to_disk()
return {"status": "configured", "server_url": config.server_url}
@app.post("/sync/trigger", response_model=SyncReportSchema)
def trigger_sync(dry_run: bool = Query(False)):
"""
EN: Trigger a manual sync. With ``?dry_run=true`` the engine builds
the sync plan but writes no files, touches no sync state, and
performs no remote uploads — handy to preview what a real sync
would do.
FR: Déclenche une synchronisation manuelle. Avec ``?dry_run=true``,
le moteur construit le plan sans rien écrire ni envoyer.
"""
if not _sync_config.get("server_url"):
raise HTTPException(400, "Sync non configurée — appeler POST /sync/configure d'abord")
from nexanote.sync.client import ConflictStrategy
config = SyncConfig(
server_url=_sync_config["server_url"],
username=_sync_config.get("username", "nexanote"),
password=_sync_config.get("password", "nexanote"),
conflict_strategy=ConflictStrategy(
_sync_config.get("conflict_strategy", "merge_strokes")
),
)
engine = NexaNoteSyncEngine(db, config, dry_run=dry_run)
report = engine.sync()
plan = report.plan
result = SyncReportSchema(
success=report.success(),
notes_pulled=report.notes_pulled,
notes_pushed=report.notes_pushed,
conflicts_resolved=report.conflicts_resolved,
errors=report.errors,
duration_seconds=report.duration_seconds(),
summary=report.summary(),
notes_ignored_legacy=report.notes_ignored_legacy,
dry_run=report.dry_run,
conflicts=[c.to_dict() for c in plan.conflicts] if plan else [],
warnings=list(plan.warnings) if plan else [],
plan=plan.to_dict() if plan else {},
)
# A dry-run is a preview — it must not clobber the last *real* status.
if not dry_run:
_last_sync_report.clear()
_last_sync_report.update(result.model_dump())
return result
@app.get("/sync/status")
def sync_status():
return _last_sync_report or {"status": "never_synced"}
@app.get("/sync/log")
def sync_log():
"""
EN: Return the latest sanitized sync log written to
``<data_dir>/sync_logs/latest.json``. Contains note ids/titles,
counts, ignored remote paths, conflicts and sanitized errors —
never note body content or credentials.
FR: Renvoie le dernier journal de sync assaini.
"""
from nexanote.sync.sync_log import read_sync_log
payload = read_sync_log(db.data_dir)
if payload is None:
return {"status": "no_log"}
return payload
# ------------------------------------------------------------------
# Export Markdown (Obsidian-friendly)
# ------------------------------------------------------------------
@app.post("/export/markdown", response_model=ExportReportSchema)
def export_markdown(data: ExportRequestSchema):
"""
EN: Write each note as a clean `<title>.md` file (body only, no
frontmatter) into `target_dir`. Defaults to `<data_dir>/export`
when no target is given. Internal NexaNote storage is untouched.
FR: Écrit chaque note en `<titre>.md` propre (corps seul) dans
`target_dir`. Par défaut `<data_dir>/export`. N'altère pas
le stockage interne.
"""
from nexanote.storage.export import export_all
target = (
Path(data.target_dir).expanduser()
if data.target_dir
else db.data_dir / "export"
)
try:
paths = export_all(db, target, include_archived=data.include_archived)
except OSError as exc:
raise HTTPException(500, f"export failed: {exc}")
return ExportReportSchema(
target_dir=str(target),
exported=len(paths),
files=[str(p) for p in paths],
)
# ------------------------------------------------------------------
# Stats et recherche
# ------------------------------------------------------------------
@app.get("/stats")
def get_stats():
return db.get_stats()
@app.get("/search", response_model=list[NoteSchema])
def search(q: str = Query(..., min_length=1)):
notes = db.list_notes(search_title=q)
return [_note_to_schema(n) for n in notes]
# ------------------------------------------------------------------
# Stockage
# ------------------------------------------------------------------
@app.get("/storage")
def get_storage_info():
"""
EN: Returns storage stats. Since v1.0.0 the backend uses a file-based
layout (notes/<id>.md + drawings/<id>.json + notebooks/<id>.yaml)
instead of a SQLite database.
FR: Renvoie les stats de stockage. Depuis la v1.0.0 le backend
utilise une arborescence fichier (notes/<id>.md +
drawings/<id>.json + notebooks/<id>.yaml) au lieu de SQLite.
"""
def _dir_size(path: Path) -> int:
total = 0
for p in path.rglob("*"):
if p.is_file():
try:
total += p.stat().st_size
except OSError:
pass
return total
total_bytes = _dir_size(db.data_dir)
return {
"data_dir": str(db.data_dir),
"storage": "file",
"notes_dir": str(db.notes_dir),
"drawings_dir": str(db.drawings_dir),
"notebooks_dir": str(db.notebooks_dir),
"total_size_mb": round(total_bytes / 1024 / 1024, 2),
}
return app