BlueGit

timfa filemanager

Files

filemanager / .github / technical-reference.md

technical-reference.md

1058bb94 History
technical-reference.md 33.3 KiB Download Raw

Technical Reference

server/index.js

  • start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
  • shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
  • GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.

server/thumbnail-cache.js

  • syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files and video files (frame around 10% via ffprobe/ffmpeg); removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
  • startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
  • stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
  • getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
  • getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
  • getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
  • getFilesWithThumbnailsInDir(dirPath) - Returns [{filePath, thumbRelPath}] for all files inside dirPath (recursive) that have a cached thumbnail; sorted by filePath.
  • getFolderIconSourceFile(folderPath) - Returns the source image path for a folder's icon: explicit assignment first, then auto-first cached image, null if none.
  • setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).

server/db.js

  • initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
  • getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
  • closeDb() - Closes singleton DB handle to release file locks.

server/auth.js

  • createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.
  • requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
  • requireAdmin(req, res, next) - Requires authenticated admin user.
  • revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
  • getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
  • getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
  • SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).

server/routes/auth.js

  • extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
  • makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.
  • POST /api/auth/setup - Creates first admin and issues token.
  • POST /api/auth/login - Authenticates user by case-insensitive username match and issues token with canonical stored username.
  • GET /api/auth/me - Returns current authenticated user profile.
  • POST /api/auth/logout - Revokes the active session.

server/routes/admin.js

  • POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
  • normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
  • ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
  • GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
  • PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
  • GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).

server/routes/files.js

  • GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
  • GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
  • loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
  • resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
  • canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
  • checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
  • POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
  • GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
  • GET /api/files/meta - Returns file metadata and lazily computes/stores sha256 when missing.
  • GET /api/files/duplicates - Returns accessible files that share the selected file's sha256 hash.
  • GET /api/files/space - Returns used/free disk space and, for personal folders, user-limit fields (userLimitBytes/userFreeBytes).
  • GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
  • GET /api/files/folder-images - Returns files inside a directory (recursive) that already have a cached thumbnail (including video thumbnails when cached).
  • GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
  • POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
  • GET /api/files/download-zip?dir=<absolute-path> - Authenticated. Streams the directory as a zip archive; caches the zip for up to 1 day in zip-cache/.
  • makeTempUploadPath(dir, originalName) - Builds a hidden per-upload staging filename in the target directory for multipart uploads.
  • unlinkIfExists(targetPath, cb) - Removes a file during upload cleanup while ignoring already-missing temp files.
  • promoteUploadedFile(tempPath, finalPath, cb) - Atomically renames a completed staged upload into place on the Linux server.
  • splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
  • pickNumberedPath(dir, requestedName) - Finds the first free name (n).ext path inside a directory.
  • removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
  • movePathWithFallback(from, dest) - Moves files/folders with an EXDEV copy-then-delete fallback so cross-device moves into My Folder still succeed.
  • POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
  • POST /api/files/move - Moves file/folder; supports conflict strategies: error (default), overwrite, or rename with optional targetName.
  • POST /api/files/copy - Copies a file to a destination folder with conflict strategies (error, overwrite, rename) and user-folder size-limit checks.
  • POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
  • DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
  • POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
  • POST /api/files/watch-progress - Records per-user watch status (partway >=10%, fully >=70%) for sidebar "Watched by" display.

server/routes/share.js

  • getUserFolderPath(config, username) - Resolves the owning user's personal folder path from config.userPath.
  • resolveRootForUser(absPath, roots, user, config) - Resolves configured roots plus the owning user's personal folder for share checks.
  • canReadInfo(user, info) - Read-check helper that always allows the owner of a personal folder root.
  • POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt} and accepts items inside the authenticated user's My Folder.
  • GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
  • GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
  • GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
  • GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
  • buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
  • buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
  • pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
  • ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).

