8000 Add WiFi deck download support with server manifest by jmahmood · Pull Request #26 · jmahmood/CardBrick · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 52 additions & 3 deletions cardbrick-py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ is done. Parents configure everything else in a separate parent mode.
The objective is *not* to recreate Anki. Anki's `.apkg` files are used
as a **content format only** — after a one-time import, the application
runs entirely from its own SQLite database with no Anki desktop, no
AnkiConnect, no Rust backend, and no network access.
AnkiConnect, no Rust backend, and no network access during study (the
network is touched only by the optional parent-mode deck download).

## Architecture

Expand Down Expand Up @@ -91,8 +92,14 @@ exact player with `CARDBRICK_AUDIO_CMD="mpg123 -q {file}"`.
pip install -r requirements.txt

# One-time import (repeatable; progress is preserved). Also available
# inside the app's parent mode.
# inside the app's parent mode. A file path or an http(s) URL.
python main.py import MyDeck.apkg
python main.py import http://192.168.1.10:8000/MyDeck.apkg

# Download decks from a server into the data folder's import/
# directory without importing them (see "Downloading decks over WiFi")
python main.py download http://192.168.1.10:8000/decks.json --list
python main.py download # uses the deck_server_url setting

# The study appliance (child/parent flow) — this is the default command
python main.py study # add --fullscreen on the handheld
Expand Down Expand Up @@ -226,7 +233,8 @@ of updating the old one's progress.
### Parent mode

`SELECT` on the start screen. From there: import `.apkg` files found in
the data folder (or `data/import/`, or the app folder), choose active
the data folder (or `data/import/`, or the app folder), download decks
from a configured server over WiFi (see below), choose active
**decks** (which imported decks are *assigned* to the child at all)
and active **categories** (Anki tags — a second, independent filter;
both must match for a card to appear), set daily limits, review/restore
Expand All @@ -245,6 +253,47 @@ python main.py profile --decks all # clear the deck filter
python main.py profile --categories restaurant,greetings
```

### Downloading decks over WiFi

Getting an `.apkg` onto the device normally means pulling the SD card
or setting up SSH. Instead, a parent can host decks on any plain
HTTP(S) server — `python -m http.server` in a folder on the family PC,
a NAS, nginx, a static bucket — and point the device at it once, in
`settings.json` in the data folder:

```json
"deck_server_url": "http://192.168.1.10:8000/decks.json"
```

The URL is either a direct link to one `.apkg`, or a JSON deck list:

```json
{
"decks": [
{"name": "Español N5", "file": "n5.apkg", "size": 52428800},
{"name": "Español N4", "url": "http://elsewhere/n4.apkg"}
]
}
```

`file`/`url` may be relative to the deck list's own URL, so a
`decks.json` can simply sit in the same folder as the decks it lists
(`size` in bytes and `name` are optional, shown in the UI). Parent
mode's **Download decks (WiFi)** screen then lists what the server
offers; picking one downloads it with a progress readout and imports
it immediately. The same plumbing is available from the CLI as
`python main.py download` (fetch only, into `data/import/`) and
`python main.py import <url>` (fetch + import).

Everything uses the standard library (`urllib`) — no new dependencies.
Downloads are streamed to a `.part` file, capped at 1 GiB, verified to
be a real zip archive, and only then renamed into place, so a dropped
connection or a captive-portal page never leaves a corrupt `.apkg`
behind; only `http://`/`https://` URLs are followed, redirects
included. There is deliberately no on-device URL keyboard — the URL is
a set-once setting edited on the SD card, in keeping with
`settings.json` being "durable and user-editable on purpose."

### Child-facing deck picker

