PRESENTATIONS_ENABLED, off by default, independent of everything else. A teacher downloads a session in ordinary Chrome and it is on the Presentations screen a few seconds later, ready for the television. No file manager, no import button, no Impress. WHY NOTHING LAUNCHES A DOCUMENT APPLICATION. The brief was to use existing presentation software, so the existing software was tried first, on Debian 13, before any of this was designed. `soffice --show` does start a real fullscreen slideshow — and needs XDG_SESSION_TYPE plus a VCL plugin or it dies with "Failed to open display", shows a splash, opened a "Tip of the Day: 1/225" dialog over the slides, and leaves the Impress editor when the show ends. `okular --presentation` opens THREE windows: the presentation, the ordinary document window behind it, and an information dialog. zathura is not a presenter. pdfpc is the closest and is another dependency with a presenter-console model. Every one of them leaves an application on screen that can open any file on the machine, and none of them knows there is a library to go back to. So LibreOffice converts once, headless, at import, with no window on any screen; poppler renders the pages; the classroom shows the pictures. Measured: 0.34s for a ten-slide PPTX, 0.03s for its ten thumbnails, 0.10s for one slide at 1920px. That is not a new renderer — it is the same engine Impress would have used live — and it means Escape is ours, presenting is instant, and a PDF exported from Google Slides skips the conversion entirely and keeps the appearance Google gave it. THE THREE THINGS KEPT APART. The library thumbnail, the starting slide and the retention clock are independent, because the first slide of a Bible study session is a generic opening shared by every session and the one that names it is usually the second. Quick Look chooses the picture; it does not change where the slideshow starts and it does not count as having presented anything. mark_presented() is called when a slide is actually drawn, not when Present is pressed: an intention is not a presentation, and a viewer that failed to start must not buy another thirty days. IMPORTING. The teacher's download is copied, never moved, renamed or deleted. A file with a .crdownload beside it is still arriving. Wonder Ink's own folder is not looked at. Two downloads of the same name are two presentations, the second titled (2) — found in the lab, where a PDF and a PPTX of one session both came out with the same name because the import being named was excluded from the taken-titles set BY TITLE, and a set holds one copy of a repeated string. Metadata is written saying "importing" before any work, so a reboot mid-conversion leaves a directory the next startup sweeps and imports again. A file that cannot be converted gets a card saying so, offering only Remove, with the teacher's download untouched. Retention: 180 days never presented, 30 days from the last presentation, every presentation starting the thirty over. The cleanup never touches a presentation being shown, never leaves the library directory, and never looks at Downloads. The dock order is unchanged: Presentations is appended after the disc player, so Wonder Ink, the browser and the player keep the places teachers have been reaching for. There is a test for exactly that. classroom-wonderink now asks feature() rather than carrying its own copy of the default, so the panel and the command cannot disagree. Co-Authored-By: Claude Opus 5 <[email protected]>
340 lines
11 KiB
Python
Executable File
340 lines
11 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
"""Watch the teacher's downloads, and keep the library tidy.
|
|
|
|
A teacher downloads a session in ordinary Chrome and then looks for it in
|
|
Presentations. Nothing in between is their job: no file manager, no
|
|
import button, no "where did you save it". This is the in between.
|
|
|
|
classroom-presentation-import run as a service, forever
|
|
classroom-presentation-import --once one pass, for a technician
|
|
classroom-presentation-import --status what the library holds
|
|
|
|
WHAT IT WILL NOT DO.
|
|
|
|
It never touches the teacher's download. The file Chrome wrote stays
|
|
where Chrome wrote it, with the name Chrome gave it, for as long as
|
|
the teacher leaves it there. Everything the library does is done to
|
|
its own copy.
|
|
|
|
It never imports a Wonder Ink worksheet. Wonder Ink downloads into a
|
|
directory of its own inside Downloads and those are worksheets, not
|
|
sessions; the cleanup will not remove one either.
|
|
|
|
It never imports a file that is still arriving. Chrome writes
|
|
`Session 7.pptx.crdownload` and renames it when the transfer is
|
|
done, so a finished name with that sibling beside it is a download in
|
|
progress, not a presentation.
|
|
|
|
It never overwrites a presentation with a later one of the same
|
|
name. Two downloads called "Bible Study.pdf" are two presentations.
|
|
"""
|
|
|
|
import argparse
|
|
import os
|
|
import shutil
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
sys.path.insert(0, "/usr/local/lib/ekklesia-classroom")
|
|
sys.path.insert(
|
|
0,
|
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "lib"),
|
|
)
|
|
|
|
import classroom_presentations as library # noqa: E402
|
|
from classroom_config import feature, read_device_config # noqa: E402
|
|
|
|
# How often the downloads directory is looked at.
|
|
#
|
|
# Polling rather than inotify, deliberately. A teacher waits a few
|
|
# seconds either way, this cannot leak a watch descriptor or miss an
|
|
# event across a restart, and it is the kind of code somebody can still
|
|
# read in two years.
|
|
SCAN_SECONDS = 4
|
|
|
|
# How often expired presentations are cleared out.
|
|
CLEANUP_SECONDS = 3600
|
|
|
|
|
|
def say(message):
|
|
print(f"classroom-presentation-import: {message}", flush=True)
|
|
|
|
|
|
def new_directory(root):
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
directory = root / uuid.uuid4().hex
|
|
|
|
directory.mkdir()
|
|
|
|
return directory
|
|
|
|
|
|
def import_one(source, root=None):
|
|
"""Take one finished download into the library.
|
|
|
|
Ordered so that an interruption is always recoverable. The metadata
|
|
is written first, saying "importing"; the sweep at startup throws
|
|
away anything still saying that and lets it be imported again. A
|
|
presentation only becomes visible to a teacher once every file it
|
|
needs is on disk.
|
|
"""
|
|
root = root if root is not None else library.library_root()
|
|
mark = library.fingerprint(source)
|
|
|
|
if mark is None:
|
|
return None
|
|
|
|
directory = new_directory(root)
|
|
managed = directory / source.name
|
|
|
|
data = {
|
|
"id": directory.name,
|
|
"state": "importing",
|
|
"title": library.readable_title(source.name),
|
|
"original_name": source.name,
|
|
"source_path": str(source),
|
|
"managed_copy": source.name,
|
|
"format": library.SUPPORTED.get(source.suffix.lower(), ""),
|
|
"imported_at": library.stamp(),
|
|
"last_presented_at": None,
|
|
"times_presented": 0,
|
|
"thumbnail_page": 1,
|
|
"pages": 0,
|
|
"error": None,
|
|
}
|
|
|
|
presentation = library.Presentation(directory, data)
|
|
presentation.save()
|
|
|
|
# Recorded before the work, so that a file which crashes the
|
|
# conversion every time cannot be retried in a loop forever. The
|
|
# startup sweep is what un-records an import interrupted part way.
|
|
library.remember(mark, directory.name, root)
|
|
|
|
say(f"importing {source.name}")
|
|
|
|
try:
|
|
# THE TEACHER'S OWN DOWNLOAD IS COPIED, NEVER MOVED.
|
|
shutil.copy2(source, managed)
|
|
|
|
if data["format"] == "pdf":
|
|
# Already the thing everything else is converted into. A
|
|
# session exported from Google Slides as a PDF keeps exactly
|
|
# the appearance Google gave it, with no conversion at all.
|
|
shutil.copy2(managed, presentation.slides)
|
|
else:
|
|
converted, error = library.convert_to_pdf(
|
|
managed, presentation.slides)
|
|
|
|
if not converted:
|
|
raise RuntimeError(error or "the file could not be converted")
|
|
|
|
pages, error = library.render_pages(
|
|
presentation.slides, presentation.pages_directory)
|
|
|
|
if not pages:
|
|
raise RuntimeError(error or "the slides could not be rendered")
|
|
|
|
data["pages"] = pages
|
|
data["title"] = library.unique_title(
|
|
library.readable_title(
|
|
source.name, library.first_text(presentation.slides)),
|
|
library.titles_in_use(root, exclude=presentation.id),
|
|
)
|
|
|
|
library.render_thumbnail(presentation.page_image(1),
|
|
presentation.thumbnail)
|
|
|
|
data["state"] = "ready"
|
|
presentation.save()
|
|
|
|
say(f"imported {data['title']!r} ({pages} slides)")
|
|
|
|
return presentation
|
|
except Exception as error: # noqa: BLE001
|
|
# A card that says it could not be opened, rather than a card
|
|
# that opens onto nothing. The teacher's download is untouched
|
|
# either way, which is what the message says.
|
|
data["state"] = "failed"
|
|
data["error"] = str(error)[:300]
|
|
presentation.save()
|
|
|
|
say(f"could not import {source.name}: {error}")
|
|
|
|
return presentation
|
|
|
|
|
|
def sweep(root=None):
|
|
"""Throw away imports that were interrupted, so they can happen again.
|
|
|
|
A reboot in the middle of a conversion leaves a directory that says
|
|
"importing" and a ledger entry claiming the download is dealt with.
|
|
Both go, and the next scan imports it properly.
|
|
"""
|
|
root = root if root is not None else library.library_root()
|
|
|
|
if not root.is_dir():
|
|
return 0
|
|
|
|
ledger = library.ledger(root)
|
|
stale = 0
|
|
|
|
for presentation in library.library(root):
|
|
if presentation.state != "importing":
|
|
continue
|
|
|
|
say(f"clearing an import that did not finish: {presentation.title!r}")
|
|
|
|
for mark, value in list(ledger.items()):
|
|
if value == presentation.id:
|
|
ledger.pop(mark, None)
|
|
|
|
shutil.rmtree(presentation.directory, ignore_errors=True)
|
|
stale += 1
|
|
|
|
if stale:
|
|
library.write_json(library.ledger_path(root), ledger)
|
|
|
|
return stale
|
|
|
|
|
|
def scan(root=None, downloads=None):
|
|
"""One look at the downloads directory."""
|
|
root = root if root is not None else library.library_root()
|
|
known = library.ledger(root)
|
|
imported = 0
|
|
|
|
for candidate in library.candidates(downloads):
|
|
mark = library.fingerprint(candidate)
|
|
|
|
if mark is None or mark in known:
|
|
continue
|
|
|
|
if import_one(candidate, root) is not None:
|
|
imported += 1
|
|
known = library.ledger(root)
|
|
|
|
return imported
|
|
|
|
|
|
def cleanup(root=None, moment=None):
|
|
"""Remove presentations whose time is up.
|
|
|
|
Only ever the library's own directory, and never the presentation on
|
|
the screen. The teacher's download is not part of this and is not
|
|
looked at.
|
|
"""
|
|
root = root if root is not None else library.library_root()
|
|
lock = library.presenting_lock()
|
|
showing = ""
|
|
|
|
try:
|
|
showing = lock.read_text().strip()
|
|
except OSError:
|
|
showing = ""
|
|
|
|
removed = 0
|
|
|
|
for presentation in library.library(root):
|
|
if not presentation.expired(moment):
|
|
continue
|
|
|
|
if presentation.id == showing:
|
|
# A retention timer must never interrupt a room. It will
|
|
# still be expired in an hour.
|
|
say(f"{presentation.title!r} is expired but is being presented")
|
|
continue
|
|
|
|
if presentation.last_presented_at is None:
|
|
why = f"never presented, imported {presentation.data['imported_at']}"
|
|
else:
|
|
why = f"last presented {presentation.data['last_presented_at']}"
|
|
|
|
say(f"removing {presentation.title!r} — {why}")
|
|
|
|
shutil.rmtree(presentation.directory, ignore_errors=True)
|
|
removed += 1
|
|
|
|
return removed
|
|
|
|
|
|
def status(root=None):
|
|
presentations = library.library(root)
|
|
|
|
if not presentations:
|
|
print("the library is empty")
|
|
return 0
|
|
|
|
for presentation in presentations:
|
|
expires = presentation.expires_at()
|
|
print(f"{presentation.title}")
|
|
print(f" state {presentation.state}"
|
|
f"{' — ' + presentation.error if presentation.error else ''}")
|
|
print(f" slides {presentation.pages}"
|
|
f" (card shows slide {presentation.thumbnail_page})")
|
|
print(f" imported {presentation.data.get('imported_at')}")
|
|
presented = presentation.data.get("last_presented_at") or "never"
|
|
print(f" presented {presented} "
|
|
f"({presentation.times_presented} times)")
|
|
print(f" expires {library.stamp(expires) if expires else 'unknown'}")
|
|
|
|
return 0
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Bring finished downloads into the Presentations library.")
|
|
parser.add_argument("--once", action="store_true",
|
|
help="one pass, then stop")
|
|
parser.add_argument("--status", action="store_true",
|
|
help="what the library holds; changes nothing")
|
|
parser.add_argument("--cleanup", action="store_true",
|
|
help="apply the retention rules now")
|
|
arguments = parser.parse_args()
|
|
|
|
if arguments.status:
|
|
return status()
|
|
|
|
# A device that does not offer Presentations does not run an importer
|
|
# for them. Said out loud for the technician who started it by hand.
|
|
if not feature(read_device_config(), "PRESENTATIONS_ENABLED"):
|
|
say("PRESENTATIONS_ENABLED is false on this device; not starting")
|
|
return 0
|
|
|
|
if arguments.cleanup:
|
|
removed = cleanup()
|
|
say(f"removed {removed} expired presentation(s)")
|
|
return 0
|
|
|
|
sweep()
|
|
|
|
if arguments.once:
|
|
imported = scan()
|
|
cleanup()
|
|
say(f"imported {imported} presentation(s)")
|
|
return 0
|
|
|
|
say(f"watching {library.downloads_root()}")
|
|
|
|
last_cleanup = 0.0
|
|
|
|
while True:
|
|
try:
|
|
scan()
|
|
|
|
if time.monotonic() - last_cleanup > CLEANUP_SECONDS:
|
|
cleanup()
|
|
last_cleanup = time.monotonic()
|
|
except Exception as error: # noqa: BLE001
|
|
# One bad file must not stop the watcher. A teacher whose
|
|
# next download never appears has no way to find out why.
|
|
say(f"scan failed: {error}")
|
|
|
|
time.sleep(SCAN_SECONDS)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|