server/video-stream.js

  • createVideoStreamSession(sourcePath) - Probes input metadata and reuses a compatible active transcode session per source file when possible; returns a per-viewer lease id as sessionId plus duration/subtitle data.
  • sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
  • releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain.
  • STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
  • STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
  • STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated (5 minutes).
  • STREAM_SEGMENT_RETENTION_COUNT - Number of most-recent HLS segment indices kept on disk while older segments are pruned; when not overridden with VIDEO_STREAM_SEGMENT_RETENTION_COUNT it is derived from hardware capacity (RAM + CPU), current memory/CPU pressure, and Raspberry Pi 5 profile bounds.

server/db.js

  • initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
  • getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
  • closeDb() - Closes singleton DB handle to release file locks.

public/share.html

  • Standalone public share page served at /share/:token; no auth required.
  • Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
  • tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
  • Share video preview - Uses the same Video.js playback behaviour as app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), and subtitle/audio track restore/save by matching track names when available.
  • Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
  • Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.

public/index.html

  • Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
  • Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
  • Import map - Maps three and three/addons/ to local vendored modules for client-side STL/OBJ previews.

public/app.js

  • showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
  • showAuthOverlay(setupMode) - Displays the login/setup overlay and switches the password autocomplete token between current-password and new-password based on mode.
  • getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
  • getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
  • saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
  • loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
  • api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
  • performLogout() - Explicit logout path that revokes server session and clears local session state.
  • initAuth() - Restores prior session when valid and auto-logins without credential prompt.
  • showConfirm(title, message, { html, okLabel }) - In-page confirm dialog; returns Promise<boolean>. html=true renders message as innerHTML (caller must escape user data). okLabel overrides the OK button text. Use instead of window.confirm().
  • escHtml(s) - HTML-escapes a string (& < > ") for safe use with innerHTML in confirm messages.
  • showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
  • showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
  • splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
  • nextAvailableName(requestedName, existingNames) - Computes name (n).ext for upload/move rename options.
  • listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
  • cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
  • showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
  • parseHumanSize(input) - Parses human-readable sizes like 25 MB/1gb into bytes for admin user-folder limits.
  • updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
  • relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
  • displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like /Downloads/A/B for folder context UI.
  • openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
  • loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
  • loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
  • loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images and videos, text snapshots for text files, and badges for other files; marks image/video icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
  • loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, videos, and supported 3D model files; text files still use text snapshots and badges remain the fallback when no thumbnail strategy exists.
  • observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
  • loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
  • applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
  • openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
  • refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
  • disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
  • getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
  • observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
  • disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
  • setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
  • buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
  • renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
  • modelPreviewType(name) - Classifies direct client-side 3D preview support for .stl and .obj.
  • loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
  • modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
  • buildModelObjectFromBlob(blob, type, modules) - Parses STL/OBJ blobs and produces a geometry-only model using the standard blue material.
  • renderModelPreview(item, blob, targetEl) - Renders interactive STL/OBJ previews (drag rotate + scroll zoom) with WebGL fallback messaging when unavailable.
  • closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.

tests/thumbnail-cache.test.js

  • thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
  • thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
  • thumbnail cache worker / creates cached thumbnail for video files using ffmpeg frame extraction - Verifies video thumbnail generation uses ffprobe duration and ffmpeg frame capture.
  • afterEach() cleanup - Removes temp roots with fs.rmSync(...maxRetries...) to tolerate transient Windows file locks.
  • detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
  • prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
  • highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
  • fileAccentColor(name) - Returns canonical file-type accent color used by icon strokes and preview sheet outline.
  • openFolderSidebar() - Persistent sidebar fallback view that shows current folder/root overview when no item is selected.
  • closeSidebar() - Clears selection; hides the panel entirely on mobile and restores folder overview sidebar on desktop.
  • isMobileViewport() - Central media-query helper for mobile-only sidebar/interaction behavior.
  • hideSidebarPanel() - Hides sidebar panel and removes sidebar-open layout class from the app shell.
  • renderBreadcrumb() - Builds clickable breadcrumb path and marks each folder segment as a drag-drop move target via .crumb-drop-target and data-path.
  • fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
  • downloadOrView(item, sourceSvgEl) - Opens preview; prefers in-place expanded tile preview when invoked from a file icon, falls back to overlay when no source tile is available.
  • downloadOrView(item, sourceSvgEl) - Opens in-place expanded tile preview from a file icon; shows error toast if no source tile is found.
  • renderPreviewBody(item, blob, objectUrl, targetEl) - Renders preview content (image/video/audio/pdf/text) or unsupported message into a target container.
  • animateRect(el, fromRect, toRect, opts) - Helper that animates element rectangle (left/top/width/height) for expand/collapse transitions.
  • openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents the real file tile to body, expands it to viewport preview, injects close/download controls.
  • openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents tile to body, shows spinner during expand animation, renders content after animation; applies file-type accent colour to tile border and outline glow.
  • openExpandedTilePreview(item, tileEl, sourceSvgEl, loadPreviewContent) - Adds preview action buttons for Download and Share; Share opens the same modal flow as sidebar sharing.
  • closeExpandedTilePreview() - Collapses expanded tile preview back to original grid position and restores original icon markup.
  • closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
  • closePreview() - Closes expanded-tile preview and revokes active preview object URL.
  • openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
  • openCopyPicker(item) - Opens Copy To selector modal with the same tree and executes /api/files/copy.
  • openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
  • moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
  • copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
  • rootPermissionLabel(root) - Resolves permission key for a root using originalName when available; personal folders resolve to the built-in My Folder label.
  • ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
  • createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
  • loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
  • isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
  • makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
  • makeFileItem(item) - Renders tile icons first, then applies any cached watched overlay state (fully full-size filled eye, partway smaller darker filled eye).
  • loadWatchedStatusesForCurrentDir() - Fetches watched states in one bulk POST /files/watched-statuses request per directory (with legacy /files/meta fallback), caches statuses per path, and updates tile overlays quickly.
  • attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
  • beginSidebarLoad() - Aborts in-flight sidebar requests and increments a load token so stale async responses cannot mutate the current sidebar state.
  • openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
  • openSidebar(item) - Personal user roots display access as private and skip /files/root-access lookups to avoid forbidden noise.
  • openSidebar(item) - Uses abortable metadata/access requests and stale-load guards to prevent race-condition UI duplication when selection changes quickly.
  • canWrite(item) - Resolves whether the current user may write to the selected item/root; personal folders are always writable for the owner.
  • fetchRootAccessList(rootPath) - Fetches root access users from the server for a specific configured root.
  • formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
  • openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
  • openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
  • openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
  • uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
  • openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked.

public/drag-move.js

  • makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
  • makeDraggable(el, item) - Touch drag now requires a short hold before movement, uses pointer capture, and keeps drag responsive on mobile.
  • (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
  • (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
  • (internal) _endDrag() - On valid target: runs drop animation, calls moveWithConflictResolution() for overwrite/rename/cancel conflicts, then refreshes dir. Otherwise snap-back.
  • (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.

public/drag-move.css

  • .file-item.dragging - Lifted style for real dragged tile.
  • .file-item.drop-target - Glows folder icon when drag hovers over it.
  • .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
  • .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
  • @keyframes drag-rise-spin-fall - Real tile rises, spins, falls/scales into folder on drop.
  • @keyframes folder-bounce - Target folder bounces down then back on accept.
  • .preview-backdrop/.file-item--preview/.preview-expand-* - In-place expanded tile preview styling (no separate overlay window), including preserved icon-outline layer.
  • .preview-expand-share - Secondary action button positioned next to .preview-expand-download in expanded file preview.
  • .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.

public/style.css

  • #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
  • .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.

tests/auth.routes.test.js

  • session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
  • session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.

tests/page.load.test.js

  • bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
  • waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
  • login overlay uses username and current-password autocomplete tokens - Verifies normal sign-in mode exposes browser-friendly login autocomplete attributes.
  • first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
  • expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
  • expanded STL preview falls back gracefully when WebGL is unavailable - Verifies STL preview path shows a clear fallback message when WebGL contexts are unavailable.
  • expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
  • video preview does not close on backdrop click and closes via X button - Verifies video previews require explicit close via X.
  • video preview restores per-user saved volume preference - Verifies per-user saved video volume is applied on preview open.
  • video preview restores saved subtitle/audio track names when available - Verifies per-user subtitle/audio selections are reapplied by matching track names.
  • video preview keeps default tracks when saved names are not present - Verifies subtitle/audio defaults remain unchanged when saved names are missing.
  • video preview saves subtitle/audio track names per user when selection changes - Verifies subtitle/audio selections are persisted into per-user video preferences.
  • video preview applies caption overrides per open - Verifies requested caption overrides are always loaded into Video.js settings.
  • video preview does not save caption style settings per user on close - Verifies caption style changes are not persisted to per-user video preferences.
  • video preview releases the backend stream session when closed - Verifies closing a streamed video preview sends an explicit backend release call.
  • rapid file reselection does not duplicate sidebar action buttons after delayed metadata - Verifies stale sidebar loads are ignored so action buttons are not duplicated.
  • video tiles show centred watched overlays after watched metadata is loaded - Verifies overlays remain absent until watched metadata is fetched, then render as solid eye icons for fully and partway statuses.
  • shows pending icon spinner when video thumbnail cache is not ready - Verifies video tiles use thumbnail-cache loading (instead of badge fallback) and pending-state UI.

tests/video-stream.test.js

  • createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
  • createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
  • createVideoStreamSession does not become ready from subtitle files alone - Verifies stream readiness is tied to HLS output instead of extracted subtitle files.
  • createVideoStreamSession keeps playback available when subtitle conversion fails - Verifies subtitle conversion failures are skipped without breaking stream playback.
  • sendVideoStreamAsset prunes old segment files after playback moves far ahead - Verifies old segments are removed only after the retention window passes.
  • createVideoStreamSession reuses one transcode for concurrent viewers of the same file - Verifies two viewers share one ffmpeg transcode while keeping independent lease release behaviour.

tests/share.page.load.test.js

  • applies default caption settings for share-page video playback - Verifies requested caption defaults are applied and persisted on share-page video preview.
  • restores and saves share-page subtitle/audio track preferences by name - Verifies share-page subtitle/audio choices are restored and persisted by track-name matching.

tests/files.routes.test.js

  • POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
  • DELETE /api/files/video-stream/:sessionId releases an active stream session - Verifies explicit stream session release route wiring.

public/vendor/three/three.module.js

  • Third-party Three.js runtime module (vendored, unmodified) used for client-side 3D previews.

public/vendor/three/addons/controls/OrbitControls.js

  • Third-party OrbitControls module (vendored, unmodified) providing drag-rotate and wheel-zoom interactions.

public/vendor/three/addons/loaders/STLLoader.js

  • Third-party STL parser module (vendored, unmodified) for client-side .stl geometry loading.

public/vendor/three/addons/loaders/OBJLoader.js

  • Third-party OBJ parser module (vendored, unmodified) for client-side .obj geometry loading.
Source
1# Technical Reference
2
3## server/index.js
4- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
5- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
7
8## server/thumbnail-cache.js
9- syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files and video files (frame around 10% via ffprobe/ffmpeg); removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
10- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
11- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
12- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
13- getThumbPathForSourceFile(sourceFile) - Maps an absolute source file path to its mirrored cache thumbnail path.
14- getThumbRelPathForSourceFile(sourceFile) - Returns public-relative thumbnail path used in manifest entries.
15- getFilesWithThumbnailsInDir(dirPath) - Returns [{filePath, thumbRelPath}] for all files inside dirPath (recursive) that have a cached thumbnail; sorted by filePath.
16- getFolderIconSourceFile(folderPath) - Returns the source image path for a folder's icon: explicit assignment first, then auto-first cached image, null if none.
17- setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
18
19## server/db.js
20- initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
21- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
22- closeDb() - Closes singleton DB handle to release file locks.
23
24## server/auth.js
25- createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.
26- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
27- requireAdmin(req, res, next) - Requires authenticated admin user.
28- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
29- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
30- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
31- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
32
33## server/routes/auth.js
34- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
35- makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.
36- POST /api/auth/setup - Creates first admin and issues token.
37- POST /api/auth/login - Authenticates user by case-insensitive username match and issues token with canonical stored username.
38- GET /api/auth/me - Returns current authenticated user profile.
39- POST /api/auth/logout - Revokes the active session.
40
41## server/routes/admin.js
42- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
43- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
44- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
45- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
46- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
47- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] }. Detects systemd via INVOCATION_ID env var; runs git fetch + git log to find commits ahead of HEAD. Used by the frontend to set button label (Shut down server / Restart Server / Restart & Update).
48
49## server/routes/files.js
50- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
51- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
52- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
53- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
54- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
55- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
56- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
57- GET /api/files/root-access - Returns users who can access an exact configured root and their access mode (R / R+W).
58- GET /api/files/meta - Returns file metadata and lazily computes/stores sha256 when missing.
59- GET /api/files/duplicates - Returns accessible files that share the selected file's sha256 hash.
60- GET /api/files/space - Returns used/free disk space and, for personal folders, user-limit fields (userLimitBytes/userFreeBytes).
61- GET /api/files/thumbnail - Serves cache-only thumbnail images for authorized files; returns 404 while cache is not ready.
62- GET /api/files/folder-images - Returns files inside a directory (recursive) that already have a cached thumbnail (including video thumbnails when cached).
63- GET /api/files/folder-icon - Returns the current icon source file for a folder ({icon:{filePath}} or {icon:null}); explicit assignment takes priority over auto-first.
64- POST /api/files/folder-icon - Sets or clears a folder's explicit icon assignment; imagePath must have a cached thumbnail; write access required.
65- GET /api/files/download-zip?dir=<absolute-path> - Authenticated. Streams the directory as a zip archive; caches the zip for up to 1 day in zip-cache/.
66- makeTempUploadPath(dir, originalName) - Builds a hidden per-upload staging filename in the target directory for multipart uploads.
67- unlinkIfExists(targetPath, cb) - Removes a file during upload cleanup while ignoring already-missing temp files.
68- promoteUploadedFile(tempPath, finalPath, cb) - Atomically renames a completed staged upload into place on the Linux server.
69- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
70- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
71- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
72- movePathWithFallback(from, dest) - Moves files/folders with an EXDEV copy-then-delete fallback so cross-device moves into My Folder still succeed.
73- POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
74- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
75- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
76- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
77- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
78- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
79- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
80
81## server/routes/share.js
82- getUserFolderPath(config, username) - Resolves the owning user's personal folder path from config.userPath.
83- resolveRootForUser(absPath, roots, user, config) - Resolves configured roots plus the owning user's personal folder for share checks.
84- canReadInfo(user, info) - Read-check helper that always allows the owner of a personal folder root.
85- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt} and accepts items inside the authenticated user's My Folder.
86- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
87- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
88- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
89- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
90- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
91- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
92- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
93- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
94
95## server/video-stream.js
96- createVideoStreamSession(sourcePath) - Probes input metadata and reuses a compatible active transcode session per source file when possible; returns a per-viewer lease id as sessionId plus duration/subtitle data.
97- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
98- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain.
99- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
100- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
101- STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated (5 minutes).
102- STREAM_SEGMENT_RETENTION_COUNT - Number of most-recent HLS segment indices kept on disk while older segments are pruned; when not overridden with VIDEO_STREAM_SEGMENT_RETENTION_COUNT it is derived from hardware capacity (RAM + CPU), current memory/CPU pressure, and Raspberry Pi 5 profile bounds.
103
104## server/db.js
105- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
106- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
107- closeDb() - Closes singleton DB handle to release file locks.
108
109## public/share.html
110- Standalone public share page served at /share/:token; no auth required.
111- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
112- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
113- Share video preview - Uses the same Video.js playback behaviour as app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), and subtitle/audio track restore/save by matching track names when available.
114- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
115- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
116
117## public/index.html
118- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
119- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
120- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
121
122## public/app.js
123- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
124- showAuthOverlay(setupMode) - Displays the login/setup overlay and switches the password autocomplete token between current-password and new-password based on mode.
125- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
126- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
127- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
128- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
129- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
130- performLogout() - Explicit logout path that revokes server session and clears local session state.
131- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
132- showConfirm(title, message, { html, okLabel }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data). `okLabel` overrides the OK button text. Use instead of window.confirm().
133- escHtml(s) - HTML-escapes a string (& < > ") for safe use with innerHTML in confirm messages.
134- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
135- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
136- splitNameExt(name) - Client-side filename splitter used for local conflict rename suggestions.
137- nextAvailableName(requestedName, existingNames) - Computes `name (n).ext` for upload/move rename options.
138- listDirNameSet(dir) - Fetches directory listing and returns a Set of existing names.
139- cloneFileWithName(file, newName) - Creates a renamed File object for non-overwrite uploads.
140- showFileConflictChoice(filename, renameTo, mode) - Dialog for single upload/move conflicts; returns overwrite/rename/cancel.
141- parseHumanSize(input) - Parses human-readable sizes like `25 MB`/`1gb` into bytes for admin user-folder limits.
142- updateAdminSizeFeedback(rawValue) - Validates size input and updates admin hint text/classes with parsed byte preview.
143- relativePathFromRoot(targetPath, rootPath) - Produces a root-relative path string for sidebar folder context display.
144- displayPathWithRootLabel(targetPath, rootPath, rootLabel) - Produces Linux-style root-relative display paths like `/Downloads/A/B` for folder context UI.
145- openShareModal(item) - Opens the Delen (share) popup, calls POST /api/share/create, shows the 24-hour URL with a copy button and OK to dismiss.
146- loadThumbnails() - Registers visible file icons for lazy thumbnail loading (both file thumbnails and folder icons); retries missing cache thumbnails during incremental refresh.
147- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, text snapshots for text files, and badges for other files; marks image icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
148- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images and videos, text snapshots for text files, and badges for other files; marks image/video icons as pending when cache returns 404 and uses direct source SVG thumbnails for SVG files under 1MB.
149- loadOneThumbnail(iconEl) - Loads thumbnails from server cache endpoint for images, videos, and supported 3D model files; text files still use text snapshots and badges remain the fallback when no thumbnail strategy exists.
150- observeFolderIcon(iconEl) - Registers a folder icon element with IntersectionObserver for lazy loading.
151- loadOneFolderIcon(iconEl) - Fetches /api/files/folder-icon then the thumbnail blob and overlays it inside the folder SVG; no-op if no icon available.
152- applyFolderThumbnail(iconEl, srcUrl) - Injects an SVG <image> element clipped to the folder outline path into the folder's icon SVG.
153- openFolderIconPicker(item) - Opens the folder icon picker modal; shows cached-thumbnail files from the folder (including video thumbnails); allows selection, clearing, and cancellation.
154- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
155- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
156- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
157- observeThumbnailIcon(iconEl) - Defers thumbnail fetch work until file icons are near/in the viewport.
158- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
159- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
160- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
161- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
162- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
163- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
164- modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
165- buildModelObjectFromBlob(blob, type, modules) - Parses STL/OBJ blobs and produces a geometry-only model using the standard blue material.
166- renderModelPreview(item, blob, targetEl) - Renders interactive STL/OBJ previews (drag rotate + scroll zoom) with WebGL fallback messaging when unavailable.
167- closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
168
169## tests/thumbnail-cache.test.js
170- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
171- thumbnail cache worker / removes cached thumbnail when source file is deleted - Verifies stale thumbnail cleanup behavior.
172- thumbnail cache worker / creates cached thumbnail for video files using ffmpeg frame extraction - Verifies video thumbnail generation uses ffprobe duration and ffmpeg frame capture.
173- afterEach() cleanup - Removes temp roots with `fs.rmSync(...maxRetries...)` to tolerate transient Windows file locks.
174- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
175- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
176- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
177- fileAccentColor(name) - Returns canonical file-type accent color used by icon strokes and preview sheet outline.
178- openFolderSidebar() - Persistent sidebar fallback view that shows current folder/root overview when no item is selected.
179- closeSidebar() - Clears selection; hides the panel entirely on mobile and restores folder overview sidebar on desktop.
180- isMobileViewport() - Central media-query helper for mobile-only sidebar/interaction behavior.
181- hideSidebarPanel() - Hides sidebar panel and removes sidebar-open layout class from the app shell.
182- renderBreadcrumb() - Builds clickable breadcrumb path and marks each folder segment as a drag-drop move target via .crumb-drop-target and data-path.
183- fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
184- downloadOrView(item, sourceSvgEl) - Opens preview; prefers in-place expanded tile preview when invoked from a file icon, falls back to overlay when no source tile is available.
185- downloadOrView(item, sourceSvgEl) - Opens in-place expanded tile preview from a file icon; shows error toast if no source tile is found.
186- renderPreviewBody(item, blob, objectUrl, targetEl) - Renders preview content (image/video/audio/pdf/text) or unsupported message into a target container.
187- animateRect(el, fromRect, toRect, opts) - Helper that animates element rectangle (left/top/width/height) for expand/collapse transitions.
188- openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents the real file tile to body, expands it to viewport preview, injects close/download controls.
189- openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents tile to body, shows spinner during expand animation, renders content after animation; applies file-type accent colour to tile border and outline glow.
190- openExpandedTilePreview(item, tileEl, sourceSvgEl, loadPreviewContent) - Adds preview action buttons for Download and Share; Share opens the same modal flow as sidebar sharing.
191- closeExpandedTilePreview() - Collapses expanded tile preview back to original grid position and restores original icon markup.
192- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
193- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
194- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
195- openCopyPicker(item) - Opens Copy To selector modal with the same tree and executes /api/files/copy.
196- openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
197- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
198- copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
199- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available; personal folders resolve to the built-in My Folder label.
200- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
201- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
202- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
203- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
204- makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
205- makeFileItem(item) - Renders tile icons first, then applies any cached watched overlay state (`fully` full-size filled eye, `partway` smaller darker filled eye).
206- loadWatchedStatusesForCurrentDir() - Fetches watched states in one bulk POST /files/watched-statuses request per directory (with legacy /files/meta fallback), caches statuses per path, and updates tile overlays quickly.
207- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
208- beginSidebarLoad() - Aborts in-flight sidebar requests and increments a load token so stale async responses cannot mutate the current sidebar state.
209- openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
210- openSidebar(item) - Personal user roots display access as private and skip /files/root-access lookups to avoid forbidden noise.
211- openSidebar(item) - Uses abortable metadata/access requests and stale-load guards to prevent race-condition UI duplication when selection changes quickly.
212- canWrite(item) - Resolves whether the current user may write to the selected item/root; personal folders are always writable for the owner.
213- fetchRootAccessList(rootPath) - Fetches root access users from the server for a specific configured root.
214- formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
215- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
216- openFolderSidebar() - Shows current folder details when nothing is selected; when at root base-level it also shows root access list.
217- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
218- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
219- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked.
220
221## public/drag-move.js
222- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
223- makeDraggable(el, item) - Touch drag now requires a short hold before movement, uses pointer capture, and keeps drag responsive on mobile.
224- (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
225- (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
226- (internal) _endDrag() - On valid target: runs drop animation, calls moveWithConflictResolution() for overwrite/rename/cancel conflicts, then refreshes dir. Otherwise snap-back.
227- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
228
229## public/drag-move.css
230- .file-item.dragging - Lifted style for real dragged tile.
231- .file-item.drop-target - Glows folder icon when drag hovers over it.
232- .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
233- .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
234- @keyframes drag-rise-spin-fall - Real tile rises, spins, falls/scales into folder on drop.
235- @keyframes folder-bounce - Target folder bounces down then back on accept.
236- .preview-backdrop/.file-item--preview/.preview-expand-* - In-place expanded tile preview styling (no separate overlay window), including preserved icon-outline layer.
237- .preview-expand-share - Secondary action button positioned next to .preview-expand-download in expanded file preview.
238- .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.
239
240## public/style.css
241- #sidebar-duplicates + related classes - Sidebar duplicate-file list styling with truncation and hover feedback.
242- .admin-size-feedback(.ok/.err) - Validation feedback styling for admin user-folder size-limit input.
243
244## tests/auth.routes.test.js
245- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
246- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
247
248## tests/page.load.test.js
249- bootClient() - Boots the app in jsdom and waits until app shell is visible or timeout before assertions.
250- waitFor(dom, predicate, timeoutMs) - Poll helper used by interaction tests to wait for rendered tiles.
251- login overlay uses username and current-password autocomplete tokens - Verifies normal sign-in mode exposes browser-friendly login autocomplete attributes.
252- first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
253- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
254- expanded STL preview falls back gracefully when WebGL is unavailable - Verifies STL preview path shows a clear fallback message when WebGL contexts are unavailable.
255- expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
256- video preview does not close on backdrop click and closes via X button - Verifies video previews require explicit close via X.
257- video preview restores per-user saved volume preference - Verifies per-user saved video volume is applied on preview open.
258- video preview restores saved subtitle/audio track names when available - Verifies per-user subtitle/audio selections are reapplied by matching track names.
259- video preview keeps default tracks when saved names are not present - Verifies subtitle/audio defaults remain unchanged when saved names are missing.
260- video preview saves subtitle/audio track names per user when selection changes - Verifies subtitle/audio selections are persisted into per-user video preferences.
261- video preview applies caption overrides per open - Verifies requested caption overrides are always loaded into Video.js settings.
262- video preview does not save caption style settings per user on close - Verifies caption style changes are not persisted to per-user video preferences.
263- video preview releases the backend stream session when closed - Verifies closing a streamed video preview sends an explicit backend release call.
264- rapid file reselection does not duplicate sidebar action buttons after delayed metadata - Verifies stale sidebar loads are ignored so action buttons are not duplicated.
265- video tiles show centred watched overlays after watched metadata is loaded - Verifies overlays remain absent until watched metadata is fetched, then render as solid eye icons for fully and partway statuses.
266- shows pending icon spinner when video thumbnail cache is not ready - Verifies video tiles use thumbnail-cache loading (instead of badge fallback) and pending-state UI.
267
268## tests/video-stream.test.js
269- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
270- createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
271- createVideoStreamSession does not become ready from subtitle files alone - Verifies stream readiness is tied to HLS output instead of extracted subtitle files.
272- createVideoStreamSession keeps playback available when subtitle conversion fails - Verifies subtitle conversion failures are skipped without breaking stream playback.
273- sendVideoStreamAsset prunes old segment files after playback moves far ahead - Verifies old segments are removed only after the retention window passes.
274- createVideoStreamSession reuses one transcode for concurrent viewers of the same file - Verifies two viewers share one ffmpeg transcode while keeping independent lease release behaviour.
275
276## tests/share.page.load.test.js
277- applies default caption settings for share-page video playback - Verifies requested caption defaults are applied and persisted on share-page video preview.
278- restores and saves share-page subtitle/audio track preferences by name - Verifies share-page subtitle/audio choices are restored and persisted by track-name matching.
279
280## tests/files.routes.test.js
281- POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
282- DELETE /api/files/video-stream/:sessionId releases an active stream session - Verifies explicit stream session release route wiring.
283
284## public/vendor/three/three.module.js
285- Third-party Three.js runtime module (vendored, unmodified) used for client-side 3D previews.
286
287## public/vendor/three/addons/controls/OrbitControls.js
288- Third-party OrbitControls module (vendored, unmodified) providing drag-rotate and wheel-zoom interactions.
289
290## public/vendor/three/addons/loaders/STLLoader.js
291- Third-party STL parser module (vendored, unmodified) for client-side `.stl` geometry loading.
292
293## public/vendor/three/addons/loaders/OBJLoader.js
294- Third-party OBJ parser module (vendored, unmodified) for client-side `.obj` geometry loading.