Parent Mode's Decks screen decides which decks are *assigned* to the
Expand Down
111 changes: 109 additions & 2 deletions cardbrick-py/cardbrick/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
-> Review again ("going ahead": the next sprint now)
-> or back to ChildStart
ChildStart / SessionSummary -> Calendar (stamp calendar) -> back
ChildStart -> ParentMode (import / decks / categories / limits /
suspended / progress / calendar /
ChildStart -> ParentMode (import / download / decks / categories /
limits / suspended / progress / calendar /
controller setup) -> ChildStart

Parent Mode's Decks screen configures which decks are *assigned* to the
Expand Down Expand Up @@ -286,6 +286,7 @@ def run(self):
"CALENDAR": self.screen_calendar,
"PARENT_MENU": self.screen_parent_menu,
"PARENT_IMPORT": self.screen_parent_import,
"PARENT_DOWNLOAD": self.screen_parent_download,
"PARENT_CATEGORIES": self.screen_parent_categories,
"PARENT_DECKS": self.screen_parent_decks,
"PARENT_LIMITS": self.screen_parent_limits,
Expand Down Expand Up @@ -1055,6 +1056,7 @@ def screen_parent_menu(self):
direction = self.profile.get("study_direction", "normal")
entries = [
("Import deck (.apkg)", "PARENT_IMPORT"),
("Download decks (WiFi)", "PARENT_DOWNLOAD"),
("Decks", "PARENT_DECKS"),
("Categories", "PARENT_CATEGORIES"),
("Daily goal & sprints", "PARENT_LIMITS"),
Expand Down Expand Up @@ -1194,6 +1196,111 @@ def _draw_import(self, files, index, message):
y += 24
self._footer("Bottom = Import Right = Back")

def screen_parent_download(self):
"""Fetch the deck list from the configured server, download the
chosen deck into the import folder, and import it right away.
Network calls block the loop like importing does — a redraw
callback keeps a progress line moving during the transfer."""
from .deck_download import (DownloadError, download_deck,
fetch_deck_list, format_size)
server_url = (self.settings.get("deck_server_url") or "").strip()
dest_dir = self.paths.import_dir if self.paths else \
os.path.join(self.settings_dir(), "import")

decks, message = [], None
if not server_url:
message = ('No server set. Add "deck_server_url" to '
'settings.json in the data folder on the SD '
'card, e.g. "http://192.168.1.10:8000/decks.json"')
else:
self._draw_download([], 0, f"Connecting to {server_url} …",
server_url)
self.present()
try:
decks = fetch_deck_list(server_url)
except DownloadError as exc:
message = str(exc)
log.error("deck list from %s failed: %s", server_url, exc)

index = 0
while True:
action = self.poll()
if action in ("start", "east_button", "select"):
return "PARENT_MENU"
if decks and action == "dpad_up":
index = (index - 1) % len(decks)
elif decks and action == "dpad_down":
index = (index + 1) % len(decks)
elif decks and action == "south_button":
entry = decks[index]
last_drawn = [0.0]

def progress(received, total):
if time.time() - last_drawn[0] < 0.1:
return
last_drawn[0] = time.time()
if total:
note = f"{received * 100 // total}% of " \
f"{format_size(total)}"
else:
note = format_size(received)
self._draw_download(decks, index,
f"Downloading {entry['name']} … "
f"{note}", server_url)
self.present()
pygame.event.pump() # keep the window responsive

self._draw_download(decks, index,
f"Downloading {entry['name']} …",
server_url)
self.present()
try:
path = download_deck(entry["url"], dest_dir,
progress=progress,
name=entry["name"])
self._draw_download(decks, index, "Importing …",
server_url)
self.present()
stats = import_apkg(
path, self.storage, self.service.scheduler,
os.path.join(self.settings_dir(), "media"))
message = stats.summary()
log.info("download+import %s: %s", entry["url"],
message)
except (DownloadError, ApkgError, OSError) as exc:
message = f"Failed: {exc}"
log.error("download %s failed: %s", entry["url"], exc)

self._draw_download(decks, index, message, server_url)
self.present()
self.clock.tick(FPS)

def _draw_download(self, decks, index, message, server_url=None):
from .deck_download import format_size
self.screen.fill(BG)
self._center(self.font_big.render("Download Decks", True, FG), 40)
if server_url:
self._center(self.font_small.render(server_url, True, DIM), 90)
if decks:
visible = 6
top = min(max(0, index - visible + 1), index)
y = 116
for i in range(top, min(top + visible, len(decks))):
entry = decks[i]
color = ACCENT if i == index else FG
prefix = "> " if i == index else " "
size = format_size(entry["size"])
label = entry["name"] + (f" ({size})" if size else "")
self.screen.blit(self.font.render(prefix + label, True,
color), (70, y))
y += 38
if message:
y = self.h - 170
for line in wrap_text(self.font_small, message, self.w - 80):
self._center(self.font_small.render(line, True, WARN), y)
y += 24
self._footer("Bottom = Download + Import Right = Back")

def screen_parent_categories(self):
return self._screen_multi_select(
title="Categories", subtitle="Choose what the child studies",
Expand Down
Loading
Loading
0