mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-19 22:46:20 -05:00
* Resume videos and audio where the user left off; show progress on cards Videos and audio resume where the user left off, on the video page and in the file preview, and keep playing. `?t=` starts at an explicit time instead. useFileProgress saves how far the user is through a file: every 15 seconds while it changes, and a final save (a beacon, which survives the page closing) on pause, end, hiding the page, leaving it, or switching files. Each save is also kept in sessionStorage; on open the newer of that and the server's position wins, so coming straight back resumes exactly even if the final save is still in flight. Cards show a progress bar along the bottom of their poster. The dashboard's Recently Viewed Files gains All / Continue; Continue uses the new `in_progress` file search filter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Progress review fixes: in_progress totals, latest dashboard request, preview viewed - The in_progress search filter skips the uncounted fast path and is part of the totals cache key, so Continue never reports All's (or the library's) count. - The dashboard's Recently Viewed hook applies only its latest response, and clears the list when switching All/Continue until the new files arrive. - POST /api/files/file returns `viewed`, so a preview can tell a file finished elsewhere from an older position this tab holds. - The progress hook tests restore Blob, fetch and sendBeacon. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2272 lines
76 KiB
JavaScript
2272 lines
76 KiB
JavaScript
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
|
|
import {
|
|
ApiDownError,
|
|
createChannel,
|
|
fetchChannels,
|
|
fetchDecoded,
|
|
fetchAuthors,
|
|
fetchDomains,
|
|
fetchSubjects,
|
|
filesSearch,
|
|
getArchive,
|
|
getDoc,
|
|
getArchiveStatistics,
|
|
getChannel,
|
|
getConfigs,
|
|
getDomain,
|
|
getDownloads,
|
|
getFiles,
|
|
getInventories,
|
|
createInventory,
|
|
saveInventory,
|
|
deleteInventory,
|
|
getCatalog,
|
|
saveCatalog,
|
|
getOutdatedZims,
|
|
getSettings,
|
|
getStatistics,
|
|
getStatus,
|
|
getVideo,
|
|
getVideoCaptions,
|
|
getVideoComments,
|
|
getVideoDescription,
|
|
getVideosStatistics,
|
|
postDumpConfig,
|
|
postImportConfig,
|
|
saveSettings,
|
|
searchArchives,
|
|
searchChannels,
|
|
searchCollections,
|
|
searchDirectories,
|
|
searchDocs,
|
|
searchRepos,
|
|
searchVideos,
|
|
searchZim,
|
|
updateChannel,
|
|
updateDomain,
|
|
} from "../api";
|
|
import {
|
|
unblockBluetooth,
|
|
blockBluetooth,
|
|
startHotspot,
|
|
stopHotspot,
|
|
startDesktop,
|
|
stopDesktop,
|
|
startVnc,
|
|
stopVnc,
|
|
enableThrottle,
|
|
disableThrottle,
|
|
getControllerStats,
|
|
} from "../api/controller";
|
|
import {createSearchParams, useLocation, useSearchParams} from "react-router";
|
|
import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common";
|
|
import {QueryContext, SettingsContext, StatusContext} from "../contexts/contexts";
|
|
import {toast} from "../components/ui";
|
|
import {useSearch} from "../components/Search";
|
|
import _ from "lodash";
|
|
import {TagsSelector} from "../Tags";
|
|
import {useForm} from "./useForm";
|
|
|
|
export const useIsTouchDevice = () => {
|
|
// Detects if the device has a coarse pointer (touch screen).
|
|
// Used to disable drag selection on mobile devices.
|
|
// 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;
|
|
});
|
|
|
|
useEffect(() => {
|
|
const touchQuery = window.matchMedia('(pointer: coarse)');
|
|
|
|
const handleChange = (e) => setIsTouchDevice(e.matches);
|
|
touchQuery.addEventListener('change', handleChange);
|
|
|
|
return () => touchQuery.removeEventListener('change', handleChange);
|
|
}, []);
|
|
|
|
return isTouchDevice;
|
|
};
|
|
|
|
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];
|
|
};
|
|
|
|
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;
|
|
};
|
|
|
|
const calculatePage = (offset, limit) => {
|
|
return offset && limit ? Math.round((offset / limit) + 1) : 1;
|
|
}
|
|
|
|
const calculateTotalPages = (total, limit) => {
|
|
// Return the total divided by the limit, but always at least 1.
|
|
if (!total || !limit || total < limit) {
|
|
return 1;
|
|
}
|
|
return Math.ceil(total / limit);
|
|
}
|
|
|
|
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])
|
|
}
|
|
|
|
export const useLatestRequest = (delay = 300, defaultLoading = false) => {
|
|
// A hook which ignores older requests and will only set `data` to the latest response's data.
|
|
// usage: sendRequest(async () => await yourAPICall(...args));
|
|
//
|
|
// Invariants:
|
|
// * `loading` is true from the moment `sendRequest` is called until the latest request settles,
|
|
// including the debounce delay. Consumers use `loading` to choose between a spinner and an
|
|
// empty state, so it must never be false while a request is pending.
|
|
// * Only the latest request may write `data` or clear `loading`. A stale request that settles
|
|
// late (resolve or reject) is ignored.
|
|
|
|
// The results from awaiting `fetchFunction`.
|
|
const [data, setData] = React.useState(null);
|
|
const latestRequestRef = React.useRef(0);
|
|
const debounceTimerRef = React.useRef(null);
|
|
// Loading while awaiting.
|
|
const [loading, setLoading] = React.useState(defaultLoading);
|
|
|
|
const sendRequest = React.useCallback((fetchFunction) => {
|
|
if (debounceTimerRef.current) {
|
|
clearTimeout(debounceTimerRef.current);
|
|
}
|
|
// Claim the latest id now, not when the debounce fires, so an earlier fetch that is still
|
|
// in flight is already stale and cannot write `data` or clear `loading` while this
|
|
// request is pending.
|
|
const requestId = ++latestRequestRef.current;
|
|
// Report the pending request before the debounce so the caller never shows "no results"
|
|
// for a search that has not run yet.
|
|
setLoading(true);
|
|
|
|
debounceTimerRef.current = setTimeout(async () => {
|
|
debounceTimerRef.current = null;
|
|
|
|
try {
|
|
const result = await fetchFunction();
|
|
|
|
if (requestId === latestRequestRef.current) {
|
|
setData(result);
|
|
}
|
|
} catch (error) {
|
|
console.error('Request failed:', error);
|
|
if (requestId === latestRequestRef.current) {
|
|
setData(null);
|
|
}
|
|
} finally {
|
|
if (requestId === latestRequestRef.current) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
}, delay);
|
|
}, [delay]);
|
|
|
|
// Do not fire a debounced request after the caller has unmounted, and treat any fetch still in
|
|
// flight as stale so it does not set state on the unmounted hook.
|
|
React.useEffect(() => {
|
|
return () => {
|
|
if (debounceTimerRef.current) {
|
|
clearTimeout(debounceTimerRef.current);
|
|
debounceTimerRef.current = null;
|
|
}
|
|
latestRequestRef.current++;
|
|
};
|
|
}, []);
|
|
|
|
return {data, sendRequest, loading};
|
|
};
|
|
|
|
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;
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
|
|
export const useQuery = () => {
|
|
const location = useLocation();
|
|
const [searchParams, setSearchParams] = useSearchParams();
|
|
|
|
const updateQuery = (newParams, replace = false) => {
|
|
// Update the old state with the new values.
|
|
let newSearchParams = replace ?
|
|
newParams
|
|
: {...getSearchParamCopy(searchParams), ...newParams};
|
|
newSearchParams = removeEmptyValues(newSearchParams);
|
|
console.debug('useQuery.updateQuery', newSearchParams);
|
|
setSearchParams(newSearchParams);
|
|
};
|
|
|
|
const getLocationStr = (newSearchParams, pathname) => {
|
|
// Get the current location, but with new params appended.
|
|
newSearchParams = removeEmptyValues({...getSearchParamCopy(searchParams), ...newSearchParams});
|
|
const newQuery = createSearchParams(newSearchParams);
|
|
return `${pathname || location.pathname}?${newQuery.toString()}`
|
|
}
|
|
|
|
return {searchParams, updateQuery, getLocationStr}
|
|
}
|
|
|
|
|
|
export const QueryProvider = (props) => {
|
|
return <QueryContext.Provider value={useQuery()}>
|
|
{props.children}
|
|
</QueryContext.Provider>
|
|
}
|
|
|
|
export const useOneQuery = (name) => {
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
const value = searchParams.get(name);
|
|
|
|
const setValue = (newValue, replace = false) => {
|
|
updateQuery({[name]: newValue}, replace);
|
|
}
|
|
|
|
return [value, setValue]
|
|
}
|
|
|
|
export const useAllQuery = (name) => {
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
const value = searchParams.getAll(name);
|
|
|
|
const setValue = (newValue, replace = false) => {
|
|
updateQuery({[name]: newValue}, replace);
|
|
}
|
|
|
|
return [value, setValue]
|
|
}
|
|
|
|
export const useDomains = () => {
|
|
const [domains, setDomains] = useState(null);
|
|
const [total, setTotal] = useState(null);
|
|
|
|
const _fetchDomains = async () => {
|
|
setDomains(null);
|
|
setTotal(0);
|
|
try {
|
|
let [domains, total] = await fetchDomains();
|
|
setDomains(domains);
|
|
setTotal(total);
|
|
} catch (e) {
|
|
setDomains(undefined); // Display error.
|
|
setTotal(0);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
_fetchDomains();
|
|
}, []);
|
|
|
|
return [domains, total];
|
|
}
|
|
|
|
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 {
|
|
const response = await getDoc(fileGroupId);
|
|
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};
|
|
}
|
|
|
|
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};
|
|
}
|
|
|
|
export const useArchive = (fileGroupId) => {
|
|
const [archiveFileGroup, setArchiveFileGroup] = useState(null);
|
|
const [history, setHistory] = useState(null);
|
|
|
|
const fetchArchive = async () => {
|
|
try {
|
|
const {file_group, history} = await getArchive(fileGroupId);
|
|
setArchiveFileGroup(file_group);
|
|
setHistory(history);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setArchiveFileGroup(undefined);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchArchive();
|
|
}, [fileGroupId]);
|
|
|
|
return {archiveFile: archiveFileGroup, history, fetchArchive};
|
|
}
|
|
|
|
export const usePages = (defaultLimit = 24, totalPages = 0) => {
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
const offset = searchParams.get('o') || 0;
|
|
const limit = parseInt(searchParams.get('l') || defaultLimit || 24);
|
|
const [activePage, setActivePage] = useState(calculatePage(offset, limit));
|
|
const [totalPages_, setTotalPages] = useState(totalPages);
|
|
|
|
const setLimit = (value) => {
|
|
setPage(1);
|
|
updateQuery({l: value, o: null});
|
|
}
|
|
|
|
const setPage = (value) => {
|
|
console.debug(`setPage ${value}`);
|
|
setActivePage(value);
|
|
value = value - 1; // Page really starts as 0.
|
|
updateQuery({o: value * limit});
|
|
}
|
|
|
|
const setTotal = (total) => {
|
|
const newTotalPages = calculateTotalPages(total, limit);
|
|
console.debug('newTotalPages', newTotalPages);
|
|
setTotalPages(newTotalPages);
|
|
}
|
|
|
|
// Used for useEffect.
|
|
const effect = JSON.stringify({offset, limit, activePage});
|
|
|
|
return {offset, limit, setLimit, activePage, setPage, totalPages: totalPages_, setTotal, effect};
|
|
}
|
|
|
|
export const useSearchArchives = (defaultLimit) => {
|
|
const {domain} = useSearchDomain();
|
|
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 {view} = useSearchView();
|
|
const headline = view === 'headline';
|
|
const {deep} = useSearchDeep();
|
|
|
|
const [archives, setArchives] = useState(null);
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
|
|
const localSearchArchives = async () => {
|
|
setArchives(null);
|
|
try {
|
|
let [archives_, total] = await searchArchives(offset, limit, domain, searchStr, order, activeTags, headline,
|
|
deep);
|
|
setArchives(archives_);
|
|
setTotalPages(calculateTotalPages(total, limit));
|
|
} catch (e) {
|
|
console.error(e);
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: 'Could not get archives',
|
|
time: 5000,
|
|
});
|
|
setArchives(undefined); // Could not get Archives, display error.
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
localSearchArchives();
|
|
}, [searchStr, limit, domain, order, offset, JSON.stringify(activeTags), headline, deep]);
|
|
|
|
const setSearchStr = (value) => {
|
|
updateQuery({q: value, o: 0, order: undefined});
|
|
}
|
|
|
|
const setOrderBy = (value) => {
|
|
setPage(1);
|
|
updateQuery({order: value});
|
|
}
|
|
|
|
return {
|
|
archives,
|
|
limit,
|
|
setLimit,
|
|
offset,
|
|
order,
|
|
setOrderBy,
|
|
totalPages,
|
|
activePage,
|
|
setPage,
|
|
searchStr,
|
|
setSearchStr,
|
|
fetchArchives: localSearchArchives,
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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') || '';
|
|
const filter = searchParams.get('filter') || '';
|
|
const {deep} = useSearchDeep();
|
|
|
|
const [docs, setDocs] = useState(null);
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
|
|
const localSearchDocs = async () => {
|
|
setDocs(null);
|
|
try {
|
|
const mimetype = docFilterToMimetype(filter);
|
|
let [docs_, total] = await searchDocs(offset, limit, searchStr, order, activeTags, author, subject,
|
|
mimetype, deep);
|
|
setDocs(docs_);
|
|
setTotalPages(calculateTotalPages(total, limit));
|
|
} catch (e) {
|
|
console.error(e);
|
|
setDocs(undefined);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
localSearchDocs();
|
|
}, [searchStr, limit, order, offset, JSON.stringify(activeTags), author, subject, filter, deep]);
|
|
|
|
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,
|
|
}
|
|
}
|
|
|
|
export const useSearchVideos = (defaultLimit, channelId, order_by) => {
|
|
const {searchParams, updateQuery} = React.useContext(QueryContext);
|
|
const {offset, limit, setLimit, activePage, setPage} = usePages(defaultLimit);
|
|
const searchStr = searchParams.get('q') || '';
|
|
const order = searchParams.get('order') || order_by;
|
|
const activeTags = searchParams.getAll('tag');
|
|
const {view} = useSearchView();
|
|
const headline = view === 'headline';
|
|
const anyTag = searchParams.get('anyTag') === 'true';
|
|
const censored = searchParams.get('censored') === 'true';
|
|
const {deep} = useSearchDeep();
|
|
|
|
const [videos, setVideos] = useState(null);
|
|
const [totalPages, setTotalPages] = useState(0);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const localSearchVideos = async () => {
|
|
setVideos(null);
|
|
setLoading(true);
|
|
try {
|
|
let [videos_, total] = await searchVideos(offset, limit, channelId, searchStr, order, activeTags, headline,
|
|
censored, deep);
|
|
setVideos(videos_);
|
|
setTotalPages(calculateTotalPages(total, limit));
|
|
} catch (e) {
|
|
console.error(e);
|
|
setVideos(undefined);// Could not get Videos, display error.
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
localSearchVideos();
|
|
}, [searchStr, limit, channelId, offset, order_by, JSON.stringify(activeTags), headline, censored, deep]);
|
|
|
|
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,
|
|
fetchVideos: localSearchVideos,
|
|
activeTags,
|
|
loading,
|
|
}
|
|
}
|
|
|
|
export const useVideo = (fileGroupId) => {
|
|
const [videoFile, setVideoFile] = useState(null);
|
|
const [prevFile, setPrevFile] = useState(null);
|
|
const [nextFile, setNextFile] = useState(null);
|
|
|
|
const fetchVideo = async () => {
|
|
if (fileGroupId && videoFile && Number(videoFile.id) !== Number(fileGroupId)) {
|
|
// Video is changing. Clear the old video before fetching.
|
|
setVideoFile(null);
|
|
setPrevFile(null);
|
|
setNextFile(null);
|
|
}
|
|
try {
|
|
const [v, p, n] = await getVideo(fileGroupId);
|
|
setVideoFile(v);
|
|
setPrevFile(p);
|
|
setNextFile(n);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setVideoFile(undefined);
|
|
setPrevFile(undefined);
|
|
setNextFile(undefined);
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: 'Could not get the video',
|
|
time: 5000,
|
|
})
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchVideo();
|
|
}, [fileGroupId]);
|
|
|
|
return {videoFile, prevFile, nextFile, fetchVideo};
|
|
}
|
|
|
|
export const useVideoExtras = (fileGroupId) => {
|
|
// 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.
|
|
//
|
|
// Each value is null while pending, undefined when the fetch failed, and empty ([] or '') when
|
|
// the server confirmed there is nothing. The API serializes a missing info_json field as null,
|
|
// so a null response is normalized to empty here; consumers must never see null for "none".
|
|
const [comments, setComments] = useState(null);
|
|
const [description, setDescription] = useState(null);
|
|
// Every fetch takes the next generation number; only the newest generation may write state.
|
|
// Matching on the video id is not enough: leaving and returning to the same video, or a save
|
|
// that refetches the description, must both beat an older request still in flight.
|
|
const commentsGen = useRef(0);
|
|
const descriptionGen = useRef(0);
|
|
|
|
const fetchComments = async () => {
|
|
const gen = ++commentsGen.current;
|
|
try {
|
|
const result = await getVideoComments(fileGroupId);
|
|
if (gen === commentsGen.current) {
|
|
setComments(result.comments || []);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
if (gen === commentsGen.current) {
|
|
setComments(undefined);
|
|
}
|
|
}
|
|
}
|
|
|
|
const fetchDescription = async () => {
|
|
const gen = ++descriptionGen.current;
|
|
try {
|
|
const result = await getVideoDescription(fileGroupId);
|
|
if (gen === descriptionGen.current) {
|
|
setDescription(result.description || '');
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
if (gen === descriptionGen.current) {
|
|
setDescription(undefined);
|
|
}
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
// Whether switching to a new video or to none, the previous video's data must not linger,
|
|
// and any request still in flight for it must not land.
|
|
commentsGen.current++;
|
|
descriptionGen.current++;
|
|
setComments(null);
|
|
setDescription(null);
|
|
if (fileGroupId) {
|
|
fetchComments();
|
|
fetchDescription();
|
|
}
|
|
}, [fileGroupId]);
|
|
|
|
return {comments, description, fetchDescription}
|
|
}
|
|
|
|
export const useVideoCaptions = (fileGroupId) => {
|
|
const [captions, setCaptions] = useState(null);
|
|
const [captionsLoading, setCaptionsLoading] = useState(false);
|
|
const captionsFetched = useRef(false);
|
|
|
|
const fetchCaptions = async () => {
|
|
if (captionsFetched.current || !fileGroupId) return;
|
|
setCaptionsLoading(true);
|
|
try {
|
|
const result = await getVideoCaptions(fileGroupId);
|
|
setCaptions(result.captions);
|
|
} catch (e) {
|
|
console.error(e);
|
|
} finally {
|
|
setCaptionsLoading(false);
|
|
captionsFetched.current = true;
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
setCaptions(null);
|
|
setCaptionsLoading(false);
|
|
captionsFetched.current = false;
|
|
}, [fileGroupId]);
|
|
|
|
return {captions, captionsLoading, fetchCaptions}
|
|
}
|
|
|
|
export const useChannel = (channel_id) => {
|
|
const emptyChannel = {
|
|
name: '',
|
|
directory: '',
|
|
url: '',
|
|
tag_name: null,
|
|
download_missing_data: null,
|
|
};
|
|
|
|
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'] || '';
|
|
c['download_missing_data'] = c['download_missing_data'] ?? true;
|
|
return c;
|
|
}
|
|
|
|
const submitChannel = async () => {
|
|
const body = {
|
|
name: form.formData.name,
|
|
directory: form.formData.directory,
|
|
url: form.formData.url,
|
|
download_missing_data: form.formData.download_missing_data,
|
|
};
|
|
|
|
if (channel_id) {
|
|
return await updateChannel(channel_id, body);
|
|
} else {
|
|
// Can create a Channel with a Tag.
|
|
body.tag_name = form.formData.tag_name;
|
|
return await createChannel(body);
|
|
}
|
|
}
|
|
|
|
const form = useForm({
|
|
fetcher: fetchChannel,
|
|
emptyFormData: emptyChannel,
|
|
clearOnSuccess: false,
|
|
submitter: submitChannel
|
|
});
|
|
|
|
React.useEffect(() => {
|
|
// Channel may be gotten from Video data, fetch the Channel again.
|
|
form.fetcher();
|
|
}, [channel_id]);
|
|
|
|
return {
|
|
channel: form.formData,
|
|
form,
|
|
fetchChannel: form.fetcher,
|
|
};
|
|
}
|
|
|
|
export const useChannels = () => {
|
|
const [channels, setChannels] = useState(null);
|
|
const [total, setTotal] = useState(null);
|
|
const [metadata, setMetadata] = useState(null);
|
|
|
|
const _fetchChannels = async () => {
|
|
setChannels(null);
|
|
setTotal(0);
|
|
setMetadata(null);
|
|
try {
|
|
let [channels, total, metadata] = await fetchChannels();
|
|
setChannels(channels);
|
|
setTotal(total);
|
|
setMetadata(metadata);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setChannels(undefined); // Display error.
|
|
setTotal(0);
|
|
setMetadata(undefined);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
_fetchChannels();
|
|
}, []);
|
|
|
|
return [channels, total, metadata];
|
|
}
|
|
|
|
export const useSearchRecentFiles = (inProgress = false) => {
|
|
const [searchFiles, setSearchFiles] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
// All and Continue share this hook; only the latest request may write, so a slow response for the
|
|
// previous mode cannot replace the current one.
|
|
const latestRequestRef = React.useRef(0);
|
|
|
|
const localSearchFiles = async () => {
|
|
const requestId = ++latestRequestRef.current;
|
|
setLoading(true);
|
|
try {
|
|
// `inProgress` returns only the files the user is part way through.
|
|
let [file_groups] = await filesSearch(
|
|
null, 12, null, null, null, [], false,
|
|
null, null, null, false, 'viewed', null, null, false, inProgress);
|
|
if (requestId === latestRequestRef.current) {
|
|
setSearchFiles(file_groups);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
if (requestId === latestRequestRef.current) {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: 'Could not get recent files',
|
|
time: 5000,
|
|
});
|
|
}
|
|
} finally {
|
|
if (requestId === latestRequestRef.current) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
React.useEffect(() => {
|
|
// The other mode's files are not this mode's; show the placeholder until they arrive.
|
|
setSearchFiles(null);
|
|
localSearchFiles();
|
|
}, [inProgress]);
|
|
|
|
return {searchFiles, loading, fetchFiles: localSearchFiles};
|
|
}
|
|
|
|
export const useSearchFiles = (defaultLimit = 48, emptySearch = false, model) => {
|
|
const {
|
|
activeTags, anyTag,
|
|
pages,
|
|
searchStr,
|
|
filter,
|
|
model: model_,
|
|
setSearchStr,
|
|
months,
|
|
dateRange,
|
|
} = useSearch(defaultLimit, emptySearch, model);
|
|
const {view} = useSearchView();
|
|
const {deep} = useSearchDeep();
|
|
|
|
const [searchFiles, setSearchFiles] = useState(null);
|
|
const [total, setTotal] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
const headline = view === 'headline';
|
|
|
|
const localSearchFiles = async () => {
|
|
if (!emptySearch && !searchStr && !activeTags) {
|
|
return;
|
|
}
|
|
const mimetypes = filterToMimetypes(filter);
|
|
setSearchFiles(null);
|
|
let fromDate;
|
|
let toDate;
|
|
if (dateRange) {
|
|
fromDate = dateRange[0];
|
|
toDate = dateRange[1];
|
|
}
|
|
setLoading(true);
|
|
console.log('localSearchFiles', fromDate, toDate, months);
|
|
try {
|
|
let [file_groups, total_] = await filesSearch(
|
|
pages.offset, pages.limit, searchStr, mimetypes, model || model_, activeTags, headline,
|
|
months, fromDate, toDate, anyTag, null, null, null, deep);
|
|
setSearchFiles(file_groups);
|
|
setTotal(total_);
|
|
pages.setTotal(total_);
|
|
} catch (e) {
|
|
setTotal(null);
|
|
pages.setTotal(0);
|
|
console.error(e);
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: 'Could not get files',
|
|
time: 5000,
|
|
});
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
|
|
// Only search after the user has stopped typing. Estimates will always happen.
|
|
const debouncedLocalSearchFiles = _.debounce(async () => {
|
|
await localSearchFiles();
|
|
}, 1000);
|
|
|
|
useEffect(() => {
|
|
if (searchStr || (activeTags && activeTags.length > 0)) {
|
|
setLoading(true);
|
|
debouncedLocalSearchFiles();
|
|
}
|
|
// Handle when this is unmounted.
|
|
return () => debouncedLocalSearchFiles.cancel();
|
|
}, [
|
|
searchStr,
|
|
pages.effect,
|
|
filter,
|
|
model,
|
|
model_,
|
|
JSON.stringify(activeTags),
|
|
headline,
|
|
JSON.stringify(months),
|
|
JSON.stringify(dateRange),
|
|
anyTag,
|
|
deep,
|
|
]);
|
|
|
|
return {
|
|
searchFiles,
|
|
total,
|
|
searchStr,
|
|
filter,
|
|
setSearchStr,
|
|
pages,
|
|
activeTags,
|
|
loading,
|
|
};
|
|
}
|
|
|
|
export const useBrowseFiles = () => {
|
|
const [browseFiles, setBrowseFiles] = useState(null);
|
|
const [openFolders, setOpenFolders] = useAllQuery('folders');
|
|
|
|
const fetchFiles = async () => {
|
|
try {
|
|
const files = await getFiles(openFolders);
|
|
setBrowseFiles(files);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setBrowseFiles(undefined); // Display error.
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchFiles();
|
|
}, [JSON.stringify(openFolders)])
|
|
|
|
return {browseFiles, openFolders, setOpenFolders, fetchFiles};
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
// 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 undefined until the status has loaded (unknown, the toggle is disabled), null once it
|
|
// has loaded without the field (unsupported on this server), and otherwise a boolean.
|
|
const useSubsystemToggle = ({
|
|
statusField,
|
|
onValue = 'on',
|
|
offValues = ['off'],
|
|
start,
|
|
stop,
|
|
errorTitle,
|
|
errorDescription,
|
|
refetchStatus = false,
|
|
}) => {
|
|
const [on, setOn] = useState(undefined);
|
|
const {status, fetchStatus, loaded} = useContext(StatusContext);
|
|
const value = status?.[statusField];
|
|
|
|
useEffect(() => {
|
|
if (!loaded) {
|
|
setOn(undefined);
|
|
} else if (value === onValue) {
|
|
setOn(true);
|
|
} else if (offValues.includes(value)) {
|
|
setOn(false);
|
|
} else {
|
|
setOn(null);
|
|
}
|
|
}, [value, loaded]);
|
|
|
|
const setSubsystem = async (enable) => {
|
|
const previous = on;
|
|
// Unknown while the call is in flight, not unsupported.
|
|
setOn(undefined);
|
|
try {
|
|
if (enable) {
|
|
await start();
|
|
} else {
|
|
await stop();
|
|
}
|
|
} catch (e) {
|
|
console.error(`${errorTitle}:`, e);
|
|
toast({
|
|
type: 'error',
|
|
title: errorTitle,
|
|
description: e.message || errorDescription,
|
|
time: 5000,
|
|
});
|
|
// 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);
|
|
}
|
|
if (refetchStatus) {
|
|
await fetchStatus();
|
|
}
|
|
}
|
|
|
|
return {on, setOn, setSubsystem};
|
|
}
|
|
|
|
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.',
|
|
});
|
|
|
|
return {
|
|
on,
|
|
inUse: hotspot_status === 'in_use',
|
|
hotspotSsid: hotspot_ssid,
|
|
setOn,
|
|
setHotspot: setSubsystem,
|
|
dockerized,
|
|
};
|
|
}
|
|
|
|
export const useThrottle = () => {
|
|
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,
|
|
});
|
|
|
|
return {on, setOn, setThrottle: setSubsystem};
|
|
}
|
|
|
|
export const useBluetooth = () => {
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
statusField: 'bluetooth_status',
|
|
start: unblockBluetooth,
|
|
stop: blockBluetooth,
|
|
errorTitle: 'Bluetooth Error',
|
|
errorDescription: 'Could not modify Bluetooth. See server logs.',
|
|
});
|
|
|
|
return {on, setBluetooth: setSubsystem};
|
|
}
|
|
|
|
export const useDesktop = () => {
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
statusField: 'desktop_status',
|
|
start: startDesktop,
|
|
stop: stopDesktop,
|
|
errorTitle: 'Desktop Error',
|
|
errorDescription: 'Could not start/stop the desktop. See server logs.',
|
|
});
|
|
|
|
return {on, setDesktop: setSubsystem};
|
|
}
|
|
|
|
export const useVnc = () => {
|
|
const {status} = useContext(StatusContext);
|
|
const {on, setSubsystem} = useSubsystemToggle({
|
|
statusField: 'vnc_status',
|
|
start: startVnc,
|
|
stop: stopVnc,
|
|
errorTitle: 'VNC Error',
|
|
errorDescription: 'Could not start/stop VNC. See server logs.',
|
|
});
|
|
|
|
// VNC serves the desktop session, so it cannot be started without one.
|
|
return {on, desktopRunning: status?.desktop_status === 'on', setVnc: setSubsystem};
|
|
}
|
|
|
|
export const useSearchDirectories = (value) => {
|
|
const [directoryName, setDirectoryName] = useState(value ?? '');
|
|
const [directories, setDirectories] = useState(null);
|
|
const [channelDirectories, setChannelDirectories] = useState(null);
|
|
const [domainDirectories, setDomainDirectories] = useState(null);
|
|
const [isDir, setIsDir] = useState(false);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const localSearchDirectories = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const result = await searchDirectories(directoryName);
|
|
setDirectories(result.directories);
|
|
setChannelDirectories(result.channel_directories);
|
|
setDomainDirectories(result.domain_directories);
|
|
setIsDir(result.is_dir);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
localSearchDirectories();
|
|
}, [directoryName]);
|
|
|
|
useEffect(() => {
|
|
// 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 ?? '');
|
|
}, [value]);
|
|
|
|
return {
|
|
directoryName,
|
|
setDirectoryName,
|
|
directories,
|
|
loading,
|
|
channelDirectories,
|
|
domainDirectories,
|
|
isDir,
|
|
}
|
|
}
|
|
|
|
export const useSettings = () => {
|
|
// `settings` is {} until the first fetch lands, and a consumer cannot tell that from real
|
|
// settings by looking at it. `loaded` is true once a fetch returned settings; `failed` is
|
|
// true when a fetch returned nothing before anything loaded. A failed refresh after a load
|
|
// keeps the last known good values and `loaded`.
|
|
const [settings, setSettings] = useState({});
|
|
const [loaded, setLoaded] = useState(false);
|
|
const [failed, setFailed] = useState(false);
|
|
const [pending, setPending] = useState(false);
|
|
// Read by fetchSettings after an await, when the closed-over `loaded` may be stale.
|
|
const loadedRef = useRef(false);
|
|
|
|
const fetchSettings = async () => {
|
|
if (window.apiDown) {
|
|
return;
|
|
}
|
|
setPending(true);
|
|
try {
|
|
const newSettings = await getSettings();
|
|
if (newSettings) {
|
|
setSettings(newSettings);
|
|
loadedRef.current = true;
|
|
setLoaded(true);
|
|
setFailed(false);
|
|
} else if (!loadedRef.current) {
|
|
setFailed(true);
|
|
}
|
|
} catch (e) {
|
|
// Don't clear settings on error — keep the last known good values.
|
|
if (!loadedRef.current) {
|
|
setFailed(true);
|
|
}
|
|
} finally {
|
|
setPending(false);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchSettings();
|
|
}, []);
|
|
|
|
return {settings, loaded, failed, pending, fetchSettings, saveSettings};
|
|
}
|
|
|
|
export const useSettingsInterval = () => {
|
|
const {settings, loaded, failed, pending, fetchSettings, saveSettings} = useSettings();
|
|
|
|
useRecurringTimeout(fetchSettings, 1000 * 10);
|
|
|
|
return {settings, loaded, failed, pending, fetchSettings, saveSettings};
|
|
}
|
|
|
|
export const useMediaDirectory = () => {
|
|
const {settings} = React.useContext(SettingsContext);
|
|
|
|
return settings['media_directory'];
|
|
}
|
|
|
|
export const useStatus = () => {
|
|
// `status` is {} until the first poll lands, and a consumer cannot tell that from a server
|
|
// that reported nothing. `loaded` is true once a poll returned a real status; the API being
|
|
// down does not count.
|
|
const [status, setStatus] = useState({});
|
|
const [loaded, setLoaded] = useState(false);
|
|
|
|
const fetchStatus = async () => {
|
|
try {
|
|
// Fetch from both endpoints in parallel
|
|
const [appStatus, controllerStats] = await Promise.all([
|
|
getStatus().then(result => {
|
|
window.apiDown = false;
|
|
return result;
|
|
}).catch(e => {
|
|
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});
|
|
if (!window.apiDown) {
|
|
setLoaded(true);
|
|
}
|
|
} catch (e) {
|
|
if (e instanceof ApiDownError) {
|
|
// API is down, do not log this error.
|
|
window.apiDown = true;
|
|
setStatus({});
|
|
return;
|
|
}
|
|
// Ignore SyntaxError because they happen when the API is down.
|
|
if (!(e instanceof SyntaxError)) {
|
|
console.error(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
// Used to tell other hooks to stop fetching intervals.
|
|
window.apiDown = false;
|
|
}, []);
|
|
|
|
return {status, loaded, fetchStatus}
|
|
}
|
|
|
|
export const useStatusInterval = () => {
|
|
const {status, loaded, fetchStatus} = useStatus();
|
|
|
|
useRecurringTimeout(fetchStatus, 1000 * 3);
|
|
|
|
return {status, loaded, fetchStatus};
|
|
}
|
|
|
|
export const StatusProvider = (props) => {
|
|
const statusValue = useStatusInterval();
|
|
const settingsValue = useSettingsInterval();
|
|
|
|
const statusMemoValue = React.useMemo(() => statusValue, [statusValue]);
|
|
const settingsMemoValue = React.useMemo(() => settingsValue, [settingsValue]);
|
|
|
|
return <StatusContext.Provider value={statusMemoValue}>
|
|
<SettingsContext.Provider value={settingsMemoValue}>
|
|
{props.children}
|
|
</SettingsContext.Provider>
|
|
</StatusContext.Provider>
|
|
}
|
|
|
|
export const useStatusFlag = (flag) => {
|
|
const {status} = useContext(StatusContext);
|
|
return status?.flags?.[flag] || false;
|
|
}
|
|
|
|
export const useCPUTemperature = () => {
|
|
const {status} = React.useContext(StatusContext);
|
|
const temperature = status?.cpu_stats?.temperature || 0;
|
|
const highTemperature = status?.cpu_stats?.high_temperature || 75;
|
|
const criticalTemperature = status?.cpu_stats?.critical_temperature || 85;
|
|
return {temperature, highTemperature, criticalTemperature}
|
|
}
|
|
|
|
// 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,
|
|
}
|
|
}
|
|
|
|
// 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.
|
|
export const useDriveHealth = () => {
|
|
const {status} = React.useContext(StatusContext);
|
|
const drives = Array.isArray(status?.smart_stats?.drives) ? status.smart_stats.drives : [];
|
|
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,
|
|
};
|
|
}
|
|
|
|
export const useLoad = () => {
|
|
const {status} = React.useContext(StatusContext);
|
|
let minute_1 = status?.load_stats?.minute_1;
|
|
let minute_5 = status?.load_stats?.minute_5;
|
|
let minute_15 = status?.load_stats?.minute_15;
|
|
let mediumLoad = false;
|
|
let highLoad = false;
|
|
let cores;
|
|
|
|
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;
|
|
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};
|
|
}
|
|
|
|
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};
|
|
}
|
|
|
|
export const useVideoStatistics = () => {
|
|
const [statistics, setStatistics] = useState(null);
|
|
|
|
const fetchStatistics = async () => {
|
|
try {
|
|
let stats = await getVideosStatistics();
|
|
stats.videos.sum_duration = secondsToFullDuration(stats.videos.sum_duration);
|
|
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);
|
|
setStatistics(stats);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setStatistics(undefined); // Display error.
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchStatistics();
|
|
}, []);
|
|
|
|
return {statistics, fetchStatistics}
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
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]);
|
|
|
|
const fetchInventories = async () => {
|
|
const result = await getInventories();
|
|
if (Array.isArray(result)) {
|
|
setInventories(result);
|
|
}
|
|
};
|
|
|
|
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();
|
|
}
|
|
return saved;
|
|
};
|
|
|
|
const addInventory = async (name, type) => {
|
|
const inventory = await createInventory({name, type});
|
|
if (inventory) {
|
|
setInventories(prev => [...(prev || []), inventory]);
|
|
}
|
|
return inventory;
|
|
};
|
|
|
|
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}
|
|
}
|
|
|
|
// 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();
|
|
};
|
|
|
|
export const useStatistics = () => {
|
|
// null = pending, undefined = fetch failed (the api helper returns undefined on a non-OK
|
|
// response), an object = loaded. Never undefined on the first render: the page shows its
|
|
// error for undefined.
|
|
const [statistics, setStatistics] = useState(null);
|
|
|
|
const fetchFileStatistics = async () => {
|
|
try {
|
|
const s = await getStatistics();
|
|
setStatistics(s ?? undefined);
|
|
} catch (e) {
|
|
console.error(e);
|
|
setStatistics(undefined);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
fetchFileStatistics();
|
|
}, []);
|
|
|
|
return {statistics};
|
|
}
|
|
|
|
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 = () => {
|
|
const [sort, setSort] = useOneQuery('order');
|
|
return {sort, setSort}
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
export const useSearchDate = () => {
|
|
// Filters files using
|
|
// ?month=1&month=2&month=3
|
|
// and
|
|
// ?fromDate=2023&toDate=2024
|
|
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;
|
|
|
|
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});
|
|
}
|
|
|
|
const anySearch = (months && months.length > 0) || (fromDate !== null || toDate !== null);
|
|
const isEmpty = !anySearch;
|
|
|
|
return {dateRange: [fromDate, toDate], setDates, months, clearDate, isEmpty}
|
|
}
|
|
|
|
export const useUploadFile = () => {
|
|
const [files, setFiles] = useState([]);
|
|
const [progresses, setProgresses] = useState({});
|
|
const [destination, setDestination] = useState('');
|
|
const [tagNames, setTagNames] = React.useState([]);
|
|
const [overwrite, setOverwrite] = React.useState(false);
|
|
const [totalSize, setTotalSize] = useState(0);
|
|
const [uploadedSize, setUploadedSize] = useState(0);
|
|
const [overallProgress, setOverallProgress] = useState(0);
|
|
const [inProgress, setInProgress] = useState(false);
|
|
|
|
const handleProgress = (name, chunk, totalChunks, status, type) => {
|
|
const percent = Math.round((100 * chunk) / totalChunks);
|
|
const newProgress = {[name]: {percent, status, type}};
|
|
|
|
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;
|
|
});
|
|
}
|
|
|
|
const handleFilesChange = (newFiles) => {
|
|
let newProgresses = {};
|
|
let newTotalSize = 0;
|
|
|
|
newFiles.forEach(file => {
|
|
newProgresses = {...newProgresses, [file.name]: {percent: 0, status: 'pending'}};
|
|
newTotalSize += file.size;
|
|
});
|
|
|
|
setProgresses(newProgresses);
|
|
setFiles(newFiles);
|
|
setTotalSize(newTotalSize);
|
|
setUploadedSize(0);
|
|
setOverallProgress(0);
|
|
}
|
|
|
|
const doUpload = async () => {
|
|
// `''` 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) {
|
|
return;
|
|
}
|
|
|
|
setInProgress(true);
|
|
|
|
for (let i = 0; i < files.length; i++) {
|
|
const file = files[i];
|
|
console.log(`Uploading file:`, file.path);
|
|
|
|
const chunkNum = 0;
|
|
const chunkSize = 10 * 1024 * 1024; // 10MB
|
|
const totalChunks = Math.ceil(file.size / chunkSize);
|
|
const tries = 0;
|
|
const maxTries = 20;
|
|
|
|
// 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
|
|
}
|
|
}
|
|
|
|
// Clear form after upload.
|
|
setFiles([]);
|
|
setInProgress(false);
|
|
}
|
|
|
|
// 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(() => {
|
|
setFiles([]);
|
|
setProgresses({});
|
|
setTotalSize(0);
|
|
setUploadedSize(0);
|
|
setOverallProgress(0);
|
|
setInProgress(false);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
doUpload()
|
|
}, [JSON.stringify(files)]);
|
|
|
|
const tagsSelector = <TagsSelector selectedTagNames={tagNames} onChange={(i,) => setTagNames(i)}/>;
|
|
|
|
return {
|
|
destination, setDestination,
|
|
doClear,
|
|
doUpload,
|
|
files,
|
|
progresses,
|
|
setFiles: handleFilesChange,
|
|
tagNames,
|
|
tagsSelector,
|
|
overwrite, setOverwrite,
|
|
overallProgress,
|
|
totalSize,
|
|
uploadedSize,
|
|
inProgress,
|
|
}
|
|
}
|
|
|
|
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();
|
|
}, []);
|
|
|
|
return {outdated, current, fetchOutdatedZims: localFetchOutdatedZims}
|
|
}
|
|
|
|
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}
|
|
}
|
|
|
|
export const useWROLMode = () => {
|
|
// Returns the current boolean WROL Mode, during fetch this returns null.
|
|
const {settings} = useContext(SettingsContext);
|
|
return settings ? settings.wrol_mode : null;
|
|
}
|
|
|
|
export const useDockerized = () => {
|
|
const {status} = React.useContext(StatusContext);
|
|
return status && status['dockerized'] === true;
|
|
}
|
|
|
|
export const useCalcQuery = () => {
|
|
const [calc, setCalc] = useOneQuery('calc');
|
|
return [calc, setCalc]
|
|
}
|
|
|
|
// Channels whose name matches `searchStr` and/or which have any of the tags.
|
|
export const useSearchChannels = (defaultTagNames, searchStr) => {
|
|
const [tagNames, setTagNames] = useState(defaultTagNames || []);
|
|
// null = pending, undefined = fetch failed, [] = no channels. A search starts on mount, so the
|
|
// first render is already loading; consumers must never see [] for a search that has not run.
|
|
const [channels, setChannels] = useState(null);
|
|
const [loading, setLoading] = useState(true);
|
|
// Only the newest request may write state; a slow response for previous tags is dropped.
|
|
const requestGen = useRef(0);
|
|
|
|
const localSearchChannels = async () => {
|
|
const gen = ++requestGen.current;
|
|
setChannels(null);
|
|
setLoading(true);
|
|
try {
|
|
const {channels: newChannels} = await searchChannels(tagNames, searchStr);
|
|
if (gen === requestGen.current) {
|
|
setChannels(newChannels || []);
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
if (gen === requestGen.current) {
|
|
setChannels(undefined);
|
|
}
|
|
} finally {
|
|
if (gen === requestGen.current) {
|
|
setLoading(false);
|
|
}
|
|
}
|
|
};
|
|
|
|
// The caller's tags come from the URL and change in place while the view stays mounted, so
|
|
// follow their contents. Keyed on the serialized list because the caller builds a new array
|
|
// every render; adopting it by reference would refetch forever.
|
|
const tagKey = JSON.stringify(defaultTagNames || []);
|
|
useEffect(() => {
|
|
setTagNames(prev => JSON.stringify(prev) === tagKey ? prev : JSON.parse(tagKey));
|
|
}, [tagKey]);
|
|
|
|
useEffect(() => {
|
|
localSearchChannels();
|
|
}, [tagNames, searchStr]);
|
|
|
|
return {
|
|
tagNames,
|
|
setTagNames,
|
|
channels,
|
|
loading,
|
|
}
|
|
}
|
|
|
|
// Collections of `kind` whose name matches `searchStr` and/or which have any of the tags. `collections`:
|
|
// null = pending, undefined = fetch failed, [] = none. Nothing to search by matches nothing (the API would list
|
|
// every Collection of the kind). Only the newest request may write state.
|
|
export const useSearchCollections = (kind, searchStr, tagNames) => {
|
|
const [collections, setCollections] = useState(null);
|
|
const requestGen = useRef(0);
|
|
const tagKey = JSON.stringify(tagNames || []);
|
|
|
|
useEffect(() => {
|
|
const gen = ++requestGen.current;
|
|
const tags = JSON.parse(tagKey);
|
|
if (!(searchStr || '').trim() && _.isEmpty(tags)) {
|
|
setCollections([]);
|
|
return;
|
|
}
|
|
setCollections(null);
|
|
searchCollections(kind, tags, searchStr)
|
|
.then(result => gen === requestGen.current && setCollections(result ? result.collections : undefined))
|
|
.catch(e => {
|
|
console.error(e);
|
|
if (gen === requestGen.current) setCollections(undefined);
|
|
});
|
|
}, [kind, searchStr, tagKey]);
|
|
|
|
return {collections};
|
|
}
|
|
|
|
// Repos matching the search (their name and README) and/or the tags. `repos`: null = pending,
|
|
// undefined = fetch failed, [] = none. Only the newest request may write state.
|
|
export const useSearchRepos = (searchStr, tagNames) => {
|
|
const [repos, setRepos] = useState(null);
|
|
const requestGen = useRef(0);
|
|
const tagKey = JSON.stringify(tagNames || []);
|
|
|
|
useEffect(() => {
|
|
const gen = ++requestGen.current;
|
|
setRepos(null);
|
|
searchRepos(searchStr, JSON.parse(tagKey))
|
|
.then(result => gen === requestGen.current && setRepos(result ? result.repos : undefined))
|
|
.catch(e => {
|
|
console.error(e);
|
|
if (gen === requestGen.current) setRepos(undefined);
|
|
});
|
|
}, [searchStr, tagKey]);
|
|
|
|
return {repos};
|
|
}
|
|
|
|
|
|
/**
|
|
* 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;
|
|
}
|