2026-07-01 19:52:15 -06:00
|
|
|
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
|
2022-02-04 09:41:08 -07:00
|
|
|
import {
|
2025-01-24 15:35:26 -07:00
|
|
|
ApiDownError,
|
2024-11-02 15:14:02 -06:00
|
|
|
createChannel,
|
2025-10-29 22:16:33 -06:00
|
|
|
fetchChannels,
|
2023-06-11 12:31:56 -06:00
|
|
|
fetchDecoded,
|
2026-03-17 18:35:57 -06:00
|
|
|
fetchAuthors,
|
2022-02-04 09:41:08 -07:00
|
|
|
fetchDomains,
|
2026-03-17 18:35:57 -06:00
|
|
|
fetchSubjects,
|
2022-02-04 09:41:08 -07:00
|
|
|
filesSearch,
|
2022-05-16 17:56:55 -06:00
|
|
|
getArchive,
|
2026-03-20 15:53:21 -06:00
|
|
|
getDoc,
|
2026-02-02 15:15:28 -07:00
|
|
|
getArchiveStatistics,
|
2022-08-06 05:22:07 +00:00
|
|
|
getChannel,
|
2024-09-28 17:28:33 -06:00
|
|
|
getConfigs,
|
2025-10-29 22:16:33 -06:00
|
|
|
getDomain,
|
2022-08-06 05:22:07 +00:00
|
|
|
getDownloads,
|
2022-02-04 09:41:08 -07:00
|
|
|
getFiles,
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
getInventories,
|
|
|
|
|
createInventory,
|
|
|
|
|
saveInventory,
|
|
|
|
|
deleteInventory,
|
|
|
|
|
getCatalog,
|
|
|
|
|
saveCatalog,
|
2023-05-29 18:04:03 -06:00
|
|
|
getOutdatedZims,
|
2022-08-06 05:22:07 +00:00
|
|
|
getSettings,
|
2022-12-23 16:04:09 -07:00
|
|
|
getStatistics,
|
2022-08-06 05:22:07 +00:00
|
|
|
getStatus,
|
|
|
|
|
getVideo,
|
2025-01-26 12:44:16 -07:00
|
|
|
getVideoCaptions,
|
|
|
|
|
getVideoComments,
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
getVideoDescription,
|
2022-12-23 16:04:09 -07:00
|
|
|
getVideosStatistics,
|
2024-12-03 22:30:12 -07:00
|
|
|
postDumpConfig,
|
2024-12-18 17:32:00 -07:00
|
|
|
postImportConfig,
|
2024-10-03 13:35:06 -06:00
|
|
|
saveSettings,
|
2024-09-28 17:28:33 -06:00
|
|
|
searchArchives,
|
|
|
|
|
searchChannels,
|
2023-04-18 22:03:45 -06:00
|
|
|
searchDirectories,
|
2026-03-17 18:35:57 -06:00
|
|
|
searchDocs,
|
2022-02-04 09:41:08 -07:00
|
|
|
searchVideos,
|
2023-05-29 18:04:03 -06:00
|
|
|
searchZim,
|
2024-11-02 15:14:02 -06:00
|
|
|
updateChannel,
|
2025-10-29 22:16:33 -06:00
|
|
|
updateDomain,
|
2022-02-04 09:41:08 -07:00
|
|
|
} from "../api";
|
2025-12-11 18:32:55 -07:00
|
|
|
import {
|
2026-07-29 14:57:28 -06:00
|
|
|
unblockBluetooth,
|
|
|
|
|
blockBluetooth,
|
|
|
|
|
startHotspot,
|
|
|
|
|
stopHotspot,
|
|
|
|
|
startDesktop,
|
|
|
|
|
stopDesktop,
|
controller: VNC toggle, gated on the Desktop running
Add a VNC toggle to the Controller (both UIs) that starts/stops whichever VNC
backend is installed: wayvnc for Wayland (Raspberry Pi OS), RealVNC for X11.
Runtime-only, like the Desktop toggle: the unit is never enabled, so VNC does
not return after a reboot. Users who want it permanently on can enable it with
raspi-config.
VNC serves the desktop session, so starting it without a desktop gives clients
a blank screen. The gate lives in the backend, not just the UI, so curl callers
get it too (409, distinct from a systemctl failure). Stopping is never gated so
a running VNC server can't be stranded on with no way to turn it off.
Backend selection deliberately avoids raspi-config's live-compositor probe
(pgrep labwc), which reports X11 — and would pick the wrong backend — whenever
the desktop is stopped. wayvnc also requires its config to exist; that is
checked directly rather than via the unit's ConditionResult, which reports 'no'
for any unit that has never been started.
Extracts _unit_properties()/_systemctl_unit() so Desktop and VNC share one
systemd probe and start/stop path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:53:45 -06:00
|
|
|
startVnc,
|
|
|
|
|
stopVnc,
|
2025-12-11 18:32:55 -07:00
|
|
|
enableThrottle,
|
|
|
|
|
disableThrottle,
|
|
|
|
|
getControllerStats,
|
|
|
|
|
} from "../api/controller";
|
2025-12-07 11:54:20 -07:00
|
|
|
import {createSearchParams, useLocation, useSearchParams} from "react-router";
|
2022-12-09 11:22:20 -07:00
|
|
|
import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common";
|
2024-03-06 17:41:04 -07:00
|
|
|
import {QueryContext, SettingsContext, StatusContext} from "../contexts/contexts";
|
ui: thirty-five files off Semantic, leaving fifteen
Phase 2, part 4. Baseline 50 -> 15.
Migrated: all eight calculators, the rest of inventory and collections, the
Map/Zim/Docs cluster, Videos, Files, Search, Archive, DashboardPage,
DatesSelector, HelpModal, Events, Tags, Flasher's neighbours, admin Settings
and Status, Download, and App.
Also the three shared modules everything imports: api.js and customHooks.js
swap the Semantic toast library for the library's shim (same call shape), and
useForm.js renders the library's Message. useForm accepts both the old
`{content, header, positive|negative}` shape and the new `{kind, title}`,
because the pages building those objects migrate separately.
Two library gaps closed, both found by call sites needing them:
ActionInput is a forwardRef now. Its ref reaches the input rather than the
wrapper, because callers use it to focus or select the field -- a ref to the
surrounding div would do neither, which is why one call site had resorted to
hand-copying the component's markup.
Header takes a `color` token name. Three separate call sites had reached for
an inline style to colour a heading that carries meaning ("3 items to add"
against "2 to remove"), which is how a hex ends up in markup.
Two files needed repair after being interrupted mid-edit: MapViewer had a
Segment left in its error branch, and VideoPlayer had lost the useContext
import its own code still used. Neither jest nor tsc noticed; only
`npm run build` did, which is the whole reason that check exists.
Fifteen files remain: Archive, BulkTagModal, Channels, Docs, FileBrowser,
FilePreview, Flasher, Nav, Playlists, Theme.tsx, Upload, VideoPlayer, Zim,
ControllerPage, admin/Downloads. Theme.tsx is deliberately last -- the
unmigrated files still import its Semantic-backed wrappers, so it can only go
once they have.
2026-07-30 12:21:30 -06:00
|
|
|
import {toast} from "../components/ui";
|
2023-05-29 18:04:03 -06:00
|
|
|
import {useSearch} from "../components/Search";
|
2023-11-02 15:24:07 -06:00
|
|
|
import _ from "lodash";
|
2024-07-21 15:04:56 -06:00
|
|
|
import {TagsSelector} from "../Tags";
|
2024-11-02 15:14:02 -06:00
|
|
|
import {useForm} from "./useForm";
|
2022-01-31 09:08:02 -07:00
|
|
|
|
2025-12-26 11:28:10 -07:00
|
|
|
export const useIsTouchDevice = () => {
|
|
|
|
|
// Detects if the device has a coarse pointer (touch screen).
|
|
|
|
|
// Used to disable drag selection on mobile devices.
|
2026-02-23 15:59:40 -07:00
|
|
|
// Initialize synchronously to avoid race conditions with dependent hooks.
|
|
|
|
|
const [isTouchDevice, setIsTouchDevice] = useState(() => {
|
|
|
|
|
if (typeof window !== 'undefined') {
|
|
|
|
|
return window.matchMedia('(pointer: coarse)').matches;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
});
|
2025-12-26 11:28:10 -07:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const touchQuery = window.matchMedia('(pointer: coarse)');
|
|
|
|
|
|
|
|
|
|
const handleChange = (e) => setIsTouchDevice(e.matches);
|
|
|
|
|
touchQuery.addEventListener('change', handleChange);
|
|
|
|
|
|
|
|
|
|
return () => touchQuery.removeEventListener('change', handleChange);
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return isTouchDevice;
|
|
|
|
|
};
|
|
|
|
|
|
2026-07-01 19:52:15 -06:00
|
|
|
export const useElementWidth = () => {
|
|
|
|
|
// Tracks the rendered width (in pixels) of an element. Returns a callback ref to attach to the element
|
|
|
|
|
// and its current width. Uses a callback ref (not a plain ref) so it re-attaches if the element mounts
|
|
|
|
|
// later (e.g. after data loads), and a ResizeObserver so the width updates as the container/viewport changes.
|
|
|
|
|
const [width, setWidth] = useState(0);
|
|
|
|
|
const observer = useRef(null);
|
|
|
|
|
|
|
|
|
|
const ref = useCallback((node) => {
|
|
|
|
|
if (observer.current) {
|
|
|
|
|
observer.current.disconnect();
|
|
|
|
|
observer.current = null;
|
|
|
|
|
}
|
|
|
|
|
if (node && typeof ResizeObserver === 'function') {
|
|
|
|
|
setWidth(node.offsetWidth);
|
|
|
|
|
observer.current = new ResizeObserver(() => setWidth(node.offsetWidth));
|
|
|
|
|
observer.current.observe(node);
|
|
|
|
|
}
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return [ref, width];
|
|
|
|
|
};
|
|
|
|
|
|
2026-02-23 15:59:40 -07:00
|
|
|
export const usePlatformModifier = () => {
|
|
|
|
|
// Detects if the user is on macOS to display the correct keyboard shortcut modifier.
|
|
|
|
|
const [isMac, setIsMac] = useState(false);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
// Modern API (Chrome 90+)
|
|
|
|
|
if (navigator.userAgentData?.platform) {
|
|
|
|
|
setIsMac(navigator.userAgentData.platform === 'macOS');
|
|
|
|
|
} else {
|
|
|
|
|
// Fallback for older browsers
|
|
|
|
|
setIsMac(/Mac|iPhone|iPad|iPod/.test(navigator.platform));
|
|
|
|
|
}
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
isMac,
|
|
|
|
|
modifierKey: isMac ? '\u2318' : 'Ctrl',
|
|
|
|
|
modifierKeyLong: isMac ? 'Cmd' : 'Ctrl',
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const useKeyboardDetected = () => {
|
|
|
|
|
// Detects if a hardware keyboard is present by listening for key presses.
|
|
|
|
|
// On desktop devices, returns true immediately.
|
|
|
|
|
// On touch devices (iPad with Bluetooth keyboard), returns true after the first key press
|
|
|
|
|
// outside of input fields. This allows showing keyboard shortcuts to iPad users with
|
|
|
|
|
// external keyboards while hiding them for pure touch users.
|
|
|
|
|
const [keyboardDetected, setKeyboardDetected] = useState(false);
|
|
|
|
|
const isTouchDevice = useIsTouchDevice();
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
// Desktop devices always have a keyboard.
|
|
|
|
|
if (!isTouchDevice) {
|
|
|
|
|
setKeyboardDetected(true);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const handleKeyDown = (e) => {
|
|
|
|
|
// A key press outside of input fields indicates a hardware keyboard is connected.
|
|
|
|
|
if (!e.target.matches('input, textarea, [contenteditable]')) {
|
|
|
|
|
setKeyboardDetected(true);
|
|
|
|
|
document.removeEventListener('keydown', handleKeyDown);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
document.addEventListener('keydown', handleKeyDown);
|
|
|
|
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
|
|
|
|
}, [isTouchDevice]);
|
|
|
|
|
|
|
|
|
|
return keyboardDetected;
|
|
|
|
|
};
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const calculatePage = (offset, limit) => {
|
|
|
|
|
return offset && limit ? Math.round((offset / limit) + 1) : 1;
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const calculateTotalPages = (total, limit) => {
|
2023-05-29 18:04:03 -06:00
|
|
|
// Return the total divided by the limit, but always at least 1.
|
|
|
|
|
if (!total || !limit || total < limit) {
|
|
|
|
|
return 1;
|
|
|
|
|
}
|
2026-04-30 17:40:26 -04:00
|
|
|
return Math.ceil(total / limit);
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
2022-10-19 09:18:53 -06:00
|
|
|
export const useRecurringTimeout = (callback, delay) => {
|
|
|
|
|
const timer = useRef(null);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const repeat = async () => {
|
|
|
|
|
// Recursively call the callback.
|
|
|
|
|
await callback();
|
|
|
|
|
timer.current = window.setTimeout(repeat, delay);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Call the repeating function instantly to fetch data fast.
|
|
|
|
|
repeat();
|
|
|
|
|
|
|
|
|
|
// Clear the timeout on unload.
|
|
|
|
|
return () => clearTimeout(timer.current);
|
|
|
|
|
}, [delay])
|
|
|
|
|
}
|
|
|
|
|
|
2024-01-01 15:16:03 -07:00
|
|
|
export const useLatestRequest = (delay = 300, defaultLoading = false) => {
|
2023-11-22 10:35:01 -07:00
|
|
|
// A hook which ignores older requests and will only set `data` to the latest response's data.
|
|
|
|
|
// usage: sendRequest(async () => await yourAPICall(...args));
|
2023-11-21 21:15:24 -07:00
|
|
|
|
2023-11-22 10:47:10 -07:00
|
|
|
// The results from awaiting `fetchFunction`.
|
2023-11-21 21:15:24 -07:00
|
|
|
const [data, setData] = React.useState(null);
|
|
|
|
|
const latestRequestRef = React.useRef(0);
|
|
|
|
|
const debounceTimerRef = React.useRef(null);
|
2023-11-22 10:47:10 -07:00
|
|
|
// Loading while awaiting.
|
2024-01-01 15:16:03 -07:00
|
|
|
const [loading, setLoading] = React.useState(defaultLoading);
|
2023-11-21 21:15:24 -07:00
|
|
|
|
2023-11-22 10:35:01 -07:00
|
|
|
const sendRequest = React.useCallback((fetchFunction) => {
|
2023-11-21 21:15:24 -07:00
|
|
|
if (debounceTimerRef.current) {
|
|
|
|
|
clearTimeout(debounceTimerRef.current);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
debounceTimerRef.current = setTimeout(async () => {
|
|
|
|
|
setLoading(true);
|
|
|
|
|
const requestId = ++latestRequestRef.current;
|
|
|
|
|
|
|
|
|
|
try {
|
2023-11-22 10:35:01 -07:00
|
|
|
const result = await fetchFunction();
|
2023-11-21 21:15:24 -07:00
|
|
|
|
|
|
|
|
if (requestId === latestRequestRef.current) {
|
|
|
|
|
setData(result);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Request failed:', error);
|
|
|
|
|
setData(null);
|
|
|
|
|
} finally {
|
|
|
|
|
if (requestId === latestRequestRef.current) {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, delay);
|
|
|
|
|
}, [delay]);
|
|
|
|
|
|
|
|
|
|
return {data, sendRequest, loading};
|
|
|
|
|
};
|
|
|
|
|
|
2024-03-06 17:41:04 -07:00
|
|
|
const getSearchParamCopy = (searchParams) => {
|
|
|
|
|
let copy = {};
|
|
|
|
|
if (searchParams) {
|
|
|
|
|
Array.from(searchParams.keys()).forEach(key => {
|
|
|
|
|
const value = searchParams.getAll(key)
|
|
|
|
|
copy[key] = value.length === 1 ? value[0] : value;
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
copy = removeEmptyValues(copy);
|
|
|
|
|
return copy;
|
|
|
|
|
}
|
2023-11-21 21:15:24 -07:00
|
|
|
|
2024-03-06 17:41:04 -07:00
|
|
|
const removeEmptyValues = (obj) => {
|
|
|
|
|
Object.entries(obj).forEach(([k, v]) => {
|
|
|
|
|
// Clear any empty values.
|
|
|
|
|
if (v === null || v === undefined || (Array.isArray(v) && v.length === 0)) {
|
|
|
|
|
delete obj[k];
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
return obj
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2024-04-14 14:01:07 -06:00
|
|
|
export const useQuery = () => {
|
2024-02-05 16:04:19 -07:00
|
|
|
const location = useLocation();
|
2023-04-10 12:27:55 -06:00
|
|
|
const [searchParams, setSearchParams] = useSearchParams();
|
2024-03-06 17:41:04 -07:00
|
|
|
|
|
|
|
|
const updateQuery = (newParams, replace = false) => {
|
|
|
|
|
// Update the old state with the new values.
|
2024-04-14 14:01:07 -06:00
|
|
|
let newSearchParams = replace ?
|
|
|
|
|
newParams
|
|
|
|
|
: {...getSearchParamCopy(searchParams), ...newParams};
|
|
|
|
|
newSearchParams = removeEmptyValues(newSearchParams);
|
|
|
|
|
console.debug('useQuery.updateQuery', newSearchParams);
|
|
|
|
|
setSearchParams(newSearchParams);
|
2024-03-06 17:41:04 -07:00
|
|
|
};
|
2023-04-10 12:27:55 -06:00
|
|
|
|
2024-02-12 12:12:07 -07:00
|
|
|
const getLocationStr = (newSearchParams, pathname) => {
|
2024-02-05 16:04:19 -07:00
|
|
|
// Get the current location, but with new params appended.
|
2024-04-14 14:01:07 -06:00
|
|
|
newSearchParams = removeEmptyValues({...getSearchParamCopy(searchParams), ...newSearchParams});
|
2024-03-06 17:41:04 -07:00
|
|
|
const newQuery = createSearchParams(newSearchParams);
|
2024-02-12 12:12:07 -07:00
|
|
|
return `${pathname || location.pathname}?${newQuery.toString()}`
|
2024-02-05 16:04:19 -07:00
|
|
|
}
|
|
|
|
|
|
2024-03-06 17:41:04 -07:00
|
|
|
return {searchParams, updateQuery, getLocationStr}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const QueryProvider = (props) => {
|
2024-04-14 14:01:07 -06:00
|
|
|
return <QueryContext.Provider value={useQuery()}>
|
2024-03-06 17:41:04 -07:00
|
|
|
{props.children}
|
|
|
|
|
</QueryContext.Provider>
|
2023-04-10 12:27:55 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useOneQuery = (name) => {
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
2023-04-10 12:27:55 -06:00
|
|
|
const value = searchParams.get(name);
|
|
|
|
|
|
2024-03-06 17:41:04 -07:00
|
|
|
const setValue = (newValue, replace = false) => {
|
|
|
|
|
updateQuery({[name]: newValue}, replace);
|
2023-04-10 12:27:55 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [value, setValue]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useAllQuery = (name) => {
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
2023-04-10 12:27:55 -06:00
|
|
|
const value = searchParams.getAll(name);
|
|
|
|
|
|
2024-03-06 17:41:04 -07:00
|
|
|
const setValue = (newValue, replace = false) => {
|
|
|
|
|
updateQuery({[name]: newValue}, replace);
|
2023-04-10 12:27:55 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return [value, setValue]
|
|
|
|
|
}
|
2022-10-19 09:18:53 -06:00
|
|
|
|
2022-01-31 09:08:02 -07:00
|
|
|
export const useDomains = () => {
|
|
|
|
|
const [domains, setDomains] = useState(null);
|
|
|
|
|
const [total, setTotal] = useState(null);
|
|
|
|
|
|
|
|
|
|
const _fetchDomains = async () => {
|
|
|
|
|
setDomains(null);
|
|
|
|
|
setTotal(0);
|
2022-05-01 21:03:30 -06:00
|
|
|
try {
|
2025-12-05 17:12:21 -07:00
|
|
|
let [domains, total] = await fetchDomains();
|
2022-05-01 21:03:30 -06:00
|
|
|
setDomains(domains);
|
|
|
|
|
setTotal(total);
|
|
|
|
|
} catch (e) {
|
2023-09-07 20:13:36 -06:00
|
|
|
setDomains(undefined); // Display error.
|
2022-05-01 21:03:30 -06:00
|
|
|
setTotal(0);
|
|
|
|
|
}
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
_fetchDomains();
|
|
|
|
|
}, []);
|
|
|
|
|
|
2025-12-05 17:12:21 -07:00
|
|
|
return [domains, total];
|
2025-10-29 22:16:33 -06:00
|
|
|
}
|
|
|
|
|
|
2026-03-17 18:35:57 -06:00
|
|
|
export const useAuthors = () => {
|
|
|
|
|
const [authors, setAuthors] = useState(null);
|
|
|
|
|
const [total, setTotal] = useState(null);
|
|
|
|
|
|
|
|
|
|
const _fetchAuthors = async () => {
|
|
|
|
|
setAuthors(null);
|
|
|
|
|
setTotal(0);
|
|
|
|
|
try {
|
|
|
|
|
let [authors, total] = await fetchAuthors();
|
|
|
|
|
setAuthors(authors);
|
|
|
|
|
setTotal(total);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
setAuthors(undefined);
|
|
|
|
|
setTotal(0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
_fetchAuthors();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return [authors, total];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useSubjects = () => {
|
|
|
|
|
const [subjects, setSubjects] = useState(null);
|
|
|
|
|
const [total, setTotal] = useState(null);
|
|
|
|
|
|
|
|
|
|
const _fetchSubjects = async () => {
|
|
|
|
|
setSubjects(null);
|
|
|
|
|
setTotal(0);
|
|
|
|
|
try {
|
|
|
|
|
let [subjects, total] = await fetchSubjects();
|
|
|
|
|
setSubjects(subjects);
|
|
|
|
|
setTotal(total);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
setSubjects(undefined);
|
|
|
|
|
setTotal(0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
_fetchSubjects();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return [subjects, total];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useDoc = (fileGroupId) => {
|
|
|
|
|
const [docFile, setDocFile] = useState(null);
|
|
|
|
|
const [doc, setDoc] = useState(null);
|
|
|
|
|
|
|
|
|
|
const fetchDoc = async () => {
|
|
|
|
|
try {
|
2026-03-20 15:53:21 -06:00
|
|
|
const response = await getDoc(fileGroupId);
|
2026-03-17 18:35:57 -06:00
|
|
|
if (response.ok) {
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
setDocFile(data.file_group);
|
|
|
|
|
setDoc(data.doc);
|
|
|
|
|
} else {
|
|
|
|
|
setDocFile(undefined);
|
|
|
|
|
}
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
setDocFile(undefined);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchDoc();
|
|
|
|
|
}, [fileGroupId]);
|
|
|
|
|
|
|
|
|
|
return {docFile, doc, fetchDoc};
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-29 22:16:33 -06:00
|
|
|
export const useDomain = (domainId) => {
|
|
|
|
|
const emptyDomain = {
|
|
|
|
|
domain: '',
|
|
|
|
|
directory: '',
|
|
|
|
|
description: '',
|
|
|
|
|
tag_name: null,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const fetchDomain = async () => {
|
|
|
|
|
if (!domainId) {
|
|
|
|
|
console.debug('Not fetching domain because no domainId is provided');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const d = await getDomain(domainId);
|
|
|
|
|
// Prevent controlled to uncontrolled
|
|
|
|
|
d.directory = d.directory || '';
|
|
|
|
|
d.description = d.description || '';
|
|
|
|
|
d.tag_name = d.tag_name || null;
|
|
|
|
|
return d;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const submitDomain = async () => {
|
|
|
|
|
const body = {
|
|
|
|
|
directory: form.formData.directory,
|
|
|
|
|
description: form.formData.description,
|
|
|
|
|
// Convert null to empty string - backend expects "" to clear tag
|
|
|
|
|
tag_name: form.formData.tag_name === null ? '' : form.formData.tag_name,
|
|
|
|
|
};
|
|
|
|
|
return await updateDomain(domainId, body);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const form = useForm({
|
|
|
|
|
fetcher: fetchDomain,
|
|
|
|
|
emptyFormData: emptyDomain,
|
|
|
|
|
clearOnSuccess: false,
|
|
|
|
|
submitter: submitDomain
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
|
form.fetcher();
|
|
|
|
|
}, [domainId]);
|
|
|
|
|
|
|
|
|
|
const domain = form.formData;
|
|
|
|
|
|
|
|
|
|
return {domain, form, fetchDomain: form.fetcher};
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 15:38:32 -06:00
|
|
|
export const useArchive = (fileGroupId) => {
|
2023-03-24 08:58:18 -06:00
|
|
|
const [archiveFileGroup, setArchiveFileGroup] = useState(null);
|
2022-11-14 15:42:57 -07:00
|
|
|
const [history, setHistory] = useState(null);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const fetchArchive = async () => {
|
|
|
|
|
try {
|
2026-03-20 15:38:32 -06:00
|
|
|
const {file_group, history} = await getArchive(fileGroupId);
|
2023-03-24 08:58:18 -06:00
|
|
|
setArchiveFileGroup(file_group);
|
2022-11-14 15:42:57 -07:00
|
|
|
setHistory(history);
|
2022-08-06 05:22:07 +00:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2023-03-24 08:58:18 -06:00
|
|
|
setArchiveFileGroup(undefined);
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchArchive();
|
2026-03-20 15:38:32 -06:00
|
|
|
}, [fileGroupId]);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
return {archiveFile: archiveFileGroup, history, fetchArchive};
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
2023-05-29 18:04:03 -06:00
|
|
|
export const usePages = (defaultLimit = 24, totalPages = 0) => {
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
2022-08-06 05:22:07 +00:00
|
|
|
const offset = searchParams.get('o') || 0;
|
2023-04-09 14:34:33 -06:00
|
|
|
const limit = parseInt(searchParams.get('l') || defaultLimit || 24);
|
2022-08-06 05:22:07 +00:00
|
|
|
const [activePage, setActivePage] = useState(calculatePage(offset, limit));
|
2023-05-29 18:04:03 -06:00
|
|
|
const [totalPages_, setTotalPages] = useState(totalPages);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const setLimit = (value) => {
|
|
|
|
|
setPage(1);
|
|
|
|
|
updateQuery({l: value, o: null});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const setPage = (value) => {
|
2023-05-29 18:04:03 -06:00
|
|
|
console.debug(`setPage ${value}`);
|
2022-08-06 05:22:07 +00:00
|
|
|
setActivePage(value);
|
|
|
|
|
value = value - 1; // Page really starts as 0.
|
|
|
|
|
updateQuery({o: value * limit});
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-29 18:04:03 -06:00
|
|
|
const setTotal = (total) => {
|
|
|
|
|
const newTotalPages = calculateTotalPages(total, limit);
|
2024-03-06 17:41:04 -07:00
|
|
|
console.debug('newTotalPages', newTotalPages);
|
2023-05-29 18:04:03 -06:00
|
|
|
setTotalPages(newTotalPages);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Used for useEffect.
|
|
|
|
|
const effect = JSON.stringify({offset, limit, activePage});
|
|
|
|
|
|
|
|
|
|
return {offset, limit, setLimit, activePage, setPage, totalPages: totalPages_, setTotal, effect};
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
2023-04-09 14:13:36 -06:00
|
|
|
export const useSearchArchives = (defaultLimit) => {
|
|
|
|
|
const {domain} = useSearchDomain();
|
|
|
|
|
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
2022-08-06 05:22:07 +00:00
|
|
|
const searchStr = searchParams.get('q') || '';
|
2023-04-09 14:13:36 -06:00
|
|
|
const order = searchParams.get('order');
|
2023-04-05 14:37:14 -06:00
|
|
|
const activeTags = searchParams.getAll('tag');
|
2023-04-12 18:51:26 -06:00
|
|
|
const {view} = useSearchView();
|
|
|
|
|
const headline = view === 'headline';
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
const {deep} = useSearchDeep();
|
2022-01-31 09:08:02 -07:00
|
|
|
|
2023-01-04 09:14:33 -07:00
|
|
|
const [archives, setArchives] = useState(null);
|
2022-02-02 14:02:51 -07:00
|
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const localSearchArchives = async () => {
|
2022-02-02 14:02:51 -07:00
|
|
|
setArchives(null);
|
2022-05-01 21:03:30 -06:00
|
|
|
try {
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
let [archives_, total] = await searchArchives(offset, limit, domain, searchStr, order, activeTags, headline,
|
|
|
|
|
deep);
|
2022-08-06 05:22:07 +00:00
|
|
|
setArchives(archives_);
|
|
|
|
|
setTotalPages(calculateTotalPages(total, limit));
|
2022-05-01 21:03:30 -06:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2022-08-06 05:22:07 +00:00
|
|
|
toast({
|
|
|
|
|
type: 'error',
|
|
|
|
|
title: 'Unexpected server response',
|
|
|
|
|
description: 'Could not get archives',
|
|
|
|
|
time: 5000,
|
|
|
|
|
});
|
2023-09-07 20:13:36 -06:00
|
|
|
setArchives(undefined); // Could not get Archives, display error.
|
2022-05-01 21:03:30 -06:00
|
|
|
}
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-08-06 05:22:07 +00:00
|
|
|
localSearchArchives();
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
}, [searchStr, limit, domain, order, offset, JSON.stringify(activeTags), headline, deep]);
|
2022-01-31 09:08:02 -07:00
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const setSearchStr = (value) => {
|
|
|
|
|
updateQuery({q: value, o: 0, order: undefined});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const setOrderBy = (value) => {
|
|
|
|
|
setPage(1);
|
|
|
|
|
updateQuery({order: value});
|
2022-02-02 14:02:51 -07:00
|
|
|
}
|
|
|
|
|
|
2022-01-31 09:08:02 -07:00
|
|
|
return {
|
2022-02-02 14:02:51 -07:00
|
|
|
archives,
|
2022-01-31 09:08:02 -07:00
|
|
|
limit,
|
|
|
|
|
setLimit,
|
2022-08-06 05:22:07 +00:00
|
|
|
offset,
|
|
|
|
|
order,
|
|
|
|
|
setOrderBy,
|
|
|
|
|
totalPages,
|
|
|
|
|
activePage,
|
|
|
|
|
setPage,
|
2022-01-31 09:08:02 -07:00
|
|
|
searchStr,
|
|
|
|
|
setSearchStr,
|
2022-09-23 16:22:57 -06:00
|
|
|
fetchArchives: localSearchArchives,
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
2026-04-14 15:32:06 -06:00
|
|
|
const docFilterToMimetype = (filter) => {
|
|
|
|
|
if (filter === 'pdf') return 'application/pdf';
|
|
|
|
|
if (filter === 'epub') return 'application/epub';
|
|
|
|
|
if (filter === 'comic') return 'application/x-cb';
|
|
|
|
|
if (filter === 'mobi') return 'application/x-mobipocket-ebook';
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-17 18:35:57 -06:00
|
|
|
export const useSearchDocs = (defaultLimit) => {
|
|
|
|
|
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
|
|
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
|
|
|
const searchStr = searchParams.get('q') || '';
|
|
|
|
|
const order = searchParams.get('order');
|
|
|
|
|
const activeTags = searchParams.getAll('tag');
|
|
|
|
|
const author = searchParams.get('author') || '';
|
|
|
|
|
const subject = searchParams.get('subject') || '';
|
2026-04-14 15:32:06 -06:00
|
|
|
const filter = searchParams.get('filter') || '';
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
const {deep} = useSearchDeep();
|
2026-03-17 18:35:57 -06:00
|
|
|
|
|
|
|
|
const [docs, setDocs] = useState(null);
|
|
|
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
|
|
|
|
|
|
|
|
const localSearchDocs = async () => {
|
|
|
|
|
setDocs(null);
|
|
|
|
|
try {
|
2026-04-14 15:32:06 -06:00
|
|
|
const mimetype = docFilterToMimetype(filter);
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
let [docs_, total] = await searchDocs(offset, limit, searchStr, order, activeTags, author, subject,
|
|
|
|
|
mimetype, deep);
|
2026-03-17 18:35:57 -06:00
|
|
|
setDocs(docs_);
|
|
|
|
|
setTotalPages(calculateTotalPages(total, limit));
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
setDocs(undefined);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localSearchDocs();
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
}, [searchStr, limit, order, offset, JSON.stringify(activeTags), author, subject, filter, deep]);
|
2026-03-17 18:35:57 -06:00
|
|
|
|
|
|
|
|
const setSearchStr = (value) => {
|
|
|
|
|
updateQuery({q: value, o: 0, order: undefined});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const setOrderBy = (value) => {
|
|
|
|
|
setPage(1);
|
|
|
|
|
updateQuery({order: value});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
docs,
|
|
|
|
|
limit,
|
|
|
|
|
setLimit,
|
|
|
|
|
offset,
|
|
|
|
|
order,
|
|
|
|
|
setOrderBy,
|
|
|
|
|
totalPages,
|
|
|
|
|
activePage,
|
|
|
|
|
setPage,
|
|
|
|
|
searchStr,
|
|
|
|
|
setSearchStr,
|
|
|
|
|
author,
|
|
|
|
|
subject,
|
|
|
|
|
fetchDocs: localSearchDocs,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
export const useSearchVideos = (defaultLimit, channelId, order_by) => {
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
2023-04-09 14:13:36 -06:00
|
|
|
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
|
2022-08-06 05:22:07 +00:00
|
|
|
const searchStr = searchParams.get('q') || '';
|
|
|
|
|
const order = searchParams.get('order') || order_by;
|
2023-04-05 14:37:14 -06:00
|
|
|
const activeTags = searchParams.getAll('tag');
|
2023-04-12 18:51:26 -06:00
|
|
|
const {view} = useSearchView();
|
|
|
|
|
const headline = view === 'headline';
|
2024-07-22 16:36:57 -06:00
|
|
|
const anyTag = searchParams.get('anyTag') === 'true';
|
2026-06-27 09:48:21 -06:00
|
|
|
const censored = searchParams.get('censored') === 'true';
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
const {deep} = useSearchDeep();
|
2022-05-16 17:56:55 -06:00
|
|
|
|
2023-09-07 20:13:36 -06:00
|
|
|
const [videos, setVideos] = useState(null);
|
2022-08-06 05:22:07 +00:00
|
|
|
const [totalPages, setTotalPages] = useState(0);
|
2024-07-22 16:36:57 -06:00
|
|
|
const [loading, setLoading] = useState(false);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const localSearchVideos = async () => {
|
|
|
|
|
setVideos(null);
|
2024-07-22 16:36:57 -06:00
|
|
|
setLoading(true);
|
2022-05-16 17:56:55 -06:00
|
|
|
try {
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
let [videos_, total] = await searchVideos(offset, limit, channelId, searchStr, order, activeTags, headline,
|
|
|
|
|
censored, deep);
|
2022-08-06 05:22:07 +00:00
|
|
|
setVideos(videos_);
|
|
|
|
|
setTotalPages(calculateTotalPages(total, limit));
|
2022-05-16 17:56:55 -06:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2023-09-07 20:13:36 -06:00
|
|
|
setVideos(undefined);// Could not get Videos, display error.
|
2024-07-22 16:36:57 -06:00
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
2022-05-16 17:56:55 -06:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-08-06 05:22:07 +00:00
|
|
|
localSearchVideos();
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
}, [searchStr, limit, channelId, offset, order_by, JSON.stringify(activeTags), headline, censored, deep]);
|
2022-05-16 17:56:55 -06:00
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const setSearchStr = (value) => {
|
|
|
|
|
updateQuery({q: value, o: 0, order: undefined});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const setOrderBy = (value) => {
|
|
|
|
|
setPage(1);
|
|
|
|
|
updateQuery({order: value});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
videos,
|
|
|
|
|
totalPages,
|
|
|
|
|
limit,
|
|
|
|
|
offset,
|
|
|
|
|
order,
|
|
|
|
|
searchStr,
|
|
|
|
|
activePage,
|
|
|
|
|
setPage,
|
|
|
|
|
setLimit,
|
|
|
|
|
setSearchStr,
|
|
|
|
|
setOrderBy,
|
2022-09-23 16:43:45 -06:00
|
|
|
fetchVideos: localSearchVideos,
|
2023-03-24 08:58:18 -06:00
|
|
|
activeTags,
|
2024-07-22 16:36:57 -06:00
|
|
|
loading,
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
2022-05-16 17:56:55 -06:00
|
|
|
}
|
|
|
|
|
|
2026-03-20 15:38:32 -06:00
|
|
|
export const useVideo = (fileGroupId) => {
|
2022-08-06 05:22:07 +00:00
|
|
|
const [videoFile, setVideoFile] = useState(null);
|
|
|
|
|
const [prevFile, setPrevFile] = useState(null);
|
|
|
|
|
const [nextFile, setNextFile] = useState(null);
|
2022-01-31 09:08:02 -07:00
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
const fetchVideo = async () => {
|
2026-03-20 15:38:32 -06:00
|
|
|
if (fileGroupId && videoFile && Number(videoFile.id) !== Number(fileGroupId)) {
|
2022-10-28 08:12:25 -06:00
|
|
|
// Video is changing. Clear the old video before fetching.
|
|
|
|
|
setVideoFile(null);
|
|
|
|
|
setPrevFile(null);
|
|
|
|
|
setNextFile(null);
|
|
|
|
|
}
|
2022-05-01 21:03:30 -06:00
|
|
|
try {
|
2026-03-20 15:38:32 -06:00
|
|
|
const [v, p, n] = await getVideo(fileGroupId);
|
2022-08-06 05:22:07 +00:00
|
|
|
setVideoFile(v);
|
|
|
|
|
setPrevFile(p);
|
|
|
|
|
setNextFile(n);
|
2022-05-01 21:03:30 -06:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2022-08-06 05:22:07 +00:00
|
|
|
setVideoFile(undefined);
|
|
|
|
|
setPrevFile(undefined);
|
|
|
|
|
setNextFile(undefined);
|
|
|
|
|
toast({
|
|
|
|
|
type: 'error',
|
|
|
|
|
title: 'Unexpected server response',
|
|
|
|
|
description: 'Could not get the video',
|
|
|
|
|
time: 5000,
|
|
|
|
|
})
|
2022-05-01 21:03:30 -06:00
|
|
|
}
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-08-06 05:22:07 +00:00
|
|
|
fetchVideo();
|
2026-03-20 15:38:32 -06:00
|
|
|
}, [fileGroupId]);
|
2022-01-31 09:08:02 -07:00
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
return {videoFile, prevFile, nextFile, fetchVideo};
|
2022-01-31 09:08:02 -07:00
|
|
|
}
|
2022-02-01 14:11:14 -07:00
|
|
|
|
2026-03-20 15:38:32 -06:00
|
|
|
export const useVideoExtras = (fileGroupId) => {
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
// Fetches extra data to display on a Video's page. These are served separately from the
|
|
|
|
|
// Video itself so list responses stay small and never read files from disk.
|
2025-01-26 12:44:16 -07:00
|
|
|
const [comments, setComments] = useState(null);
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
const [description, setDescription] = useState(null);
|
2025-01-26 12:44:16 -07:00
|
|
|
|
|
|
|
|
const fetchComments = async () => {
|
|
|
|
|
try {
|
2026-03-20 15:38:32 -06:00
|
|
|
const result = await getVideoComments(fileGroupId);
|
2025-01-26 12:44:16 -07:00
|
|
|
setComments(result.comments);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
const fetchDescription = async () => {
|
|
|
|
|
try {
|
|
|
|
|
const result = await getVideoDescription(fileGroupId);
|
|
|
|
|
setDescription(result.description);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-21 16:50:27 -06:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (fileGroupId) {
|
|
|
|
|
fetchComments();
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
fetchDescription();
|
2026-03-21 16:50:27 -06:00
|
|
|
} else {
|
|
|
|
|
setComments(null);
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
setDescription(null);
|
2026-03-21 16:50:27 -06:00
|
|
|
}
|
|
|
|
|
}, [fileGroupId]);
|
|
|
|
|
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
return {comments, description}
|
2026-03-21 16:50:27 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useVideoCaptions = (fileGroupId) => {
|
|
|
|
|
const [captions, setCaptions] = useState(null);
|
|
|
|
|
const [captionsLoading, setCaptionsLoading] = useState(false);
|
|
|
|
|
const captionsFetched = useRef(false);
|
|
|
|
|
|
2025-01-26 12:44:16 -07:00
|
|
|
const fetchCaptions = async () => {
|
2026-03-21 16:50:27 -06:00
|
|
|
if (captionsFetched.current || !fileGroupId) return;
|
|
|
|
|
setCaptionsLoading(true);
|
2025-01-26 12:44:16 -07:00
|
|
|
try {
|
2026-03-20 15:38:32 -06:00
|
|
|
const result = await getVideoCaptions(fileGroupId);
|
2025-01-26 12:44:16 -07:00
|
|
|
setCaptions(result.captions);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2026-03-21 16:50:27 -06:00
|
|
|
} finally {
|
|
|
|
|
setCaptionsLoading(false);
|
|
|
|
|
captionsFetched.current = true;
|
2025-01-26 12:44:16 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-03-21 16:50:27 -06:00
|
|
|
setCaptions(null);
|
|
|
|
|
setCaptionsLoading(false);
|
|
|
|
|
captionsFetched.current = false;
|
2026-03-20 15:38:32 -06:00
|
|
|
}, [fileGroupId]);
|
2025-01-26 12:44:16 -07:00
|
|
|
|
2026-03-21 16:50:27 -06:00
|
|
|
return {captions, captionsLoading, fetchCaptions}
|
2025-01-26 12:44:16 -07:00
|
|
|
}
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
export const useChannel = (channel_id) => {
|
|
|
|
|
const emptyChannel = {
|
|
|
|
|
name: '',
|
|
|
|
|
directory: '',
|
|
|
|
|
url: '',
|
2024-10-04 16:32:48 -06:00
|
|
|
tag_name: null,
|
2025-02-19 14:52:50 -07:00
|
|
|
download_missing_data: null,
|
2022-08-06 05:22:07 +00:00
|
|
|
};
|
2022-02-01 14:11:14 -07:00
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
const fetchChannel = async () => {
|
|
|
|
|
if (!channel_id) {
|
|
|
|
|
console.debug('Not fetching channel because no channel_id is provided');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const c = await getChannel(channel_id);
|
|
|
|
|
// Prevent controlled to uncontrolled.
|
|
|
|
|
c['url'] = c['url'] || '';
|
|
|
|
|
c['download_frequency'] = c['download_frequency'] || '';
|
|
|
|
|
c['match_regex'] = c['match_regex'] || '';
|
2025-05-14 18:25:00 -06:00
|
|
|
c['download_missing_data'] = c['download_missing_data'] ?? true;
|
2024-11-02 15:14:02 -06:00
|
|
|
return c;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const submitChannel = async () => {
|
|
|
|
|
const body = {
|
|
|
|
|
name: form.formData.name,
|
|
|
|
|
directory: form.formData.directory,
|
|
|
|
|
url: form.formData.url,
|
2025-02-19 14:52:50 -07:00
|
|
|
download_missing_data: form.formData.download_missing_data,
|
2024-11-02 15:14:02 -06:00
|
|
|
};
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
if (channel_id) {
|
2026-02-05 11:12:44 -07:00
|
|
|
return await updateChannel(channel_id, body);
|
|
|
|
|
} else {
|
2024-11-02 15:14:02 -06:00
|
|
|
// Can create a Channel with a Tag.
|
|
|
|
|
body.tag_name = form.formData.tag_name;
|
|
|
|
|
return await createChannel(body);
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
const form = useForm({
|
|
|
|
|
fetcher: fetchChannel,
|
|
|
|
|
emptyFormData: emptyChannel,
|
|
|
|
|
clearOnSuccess: false,
|
|
|
|
|
submitter: submitChannel
|
|
|
|
|
});
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
React.useEffect(() => {
|
|
|
|
|
// Channel may be gotten from Video data, fetch the Channel again.
|
|
|
|
|
form.fetcher();
|
|
|
|
|
}, [channel_id]);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2024-11-02 15:14:02 -06:00
|
|
|
return {
|
|
|
|
|
channel: form.formData,
|
|
|
|
|
form,
|
2026-01-23 19:51:02 -07:00
|
|
|
fetchChannel: form.fetcher,
|
2024-11-02 15:14:02 -06:00
|
|
|
};
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useChannels = () => {
|
|
|
|
|
const [channels, setChannels] = useState(null);
|
2025-10-29 22:16:33 -06:00
|
|
|
const [total, setTotal] = useState(null);
|
|
|
|
|
const [metadata, setMetadata] = useState(null);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2025-10-29 22:16:33 -06:00
|
|
|
const _fetchChannels = async () => {
|
2022-08-06 05:22:07 +00:00
|
|
|
setChannels(null);
|
2025-10-29 22:16:33 -06:00
|
|
|
setTotal(0);
|
|
|
|
|
setMetadata(null);
|
2022-08-06 05:22:07 +00:00
|
|
|
try {
|
2025-10-29 22:16:33 -06:00
|
|
|
let [channels, total, metadata] = await fetchChannels();
|
|
|
|
|
setChannels(channels);
|
|
|
|
|
setTotal(total);
|
|
|
|
|
setMetadata(metadata);
|
2022-08-06 05:22:07 +00:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2025-10-29 22:16:33 -06:00
|
|
|
setChannels(undefined); // Display error.
|
|
|
|
|
setTotal(0);
|
|
|
|
|
setMetadata(undefined);
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2025-10-29 22:16:33 -06:00
|
|
|
_fetchChannels();
|
2022-08-06 05:22:07 +00:00
|
|
|
}, []);
|
|
|
|
|
|
2025-10-29 22:16:33 -06:00
|
|
|
return [channels, total, metadata];
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
2025-01-26 12:44:16 -07:00
|
|
|
export const useSearchRecentFiles = () => {
|
|
|
|
|
const [searchFiles, setSearchFiles] = useState(null);
|
|
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const localSearchFiles = async () => {
|
|
|
|
|
setLoading(true);
|
|
|
|
|
try {
|
|
|
|
|
let [file_groups, total] = await filesSearch(
|
|
|
|
|
null, 12, null, null, null, [], false,
|
|
|
|
|
null, null, null, false, 'viewed');
|
|
|
|
|
setSearchFiles(file_groups);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
toast({
|
|
|
|
|
type: 'error',
|
|
|
|
|
title: 'Unexpected server response',
|
|
|
|
|
description: 'Could not get recent files',
|
|
|
|
|
time: 5000,
|
|
|
|
|
});
|
|
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
|
localSearchFiles();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return {searchFiles, loading, fetchFiles: localSearchFiles};
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-09 11:22:20 -07:00
|
|
|
export const useSearchFiles = (defaultLimit = 48, emptySearch = false, model) => {
|
2023-05-29 18:04:03 -06:00
|
|
|
const {
|
2024-07-22 16:36:57 -06:00
|
|
|
activeTags, anyTag,
|
2023-05-29 18:04:03 -06:00
|
|
|
pages,
|
|
|
|
|
searchStr,
|
|
|
|
|
filter,
|
|
|
|
|
model: model_,
|
2024-03-06 17:41:04 -07:00
|
|
|
setSearchStr,
|
|
|
|
|
months,
|
|
|
|
|
dateRange,
|
2023-05-29 18:04:03 -06:00
|
|
|
} = useSearch(defaultLimit, emptySearch, model);
|
2023-04-12 18:51:26 -06:00
|
|
|
const {view} = useSearchView();
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
const {deep} = useSearchDeep();
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const [searchFiles, setSearchFiles] = useState(null);
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
const [total, setTotal] = useState(null);
|
2024-07-22 16:36:57 -06:00
|
|
|
const [loading, setLoading] = useState(false);
|
2023-04-12 18:51:26 -06:00
|
|
|
const headline = view === 'headline';
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const localSearchFiles = async () => {
|
2023-03-24 08:58:18 -06:00
|
|
|
if (!emptySearch && !searchStr && !activeTags) {
|
2022-08-06 05:22:07 +00:00
|
|
|
return;
|
|
|
|
|
}
|
2022-12-09 11:22:20 -07:00
|
|
|
const mimetypes = filterToMimetypes(filter);
|
2022-08-06 05:22:07 +00:00
|
|
|
setSearchFiles(null);
|
2024-04-14 14:01:07 -06:00
|
|
|
let fromDate;
|
|
|
|
|
let toDate;
|
2024-03-06 17:41:04 -07:00
|
|
|
if (dateRange) {
|
2024-04-14 14:01:07 -06:00
|
|
|
fromDate = dateRange[0];
|
|
|
|
|
toDate = dateRange[1];
|
2024-03-06 17:41:04 -07:00
|
|
|
}
|
2024-07-22 16:36:57 -06:00
|
|
|
setLoading(true);
|
2024-04-14 14:01:07 -06:00
|
|
|
console.log('localSearchFiles', fromDate, toDate, months);
|
2022-08-06 05:22:07 +00:00
|
|
|
try {
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
let [file_groups, total_] = await filesSearch(
|
2024-03-06 17:41:04 -07:00
|
|
|
pages.offset, pages.limit, searchStr, mimetypes, model || model_, activeTags, headline,
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
months, fromDate, toDate, anyTag, null, null, null, deep);
|
2023-03-24 08:58:18 -06:00
|
|
|
setSearchFiles(file_groups);
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
setTotal(total_);
|
|
|
|
|
pages.setTotal(total_);
|
2022-08-06 05:22:07 +00:00
|
|
|
} catch (e) {
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
setTotal(null);
|
2023-05-29 18:04:03 -06:00
|
|
|
pages.setTotal(0);
|
2022-08-06 05:22:07 +00:00
|
|
|
console.error(e);
|
|
|
|
|
toast({
|
|
|
|
|
type: 'error',
|
|
|
|
|
title: 'Unexpected server response',
|
|
|
|
|
description: 'Could not get files',
|
|
|
|
|
time: 5000,
|
|
|
|
|
});
|
2024-07-22 16:36:57 -06:00
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
2022-02-01 14:11:14 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-11-02 15:24:07 -06:00
|
|
|
// Only search after the user has stopped typing. Estimates will always happen.
|
|
|
|
|
const debouncedLocalSearchFiles = _.debounce(async () => {
|
|
|
|
|
await localSearchFiles();
|
|
|
|
|
}, 1000);
|
|
|
|
|
|
2022-02-01 14:11:14 -07:00
|
|
|
useEffect(() => {
|
2023-11-02 15:24:07 -06:00
|
|
|
if (searchStr || (activeTags && activeTags.length > 0)) {
|
2024-07-22 16:36:57 -06:00
|
|
|
setLoading(true);
|
2023-11-02 15:24:07 -06:00
|
|
|
debouncedLocalSearchFiles();
|
|
|
|
|
}
|
|
|
|
|
// Handle when this is unmounted.
|
|
|
|
|
return () => debouncedLocalSearchFiles.cancel();
|
2024-03-06 17:41:04 -07:00
|
|
|
}, [
|
|
|
|
|
searchStr,
|
|
|
|
|
pages.effect,
|
|
|
|
|
filter,
|
|
|
|
|
model,
|
|
|
|
|
model_,
|
|
|
|
|
JSON.stringify(activeTags),
|
|
|
|
|
headline,
|
|
|
|
|
JSON.stringify(months),
|
|
|
|
|
JSON.stringify(dateRange),
|
2024-07-22 16:36:57 -06:00
|
|
|
anyTag,
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
deep,
|
2024-03-06 17:41:04 -07:00
|
|
|
]);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2023-05-29 18:04:03 -06:00
|
|
|
return {
|
|
|
|
|
searchFiles,
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
total,
|
2023-05-29 18:04:03 -06:00
|
|
|
searchStr,
|
|
|
|
|
filter,
|
|
|
|
|
setSearchStr,
|
|
|
|
|
pages,
|
2024-07-22 16:36:57 -06:00
|
|
|
activeTags,
|
|
|
|
|
loading,
|
2023-05-29 18:04:03 -06:00
|
|
|
};
|
2022-02-01 14:11:14 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useBrowseFiles = () => {
|
2023-01-04 09:14:33 -07:00
|
|
|
const [browseFiles, setBrowseFiles] = useState(null);
|
2023-04-10 12:27:55 -06:00
|
|
|
const [openFolders, setOpenFolders] = useAllQuery('folders');
|
2022-02-01 14:11:14 -07:00
|
|
|
|
|
|
|
|
const fetchFiles = async () => {
|
2022-05-01 21:03:30 -06:00
|
|
|
try {
|
|
|
|
|
const files = await getFiles(openFolders);
|
|
|
|
|
setBrowseFiles(files);
|
|
|
|
|
} catch (e) {
|
2023-09-13 10:39:06 -06:00
|
|
|
console.error(e);
|
2023-09-07 20:13:36 -06:00
|
|
|
setBrowseFiles(undefined); // Display error.
|
2022-05-01 21:03:30 -06:00
|
|
|
}
|
2022-02-01 14:11:14 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchFiles();
|
2023-04-10 12:27:55 -06:00
|
|
|
}, [JSON.stringify(openFolders)])
|
2022-02-01 14:11:14 -07:00
|
|
|
|
|
|
|
|
return {browseFiles, openFolders, setOpenFolders, fetchFiles};
|
|
|
|
|
}
|
2022-02-04 09:41:08 -07:00
|
|
|
|
2026-07-29 19:41:55 -06:00
|
|
|
export const useConfigs = () => {
|
|
|
|
|
const [configs, setConfigs] = useState(null);
|
|
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const fetchConfigs = async () => {
|
|
|
|
|
setLoading(true);
|
|
|
|
|
console.log('fetching configs...');
|
|
|
|
|
try {
|
|
|
|
|
const data = await getConfigs();
|
|
|
|
|
setConfigs(data['configs']);
|
|
|
|
|
console.debug('fetching configs successful');
|
|
|
|
|
} catch (e) {
|
|
|
|
|
// Ignore SyntaxError because they happen when the API is down.
|
|
|
|
|
if (!(e instanceof SyntaxError)) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
setConfigs(undefined);
|
|
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const importConfig = async (fileName) => {
|
|
|
|
|
try {
|
|
|
|
|
await postImportConfig(fileName);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const saveConfig = async (fileName) => {
|
|
|
|
|
try {
|
|
|
|
|
await postDumpConfig(fileName);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {configs, loading, fetchConfigs, importConfig, saveConfig}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useDownloads = () => {
|
|
|
|
|
const [onceDownloads, setOnceDownloads] = useState(null);
|
|
|
|
|
const [recurringDownloads, setRecurringDownloads] = useState(null);
|
|
|
|
|
const [pendingOnceDownloads, setPendingOnceDownloads] = useState(null);
|
|
|
|
|
|
|
|
|
|
const fetchDownloads = async () => {
|
|
|
|
|
try {
|
|
|
|
|
const data = await getDownloads();
|
|
|
|
|
setOnceDownloads(data['once_downloads']);
|
|
|
|
|
setRecurringDownloads(data['recurring_downloads']);
|
|
|
|
|
setPendingOnceDownloads(data['pending_once_downloads']);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
// Display errors.
|
|
|
|
|
setOnceDownloads(undefined);
|
|
|
|
|
setRecurringDownloads(undefined);
|
|
|
|
|
setPendingOnceDownloads(undefined);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useRecurringTimeout(fetchDownloads, 3 * 1000);
|
|
|
|
|
|
|
|
|
|
return {onceDownloads, recurringDownloads, pendingOnceDownloads, fetchDownloads}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
// Every hardware toggle works the same way: one field of the shared status object
|
|
|
|
|
// says whether the subsystem is on, and starting/stopping it is a Controller call.
|
|
|
|
|
// `on` is null when the status is unknown, which the UI renders as unsupported.
|
|
|
|
|
const useSubsystemToggle = ({
|
|
|
|
|
statusField,
|
|
|
|
|
onValue = 'on',
|
|
|
|
|
offValues = ['off'],
|
|
|
|
|
start,
|
|
|
|
|
stop,
|
|
|
|
|
errorTitle,
|
|
|
|
|
errorDescription,
|
|
|
|
|
refetchStatus = false,
|
|
|
|
|
}) => {
|
2022-02-04 09:41:08 -07:00
|
|
|
const [on, setOn] = useState(null);
|
2026-07-29 18:21:03 -06:00
|
|
|
const {status, fetchStatus} = useContext(StatusContext);
|
|
|
|
|
const value = status?.[statusField];
|
2022-02-04 09:41:08 -07:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
2026-07-29 18:21:03 -06:00
|
|
|
if (value === onValue) {
|
|
|
|
|
setOn(true);
|
|
|
|
|
} else if (offValues.includes(value)) {
|
|
|
|
|
setOn(false);
|
|
|
|
|
} else {
|
|
|
|
|
setOn(null);
|
2022-10-19 09:18:53 -06:00
|
|
|
}
|
2026-07-29 18:21:03 -06:00
|
|
|
}, [value]);
|
2022-02-04 09:41:08 -07:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
const setSubsystem = async (enable) => {
|
|
|
|
|
const previous = on;
|
2022-02-04 09:41:08 -07:00
|
|
|
setOn(null);
|
2025-12-11 18:32:55 -07:00
|
|
|
try {
|
|
|
|
|
if (enable) {
|
2026-07-29 18:21:03 -06:00
|
|
|
await start();
|
2025-12-11 18:32:55 -07:00
|
|
|
} else {
|
2026-07-29 18:21:03 -06:00
|
|
|
await stop();
|
2025-12-11 18:32:55 -07:00
|
|
|
}
|
|
|
|
|
} catch (e) {
|
2026-07-29 18:21:03 -06:00
|
|
|
console.error(`${errorTitle}:`, e);
|
2025-12-11 18:32:55 -07:00
|
|
|
toast({
|
|
|
|
|
type: 'error',
|
2026-07-29 18:21:03 -06:00
|
|
|
title: errorTitle,
|
|
|
|
|
description: e.message || errorDescription,
|
2025-12-11 18:32:55 -07:00
|
|
|
time: 5000,
|
|
|
|
|
});
|
2026-07-29 18:21:03 -06:00
|
|
|
// Nothing changed, so the status poll will not re-sync `on`; without this
|
|
|
|
|
// the toggle stays disabled and reads as unsupported until it remounts.
|
|
|
|
|
setOn(previous);
|
2025-12-11 18:32:55 -07:00
|
|
|
}
|
2026-07-29 18:21:03 -06:00
|
|
|
if (refetchStatus) {
|
|
|
|
|
await fetchStatus();
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
return {on, setOn, setSubsystem};
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
export const useHotspot = () => {
|
|
|
|
|
const {status} = useContext(StatusContext);
|
|
|
|
|
// Hotspot is unsupported on Docker.
|
|
|
|
|
const {dockerized, hotspot_ssid, hotspot_status} = status;
|
|
|
|
|
const {on, setOn, setSubsystem} = useSubsystemToggle({
|
|
|
|
|
statusField: 'hotspot_status',
|
|
|
|
|
onValue: 'connected',
|
|
|
|
|
// The WiFi device being in use for a network is a kind of "off": the hotspot
|
|
|
|
|
// is not running, but starting it takes the user off that network.
|
|
|
|
|
offValues: ['disconnected', 'off', 'in_use'],
|
|
|
|
|
start: startHotspot,
|
|
|
|
|
stop: stopHotspot,
|
|
|
|
|
errorTitle: 'Hotspot Error',
|
|
|
|
|
errorDescription: 'Could not modify hotspot. See server logs.',
|
|
|
|
|
});
|
2024-09-28 17:28:33 -06:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
return {
|
|
|
|
|
on,
|
|
|
|
|
inUse: hotspot_status === 'in_use',
|
|
|
|
|
hotspotSsid: hotspot_ssid,
|
|
|
|
|
setOn,
|
|
|
|
|
setHotspot: setSubsystem,
|
|
|
|
|
dockerized,
|
|
|
|
|
};
|
2024-09-28 17:28:33 -06:00
|
|
|
}
|
|
|
|
|
|
2022-02-07 13:37:58 -07:00
|
|
|
export const useThrottle = () => {
|
2026-07-29 18:21:03 -06:00
|
|
|
const {on, setOn, setSubsystem} = useSubsystemToggle({
|
|
|
|
|
statusField: 'throttle_status',
|
|
|
|
|
onValue: 'powersave',
|
|
|
|
|
offValues: ['ondemand'],
|
|
|
|
|
start: enableThrottle,
|
|
|
|
|
stop: disableThrottle,
|
|
|
|
|
errorTitle: 'Throttle Error',
|
|
|
|
|
errorDescription: 'Could not modify throttle. See server logs.',
|
|
|
|
|
// The governor is read from sysfs, so refetch rather than wait for the poll.
|
|
|
|
|
refetchStatus: true,
|
|
|
|
|
});
|
2022-02-07 13:37:58 -07:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
return {on, setOn, setThrottle: setSubsystem};
|
2022-02-07 13:37:58 -07:00
|
|
|
}
|
2022-05-01 21:03:30 -06:00
|
|
|
|
2026-03-28 10:09:58 -06:00
|
|
|
export const useBluetooth = () => {
|
2026-07-29 18:21:03 -06:00
|
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
|
|
|
statusField: 'bluetooth_status',
|
|
|
|
|
start: unblockBluetooth,
|
|
|
|
|
stop: blockBluetooth,
|
|
|
|
|
errorTitle: 'Bluetooth Error',
|
|
|
|
|
errorDescription: 'Could not modify Bluetooth. See server logs.',
|
|
|
|
|
});
|
2026-03-28 10:09:58 -06:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
return {on, setBluetooth: setSubsystem};
|
2026-03-28 10:09:58 -06:00
|
|
|
}
|
|
|
|
|
|
2026-07-29 14:57:28 -06:00
|
|
|
export const useDesktop = () => {
|
2026-07-29 18:21:03 -06:00
|
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
|
|
|
statusField: 'desktop_status',
|
|
|
|
|
start: startDesktop,
|
|
|
|
|
stop: stopDesktop,
|
|
|
|
|
errorTitle: 'Desktop Error',
|
|
|
|
|
errorDescription: 'Could not start/stop the desktop. See server logs.',
|
|
|
|
|
});
|
2026-07-29 14:57:28 -06:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
return {on, setDesktop: setSubsystem};
|
2026-07-29 14:57:28 -06:00
|
|
|
}
|
|
|
|
|
|
controller: VNC toggle, gated on the Desktop running
Add a VNC toggle to the Controller (both UIs) that starts/stops whichever VNC
backend is installed: wayvnc for Wayland (Raspberry Pi OS), RealVNC for X11.
Runtime-only, like the Desktop toggle: the unit is never enabled, so VNC does
not return after a reboot. Users who want it permanently on can enable it with
raspi-config.
VNC serves the desktop session, so starting it without a desktop gives clients
a blank screen. The gate lives in the backend, not just the UI, so curl callers
get it too (409, distinct from a systemctl failure). Stopping is never gated so
a running VNC server can't be stranded on with no way to turn it off.
Backend selection deliberately avoids raspi-config's live-compositor probe
(pgrep labwc), which reports X11 — and would pick the wrong backend — whenever
the desktop is stopped. wayvnc also requires its config to exist; that is
checked directly rather than via the unit's ConditionResult, which reports 'no'
for any unit that has never been started.
Extracts _unit_properties()/_systemctl_unit() so Desktop and VNC share one
systemd probe and start/stop path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:53:45 -06:00
|
|
|
export const useVnc = () => {
|
|
|
|
|
const {status} = useContext(StatusContext);
|
2026-07-29 18:21:03 -06:00
|
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
|
|
|
statusField: 'vnc_status',
|
|
|
|
|
start: startVnc,
|
|
|
|
|
stop: stopVnc,
|
|
|
|
|
errorTitle: 'VNC Error',
|
|
|
|
|
errorDescription: 'Could not start/stop VNC. See server logs.',
|
|
|
|
|
});
|
controller: VNC toggle, gated on the Desktop running
Add a VNC toggle to the Controller (both UIs) that starts/stops whichever VNC
backend is installed: wayvnc for Wayland (Raspberry Pi OS), RealVNC for X11.
Runtime-only, like the Desktop toggle: the unit is never enabled, so VNC does
not return after a reboot. Users who want it permanently on can enable it with
raspi-config.
VNC serves the desktop session, so starting it without a desktop gives clients
a blank screen. The gate lives in the backend, not just the UI, so curl callers
get it too (409, distinct from a systemctl failure). Stopping is never gated so
a running VNC server can't be stranded on with no way to turn it off.
Backend selection deliberately avoids raspi-config's live-compositor probe
(pgrep labwc), which reports X11 — and would pick the wrong backend — whenever
the desktop is stopped. wayvnc also requires its config to exist; that is
checked directly rather than via the unit's ConditionResult, which reports 'no'
for any unit that has never been started.
Extracts _unit_properties()/_systemctl_unit() so Desktop and VNC share one
systemd probe and start/stop path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:53:45 -06:00
|
|
|
|
2026-07-29 18:21:03 -06:00
|
|
|
// VNC serves the desktop session, so it cannot be started without one.
|
|
|
|
|
return {on, desktopRunning: status?.desktop_status === 'on', setVnc: setSubsystem};
|
controller: VNC toggle, gated on the Desktop running
Add a VNC toggle to the Controller (both UIs) that starts/stops whichever VNC
backend is installed: wayvnc for Wayland (Raspberry Pi OS), RealVNC for X11.
Runtime-only, like the Desktop toggle: the unit is never enabled, so VNC does
not return after a reboot. Users who want it permanently on can enable it with
raspi-config.
VNC serves the desktop session, so starting it without a desktop gives clients
a blank screen. The gate lives in the backend, not just the UI, so curl callers
get it too (409, distinct from a systemctl failure). Stopping is never gated so
a running VNC server can't be stranded on with no way to turn it off.
Backend selection deliberately avoids raspi-config's live-compositor probe
(pgrep labwc), which reports X11 — and would pick the wrong backend — whenever
the desktop is stopped. wayvnc also requires its config to exist; that is
checked directly rather than via the unit's ConditionResult, which reports 'no'
for any unit that has never been started.
Extracts _unit_properties()/_systemctl_unit() so Desktop and VNC share one
systemd probe and start/stop path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-29 16:53:45 -06:00
|
|
|
}
|
|
|
|
|
|
2023-04-18 22:03:45 -06:00
|
|
|
export const useSearchDirectories = (value) => {
|
|
|
|
|
const [directoryName, setDirectoryName] = useState(value ?? '');
|
|
|
|
|
const [directories, setDirectories] = useState(null);
|
|
|
|
|
const [channelDirectories, setChannelDirectories] = useState(null);
|
|
|
|
|
const [domainDirectories, setDomainDirectories] = useState(null);
|
2024-10-02 21:59:33 -06:00
|
|
|
const [isDir, setIsDir] = useState(false);
|
2023-04-18 22:03:45 -06:00
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const localSearchDirectories = async () => {
|
|
|
|
|
setLoading(true);
|
|
|
|
|
try {
|
2024-10-02 21:59:33 -06:00
|
|
|
const result = await searchDirectories(directoryName);
|
|
|
|
|
setDirectories(result.directories);
|
|
|
|
|
setChannelDirectories(result.channel_directories);
|
|
|
|
|
setDomainDirectories(result.domain_directories);
|
|
|
|
|
setIsDir(result.is_dir);
|
2023-04-18 22:03:45 -06:00
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localSearchDirectories();
|
|
|
|
|
}, [directoryName]);
|
|
|
|
|
|
2024-10-02 21:59:33 -06:00
|
|
|
useEffect(() => {
|
2026-06-24 15:23:32 -06:00
|
|
|
// Directory value was changed above. Coerce null/undefined (an unset form field) to an
|
|
|
|
|
// empty string so the controlled input stays controlled and never builds a null result.
|
|
|
|
|
setDirectoryName(value ?? '');
|
2024-10-02 21:59:33 -06:00
|
|
|
}, [value]);
|
|
|
|
|
|
2023-04-18 22:03:45 -06:00
|
|
|
return {
|
|
|
|
|
directoryName,
|
|
|
|
|
setDirectoryName,
|
|
|
|
|
directories,
|
|
|
|
|
loading,
|
|
|
|
|
channelDirectories,
|
2024-10-02 21:59:33 -06:00
|
|
|
domainDirectories,
|
|
|
|
|
isDir,
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
export const useSettings = () => {
|
|
|
|
|
const [settings, setSettings] = useState({});
|
2024-10-03 13:35:06 -06:00
|
|
|
const [pending, setPending] = useState(false);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const fetchSettings = async () => {
|
2025-01-24 15:35:26 -07:00
|
|
|
if (window.apiDown) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2024-10-03 13:35:06 -06:00
|
|
|
setPending(true);
|
2022-08-06 05:22:07 +00:00
|
|
|
try {
|
2026-03-07 16:24:20 -07:00
|
|
|
const newSettings = await getSettings();
|
|
|
|
|
if (newSettings) {
|
|
|
|
|
setSettings(newSettings);
|
|
|
|
|
}
|
2022-08-06 05:22:07 +00:00
|
|
|
} catch (e) {
|
2026-03-07 16:24:20 -07:00
|
|
|
// Don't clear settings on error — keep the last known good values.
|
2024-10-03 13:35:06 -06:00
|
|
|
} finally {
|
|
|
|
|
setPending(false);
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchSettings();
|
|
|
|
|
}, []);
|
|
|
|
|
|
2024-10-03 13:35:06 -06:00
|
|
|
return {settings, pending, fetchSettings, saveSettings};
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
export const useSettingsInterval = () => {
|
2024-10-03 13:35:06 -06:00
|
|
|
const {settings, pending, fetchSettings, saveSettings} = useSettings();
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2024-02-19 13:45:41 -07:00
|
|
|
useRecurringTimeout(fetchSettings, 1000 * 10);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2024-10-03 13:35:06 -06:00
|
|
|
return {settings, pending, fetchSettings, saveSettings};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useMediaDirectory = () => {
|
|
|
|
|
const {settings} = React.useContext(SettingsContext);
|
|
|
|
|
|
|
|
|
|
return settings['media_directory'];
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useStatus = () => {
|
|
|
|
|
const [status, setStatus] = useState({});
|
|
|
|
|
|
|
|
|
|
const fetchStatus = async () => {
|
|
|
|
|
try {
|
2025-12-11 18:32:55 -07:00
|
|
|
// Fetch from both endpoints in parallel
|
|
|
|
|
const [appStatus, controllerStats] = await Promise.all([
|
2026-03-07 16:24:20 -07:00
|
|
|
getStatus().then(result => {
|
|
|
|
|
window.apiDown = false;
|
|
|
|
|
return result;
|
|
|
|
|
}).catch(e => {
|
2025-12-11 18:32:55 -07:00
|
|
|
if (e instanceof ApiDownError) {
|
|
|
|
|
window.apiDown = true;
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
throw e;
|
|
|
|
|
}),
|
|
|
|
|
getControllerStats().catch(e => {
|
|
|
|
|
// Controller may be down, continue with app status only
|
|
|
|
|
console.debug('Controller stats unavailable:', e.message);
|
|
|
|
|
return {};
|
|
|
|
|
}),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
// Merge both responses - controller stats override app status for system info
|
|
|
|
|
setStatus({...appStatus, ...controllerStats});
|
2022-08-06 05:22:07 +00:00
|
|
|
} catch (e) {
|
2025-01-24 15:35:26 -07:00
|
|
|
if (e instanceof ApiDownError) {
|
|
|
|
|
// API is down, do not log this error.
|
|
|
|
|
window.apiDown = true;
|
|
|
|
|
setStatus({});
|
|
|
|
|
return;
|
|
|
|
|
}
|
2024-12-18 17:32:00 -07:00
|
|
|
// Ignore SyntaxError because they happen when the API is down.
|
|
|
|
|
if (!(e instanceof SyntaxError)) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-24 15:35:26 -07:00
|
|
|
useEffect(() => {
|
|
|
|
|
// Used to tell other hooks to stop fetching intervals.
|
|
|
|
|
window.apiDown = false;
|
|
|
|
|
}, []);
|
|
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
return {status, fetchStatus}
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-16 11:53:44 -06:00
|
|
|
export const useStatusInterval = () => {
|
|
|
|
|
const {status, fetchStatus} = useStatus();
|
|
|
|
|
|
2022-10-19 09:18:53 -06:00
|
|
|
useRecurringTimeout(fetchStatus, 1000 * 3);
|
2022-10-16 11:53:44 -06:00
|
|
|
|
|
|
|
|
return {status, fetchStatus};
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-03 12:46:57 -06:00
|
|
|
export const StatusProvider = (props) => {
|
2024-02-19 13:45:41 -07:00
|
|
|
const statusValue = useStatusInterval();
|
|
|
|
|
const settingsValue = useSettingsInterval();
|
2023-05-03 12:46:57 -06:00
|
|
|
|
2024-02-19 13:45:41 -07:00
|
|
|
const statusMemoValue = React.useMemo(() => statusValue, [statusValue]);
|
|
|
|
|
const settingsMemoValue = React.useMemo(() => settingsValue, [settingsValue]);
|
2023-11-22 12:19:49 -07:00
|
|
|
|
2024-02-19 13:45:41 -07:00
|
|
|
return <StatusContext.Provider value={statusMemoValue}>
|
|
|
|
|
<SettingsContext.Provider value={settingsMemoValue}>
|
|
|
|
|
{props.children}
|
|
|
|
|
</SettingsContext.Provider>
|
2023-05-03 12:46:57 -06:00
|
|
|
</StatusContext.Provider>
|
|
|
|
|
}
|
|
|
|
|
|
2023-07-27 15:53:47 -06:00
|
|
|
export const useStatusFlag = (flag) => {
|
|
|
|
|
const {status} = useContext(StatusContext);
|
2025-01-10 11:33:21 -07:00
|
|
|
return status?.flags?.[flag] || false;
|
2023-07-27 15:53:47 -06:00
|
|
|
}
|
|
|
|
|
|
2023-08-13 10:54:43 -06:00
|
|
|
export const useCPUTemperature = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
2025-01-10 11:33:21 -07:00
|
|
|
const temperature = status?.cpu_stats?.temperature || 0;
|
|
|
|
|
const highTemperature = status?.cpu_stats?.high_temperature || 75;
|
|
|
|
|
const criticalTemperature = status?.cpu_stats?.critical_temperature || 85;
|
2023-10-06 12:48:20 -06:00
|
|
|
return {temperature, highTemperature, criticalTemperature}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-03 18:46:29 -06:00
|
|
|
// Reports the hottest drive's SMART temperature so the navbar can warn about
|
|
|
|
|
// an overheating disk, mirroring useCPUTemperature. Drives without a
|
|
|
|
|
// temperature reading (USB flash, unsupported bridges, spun-down) are ignored.
|
|
|
|
|
export const useDriveTemperature = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
const smart = status?.smart_stats;
|
|
|
|
|
const highTemperature = smart?.high_temperature || 55;
|
|
|
|
|
const criticalTemperature = smart?.critical_temperature || 65;
|
|
|
|
|
|
|
|
|
|
const drives = Array.isArray(smart?.drives) ? smart.drives : [];
|
|
|
|
|
const hottest = drives
|
|
|
|
|
.filter((d) => typeof d.temperature === 'number')
|
|
|
|
|
.reduce((max, d) => (max === null || d.temperature > max.temperature ? d : max), null);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
device: hottest?.device || null,
|
|
|
|
|
temperature: hottest?.temperature ?? 0,
|
|
|
|
|
highTemperature,
|
|
|
|
|
criticalTemperature,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-24 15:59:34 -06:00
|
|
|
// Reports drives whose SMART health is degraded, so the navbar can warn of an
|
|
|
|
|
// imminent or developing drive failure. The backend's derived `health` is
|
|
|
|
|
// 'PASS', 'WARN', 'FAIL', or null (unknown): FAIL is an imminent failure
|
|
|
|
|
// (back up now), WARN means unreadable/pending sectors are accumulating.
|
2026-06-03 20:02:59 -06:00
|
|
|
export const useDriveHealth = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
const drives = Array.isArray(status?.smart_stats?.drives) ? status.smart_stats.drives : [];
|
2026-06-24 15:59:34 -06:00
|
|
|
const verdict = (d) => (d.health || d.assessment);
|
|
|
|
|
const failingDevices = drives.filter((d) => verdict(d) === 'FAIL').map((d) => d.device);
|
|
|
|
|
const warningDevices = drives.filter((d) => verdict(d) === 'WARN').map((d) => d.device);
|
|
|
|
|
return {
|
|
|
|
|
failingDevices, failing: failingDevices.length > 0,
|
|
|
|
|
warningDevices, warning: warningDevices.length > 0,
|
|
|
|
|
};
|
2026-06-03 20:02:59 -06:00
|
|
|
}
|
|
|
|
|
|
2023-10-06 12:48:20 -06:00
|
|
|
export const useLoad = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
2025-01-10 11:33:21 -07:00
|
|
|
let minute_1 = status?.load_stats?.minute_1;
|
|
|
|
|
let minute_5 = status?.load_stats?.minute_5;
|
|
|
|
|
let minute_15 = status?.load_stats?.minute_15;
|
2023-10-06 12:48:20 -06:00
|
|
|
let mediumLoad = false;
|
|
|
|
|
let highLoad = false;
|
|
|
|
|
let cores;
|
|
|
|
|
|
2025-01-10 11:33:21 -07:00
|
|
|
if (status && status.cpu_stats) {
|
|
|
|
|
// Medium load when 1/2 cores are busy, High load when 3/4+ cores are busy.
|
|
|
|
|
cores = status.cpu_stats.cores;
|
2023-10-06 12:48:20 -06:00
|
|
|
const quarter = cores / 4;
|
|
|
|
|
if (cores && minute_1 >= (quarter * 3)) {
|
|
|
|
|
highLoad = true;
|
|
|
|
|
} else if (cores && minute_1 >= (quarter * 2)) {
|
|
|
|
|
mediumLoad = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {minute_1, minute_5, minute_15, mediumLoad, highLoad, cores};
|
2023-08-13 10:54:43 -06:00
|
|
|
}
|
|
|
|
|
|
2025-01-10 11:33:21 -07:00
|
|
|
export const useIOStats = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
const percentIdle = status?.iostat_stats?.percent_idle;
|
|
|
|
|
const percentIOWait = status?.iostat_stats?.percent_iowait;
|
|
|
|
|
const percentNice = status?.iostat_stats?.percent_nice;
|
|
|
|
|
const percentSteal = status?.iostat_stats?.percent_steal;
|
|
|
|
|
const percentSystem = status?.iostat_stats?.percent_system;
|
|
|
|
|
const percentUser = status?.iostat_stats?.percent_user;
|
|
|
|
|
|
|
|
|
|
return {percentIdle, percentIOWait, percentNice, percentSteal, percentSystem, percentUser};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useMemoryStats = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
const total = status?.memory_stats?.total;
|
|
|
|
|
const used = status?.memory_stats?.used;
|
|
|
|
|
const free = status?.memory_stats?.free;
|
|
|
|
|
const cached = status?.memory_stats?.cached;
|
|
|
|
|
let percent;
|
|
|
|
|
if (total && used) {
|
|
|
|
|
percent = Math.round((used / total) * 100);
|
|
|
|
|
}
|
|
|
|
|
return {total, used, free, cached, percent}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const usePowerStats = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
const underVoltage = status?.power_stats?.under_voltage;
|
|
|
|
|
const overCurrent = status?.power_stats?.over_current;
|
|
|
|
|
return {underVoltage, overCurrent};
|
|
|
|
|
}
|
2022-12-23 16:04:09 -07:00
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
export const useVideoStatistics = () => {
|
2023-09-07 20:13:36 -06:00
|
|
|
const [statistics, setStatistics] = useState(null);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
const fetchStatistics = async () => {
|
|
|
|
|
try {
|
2022-12-16 11:10:01 -07:00
|
|
|
let stats = await getVideosStatistics();
|
2022-09-28 09:38:05 -06:00
|
|
|
stats.videos.sum_duration = secondsToFullDuration(stats.videos.sum_duration);
|
2022-10-24 17:15:15 -06:00
|
|
|
stats.videos.sum_size = humanFileSize(stats.videos.sum_size);
|
|
|
|
|
stats.videos.max_size = humanFileSize(stats.videos.max_size);
|
|
|
|
|
stats.historical.average_size = humanFileSize(stats.historical.average_size);
|
2022-08-06 05:22:07 +00:00
|
|
|
setStatistics(stats);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2023-09-07 20:13:36 -06:00
|
|
|
setStatistics(undefined); // Display error.
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchStatistics();
|
2022-05-01 21:03:30 -06:00
|
|
|
}, []);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
return {statistics, fetchStatistics}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-02 15:15:28 -07:00
|
|
|
export const useArchiveStatistics = () => {
|
|
|
|
|
const [statistics, setStatistics] = useState(null);
|
|
|
|
|
|
|
|
|
|
const fetchStatistics = async () => {
|
|
|
|
|
try {
|
|
|
|
|
let stats = await getArchiveStatistics();
|
|
|
|
|
stats.archives.sum_size = humanFileSize(stats.archives.sum_size);
|
|
|
|
|
stats.archives.max_size = humanFileSize(stats.archives.max_size);
|
|
|
|
|
stats.historical.average_size = humanFileSize(stats.historical.average_size);
|
|
|
|
|
setStatistics(stats);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
|
|
|
|
setStatistics(undefined); // Display error.
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchStatistics();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return {statistics, fetchStatistics}
|
|
|
|
|
}
|
|
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
export const useInventories = () => {
|
|
|
|
|
// Single in-memory store: every inventory (full) is loaded once. The list, the selected inventory's items,
|
|
|
|
|
// the summary, location suggestions, and the ration calculator all derive from this — no per-action GETs.
|
|
|
|
|
// Mutations persist the whole changed inventory (optimistically) instead of calling granular endpoints.
|
|
|
|
|
const [inventories, setInventories] = useState(null);
|
|
|
|
|
const ref = useRef([]);
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
ref.current = inventories || [];
|
|
|
|
|
}, [inventories]);
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
const fetchInventories = async () => {
|
|
|
|
|
const result = await getInventories();
|
|
|
|
|
if (Array.isArray(result)) {
|
|
|
|
|
setInventories(result);
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
};
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
useEffect(() => {
|
|
|
|
|
fetchInventories();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
// Persist a patch ({name?, fields?, items?}) to one inventory: update locally first for snappy UI, then save.
|
|
|
|
|
// On conflict/error the saved value is null, so we re-fetch to reconcile with the server.
|
|
|
|
|
const persistInventory = async (slug, patch) => {
|
|
|
|
|
const current = ref.current.find(i => i.slug === slug);
|
|
|
|
|
const version = current ? current.version : undefined;
|
|
|
|
|
setInventories(prev => (prev || []).map(i => i.slug === slug ? {...i, ...patch} : i));
|
|
|
|
|
const saved = await saveInventory(slug, {...patch, version});
|
|
|
|
|
if (saved) {
|
|
|
|
|
setInventories(prev => (prev || []).map(i => i.slug === slug ? saved : i));
|
|
|
|
|
} else {
|
|
|
|
|
await fetchInventories();
|
2022-08-06 05:22:07 +00:00
|
|
|
}
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
return saved;
|
|
|
|
|
};
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
const addInventory = async (name, type) => {
|
|
|
|
|
const inventory = await createInventory({name, type});
|
|
|
|
|
if (inventory) {
|
|
|
|
|
setInventories(prev => [...(prev || []), inventory]);
|
|
|
|
|
}
|
|
|
|
|
return inventory;
|
|
|
|
|
};
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
const removeInventory = async (slug) => {
|
|
|
|
|
const response = await deleteInventory(slug);
|
|
|
|
|
if (response.ok) {
|
|
|
|
|
setInventories(prev => (prev || []).filter(i => i.slug !== slug));
|
|
|
|
|
}
|
|
|
|
|
return response;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return {inventories, fetchInventories, persistInventory, addInventory, removeInventory}
|
2022-05-01 21:03:30 -06:00
|
|
|
}
|
2022-12-15 11:48:46 -07:00
|
|
|
|
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.
Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
into memory and the single source of truth. New reusable MultiFileConfig
(wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
(text/number/quantity/date/select/location/calories). Unit math/aggregation
moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
inventory save with version-based optimistic concurrency; 404 for missing),
DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
(pound->lb), and an alembic migration drops the tables.
Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
calories column, and embeds a ration estimate (how long the stock lasts).
Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
catalog_defaults.yaml (~60 generic items, total calories per package) with
merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
modal, and entry-row pre-fill of category/size/calories from a name match.
Calculators
- Generic Food Storage planner (like the Water calculator): household +
editable per-person/year amounts -> total to store over a chosen duration,
with women/children weighted by DGA calorie shares and an imperial/metric
toggle.
Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:20:10 -06:00
|
|
|
// The shared food catalog: load once, persist the whole list on change (optimistic).
|
|
|
|
|
export const useCatalog = () => {
|
|
|
|
|
const [catalog, setCatalog] = useState(null);
|
|
|
|
|
|
|
|
|
|
const fetchCatalog = async () => {
|
|
|
|
|
const result = await getCatalog();
|
|
|
|
|
if (Array.isArray(result)) {
|
|
|
|
|
setCatalog(result);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
fetchCatalog();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const persistCatalog = async (items) => {
|
|
|
|
|
setCatalog(items);
|
|
|
|
|
const saved = await saveCatalog(items);
|
|
|
|
|
if (Array.isArray(saved)) {
|
|
|
|
|
setCatalog(saved);
|
|
|
|
|
} else {
|
|
|
|
|
await fetchCatalog();
|
|
|
|
|
}
|
|
|
|
|
return saved;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return {catalog, fetchCatalog, persistCatalog};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Pool location suggestions from every inventory's `location`-type fields (shared across inventories).
|
|
|
|
|
export const collectLocations = (inventories) => {
|
|
|
|
|
const locations = new Set();
|
|
|
|
|
(inventories || []).forEach(inv => {
|
|
|
|
|
const keys = (inv.fields || []).filter(f => f.type === 'location').map(f => f.key);
|
|
|
|
|
if (keys.length === 0) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
(inv.items || []).forEach(item => keys.forEach(k => {
|
|
|
|
|
if (item[k]) {
|
|
|
|
|
locations.add(item[k]);
|
|
|
|
|
}
|
|
|
|
|
}));
|
|
|
|
|
});
|
|
|
|
|
return Array.from(locations).sort();
|
|
|
|
|
};
|
|
|
|
|
|
2022-12-16 11:10:01 -07:00
|
|
|
export const useStatistics = () => {
|
2022-12-15 11:48:46 -07:00
|
|
|
const [statistics, setStatistics] = useState();
|
|
|
|
|
|
|
|
|
|
const fetchFileStatistics = async () => {
|
|
|
|
|
try {
|
2022-12-16 11:10:01 -07:00
|
|
|
const s = await getStatistics();
|
|
|
|
|
setStatistics(s);
|
2022-12-15 11:48:46 -07:00
|
|
|
} catch (e) {
|
|
|
|
|
console.error(e);
|
2022-12-15 13:50:58 -07:00
|
|
|
setStatistics(undefined);
|
2022-12-15 11:48:46 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-12-16 11:10:01 -07:00
|
|
|
setStatistics({});
|
2022-12-15 11:48:46 -07:00
|
|
|
fetchFileStatistics();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
return {statistics};
|
|
|
|
|
}
|
2023-04-09 14:13:36 -06:00
|
|
|
|
|
|
|
|
export const useSearchFilter = () => {
|
|
|
|
|
const [filter, setFilter] = useOneQuery('filter');
|
|
|
|
|
return {filter, setFilter}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useSearchDomain = () => {
|
|
|
|
|
const [domains] = useDomains();
|
|
|
|
|
const [domain, setDomain] = useOneQuery('domain');
|
|
|
|
|
return {domain, domains, setDomain}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useSearchView = () => {
|
|
|
|
|
const [view, setView] = useOneQuery('view');
|
|
|
|
|
return {view, setView}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useSearchOrder = () => {
|
2023-04-12 16:09:09 -06:00
|
|
|
const [sort, setSort] = useOneQuery('order');
|
|
|
|
|
return {sort, setSort}
|
2023-04-09 14:13:36 -06:00
|
|
|
}
|
2023-04-18 22:03:45 -06:00
|
|
|
|
2026-06-27 09:48:21 -06:00
|
|
|
export const useSearchCensored = () => {
|
|
|
|
|
// Filters Videos to only those which are no longer available for download (?censored=true).
|
|
|
|
|
const [value, setValue] = useOneQuery('censored');
|
|
|
|
|
const censored = value === 'true';
|
|
|
|
|
const setCensored = (newValue) => setValue(newValue ? 'true' : undefined);
|
|
|
|
|
return {censored, setCensored}
|
|
|
|
|
}
|
|
|
|
|
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
export const useSearchDeep = () => {
|
|
|
|
|
// Search all text including captions/document contents (?deep=true). Slower, but more thorough.
|
|
|
|
|
const [value, setValue] = useOneQuery('deep');
|
|
|
|
|
const deep = value === 'true';
|
|
|
|
|
const setDeep = (newValue) => setValue(newValue ? 'true' : undefined);
|
|
|
|
|
return {deep, setDeep}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-14 14:01:07 -06:00
|
|
|
export const useSearchDate = () => {
|
|
|
|
|
// Filters files using
|
|
|
|
|
// ?month=1&month=2&month=3
|
|
|
|
|
// and
|
|
|
|
|
// ?fromDate=2023&toDate=2024
|
2024-03-06 17:41:04 -07:00
|
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
|
|
|
const months = searchParams.getAll('month');
|
|
|
|
|
let fromDate = searchParams.get('fromDate');
|
|
|
|
|
let toDate = searchParams.get('toDate');
|
|
|
|
|
fromDate = fromDate ? parseInt(fromDate) : null;
|
|
|
|
|
toDate = toDate ? parseInt(toDate) : null;
|
|
|
|
|
|
2024-04-14 14:01:07 -06:00
|
|
|
const clearDate = () => {
|
|
|
|
|
console.log('clearDate');
|
|
|
|
|
updateQuery({fromDate: null, toDate: null, month: null, 'o': 0});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const setDates = (newFromDate, newToDate, newMonths) => {
|
|
|
|
|
console.log('setDates', newFromDate, newToDate, newMonths);
|
|
|
|
|
updateQuery({fromDate: newFromDate, toDate: newToDate, month: newMonths, 'o': 0});
|
2024-03-06 17:41:04 -07:00
|
|
|
}
|
|
|
|
|
|
2024-05-25 10:48:08 -06:00
|
|
|
const anySearch = (months && months.length > 0) || (fromDate !== null || toDate !== null);
|
|
|
|
|
const isEmpty = !anySearch;
|
|
|
|
|
|
|
|
|
|
return {dateRange: [fromDate, toDate], setDates, months, clearDate, isEmpty}
|
2024-03-06 17:41:04 -07:00
|
|
|
}
|
|
|
|
|
|
2023-04-18 22:03:45 -06:00
|
|
|
export const useUploadFile = () => {
|
|
|
|
|
const [files, setFiles] = useState([]);
|
|
|
|
|
const [progresses, setProgresses] = useState({});
|
|
|
|
|
const [destination, setDestination] = useState('');
|
2024-07-21 15:04:56 -06:00
|
|
|
const [tagNames, setTagNames] = React.useState([]);
|
2025-02-03 17:16:13 -07:00
|
|
|
const [overwrite, setOverwrite] = React.useState(false);
|
2025-05-14 18:25:00 -06:00
|
|
|
const [totalSize, setTotalSize] = useState(0);
|
|
|
|
|
const [uploadedSize, setUploadedSize] = useState(0);
|
|
|
|
|
const [overallProgress, setOverallProgress] = useState(0);
|
|
|
|
|
const [inProgress, setInProgress] = useState(false);
|
2023-04-18 22:03:45 -06:00
|
|
|
|
|
|
|
|
const handleProgress = (name, chunk, totalChunks, status, type) => {
|
|
|
|
|
const percent = Math.round((100 * chunk) / totalChunks);
|
|
|
|
|
const newProgress = {[name]: {percent, status, type}};
|
2025-05-14 18:25:00 -06:00
|
|
|
|
|
|
|
|
setProgresses(prevState => {
|
|
|
|
|
const updatedProgresses = {...prevState, ...newProgress};
|
|
|
|
|
|
|
|
|
|
// Calculate total uploaded size based on all files' progress
|
|
|
|
|
let totalUploaded = 0;
|
|
|
|
|
files.forEach(file => {
|
|
|
|
|
const fileProgress = updatedProgresses[file.name];
|
|
|
|
|
if (fileProgress) {
|
|
|
|
|
const chunkSize = 10 * 1024 * 1024; // 10MB - same as in doUpload
|
|
|
|
|
const fileSize = file.size;
|
|
|
|
|
const totalFileChunks = Math.ceil(fileSize / chunkSize);
|
|
|
|
|
|
|
|
|
|
// For completed files, count the full size
|
|
|
|
|
if (fileProgress.status === 'complete' || fileProgress.status === 'conflicting') {
|
|
|
|
|
totalUploaded += fileSize;
|
|
|
|
|
}
|
|
|
|
|
// For files in progress, count the completed chunks
|
|
|
|
|
else if (fileProgress.percent > 0) {
|
|
|
|
|
const completedChunks = Math.floor((fileProgress.percent / 100) * totalFileChunks);
|
|
|
|
|
const completedSize = Math.min(completedChunks * chunkSize, fileSize);
|
|
|
|
|
totalUploaded += completedSize;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
setUploadedSize(totalUploaded);
|
|
|
|
|
|
|
|
|
|
if (totalSize > 0) {
|
|
|
|
|
const newOverallProgress = Math.round((totalUploaded / totalSize) * 100);
|
|
|
|
|
setOverallProgress(newOverallProgress);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return updatedProgresses;
|
|
|
|
|
});
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const handleFilesChange = (newFiles) => {
|
|
|
|
|
let newProgresses = {};
|
2025-05-14 18:25:00 -06:00
|
|
|
let newTotalSize = 0;
|
|
|
|
|
|
|
|
|
|
newFiles.forEach(file => {
|
|
|
|
|
newProgresses = {...newProgresses, [file.name]: {percent: 0, status: 'pending'}};
|
|
|
|
|
newTotalSize += file.size;
|
2023-04-18 22:03:45 -06:00
|
|
|
});
|
2025-05-14 18:25:00 -06:00
|
|
|
|
2023-04-18 22:03:45 -06:00
|
|
|
setProgresses(newProgresses);
|
|
|
|
|
setFiles(newFiles);
|
2025-05-14 18:25:00 -06:00
|
|
|
setTotalSize(newTotalSize);
|
|
|
|
|
setUploadedSize(0);
|
|
|
|
|
setOverallProgress(0);
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const doUpload = async () => {
|
ui: two upload dialogs that had drifted apart (#664)
* ui: two upload dialogs that had drifted apart
The dashboard and the file browser each had their own upload component: two
dropzones, two overwrite toggles, two copies of the progress-bar rendering,
against the same `useUploadFile` state. The file browser's dialog was made
fullscreen with a drop target that grows; the dashboard's stayed a `large`
dialog with a strip to drop onto, because it was a different file.
They differ in one thing that is real: the file browser knows the destination
because the user selected it, and the dashboard has to ask. That is now the
`destination` prop -- `undefined` asks, a string uploads there, and '' is the
media directory rather than a missing destination.
Everything else is one component, so the next change to either entry point
lands on both.
* review: an upload dialog that looped on the media directory
Pressing Upload in the file browser with nothing selected passes `''` -- the
media directory. Three checks along that path read it as "no destination":
* The clearing effect ran, and `doClear` is a new function every render whose
own setState scheduled the next one. React ended it with "Maximum update
depth exceeded", 16 warnings deep, on the default Upload path. The effect
now clears only while asking, and `doClear` is stable.
* The title read `Upload to: /media/wrolpi/`.
* `doUpload` bailed, so a drop on the media root uploaded nothing.
All three predate this branch; moving the dialog is what put them behind one
component. Tests cover the title, what the hook is told, and that a fixed
destination is never the thing that empties the queue.
2026-08-13 15:14:53 -06:00
|
|
|
// `''` is the media directory, which the file browser uploads to when no folder is
|
|
|
|
|
// selected; only a missing destination means there is nowhere to put the files.
|
|
|
|
|
if (!files || files.length === 0 || destination === null || destination === undefined) {
|
2023-04-18 22:03:45 -06:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-05-14 18:25:00 -06:00
|
|
|
setInProgress(true);
|
|
|
|
|
|
2023-04-18 22:03:45 -06:00
|
|
|
for (let i = 0; i < files.length; i++) {
|
|
|
|
|
const file = files[i];
|
2024-10-16 13:13:45 -06:00
|
|
|
console.log(`Uploading file:`, file.path);
|
2023-04-18 22:03:45 -06:00
|
|
|
|
|
|
|
|
const chunkNum = 0;
|
|
|
|
|
const chunkSize = 10 * 1024 * 1024; // 10MB
|
|
|
|
|
const totalChunks = Math.ceil(file.size / chunkSize);
|
|
|
|
|
const tries = 0;
|
|
|
|
|
const maxTries = 20;
|
|
|
|
|
|
2025-05-14 18:25:00 -06:00
|
|
|
// Start recursive function to upload the file and wait for it to complete
|
|
|
|
|
// before moving to the next file
|
|
|
|
|
try {
|
|
|
|
|
await new Promise((resolve, reject) => {
|
|
|
|
|
const uploadNextChunk = async (currentChunkNum, currentTries) => {
|
|
|
|
|
if (currentTries > maxTries) {
|
|
|
|
|
console.error(`Exceeded max tries ${maxTries}`);
|
|
|
|
|
reject(new Error(`Exceeded max tries ${maxTries}`));
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const start = currentChunkNum * chunkSize;
|
|
|
|
|
const end = Math.min(start + chunkSize, file.size);
|
|
|
|
|
const chunk = file.slice(start, end);
|
|
|
|
|
|
|
|
|
|
const formData = new FormData();
|
|
|
|
|
formData.append('chunkNumber', currentChunkNum.toString());
|
|
|
|
|
formData.append('filename', file.path);
|
|
|
|
|
formData.append('totalChunks', totalChunks.toString());
|
|
|
|
|
formData.append('destination', destination);
|
|
|
|
|
formData.append('mkdir', 'true');
|
|
|
|
|
if (overwrite) {
|
|
|
|
|
formData.append('overwrite', 'true');
|
|
|
|
|
}
|
|
|
|
|
formData.append('chunkSize', chunk.size.toString());
|
|
|
|
|
formData.append('chunk', chunk);
|
|
|
|
|
for (let j = 0; j < tagNames.length; j++) {
|
|
|
|
|
formData.append('tagNames', tagNames[j]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.debug(`file upload: tries=${currentTries} chunkNum=${currentChunkNum} totalChunks=${totalChunks} chunkSize=${chunk.size} destination=${destination} tagNames=${tagNames}`);
|
|
|
|
|
|
|
|
|
|
// Create a new XMLHttpRequest for each chunk to avoid InvalidStateError
|
|
|
|
|
const chunkXhr = new XMLHttpRequest();
|
|
|
|
|
chunkXhr.open('POST', '/api/files/upload', true);
|
|
|
|
|
|
|
|
|
|
chunkXhr.onreadystatechange = async () => {
|
|
|
|
|
if (chunkXhr.readyState === 4) {
|
|
|
|
|
if (chunkXhr.status === 200 || chunkXhr.status === 416) {
|
|
|
|
|
const data = JSON.parse(chunkXhr.responseText);
|
|
|
|
|
handleProgress(file.name, currentChunkNum, totalChunks, 'pending', file.type);
|
|
|
|
|
const expectedChunk = data['expected_chunk'];
|
|
|
|
|
if (chunkXhr.status === 416) {
|
|
|
|
|
console.warn(`Server requested a different chunk ${currentChunkNum}`);
|
|
|
|
|
uploadNextChunk(expectedChunk, currentTries + 1);
|
|
|
|
|
} else {
|
|
|
|
|
console.debug(`Uploading of chunk ${currentChunkNum} succeeded, got request for chunk ${expectedChunk}`);
|
|
|
|
|
// Success, reset tries.
|
|
|
|
|
uploadNextChunk(expectedChunk, 0);
|
|
|
|
|
}
|
|
|
|
|
} else if (chunkXhr.status === 201) {
|
|
|
|
|
handleProgress(file.name, totalChunks, totalChunks, 'complete', file.type);
|
|
|
|
|
console.info(`Uploading of ${file.path} completed.`);
|
|
|
|
|
resolve(); // File upload completed successfully
|
|
|
|
|
} else if (chunkXhr.status === 400) {
|
|
|
|
|
handleProgress(file.name, totalChunks, totalChunks, 'conflicting', file.type);
|
|
|
|
|
const data = JSON.parse(chunkXhr.responseText);
|
|
|
|
|
if (data['code'] === 'FILE_UPLOAD_FAILED') {
|
|
|
|
|
console.error('File already exists. Giving up.');
|
|
|
|
|
reject(new Error('File already exists'));
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
handleProgress(file.name, totalChunks, totalChunks, 'failed', file.type);
|
|
|
|
|
console.error(`Failed to upload chunk ${currentChunkNum}. Giving up.`);
|
|
|
|
|
reject(new Error(`Failed to upload chunk ${currentChunkNum}`));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
chunkXhr.send(formData);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Start uploading the first chunk
|
|
|
|
|
uploadNextChunk(chunkNum, tries);
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error(`Error uploading file ${file.path}:`, error);
|
|
|
|
|
// Continue with the next file even if this one failed
|
|
|
|
|
}
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Clear form after upload.
|
|
|
|
|
setFiles([]);
|
2025-05-14 18:25:00 -06:00
|
|
|
setInProgress(false);
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
|
|
|
|
|
ui: two upload dialogs that had drifted apart (#664)
* ui: two upload dialogs that had drifted apart
The dashboard and the file browser each had their own upload component: two
dropzones, two overwrite toggles, two copies of the progress-bar rendering,
against the same `useUploadFile` state. The file browser's dialog was made
fullscreen with a drop target that grows; the dashboard's stayed a `large`
dialog with a strip to drop onto, because it was a different file.
They differ in one thing that is real: the file browser knows the destination
because the user selected it, and the dashboard has to ask. That is now the
`destination` prop -- `undefined` asks, a string uploads there, and '' is the
media directory rather than a missing destination.
Everything else is one component, so the next change to either entry point
lands on both.
* review: an upload dialog that looped on the media directory
Pressing Upload in the file browser with nothing selected passes `''` -- the
media directory. Three checks along that path read it as "no destination":
* The clearing effect ran, and `doClear` is a new function every render whose
own setState scheduled the next one. React ended it with "Maximum update
depth exceeded", 16 warnings deep, on the default Upload path. The effect
now clears only while asking, and `doClear` is stable.
* The title read `Upload to: /media/wrolpi/`.
* `doUpload` bailed, so a drop on the media root uploaded nothing.
All three predate this branch; moving the dialog is what put them behind one
component. Tests cover the title, what the hook is told, and that a fixed
destination is never the thing that empties the queue.
2026-08-13 15:14:53 -06:00
|
|
|
// Stable across renders. Callers put it in effect dependencies, and every call sets state
|
|
|
|
|
// with fresh objects -- an unstable identity there re-runs the effect on the render its own
|
|
|
|
|
// setState caused, which React ends with "Maximum update depth exceeded".
|
|
|
|
|
const doClear = React.useCallback(() => {
|
2023-04-18 22:03:45 -06:00
|
|
|
setFiles([]);
|
|
|
|
|
setProgresses({});
|
2025-05-14 18:25:00 -06:00
|
|
|
setTotalSize(0);
|
|
|
|
|
setUploadedSize(0);
|
|
|
|
|
setOverallProgress(0);
|
|
|
|
|
setInProgress(false);
|
ui: two upload dialogs that had drifted apart (#664)
* ui: two upload dialogs that had drifted apart
The dashboard and the file browser each had their own upload component: two
dropzones, two overwrite toggles, two copies of the progress-bar rendering,
against the same `useUploadFile` state. The file browser's dialog was made
fullscreen with a drop target that grows; the dashboard's stayed a `large`
dialog with a strip to drop onto, because it was a different file.
They differ in one thing that is real: the file browser knows the destination
because the user selected it, and the dashboard has to ask. That is now the
`destination` prop -- `undefined` asks, a string uploads there, and '' is the
media directory rather than a missing destination.
Everything else is one component, so the next change to either entry point
lands on both.
* review: an upload dialog that looped on the media directory
Pressing Upload in the file browser with nothing selected passes `''` -- the
media directory. Three checks along that path read it as "no destination":
* The clearing effect ran, and `doClear` is a new function every render whose
own setState scheduled the next one. React ended it with "Maximum update
depth exceeded", 16 warnings deep, on the default Upload path. The effect
now clears only while asking, and `doClear` is stable.
* The title read `Upload to: /media/wrolpi/`.
* `doUpload` bailed, so a drop on the media root uploaded nothing.
All three predate this branch; moving the dialog is what put them behind one
component. Tests cover the title, what the hook is told, and that a fixed
destination is never the thing that empties the queue.
2026-08-13 15:14:53 -06:00
|
|
|
}, []);
|
2023-04-18 22:03:45 -06:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
doUpload()
|
|
|
|
|
}, [JSON.stringify(files)]);
|
|
|
|
|
|
2024-07-22 16:36:57 -06:00
|
|
|
const tagsSelector = <TagsSelector selectedTagNames={tagNames} onChange={(i,) => setTagNames(i)}/>;
|
2024-07-21 15:04:56 -06:00
|
|
|
|
|
|
|
|
return {
|
2025-02-03 17:16:13 -07:00
|
|
|
destination, setDestination,
|
2024-07-21 15:04:56 -06:00
|
|
|
doClear,
|
|
|
|
|
doUpload,
|
|
|
|
|
files,
|
|
|
|
|
progresses,
|
|
|
|
|
setFiles: handleFilesChange,
|
|
|
|
|
tagNames,
|
|
|
|
|
tagsSelector,
|
2025-02-03 17:16:13 -07:00
|
|
|
overwrite, setOverwrite,
|
2025-05-14 18:25:00 -06:00
|
|
|
overallProgress,
|
|
|
|
|
totalSize,
|
|
|
|
|
uploadedSize,
|
|
|
|
|
inProgress,
|
2024-07-21 15:04:56 -06:00
|
|
|
}
|
2023-04-18 22:03:45 -06:00
|
|
|
}
|
2023-06-11 12:31:56 -06:00
|
|
|
|
2023-05-29 18:04:03 -06:00
|
|
|
export const useSearchZim = (searchStr, zimId, active, activeTags, defaultLimit = 10) => {
|
|
|
|
|
const [zim, setZim] = useState(null);
|
|
|
|
|
const pages = usePages(defaultLimit);
|
|
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const localFetchSearch = async () => {
|
|
|
|
|
if (!active) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
setLoading(true);
|
|
|
|
|
try {
|
|
|
|
|
const zim = await searchZim(pages.offset, pages.limit, searchStr, zimId, activeTags);
|
|
|
|
|
setZim(zim);
|
|
|
|
|
pages.setTotal(zim.estimate);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
pages.setTotal(0);
|
|
|
|
|
console.error(`Failed to search Zim ${zimId}`);
|
|
|
|
|
console.error(e);
|
|
|
|
|
}
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localFetchSearch();
|
|
|
|
|
}, [active, searchStr, JSON.stringify(activeTags), pages.effect]);
|
|
|
|
|
|
|
|
|
|
return {zim, fetchSearch: localFetchSearch, pages, loading}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useOutdatedZims = () => {
|
|
|
|
|
const [outdated, setOutdated] = useState(null);
|
|
|
|
|
const [current, setCurrent] = useState(null);
|
|
|
|
|
|
|
|
|
|
const localFetchOutdatedZims = async () => {
|
|
|
|
|
const zims = await getOutdatedZims();
|
|
|
|
|
setOutdated(zims['outdated']);
|
|
|
|
|
setCurrent(zims['current']);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localFetchOutdatedZims();
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-09-12 15:18:13 -06:00
|
|
|
return {outdated, current, fetchOutdatedZims: localFetchOutdatedZims}
|
2023-05-29 18:04:03 -06:00
|
|
|
}
|
|
|
|
|
|
2023-06-11 12:31:56 -06:00
|
|
|
export const useVINDecoder = (defaultVINNumber = '') => {
|
|
|
|
|
const [value, setValue] = useState(defaultVINNumber);
|
|
|
|
|
// The response vin from the API.
|
|
|
|
|
const [vin, setVin] = useState(null);
|
|
|
|
|
|
|
|
|
|
const localFetchDecoded = async () => {
|
|
|
|
|
if (!value) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const vin = await fetchDecoded(value);
|
|
|
|
|
setVin(vin);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.error('Failed to decode VIN number');
|
|
|
|
|
setVin(null);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localFetchDecoded();
|
|
|
|
|
}, [value]);
|
|
|
|
|
|
|
|
|
|
return {value, setValue, vin}
|
|
|
|
|
}
|
2023-07-21 15:14:09 -06:00
|
|
|
|
|
|
|
|
export const useWROLMode = () => {
|
|
|
|
|
// Returns the current boolean WROL Mode, during fetch this returns null.
|
2025-12-11 18:32:55 -07:00
|
|
|
const {settings} = useContext(SettingsContext);
|
|
|
|
|
return settings ? settings.wrol_mode : null;
|
2023-08-17 20:07:02 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useDockerized = () => {
|
|
|
|
|
const {status} = React.useContext(StatusContext);
|
|
|
|
|
return status && status['dockerized'] === true;
|
|
|
|
|
}
|
2024-05-31 23:53:30 -06:00
|
|
|
|
|
|
|
|
export const useCalcQuery = () => {
|
|
|
|
|
const [calc, setCalc] = useOneQuery('calc');
|
2025-01-19 11:58:43 -07:00
|
|
|
return [calc, setCalc]
|
2024-08-15 19:32:01 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const useSearchChannels = (defaultTagNames) => {
|
|
|
|
|
const [tagNames, setTagNames] = useState(defaultTagNames || []);
|
|
|
|
|
const [channels, setChannels] = useState([]);
|
|
|
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
|
|
|
|
|
|
const localSearchChannels = async () => {
|
|
|
|
|
setLoading(true);
|
|
|
|
|
try {
|
|
|
|
|
const {channels: newChannels} = await searchChannels(tagNames);
|
|
|
|
|
setChannels(newChannels);
|
|
|
|
|
} finally {
|
|
|
|
|
setLoading(false);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
localSearchChannels();
|
|
|
|
|
}, [tagNames]);
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
tagNames,
|
|
|
|
|
setTagNames,
|
|
|
|
|
channels,
|
|
|
|
|
loading,
|
|
|
|
|
}
|
2025-05-14 18:25:00 -06:00
|
|
|
}
|
2026-05-02 14:31:54 -06:00
|
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Detect whether the WROLPi browser extension is installed AND has this
|
|
|
|
|
* destination configured. The extension's background worker dynamically
|
|
|
|
|
* registers a content script on each configured destination origin; that
|
|
|
|
|
* script appends `<meta name="wrolpi-extension" content="<version>">` to the
|
|
|
|
|
* head. We read for that marker.
|
|
|
|
|
*
|
|
|
|
|
* Three-state result so callers can avoid flashing UI during the race
|
|
|
|
|
* between React's first render and the content script's document_idle:
|
|
|
|
|
* null — checking; render nothing
|
|
|
|
|
* false — confirmed absent (after recheck); show "install me" UI
|
|
|
|
|
* <string> — installed; the version string the extension reported
|
|
|
|
|
*
|
|
|
|
|
* Observes <head> for a late-arriving marker (e.g., the user installs the
|
|
|
|
|
* extension while the page is open, or grants the destination permission
|
|
|
|
|
* after page load) so the banner clears without requiring a manual reload.
|
|
|
|
|
*/
|
|
|
|
|
export function useExtensionInstalled() {
|
|
|
|
|
const detect = () => {
|
|
|
|
|
const meta = document.querySelector('meta[name="wrolpi-extension"]');
|
|
|
|
|
if (!meta) return null;
|
|
|
|
|
return meta.getAttribute('content') || true;
|
|
|
|
|
};
|
|
|
|
|
const [state, setState] = useState(detect);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
// Observe <head> for the marker meta tag appearing at any time.
|
|
|
|
|
// Once we see it we clean up — there's no need to keep watching.
|
|
|
|
|
const observer = new MutationObserver(() => {
|
|
|
|
|
const result = detect();
|
|
|
|
|
if (result) setState(result);
|
|
|
|
|
});
|
|
|
|
|
if (document.head) {
|
|
|
|
|
observer.observe(document.head, {childList: true, subtree: true});
|
|
|
|
|
}
|
|
|
|
|
return () => observer.disconnect();
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (state !== null) return;
|
|
|
|
|
// Recheck once after the document_idle window closes; only then
|
|
|
|
|
// commit to "false". Avoids flashing the banner on every dashboard
|
|
|
|
|
// load while we're just waiting for the content script to run.
|
|
|
|
|
const t = setTimeout(() => setState(detect() ?? false), 500);
|
|
|
|
|
return () => clearTimeout(t);
|
|
|
|
|
}, [state]);
|
|
|
|
|
|
|
|
|
|
return state;
|
|
|
|
|
}
|