mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-04 13:49:57 -05:00
* Add iNaturalist species pack build script
Builds one `inat-<region>-<version>.species.db` per map region from the
iNaturalist research-grade GBIF export (CC BY-NC 4.0). Each species row
links to its English Wikipedia article (via Wikidata) so Kiwix supplies
the details, and carries its range as compressed per-cell dots (0.1° from
all observations, 0.02° from precise ones only). A cell lookup table
answers "what lives near here", and FTS5 searches names. Packs, meta4
files and a signed manifest are written for upload to the CDN.
modules/map/species.py holds the pack format shared with WROLPi.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Download iNaturalist species packs by subscription
A species subscription is one recurring (30 day) `species_catalog` Download
of the signed species manifest, saved in the downloads config like map
subscriptions. Each run creates a `species_pack` Download per subscribed
region, which aria2c checks against the manifest's signed hash before the
pack is moved into map/inat/; only then are the region's older packs
deleted.
The map's Manage tab gets a Species section: subscribe, unsubscribe (the
pack is kept), and delete a downloaded pack. Pack file names are built and
parsed in modules/map/species.py, shared with the build script.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Search the downloaded species packs, with their range and Wikipedia article
- GET /api/map/species: search by name (every word a prefix), and/or what
was seen within radius_km of lat/lon. Nearby species come first, most
seen nearby first; an exact name match comes first of all.
- GET /api/map/species/<taxon_id>: details, and the species' article in
the best English Wikipedia Zim (maxi, nopic, mini; newest), found by the
libzim worker's new `find` op, else a search link for its name.
- GET /api/map/species/<taxon_id>/range?grid=low|high: GeoJSON dots.
Packs are read directly and read-only; a species in several regions is
merged (counts summed, bbox and range unioned).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Use iNaturalist's common names in the species packs
Wikidata's P1843 holds many English names per species and the one we got
was arbitrary ("black-tailed deer" for mule deer, "Greek milkweed" for
showy milkweed). The build now reads iNaturalist's taxonomy archive
(VernacularNames-english.csv) and takes each species' first name not tied
to a place ("quaking aspen", not Canada's "trembling aspen"), else its
first name; Wikidata's is only a fallback. In us-west this names 30,642
of 52,015 species, up from 17,805.
--version publishes a rebuild of the same observations under a new
version, and --reuse-split rebuilds from the last build's region work
files instead of reading the observations again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species panel on the map: what lives here, and a species' range as dots
A 🌿 button opens the Species panel (it and nuclear mode share the
panel's place, so one closes the other). It lists the species seen
within 10/30/100 km of the middle of the map, following the map as it
moves, with how often each was seen nearby; it can search by name and
filter by group. Choosing a species draws its range: the 0.1° grid of
every observation below zoom 7, the 0.02° grid of precise ones from it
(or the 0.1° grid at every zoom when there is none), put back after a
style change and erased on Back or close. "Zoom to range" fits its
bbox, and its Wikipedia article opens from the best Wikipedia Zim (or a
search, or where to download Wikipedia).
The panel is at most half the screen tall and clears the map's buttons,
so the range stays in sight on a phone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species tests: neutral Oregon fixtures
Bend, Prineville (~47 km apart) and Crater Lake replace the earlier
fixture points; the cases are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: zoom to a range without its outliers, beside the panel
"Zoom to range" fitted the species' bbox, so a few planted trees far
away (giant sequoias in Seattle and Los Angeles) zoomed the map out to
the whole coast, and the panel covered part of the range. It now fits
the range's dots less the outermost 2% on each side (from 20 dots), and
pads by the panel: beside it on a wide map, above it on a narrow one.
The outlying dots are still drawn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: the Species page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: months seen, a popup on each dot, and review fixes
Months: packs now keep how many observations each species had in each
month, and the months it was seen in each ~11 km square (a bit per
month). The species details show a bar per month; clicking a range dot
opens a popup of that square: how often the species was seen there and
in which months, and the other species seen there, any of which can be
opened (GET /api/map/species/here). Packs without months still work.
Review fixes:
- Common names: the archive's first listed English name, not the first
without a place (which was an alias: "Robin Redbreast", "Wanderer",
"Duck Hawk"); every other English name is kept in `other_names` and
is searchable, and shown as "Also called".
- Only the newest pack of each region is read, so a version left beside
a newer one is not counted twice; a finished download also removes
older versions. A name one pack lacks is taken from another.
- No bbox for a species whose packs are on both sides of the
antimeridian; Zoom to range takes the short way across it, drops at
least one outlier on each side from 20 dots, waits for the dots, and
measures the panel against the map.
- Wikipedia Zims are tried one at a time, best first, all of Wikipedia
before a selection of it.
- A failed search keeps the last list and says so; failed details no
longer suggest downloading Wikipedia, and the range is still drawn.
- Species range dots are left out of PDF exports.
- Unsubscribe (species and map regions) is red again; the Manage table
refreshes until a subscribed pack arrives; a refused Delete fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: less work for the WROLPi per search and range
Measured on a Pi 4 with the us-west pack, the panel's search (species
within 30 km, asked each time the map stops moving) took 146 ms, and a
wide species' fine range 280 ms and 2.7 MB of GeoJSON.
- Search ranks the matching species from bare (taxon, names, counts)
tuples and reads only the species it returns in full: 30 km 87 ms,
100 km 445 -> 277 ms, a broad name prefix 480 -> 200 ms.
- The range is sent as its sorted cells, as differences, and the
browser makes the dots: the red-tailed hawk's fine range 34 ms and
95 KB, its coarse range 87 -> 10 ms and 939 -> 29 KB.
A dot's popup asks for the species clicked, and always shows how often
and in which months it was seen in that square, not only when it is
among the most seen there. The popup is drawn over the Species panel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: a planet pack, every region in one file
`--planet` merges every region's pack into `inat-planet-<version>`
(counts and months summed, ranges, bboxes and lookup cells joined, the
first name a pack has), and adds it to the manifest; `--merge-only`
makes it from the region packs of a finished build. An observation
exactly on a shared region edge is in both regions' packs, so the
planet counts it twice; that is rare enough to leave.
On the device the planet is a choice in the Species catalog, and when
its pack is downloaded it is the only one read, so the regions it holds
are not counted again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: sizes of the 20261129 packs; no hang re-signing a manifest
The packs grew about 15% with months and other names; the planet pack
is 993 MB. Re-signing a manifest (--planet --merge-only) hung: gpg
asks before replacing an existing signature and nothing could answer.
The old signature is now removed first. Help: a dot's popup, months,
other names, and the planet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: the planet from each observation once; overlaps counted once
Map regions overlap, some widely (southern Arizona is in us-west and
mexico, north Africa in five regions): about 42M of 173M observations
are in two or more. Merging the region packs counted those twice, so
the planet is now built like a region from every observation once.
Its work is split into 8 files by species and built a file at a time
(all at once its sets would need ~25 GB). `planet` is a region for
--regions, built by default, and the manifest lists every pack of the
version in the folder, so a planet-only run keeps the regions. The
merge and its flags are gone.
On a device with overlapping region packs, a square both hold was
counted twice in "near" and in a dot's popup; each square now counts
the larger of the packs' counts. Species totals still add up across
overlapping packs; the planet pack is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Help: Species screenshots from the planet pack
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Zoom to range fits the cluster of dots nearest the view
On the planet pack, giant sequoia (planted in Britain, New Zealand and
elsewhere) zoomed out to the whole world: far more than the 2% of dots
the zoom left out were planted away from its groves. Dots in touching
2° squares (about 220 km, also across the antimeridian) are now one
cluster, and Zoom to range fits the cluster nearest the middle of the
map: California from Yosemite, the planted trees from London. A range
spread across a continent is one cluster. Help updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Species: Planet is listed first on the Manage tab
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
3116 lines
111 KiB
JavaScript
3116 lines
111 KiB
JavaScript
import {emptyToNull} from "./components/Common";
|
|
import {toast} from "./components/ui";
|
|
import _ from "lodash";
|
|
import {
|
|
API_URI,
|
|
ARCHIVES_API,
|
|
COLLECTIONS_API,
|
|
DEFAULT_LIMIT,
|
|
Downloaders,
|
|
REPOS_API,
|
|
VIDEOS_API,
|
|
ZIM_API
|
|
} from "./components/Vars";
|
|
|
|
function timeoutPromise(ms, promise) {
|
|
// Create a timeout wrapper around a promise. If the timeout is reached, throw an error. Otherwise, return
|
|
// the results of the promise.
|
|
return new Promise((resolve, reject) => {
|
|
const timeoutId = setTimeout(() => {
|
|
reject(new Error("promise timeout"))
|
|
}, ms);
|
|
promise.then((res) => {
|
|
clearTimeout(timeoutId);
|
|
resolve(res);
|
|
}, (err) => {
|
|
clearTimeout(timeoutId);
|
|
reject(err);
|
|
});
|
|
})
|
|
}
|
|
|
|
export class ApiDownError extends Error {
|
|
}
|
|
|
|
const apiDownError = new ApiDownError('API is down');
|
|
|
|
async function apiCall(url, method, body, ms = 60_000) {
|
|
let init = {method};
|
|
if (body !== undefined) {
|
|
init.body = JSON.stringify(body);
|
|
}
|
|
|
|
let promise;
|
|
try {
|
|
// Create a fetch promise, this will be awaited by the timeout.
|
|
promise = fetch(url, init);
|
|
|
|
// await the response or error.
|
|
const response = await timeoutPromise(ms, promise);
|
|
if (200 <= response.status && response.status < 300) {
|
|
// Request was successful.
|
|
return response;
|
|
}
|
|
if (response.status === 502) {
|
|
// API is down.
|
|
throw apiDownError;
|
|
}
|
|
// Request encountered an error.
|
|
let copy = response.clone();
|
|
const content = await copy.json();
|
|
const code = content['code'];
|
|
console.error('API error response json', content);
|
|
if (response.status === 403 && code === 'WROL_MODE_ENABLED') {
|
|
toast({
|
|
type: 'error',
|
|
title: 'WROL Mode is enabled!',
|
|
description: 'This functionality is disabled while WROL Mode is enabled!',
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
} catch (e) {
|
|
if (e instanceof ApiDownError) {
|
|
// Throw ApiDownError immediately without logging.
|
|
throw e;
|
|
}
|
|
// Ignore SyntaxError because they happen when the API is down.
|
|
if (!(e instanceof SyntaxError)) {
|
|
console.error(e);
|
|
}
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
// Convenience functions for API calls.
|
|
let apiGet = async (url) => {
|
|
return await apiCall(url, 'GET')
|
|
};
|
|
let apiDelete = async (url) => {
|
|
return await apiCall(url, 'DELETE')
|
|
};
|
|
let apiPost = async (url, body) => {
|
|
return await apiCall(url, 'POST', body)
|
|
};
|
|
let apiPut = async (url, body) => {
|
|
return await apiCall(url, 'PUT', body)
|
|
};
|
|
let apiPatch = async (url, body) => {
|
|
return await apiCall(url, 'PATCH', body)
|
|
};
|
|
|
|
async function getErrorMessage(response, fallbackMessage) {
|
|
try {
|
|
const json = await response.clone().json();
|
|
return json.error || json.message || fallbackMessage;
|
|
} catch (error) {
|
|
// Server did not response with JSON. Return default message.
|
|
return fallbackMessage;
|
|
}
|
|
}
|
|
|
|
export async function updateChannel(id, channel) {
|
|
channel = emptyToNull(channel);
|
|
return await apiPut(`${VIDEOS_API}/channels/${id}`, channel);
|
|
}
|
|
|
|
export async function createChannel(channel) {
|
|
channel = emptyToNull(channel);
|
|
return await apiPost(`${VIDEOS_API}/channels`, channel);
|
|
}
|
|
|
|
export async function deleteChannel(channelId) {
|
|
const response = await apiDelete(`${VIDEOS_API}/channels/${channelId}`);
|
|
if (response.status !== 204) {
|
|
const message = await getErrorMessage(response, 'Failed to delete channel.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function getChannels() {
|
|
const response = await apiGet(`${VIDEOS_API}/channels`);
|
|
if (response.status === 200) {
|
|
return (await response.json())['channels'];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to get channels.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unexpected server response',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function getChannel(id) {
|
|
const response = await apiGet(`${VIDEOS_API}/channels/${id}`);
|
|
return (await response.json())['channel'];
|
|
}
|
|
|
|
export async function tagChannel(channelId, tagName, directory) {
|
|
const body = {
|
|
tag_name: tagName,
|
|
}
|
|
if (directory) {
|
|
body['directory'] = directory;
|
|
}
|
|
const response = await apiPost(`${VIDEOS_API}/channels/${channelId}/tag`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to tag channel. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Tagging Channel Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function tagChannelInfo(channelId, tagName) {
|
|
channelId = channelId ? parseInt(channelId) : null;
|
|
const body = {channel_id: channelId, tag_name: tagName};
|
|
const response = await apiPost(`${VIDEOS_API}/tag_info`, body);
|
|
if (response.ok) {
|
|
return (await response.json()).videos_destination;
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to get channel tag info.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Getting Channel Tag Info Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
|
|
export async function searchVideos(offset, limit, channelId, searchStr, order_by, tagNames, headline, censored, deep, anyTag) {
|
|
// Build a search query to retrieve a list of videos from the API
|
|
offset = parseInt(offset || 0);
|
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
|
let body = {offset, limit, order_by: order_by || 'rank'};
|
|
|
|
if (searchStr) {
|
|
body['search_str'] = searchStr;
|
|
}
|
|
if (channelId) {
|
|
body['channel_id'] = parseInt(channelId);
|
|
}
|
|
if (tagNames) {
|
|
body['tag_names'] = tagNames;
|
|
}
|
|
if (headline) {
|
|
body['headline'] = true;
|
|
}
|
|
if (censored) {
|
|
body['censored'] = true;
|
|
}
|
|
if (deep) {
|
|
body['deep'] = true;
|
|
}
|
|
if (anyTag) {
|
|
body['any_tag'] = true;
|
|
}
|
|
|
|
console.debug('searching videos', body);
|
|
|
|
const response = await apiPost(`${VIDEOS_API}/search`, body);
|
|
if (response.status === 200) {
|
|
let data = await response.json();
|
|
return [data['file_groups'], data['totals']['file_groups']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to search videos.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Searching Videos failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
return [[], 0];
|
|
}
|
|
}
|
|
|
|
export async function getVideo(fileGroupId) {
|
|
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}`);
|
|
let data = await response.json();
|
|
return [data['file_group'], data['prev'], data['next']];
|
|
}
|
|
|
|
export async function updateVideo(fileGroupId, {title, description}) {
|
|
// Edits the Video's details (written to its info json). Only the fields given are changed.
|
|
// Returns the updated video file group.
|
|
const response = await apiPut(`${VIDEOS_API}/${fileGroupId}`, {title, description});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to save the video. See server logs.');
|
|
toast({type: 'error', title: 'Failed to save', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
const data = await response.json();
|
|
return data['file_group'];
|
|
}
|
|
|
|
export async function transcodeVideo(fileGroupId, {
|
|
video_codec = null, audio_codec = null, container = 'mp4', fragmented = false,
|
|
}) {
|
|
// Queues a transcode Job; returns the job id. Watch it with `getJob`.
|
|
const body = {video_codec, audio_codec, container, fragmented};
|
|
const response = await apiPost(`${VIDEOS_API}/${fileGroupId}/transcode`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to queue the transcode. See server logs.');
|
|
toast({type: 'error', title: 'Failed to transcode', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
const data = await response.json();
|
|
return data['job_id'];
|
|
}
|
|
|
|
export async function getJobs() {
|
|
const response = await apiGet(`${API_URI}/jobs`);
|
|
if (!response.ok) {
|
|
throw new Error(await getErrorMessage(response, 'Unable to get the jobs'));
|
|
}
|
|
const data = await response.json();
|
|
return data['jobs'];
|
|
}
|
|
|
|
export async function getJob(jobId) {
|
|
const response = await apiGet(`${API_URI}/jobs/${jobId}`);
|
|
if (!response.ok) {
|
|
const error = new Error(await getErrorMessage(response, 'Unable to get the job'));
|
|
error.status = response.status;
|
|
throw error;
|
|
}
|
|
const data = await response.json();
|
|
return data['job'];
|
|
}
|
|
|
|
export async function cancelJob(jobId) {
|
|
const response = await apiDelete(`${API_URI}/jobs/${jobId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to cancel the job');
|
|
toast({type: 'error', title: 'Failed to cancel', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
const data = await response.json();
|
|
return data['job'];
|
|
}
|
|
|
|
export async function getVideoComments(fileGroupId) {
|
|
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/comments`);
|
|
let data = await response.json();
|
|
return {
|
|
comments: data.comments,
|
|
}
|
|
}
|
|
|
|
export async function getVideoDescription(fileGroupId) {
|
|
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/description`);
|
|
let data = await response.json();
|
|
return {
|
|
description: data.description,
|
|
}
|
|
}
|
|
|
|
export async function getVideoCaptions(fileGroupId) {
|
|
const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/captions`);
|
|
let data = await response.json();
|
|
return {
|
|
captions: data.captions,
|
|
}
|
|
}
|
|
|
|
export async function deleteFileGroups(fileGroupIds, force = false) {
|
|
if (!fileGroupIds || fileGroupIds.length === 0) {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Empty request',
|
|
description: 'Unable to delete FileGroups because no IDs were passed.',
|
|
time: 5000,
|
|
});
|
|
return;
|
|
}
|
|
console.info(`Deleting FileGroups: ${fileGroupIds}`);
|
|
const body = {file_group_ids: fileGroupIds, force};
|
|
const response = await apiPost(`${API_URI}/files/delete_groups`, body);
|
|
if (response.ok) {
|
|
return response;
|
|
}
|
|
try {
|
|
const json = await response.clone().json();
|
|
if (json.code === 'FILE_GROUP_IS_TAGGED' && json.file_groups) {
|
|
return {tagged: true, file_groups: json.file_groups};
|
|
}
|
|
} catch (e) {
|
|
// Not JSON, fall through to generic error.
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to delete files.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Delete failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function downloadVideoMetadata(videoUrl) {
|
|
const downloadData = {
|
|
urls: [videoUrl],
|
|
downloader: Downloaders.Video,
|
|
settings: {download_metadata_only: true},
|
|
};
|
|
return await postDownload(downloadData);
|
|
}
|
|
|
|
export async function getStatus() {
|
|
const response = await apiGet(`${API_URI}/status`);
|
|
if (response.status === 200) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get server status.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Fetching Status Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function getSettings() {
|
|
const response = await apiGet(`${API_URI}/settings`);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
archive_destination: content.archive_destination,
|
|
backup_delete_after_days: content.backup_delete_after_days,
|
|
backup_device_uuid: content.backup_device_uuid,
|
|
backup_directory: content.backup_directory,
|
|
backup_excluded_directories: content.backup_excluded_directories,
|
|
backup_window_end: content.backup_window_end,
|
|
backup_window_start: content.backup_window_start,
|
|
download_manager_disabled: content.download_manager_disabled,
|
|
download_manager_stopped: content.download_manager_stopped,
|
|
download_daily_limit_global: content.download_daily_limit_global,
|
|
download_daily_limit_per_domain: content.download_daily_limit_per_domain,
|
|
download_on_startup: content.download_on_startup,
|
|
download_timeout: content.download_timeout,
|
|
download_wait: content.download_wait,
|
|
download_window_start: content.download_window_start,
|
|
download_window_end: content.download_window_end,
|
|
hotspot_device: content.hotspot_device,
|
|
hotspot_on_startup: content.hotspot_on_startup,
|
|
hotspot_password: content.hotspot_password,
|
|
hotspot_ssid: content.hotspot_ssid,
|
|
hotspot_status: content.hotspot_status,
|
|
check_for_upgrades: content.check_for_upgrades,
|
|
ignore_outdated_zims: content.ignore_outdated_zims,
|
|
ignored_directories: content.ignored_directories,
|
|
log_level: content.log_level,
|
|
map_default_location: content.map_default_location,
|
|
map_destination: content.map_destination,
|
|
nav_color: content.nav_color,
|
|
media_directory: content.media_directory,
|
|
playlists_destination: content.playlists_destination,
|
|
repos_destination: content.repos_destination,
|
|
require_cookies_unlocked: content.require_cookies_unlocked,
|
|
require_media_mounted: content.require_media_mounted,
|
|
role: content.role,
|
|
save_ffprobe_json: content.save_ffprobe_json,
|
|
sync_delete_after_days: content.sync_delete_after_days,
|
|
sync_excluded_directories: content.sync_excluded_directories,
|
|
sync_primary_url: content.sync_primary_url,
|
|
sync_window_end: content.sync_window_end,
|
|
sync_window_start: content.sync_window_start,
|
|
tags_directory: content.tags_directory,
|
|
throttle_on_startup: content.throttle_on_startup,
|
|
throttle_status: content.throttle_status,
|
|
timezone: content.timezone,
|
|
version: content.version,
|
|
videos_destination: content.videos_destination,
|
|
wrol_mode: content.wrol_mode,
|
|
zims_destination: content.zims_destination,
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get settings.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Fetching Settings Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Sync: a secondary WROLPi copies its library from its primary.
|
|
|
|
export async function saveSyncSettings(settings) {
|
|
const response = await apiPut(`${API_URI}/sync/settings`, settings);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not save sync settings.');
|
|
toast({type: 'error', title: 'Saving Sync Settings Failed', description: message, time: 5000});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export class PrimaryUnreachableError extends Error {
|
|
}
|
|
|
|
/** The folders directly inside `path`; `source` is 'local' (this WROLPi) or 'primary' (its primary). */
|
|
export async function getSyncDirectories(path, source) {
|
|
const response = await apiPost(`${API_URI}/sync/directories`, {path: path || '', source});
|
|
if (response.ok) {
|
|
const {directories} = await response.json();
|
|
return directories;
|
|
}
|
|
if (response.status === 502) {
|
|
const {error} = await response.json();
|
|
throw new PrimaryUnreachableError(error || 'The primary did not answer');
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not list the folders.');
|
|
throw new Error(message);
|
|
}
|
|
|
|
export async function runBackup() {
|
|
const response = await apiPost(`${API_URI}/sync/backup/run`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not start the backup.');
|
|
toast({type: 'error', title: 'Backup Failed', description: message, time: 5000});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function cancelBackup() {
|
|
return await apiPost(`${API_URI}/sync/backup/cancel`);
|
|
}
|
|
|
|
export async function testSync() {
|
|
const response = await apiGet(`${API_URI}/sync/test`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not reach the primary.');
|
|
return {ok: false, error: message};
|
|
}
|
|
|
|
export async function saveSettings(settings) {
|
|
const response = await apiPatch(`${API_URI}/settings`, settings);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not save settings.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Saving Settings Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function getDownloads() {
|
|
const response = await apiGet(`${API_URI}/download`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get downloads.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Getting Downloads Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function getConfigs() {
|
|
const response = await apiGet(`${API_URI}/config`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return {
|
|
configs: data.configs,
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get configs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Getting Configs Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function postImportConfig(fileName) {
|
|
const body = {file_name: fileName};
|
|
const response = await apiPost(`${API_URI}/config/import`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not import config.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Importing config Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function postDumpConfig(fileName) {
|
|
const body = {file_name: fileName, overwrite: true};
|
|
const response = await apiPost(`${API_URI}/config/dump`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not dump config.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Dumping config failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function getConfig(fileName) {
|
|
const response = await apiGet(`${API_URI}/config?file_name=${fileName}`);
|
|
return (await response.json())['config'];
|
|
}
|
|
|
|
export async function getConfigText(fileName) {
|
|
const response = await apiGet(`${API_URI}/config?file_name=${fileName}`);
|
|
return (await response.json())['config_text'];
|
|
}
|
|
|
|
export async function getConfigBackups(fileName) {
|
|
const response = await apiGet(`${API_URI}/config/backups?file_name=${fileName}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
// Undefined, not {dates: []}, so the modal can tell a failed fetch from having no backups.
|
|
}
|
|
|
|
export async function postConfigBackupPreview(fileName, backupDate, mode) {
|
|
const body = {file_name: fileName, backup_date: backupDate, mode};
|
|
const response = await apiPost(`${API_URI}/config/backup/preview`, body);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not preview backup.');
|
|
toast({type: 'error', title: 'Preview failed', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function postConfigBackupImport(fileName, backupDate, mode) {
|
|
const body = {file_name: fileName, backup_date: backupDate, mode};
|
|
const response = await apiPost(`${API_URI}/config/backup/import`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not import backup.');
|
|
toast({type: 'error', title: 'Backup import failed', description: message, time: 5000});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function fetchVideoDownloaderConfig() {
|
|
return await getConfig('videos_downloader.yaml');
|
|
}
|
|
|
|
export async function fetchVideoDownloadDefaults() {
|
|
const response = await apiGet(`${VIDEOS_API}/download-defaults`);
|
|
return await response.json();
|
|
}
|
|
|
|
export async function updateConfig(fileName, config) {
|
|
const body = {config};
|
|
const response = await apiPost(`${API_URI}/config?file_name=${fileName}`, body);
|
|
if (!response.ok) {
|
|
throw Error('Failed to save config');
|
|
}
|
|
}
|
|
|
|
export async function updateVideoDownloaderConfig(config) {
|
|
return await updateConfig('videos_downloader.yaml', config);
|
|
}
|
|
|
|
export async function fetchArchiveDownloaderConfig() {
|
|
return await getConfig('archives_downloader.yaml');
|
|
}
|
|
|
|
export async function updateArchiveDownloaderConfig(config) {
|
|
return await updateConfig('archives_downloader.yaml', config);
|
|
}
|
|
|
|
export async function postArchiveFileFormat(archive_file_format) {
|
|
const body = {archive_file_format};
|
|
return await apiPost(`${ARCHIVES_API}/file_format`, body);
|
|
}
|
|
|
|
export async function fetchArchiveBrowsers() {
|
|
const response = await apiGet(`${ARCHIVES_API}/browsers`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
return {browsers: [], available: false};
|
|
}
|
|
|
|
export async function getArchiveStatistics() {
|
|
const response = await apiGet(`${ARCHIVES_API}/statistics`);
|
|
if (response.status === 200) {
|
|
return (await response.json())['statistics'];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get archive statistics.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Getting Archive Statistics Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function updateVideoDownloaderSettings(settings) {
|
|
const response = await apiPut(`${API_URI}/videos/settings`, settings);
|
|
if (response.status === 200) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to save settings.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Saving Settings Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function validateRegex(regex) {
|
|
const response = await apiPost(`${API_URI}/valid_regex`, {regex});
|
|
try {
|
|
return (await response.json())['valid'];
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function getVideosStatistics() {
|
|
const response = await apiGet(`${VIDEOS_API}/statistics`);
|
|
if (response.status === 200) {
|
|
return (await response.json())['statistics'];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get statistics.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Getting Statistics Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function refreshChannel(channelId) {
|
|
let url = `${VIDEOS_API}/channels/refresh/${channelId}`;
|
|
const response = await apiPost(url);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, "Failed to refresh this channel's directory");
|
|
toast({
|
|
type: 'error',
|
|
title: 'Failed to refresh',
|
|
description: message,
|
|
time: 5000,
|
|
})
|
|
}
|
|
return response;
|
|
}
|
|
// Inventory is config-only on the backend (no DB). The frontend loads every inventory once (full), derives
|
|
// list/items/summary/locations client-side, and persists whole inventories on change — so there are only four
|
|
// inventory calls.
|
|
|
|
export async function getInventories() {
|
|
// Returns every inventory in full (fields + items).
|
|
const response = await apiGet(`${API_URI}/inventory`);
|
|
if (response.ok) {
|
|
return (await response.json())['inventories'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not get inventories');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function createInventory({name, type}) {
|
|
const response = await apiPost(`${API_URI}/inventory`, {name, type});
|
|
if (response.ok) {
|
|
return (await response.json())['inventory'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to create inventory');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function saveInventory(slug, data) {
|
|
// Whole-inventory save (data = {name?, fields?, items?, version?}). Returns the saved inventory, or null on
|
|
// error/conflict so the caller can reconcile.
|
|
const response = await apiPut(`${API_URI}/inventory/${slug}`, data);
|
|
if (response.ok) {
|
|
return (await response.json())['inventory'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to save inventory');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function deleteInventory(slug) {
|
|
const response = await apiDelete(`${API_URI}/inventory/${slug}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to delete inventory');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function reimportInventories() {
|
|
// Re-read every inventory config file from disk (picks up hand-edits and copied-in files).
|
|
const response = await apiPost(`${API_URI}/inventory/reimport`);
|
|
if (response.ok) {
|
|
return (await response.json())['inventories'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to re-import inventories');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function getInventoryBackups(slug) {
|
|
const response = await apiGet(`${API_URI}/inventory/${slug}/backups`);
|
|
if (response.ok) {
|
|
return (await response.json())['dates'];
|
|
}
|
|
// Undefined, not [], so the modal can tell a failed fetch from having no backups.
|
|
}
|
|
|
|
export async function postInventoryRestorePreview(slug, backupDate, mode) {
|
|
const body = {backup_date: backupDate, mode};
|
|
const response = await apiPost(`${API_URI}/inventory/${slug}/restore/preview`, body);
|
|
if (response.ok) {
|
|
return (await response.json())['preview'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to preview the backup');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function postInventoryRestore(slug, backupDate, mode) {
|
|
const body = {backup_date: backupDate, mode};
|
|
const response = await apiPost(`${API_URI}/inventory/${slug}/restore`, body);
|
|
if (response.ok) {
|
|
return (await response.json())['inventory'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to restore the backup');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function getCatalog() {
|
|
// The shared food catalog (known items with total calories per package).
|
|
const response = await apiGet(`${API_URI}/inventory/catalog`);
|
|
if (response.ok) {
|
|
return (await response.json())['catalog'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not get the food catalog');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function saveCatalog(items) {
|
|
const response = await apiPut(`${API_URI}/inventory/catalog`, {items});
|
|
if (response.ok) {
|
|
return (await response.json())['catalog'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to save the food catalog');
|
|
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
|
|
export async function searchArchives(offset, limit, domain, searchStr, order, tagNames, headline, deep, anyTag) {
|
|
// Build a search query to retrieve a list of videos from the API
|
|
offset = parseInt(offset || 0);
|
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
|
let body = {offset, limit};
|
|
if (domain) {
|
|
body['domain'] = domain;
|
|
}
|
|
if (searchStr) {
|
|
body['search_str'] = searchStr;
|
|
}
|
|
if (order) {
|
|
body['order_by'] = order;
|
|
}
|
|
if (tagNames) {
|
|
body['tag_names'] = tagNames;
|
|
}
|
|
if (headline) {
|
|
body['headline'] = true;
|
|
}
|
|
if (deep) {
|
|
body['deep'] = true;
|
|
}
|
|
if (anyTag) {
|
|
body['any_tag'] = true;
|
|
}
|
|
|
|
console.debug('searching archives', body);
|
|
const response = await apiPost(`${ARCHIVES_API}/search`, body);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['file_groups'], data['totals']['file_groups']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot search archives. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unable to search archives',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
return [[], 0];
|
|
}
|
|
}
|
|
|
|
export async function fetchDomains() {
|
|
const response = await apiGet(`${COLLECTIONS_API}?kind=domain`);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['collections'], data['totals']['collections']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch Domains. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Domains Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function fetchAuthors() {
|
|
const response = await apiGet(`${COLLECTIONS_API}?kind=author`);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['collections'], data['totals']['collections']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch Authors. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Authors Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function fetchSubjects() {
|
|
const response = await apiGet(`${COLLECTIONS_API}?kind=subject`);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['collections'], data['totals']['collections']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch Subjects. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Subjects Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function fetchChannels() {
|
|
const response = await apiGet(`${COLLECTIONS_API}?kind=channel`);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['collections'], data['totals']['collections']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch Channels. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Channels Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function getDomain(domainId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/${domainId}`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data['collection'];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch Domain. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Domain Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function updateDomain(domainId, updates) {
|
|
updates = emptyToNull(updates);
|
|
const response = await apiPut(`${COLLECTIONS_API}/${domainId}`, updates);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data['collection'];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to update Domain. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Domain Update Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function getCollectionTagInfo(collectionId, tagName) {
|
|
const body = {
|
|
tag_name: tagName,
|
|
}
|
|
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag_info`, body);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to get tag info. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Tag Info Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
// Tag any Collection (and optionally move its directory).
|
|
export async function tagCollection(collectionId, tagName, directory) {
|
|
const body = {tag_name: tagName};
|
|
if (directory) {
|
|
body['directory'] = directory;
|
|
}
|
|
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/tag`, body);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Unable to tag. See server logs.');
|
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
|
|
export async function tagDomain(domainId, tagName, directory) {
|
|
const body = {
|
|
tag_name: tagName,
|
|
}
|
|
if (directory) {
|
|
body['directory'] = directory;
|
|
}
|
|
const response = await apiPost(`${COLLECTIONS_API}/${domainId}/tag`, body);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to tag Domain. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Domain Tag Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function deleteDomain(domainId) {
|
|
const response = await apiDelete(`${COLLECTIONS_API}/${domainId}`);
|
|
if (response.status !== 204) {
|
|
const message = await getErrorMessage(response, 'Failed to delete domain.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Delete Failed',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function refreshDomain(domainId) {
|
|
let url = `${COLLECTIONS_API}/${domainId}/refresh`;
|
|
const response = await apiPost(url);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, "Failed to refresh this domain's directory");
|
|
toast({
|
|
type: 'error',
|
|
title: 'Failed to refresh',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
} else {
|
|
toast({
|
|
type: 'success',
|
|
title: 'Domain refresh started',
|
|
description: 'The domain directory is being refreshed',
|
|
time: 3000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function previewCollectionReorganization(collectionId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/${collectionId}/reorganize/preview`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to preview reorganization. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Reorganization Preview Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function executeCollectionReorganization(collectionId) {
|
|
const response = await apiPost(`${COLLECTIONS_API}/${collectionId}/reorganize`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
if (data.job_id) {
|
|
toast({
|
|
type: 'success',
|
|
title: 'Reorganization Started',
|
|
description: 'Files are being reorganized in the background',
|
|
time: 3000,
|
|
});
|
|
} else {
|
|
toast({
|
|
type: 'info',
|
|
title: 'No Changes Needed',
|
|
description: data.message || 'No files need reorganization',
|
|
time: 3000,
|
|
});
|
|
}
|
|
return data;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to start reorganization. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Reorganization Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function getReorganizationStatus(collectionId, jobId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/${collectionId}/reorganize/status/${jobId}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to get reorganization status.');
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
// Batch Reorganization API Functions
|
|
|
|
export async function previewBatchReorganization(kind) {
|
|
const endpoint = kind === 'channel' ? 'channels' : 'domains';
|
|
const response = await apiGet(`${COLLECTIONS_API}/reorganize/${endpoint}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, `Unable to get ${kind}s needing reorganization.`);
|
|
toast({
|
|
type: 'error',
|
|
title: 'Batch Reorganization Preview Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function executeBatchReorganization(kind) {
|
|
const endpoint = kind === 'channel' ? 'channels' : 'domains';
|
|
const response = await apiPost(`${COLLECTIONS_API}/reorganize/${endpoint}`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
if (data.batch_job_id) {
|
|
toast({
|
|
type: 'success',
|
|
title: 'Batch Reorganization Started',
|
|
description: `${data.collection_count} ${kind}s are being reorganized`,
|
|
time: 3000,
|
|
});
|
|
} else {
|
|
toast({
|
|
type: 'info',
|
|
title: 'No Changes Needed',
|
|
description: data.message || `No ${kind}s need reorganization`,
|
|
time: 3000,
|
|
});
|
|
}
|
|
return data;
|
|
} else {
|
|
const message = await getErrorMessage(response, `Unable to start batch reorganization. See server logs.`);
|
|
toast({
|
|
type: 'error',
|
|
title: 'Batch Reorganization Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function getBatchReorganizationStatus(batchJobId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/reorganize/batch/status/${batchJobId}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to get batch reorganization status.');
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function fetchCollectionConflicts(collectionId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/${collectionId}/reorganize/conflicts`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to fetch conflicts. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Conflict Fetch Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
export async function getArchive(fileGroupId) {
|
|
const response = await apiGet(`${ARCHIVES_API}/${fileGroupId}`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return {
|
|
file_group: data['file_group'],
|
|
history: data['history'],
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to get Archive. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Archive Error', description: message, time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function generateArchiveScreenshot(fileGroupId) {
|
|
const response = await apiPost(`${ARCHIVES_API}/${fileGroupId}/generate_screenshot`);
|
|
if (response.ok) {
|
|
toast({
|
|
type: 'success',
|
|
title: 'Screenshot Generation Queued',
|
|
description: 'Screenshot generation has been queued. This may take a moment.',
|
|
time: 3000,
|
|
});
|
|
return true;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to queue screenshot generation.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Screenshot Generation Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function postDownload(downloadData) {
|
|
if (!downloadData.downloader) {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Failed to submit download',
|
|
description: 'downloader is required, but was not provided',
|
|
time: 5000,
|
|
})
|
|
throw new Error('downloader is required, but was not provided');
|
|
}
|
|
|
|
const body = {
|
|
urls: downloadData.urls,
|
|
destination: downloadData.destination,
|
|
downloader: downloadData.downloader,
|
|
sub_downloader: downloadData.sub_downloader || null,
|
|
frequency: downloadData.frequency || null,
|
|
tag_names: downloadData.tag_names || null,
|
|
settings: downloadData.settings,
|
|
};
|
|
const response = await apiPost(`${API_URI}/download`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to create Download. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
throw new Error('Failed to create download');
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function putDownload(download_id, downloadData) {
|
|
if (!downloadData.downloader) {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Failed to submit download',
|
|
description: 'downloader is required, but was not provided',
|
|
time: 5000,
|
|
})
|
|
throw new Error('downloader is required, but was not provided');
|
|
}
|
|
|
|
const response = await apiPut(`${API_URI}/download/${download_id}`, downloadData);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to update Download. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
throw new Error('Failed to update download');
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function killDownload(download_id) {
|
|
const response = await apiPost(`${API_URI}/download/${download_id}/kill`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to stop Download. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function restartDownload(download_id) {
|
|
const response = await apiPost(`${API_URI}/download/${download_id}/restart`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to restart Download. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function killDownloads() {
|
|
const response = await apiPost(`${API_URI}/download/kill`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to stop downloading. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function startDownloads() {
|
|
const response = await apiPost(`${API_URI}/download/enable`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to start downloading. See server logs.');
|
|
toast({
|
|
type: 'error', title: 'Download Error', description: message, time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function getDownloaders() {
|
|
// Not toasting because this will happen often. Undefined on any failure, not an empty list, so
|
|
// the form can say the downloaders could not be fetched.
|
|
try {
|
|
const response = await apiGet(`${API_URI}/downloaders`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
} catch (e) {
|
|
// The API is down; reported as undefined below.
|
|
}
|
|
}
|
|
|
|
export async function deleteDownload(downloadId) {
|
|
try {
|
|
const response = await apiDelete(`${API_URI}/download/${downloadId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to delete the download. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Download Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function filesSearch(offset, limit, searchStr, mimetypes, model, tagNames, headline, months, fromYear, toYear, anyTag, order, suffix, path, deep, inProgress) {
|
|
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit), any_tag: anyTag};
|
|
if (suffix) {
|
|
body['suffix'] = suffix;
|
|
}
|
|
if (path) {
|
|
body['path'] = path;
|
|
}
|
|
if (mimetypes) {
|
|
body['mimetypes'] = mimetypes;
|
|
}
|
|
if (model) {
|
|
body['model'] = model;
|
|
}
|
|
if (tagNames) {
|
|
body['tag_names'] = tagNames;
|
|
}
|
|
if (headline) {
|
|
body['headline'] = true;
|
|
}
|
|
if (!_.isEmpty(months)) {
|
|
body['months'] = months.map(i => parseInt(i));
|
|
}
|
|
if (fromYear) {
|
|
body['from_year'] = fromYear;
|
|
}
|
|
if (toYear) {
|
|
body['to_year'] = toYear;
|
|
}
|
|
if (order) {
|
|
body['order'] = order;
|
|
}
|
|
if (deep) {
|
|
body['deep'] = true;
|
|
}
|
|
if (inProgress) {
|
|
body['in_progress'] = true;
|
|
}
|
|
console.info('searching files', body);
|
|
const response = await apiPost(`${API_URI}/files/search`, body);
|
|
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
let [file_groups, total] = [data['file_groups'], data['totals']['file_groups']];
|
|
return [file_groups, total];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot search files. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unable to search files',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
return [null, null];
|
|
}
|
|
}
|
|
|
|
export async function flasherSearch(chip, path) {
|
|
// Search .bin firmware, filtered to ESP images for the given chip (from connecting to the device).
|
|
const body = {};
|
|
if (chip) body['chip'] = chip;
|
|
if (path) body['path'] = path;
|
|
const response = await apiPost(`${API_URI}/flasher/search`, body);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return [data['file_groups'], data['totals']['file_groups']];
|
|
}
|
|
const message = await getErrorMessage(response, 'Cannot search firmware. See server logs.');
|
|
toast({type: 'error', title: 'Unable to search firmware', description: message, time: 5000});
|
|
// Undefined, not [null, null], so the picker can tell a failed search from finding nothing.
|
|
}
|
|
|
|
export async function getFlasherConfigs() {
|
|
// Return the user's saved firmware flashing configurations.
|
|
const response = await apiGet(`${API_URI}/flasher/configs`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data['configurations'] || [];
|
|
}
|
|
// Undefined, not [], so the page can tell a failed fetch from an empty list.
|
|
const message = await getErrorMessage(response, 'Could not get saved firmware configurations');
|
|
toast({type: 'error', title: 'Flasher Error', description: message, time: 5000});
|
|
}
|
|
|
|
export async function saveFlasherConfig(name, files, eraseAll) {
|
|
const response = await apiPost(`${API_URI}/flasher/configs`, {name, files, erase_all: eraseAll});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Cannot save configuration. See server logs.');
|
|
toast({type: 'error', title: 'Unable to save configuration', description: message, time: 5000});
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export async function deleteFlasherConfig(name) {
|
|
const response = await apiDelete(`${API_URI}/flasher/configs/${encodeURIComponent(name)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Cannot delete configuration. See server logs.');
|
|
toast({type: 'error', title: 'Unable to delete configuration', description: message, time: 5000});
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export async function refreshFiles(paths) {
|
|
let response;
|
|
if (Array.isArray(paths) && paths.length > 0) {
|
|
// Refresh user-selected files/directories only.
|
|
const body = {paths};
|
|
console.info(`Refreshing: ${paths}`);
|
|
response = await apiPost(`${API_URI}/files/refresh`, body);
|
|
} else {
|
|
console.info(`Refreshing all files`);
|
|
response = await apiPost(`${API_URI}/files/refresh`);
|
|
}
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Cannot refresh files. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Files Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function makeDirectory(path) {
|
|
const body = {path: path};
|
|
const response = await apiPost(`${API_URI}/files/directory`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to create directory. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unable to create directory',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function getFiles(directories) {
|
|
console.debug(`getFiles ${directories}`);
|
|
let body = {directories: directories || []};
|
|
const response = await apiPost(`${API_URI}/files`, body);
|
|
// Not toasting because this will happen often.
|
|
let {files} = await response.json();
|
|
return files;
|
|
}
|
|
|
|
export async function getFile(path, skipTracking = false) {
|
|
let body = {file: path, skip_tracking: skipTracking};
|
|
const response = await apiPost(`${API_URI}/files/file`, body);
|
|
if (response.ok) {
|
|
const {file} = await response.json();
|
|
return file;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to get file data. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Files Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function deleteFile(paths, force = false) {
|
|
let body = {paths: paths, force: force};
|
|
const response = await apiPost(`${API_URI}/files/delete`, body);
|
|
if (!response.ok) {
|
|
try {
|
|
const json = await response.clone().json();
|
|
if (json.code === 'FILE_GROUP_IS_TAGGED' && json.file_groups) {
|
|
return {tagged: true, file_groups: json.file_groups};
|
|
}
|
|
} catch (e) {
|
|
// Not JSON, fall through to generic error.
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to delete file. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Files Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function getArchiveContents(path) {
|
|
const response = await apiPost(`${API_URI}/files/zip/contents`, {path});
|
|
if (response.ok) {
|
|
const {contents} = await response.json();
|
|
return contents;
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not read archive contents.');
|
|
toast({type: 'error', title: 'Archive Error', description: message, time: 5000});
|
|
}
|
|
|
|
export function downloadArchiveMember(path, member) {
|
|
const params = new URLSearchParams({path, member});
|
|
window.open(`${API_URI}/files/zip/download?${params}`, '_blank');
|
|
}
|
|
|
|
export function getArchiveMemberUrl(path, member) {
|
|
const params = new URLSearchParams({path, member});
|
|
return `${API_URI}/files/zip/download?${params}`;
|
|
}
|
|
|
|
export async function fetchFilesProgress() {
|
|
const response = await apiGet(`${API_URI}/files/worker_status`);
|
|
if (response.ok) {
|
|
const json = await response.json();
|
|
return json['status'];
|
|
}
|
|
}
|
|
|
|
export async function setHotspot(on) {
|
|
let response;
|
|
if (on) {
|
|
response = await apiPost(`${API_URI}/hotspot/on`);
|
|
} else {
|
|
response = await apiPost(`${API_URI}/hotspot/off`);
|
|
}
|
|
if (response.ok) {
|
|
return null;
|
|
} else {
|
|
const content = await response.json();
|
|
const code = content['code'];
|
|
if (code === 'NATIVE_ONLY') {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unsupported!',
|
|
description: 'Hotspot is only supported outside Docker!',
|
|
time: 5000,
|
|
});
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not modify hotspot. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Hotspot Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function setThrottle(on) {
|
|
let response;
|
|
if (on) {
|
|
response = await apiPost(`${API_URI}/throttle/on`);
|
|
} else {
|
|
response = await apiPost(`${API_URI}/throttle/off`);
|
|
}
|
|
if (response.ok) {
|
|
return null;
|
|
} else {
|
|
const content = await response.json();
|
|
const code = content['code'];
|
|
if (code === 'NATIVE_ONLY') {
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unsupported!',
|
|
description: 'Throttle is only supported on a Raspberry Pi!',
|
|
time: 5000,
|
|
});
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not modify throttle. See server logs.');
|
|
toast({type: 'error', title: 'Throttle Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function getMapFiles() {
|
|
const response = await apiGet(`${API_URI}/map/files`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get map files');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
// A map file is named by its path within the map directory; it may be in a sub-directory.
|
|
function encodeMapPath(mapPath) {
|
|
return String(mapPath).split('/').map(encodeURIComponent).join('/');
|
|
}
|
|
|
|
export async function deleteMapFile(mapPath) {
|
|
const response = await apiDelete(`${API_URI}/map/files/${encodeMapPath(mapPath)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete map file');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
// Show a map file on the map, or ignore it.
|
|
export async function setMapFileVisible(mapPath, visible) {
|
|
const response = await apiPost(`${API_URI}/map/files/visible`, {map_path: mapPath, visible});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not change the map file');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function fetchMapSubscriptions() {
|
|
const response = await apiGet(`${API_URI}/map/subscribe`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get map subscriptions');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function mapSubscribe(name, region) {
|
|
const body = {name, region};
|
|
const response = await apiPost(`${API_URI}/map/subscribe`, body);
|
|
if (response.ok) {
|
|
return true;
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not subscribe to map region');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function mapUnsubscribe(region) {
|
|
const response = await apiDelete(`${API_URI}/map/subscribe/${encodeURIComponent(region)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not unsubscribe from map region');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
// The species pack catalog, subscriptions, and downloaded packs: {catalog, subscriptions, files}, or undefined.
|
|
export async function fetchSpeciesSubscriptions() {
|
|
const response = await apiGet(`${API_URI}/map/species/subscribe`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not get species subscriptions');
|
|
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function speciesSubscribe(region) {
|
|
const response = await apiPost(`${API_URI}/map/species/subscribe`, {region});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not subscribe to species');
|
|
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function speciesUnsubscribe(region) {
|
|
const response = await apiDelete(`${API_URI}/map/species/subscribe/${encodeURIComponent(region)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not unsubscribe from species');
|
|
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
// GET a species endpoint: its JSON, or undefined when it failed (a response that was not OK, or no response at
|
|
// all), after an error was shown.
|
|
async function getSpeciesJson(url, failure) {
|
|
try {
|
|
const response = await apiGet(url);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, failure);
|
|
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
|
} catch (e) {
|
|
console.error(e);
|
|
toast({type: 'error', title: 'Species Error', description: failure, time: 5000});
|
|
}
|
|
}
|
|
|
|
// Search the downloaded species: {q, lat, lon, radius_km, group, limit} (any may be omitted).
|
|
// Returns {species, packs, groups}, or undefined (an error was shown).
|
|
export async function searchSpecies(params) {
|
|
const query = new URLSearchParams();
|
|
Object.entries(params).forEach(([key, value]) => {
|
|
if (value !== null && value !== undefined && value !== '') query.set(key, value);
|
|
});
|
|
return await getSpeciesJson(`${API_URI}/map/species?${query}`, 'Could not search species');
|
|
}
|
|
|
|
// A species' details and its Wikipedia article: {taxon_id, name, ..., wikipedia}, or undefined.
|
|
export async function getSpecies(taxonId) {
|
|
return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}`,
|
|
'Could not get the species');
|
|
}
|
|
|
|
// What was seen in the ~11 km square of a point: {bbox, species_count, species: [{..., here_count, here_months}]}.
|
|
// `taxonId`: the species clicked, returned as `taxon` however few times it was seen there.
|
|
export async function getSpeciesHere(lat, lon, limit, taxonId) {
|
|
const query = new URLSearchParams({lat, lon});
|
|
if (limit) query.set('limit', limit);
|
|
if (taxonId) query.set('taxon_id', taxonId);
|
|
return await getSpeciesJson(`${API_URI}/map/species/here?${query}`, 'Could not get the species seen here');
|
|
}
|
|
|
|
// A species' range: {grid, count, deltas} of grid 'low' (0.1°, every observation) or 'high' (0.02°, precise); see
|
|
// rangeGeoJSON.
|
|
export async function getSpeciesRange(taxonId, grid) {
|
|
return await getSpeciesJson(`${API_URI}/map/species/${encodeURIComponent(taxonId)}/range?grid=${grid}`,
|
|
"Could not get the species' range");
|
|
}
|
|
|
|
// Throws (after showing why) when the pack was not deleted, so the button that asked shows it failed.
|
|
export async function deleteSpeciesFiles(region) {
|
|
const response = await apiDelete(`${API_URI}/map/species/files/${encodeURIComponent(region)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete species pack');
|
|
toast({type: 'error', title: 'Species Error', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
}
|
|
|
|
// Which months of the fallout climatology are kept: {version, months, missing, published}, or null.
|
|
export async function getFalloutClimatology() {
|
|
const response = await apiGet(`${API_URI}/map/fallout/climatology`);
|
|
return response.ok ? await response.json() : null;
|
|
}
|
|
|
|
// One month of the fallout climatology, as kept (gzip bytes), or null.
|
|
export async function getFalloutClimatologyMonth(month) {
|
|
const response = await apiGet(`${API_URI}/map/fallout/climatology/${month}`);
|
|
return response.ok ? await response.arrayBuffer() : null;
|
|
}
|
|
|
|
// The field of forecast winds aloft fetched most recently (the fallout simulator), or null.
|
|
export async function getLatestFalloutWinds() {
|
|
const response = await apiGet(`${API_URI}/map/fallout/winds/latest`);
|
|
if (response.ok) {
|
|
return (await response.json()).winds;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// The saved nuclear targets ([{id, lat, lon, label, created, weapon, yield_kt?, fission_fraction?}]), or
|
|
// undefined when they could not be fetched.
|
|
export async function getMapTargets() {
|
|
const response = await apiGet(`${API_URI}/map/nuclear/targets`);
|
|
if (response.ok) {
|
|
return (await response.json()).targets;
|
|
}
|
|
}
|
|
|
|
export async function deleteMapTarget(targetId) {
|
|
const response = await apiDelete(`${API_URI}/map/nuclear/targets/${targetId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete the target');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
return response.ok;
|
|
}
|
|
|
|
// Save `targets` ([{lat, lon, label, weapon, yield_kt?, fission_fraction?, id?}]) in place of the
|
|
// saved targets, which are those of `loadedIds` (refused if they are not): the saved targets, or null.
|
|
export async function saveMapTargets(targets, loadedIds) {
|
|
const response = await apiPut(`${API_URI}/map/nuclear/targets`, {targets, loaded_ids: loadedIds});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not save the targets');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
return (await response.json()).targets;
|
|
}
|
|
|
|
// The weather subscription (a forecast around the nuclear targets, downloaded every day): {enabled,
|
|
// download, targets, spacing, points, seconds, field}, or undefined when it could not be fetched.
|
|
export async function getWeather() {
|
|
const response = await apiGet(`${API_URI}/map/weather`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
}
|
|
|
|
// Subscribe to the weather, or not: the subscription as it is then, or null.
|
|
export async function setWeatherSubscription(enabled) {
|
|
const response = await apiPut(`${API_URI}/map/weather`, {enabled});
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not change the weather download');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
// Download the weather now, rather than when it is next due: the subscription as it is then, or null.
|
|
export async function downloadWeatherNow() {
|
|
const response = await apiPost(`${API_URI}/map/weather/download`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Could not download the weather');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function getMapPins() {
|
|
const response = await apiGet(`${API_URI}/map/pins`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
}
|
|
|
|
export async function addMapPin(lat, lon, label, color) {
|
|
const body = {lat, lon, label, color};
|
|
const response = await apiPost(`${API_URI}/map/pins`, body);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Could not add map pin');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function deleteMapPin(pinId) {
|
|
const response = await apiDelete(`${API_URI}/map/pins/${pinId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete map pin');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function updateMapPin(pinId, label, color) {
|
|
const body = {label, color};
|
|
const response = await apiPut(`${API_URI}/map/pins/${pinId}`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not update map pin');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function setMapDefaultLocation(lat, lon, zoom) {
|
|
try {
|
|
await updateConfig('wrolpi.yaml', {map_default_location: {lat, lon, zoom}});
|
|
toast({type: 'success', title: 'Default Location', description: 'Default map location saved', time: 3000});
|
|
return true;
|
|
} catch (e) {
|
|
toast({type: 'error', title: 'Map Error', description: 'Could not set default location', time: 5000});
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Make a PDF of a map from the images of its layers ({name, blob}, from the bottom up). Returns the
|
|
// PDF (a Blob); throws an Error which says what went wrong.
|
|
// `bounds` is the west, south, east and north edges of the images, in degrees.
|
|
// What exportMapPdf throws when the person exporting stopped it: not a failure to be told of.
|
|
export class ExportCancelled extends Error {
|
|
constructor() {
|
|
super('The export was cancelled');
|
|
this.name = 'ExportCancelled';
|
|
this.cancelled = true;
|
|
}
|
|
}
|
|
|
|
// How many times in a row the server may not answer, while the PDF of an export is made or fetched,
|
|
// before the export is given up on: the API is busy while it makes a PDF, and a Raspberry Pi more so.
|
|
const EXPORT_POLL_FAILURES = 10;
|
|
|
|
// Make the PDF of a map from the images of its layers (see modules/map/export_job.py). The PDF is a
|
|
// minute or two of work on a Raspberry Pi, so it is a Job: the map is described, the image of each
|
|
// layer is sent, the Job is started and watched, and the PDF is fetched when the Job is done.
|
|
//
|
|
// onStatus(text): told how far along it is. isCancelled(): asked, between steps, whether to stop;
|
|
// signal: an AbortSignal which stops it at once, in the middle of a request (an image of a layer
|
|
// is tens of megabytes, and a request to a server which has stopped answering never ends);
|
|
// the server is then told to stop the export and remove what was sent. Rejects with
|
|
// ExportCancelled when it was stopped.
|
|
//
|
|
// However it ends, the server is told to remove what it has of the export: the images are a hundred
|
|
// megabytes and the PDF tens, on a disk which may be an SD card.
|
|
export async function exportMapPdf(
|
|
{width, height, dpi, title, bounds, layers, sheet},
|
|
{onStatus = () => undefined, isCancelled = () => false, signal = undefined, pollMs = 1000} = {},
|
|
) {
|
|
const exports = `${API_URI}/map/export`;
|
|
let exportId = null;
|
|
// Best effort: the server removes old exports itself, later. An export which is stopped while
|
|
// it is being described has no id yet to remove it by: what the server made of it is one small
|
|
// file, which it removes with the old ones.
|
|
const remove = async () => {
|
|
if (exportId) await fetch(`${exports}/${exportId}`, {method: 'DELETE'}).catch(() => undefined);
|
|
};
|
|
try {
|
|
return await sendAndFetch();
|
|
} catch (e) {
|
|
// A request which was stopped because the export was is not a failure to be told of.
|
|
throw signal?.aborted ? new ExportCancelled() : e;
|
|
} finally {
|
|
// Not waited for: a server which is slow to answer is not to keep a PDF from who made it.
|
|
remove();
|
|
}
|
|
|
|
async function sendAndFetch() {
|
|
const send = async (url, init, fallback) => {
|
|
let response;
|
|
try {
|
|
response = await fetch(url, {...init, signal});
|
|
} catch (e) {
|
|
throw new Error('Could not reach the server');
|
|
}
|
|
if (!response.ok) throw new Error(await getErrorMessage(response, fallback));
|
|
return response;
|
|
};
|
|
const pause = () => new Promise(resolve => setTimeout(resolve, pollMs));
|
|
// Stopped by the person exporting: removing the export cancels its Job.
|
|
const stopIfCancelled = async () => {
|
|
if (isCancelled() || signal?.aborted) throw new ExportCancelled();
|
|
};
|
|
|
|
await stopIfCancelled();
|
|
onStatus('Sending the map…');
|
|
const created = await send(exports, {
|
|
method: 'POST',
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: JSON.stringify({width, height, dpi, title, bounds, sheet, layers: layers.map(i => i.name)}),
|
|
}, 'Could not export the map');
|
|
exportId = (await created.json()).export_id;
|
|
|
|
// One layer a request: together they are more than a request may be, and more than a slow
|
|
// connection sends in the time a request is given.
|
|
for (const [index, layer] of layers.entries()) {
|
|
await stopIfCancelled();
|
|
onStatus(`Sending ${layer.name} (${index + 1} of ${layers.length})…`);
|
|
await send(`${exports}/${exportId}/layer/${index}`, {method: 'POST', body: layer.blob},
|
|
`Could not send ${layer.name}`);
|
|
}
|
|
|
|
await stopIfCancelled();
|
|
const started = await send(`${exports}/${exportId}/start`, {method: 'POST'}, 'Could not make the PDF');
|
|
const {job_id: jobId} = await started.json();
|
|
|
|
let failures = 0;
|
|
let waited = 0;
|
|
while (true) {
|
|
await stopIfCancelled();
|
|
let job;
|
|
try {
|
|
const response = await fetch(`${API_URI}/jobs/${jobId}`, {signal});
|
|
if (response.status === 404) throw Object.assign(new Error('The server forgot the export'), {final: true});
|
|
if (!response.ok) throw new Error('Could not ask how the PDF is coming');
|
|
job = (await response.json()).job;
|
|
failures = 0;
|
|
} catch (e) {
|
|
if (e.final || ++failures >= EXPORT_POLL_FAILURES) {
|
|
throw e.final ? e : new Error('Could not reach the server');
|
|
}
|
|
}
|
|
if (job?.status === 'complete') break;
|
|
if (job?.status === 'failed') throw new Error(job.error || 'The PDF could not be made');
|
|
if (job?.status === 'cancelled') throw new ExportCancelled();
|
|
if (job?.status === 'pending') {
|
|
// A Job is taken up within a moment, unless another (a video being transcoded) is in its way.
|
|
onStatus(++waited > 3 ? 'Waiting for another job to finish…' : 'Starting the PDF…');
|
|
} else if (job) {
|
|
onStatus(`Making the PDF (${Math.round(job.progress || 0)}%)…`);
|
|
}
|
|
await pause();
|
|
}
|
|
|
|
// The PDF is made, and kept for an hour. A request which is lost now is asked again: not to be
|
|
// the reason all of it is done again.
|
|
onStatus('Fetching the PDF…');
|
|
for (failures = 0; ; ) {
|
|
await stopIfCancelled();
|
|
let response;
|
|
try {
|
|
response = await fetch(`${exports}/${exportId}/pdf`, {signal});
|
|
} catch (e) {
|
|
response = null;
|
|
}
|
|
if (response?.ok) return await response.blob();
|
|
// What the server refuses, it will refuse again.
|
|
if (response && response.status < 500) {
|
|
throw new Error(await getErrorMessage(response, 'Could not fetch the PDF'));
|
|
}
|
|
if (++failures >= EXPORT_POLL_FAILURES) throw new Error('Could not fetch the PDF');
|
|
await pause();
|
|
}
|
|
}
|
|
}
|
|
|
|
// What the USGS calls a quadrangle: {name, state, exact}, or null where it has no name (most of the
|
|
// world), and when it can not be asked. A map is exported without its name as well as with it.
|
|
export async function getMapQuadName({west, south, east, north}) {
|
|
try {
|
|
const response = await apiGet(
|
|
`${API_URI}/map/quad?west=${west}&south=${south}&east=${east}&north=${north}`);
|
|
if (!response.ok) return null;
|
|
return (await response.json()).quad || null;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function searchMap(query, limit = 12, offset = 0, lat = null, lon = null) {
|
|
let url = `${API_URI}/map/search?q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}`;
|
|
if (lat !== null && lon !== null) {
|
|
url += `&lat=${lat}&lon=${lon}`;
|
|
}
|
|
const response = await apiGet(url);
|
|
if (!response.ok) {
|
|
// Undefined, not {results: []}, so a failed search is not shown as finding nothing.
|
|
return undefined;
|
|
}
|
|
return await response.json();
|
|
}
|
|
|
|
export async function getMapSearchStatus() {
|
|
const response = await apiGet(`${API_URI}/map/search/status`);
|
|
if (!response.ok) {
|
|
// Undefined, not {indexed: [], missing: []}, which read as "no maps are installed".
|
|
return undefined;
|
|
}
|
|
return await response.json();
|
|
}
|
|
|
|
export async function searchEstimateMap(search_str) {
|
|
if (!search_str) return {mapPlaces: 0};
|
|
const response = await apiGet(`${API_URI}/map/search/estimate?q=${encodeURIComponent(search_str)}`);
|
|
if (!response.ok) return {mapPlaces: 0};
|
|
const data = await response.json();
|
|
return {mapPlaces: data.map_places || 0};
|
|
}
|
|
|
|
export async function rebuildMapSearchIndex(mapPath) {
|
|
const response = await apiPost(`${API_URI}/map/search/rebuild/${encodeMapPath(mapPath)}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not rebuild search index');
|
|
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
|
|
} else {
|
|
toast({type: 'success', title: 'Search Index', description: 'Search index build started', time: 3000});
|
|
}
|
|
}
|
|
|
|
export async function clearCompletedDownloads() {
|
|
const response = await apiPost(`${API_URI}/download/clear_completed`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not clear completed downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function deleteOnceDownloads() {
|
|
const response = await apiPost(`${API_URI}/download/delete_once`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete once downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function retryOnceDownloads() {
|
|
const response = await apiPost(`${API_URI}/download/retry_once`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not retry once downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function batchDeleteDownloads(downloadIds) {
|
|
const response = await apiPost(`${API_URI}/download/batch/delete`, {download_ids: downloadIds});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not delete downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function batchRetryDownloads(downloadIds) {
|
|
const response = await apiPost(`${API_URI}/download/batch/retry`, {download_ids: downloadIds});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not retry downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function batchClearDownloads(downloadIds) {
|
|
const response = await apiPost(`${API_URI}/download/batch/clear`, {download_ids: downloadIds});
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Could not clear downloads! See server logs.');
|
|
toast({type: 'error', title: 'Downloads Error', description: message, time: 5000});
|
|
}
|
|
return response
|
|
}
|
|
|
|
export async function getStatistics() {
|
|
const response = await apiGet(`${API_URI}/statistics`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to get file statistics');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function getEvents(after) {
|
|
let uri = `${API_URI}/events/feed`;
|
|
if (after) {
|
|
uri = `${uri}?after=${encodeURIComponent(after)}`
|
|
}
|
|
const response = await apiGet(uri);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
// Not toasting because this happens often.
|
|
return response
|
|
}
|
|
|
|
export async function getTags(tagNames) {
|
|
let uri = `${API_URI}/tag`;
|
|
if (tagNames && tagNames.length > 0) {
|
|
const params = new URLSearchParams();
|
|
(typeof tagNames === 'string' ? [tagNames] : tagNames).forEach(name => params.append('tag_names', name));
|
|
uri = `${uri}?${params.toString()}`;
|
|
}
|
|
const response = await apiGet(uri);
|
|
if (response.ok) {
|
|
const body = await response.json();
|
|
return body;
|
|
}
|
|
// Not toasting because this happens often.
|
|
return response
|
|
}
|
|
|
|
export async function getRecentTags() {
|
|
const uri = `${API_URI}/tag/recent`;
|
|
const response = await apiGet(uri);
|
|
if (response.ok) {
|
|
const body = await response.json();
|
|
return body['tag_names'] || [];
|
|
}
|
|
return [];
|
|
}
|
|
|
|
|
|
export async function tagFileGroup(fileGroup, name) {
|
|
const body = {tag_name: name};
|
|
|
|
const {id, primary_path, path} = fileGroup;
|
|
if (id) {
|
|
body['file_group_id'] = id;
|
|
} else if (primary_path) {
|
|
body['file_group_primary_path'] = primary_path;
|
|
} else if (path) {
|
|
body['file_group_primary_path'] = path;
|
|
}
|
|
|
|
const uri = `${API_URI}/files/tag`;
|
|
const response = await apiPost(uri, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to add tag');
|
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function untagFileGroup(fileGroup, name) {
|
|
const body = {tag_name: name};
|
|
|
|
const {id, primary_path, path} = fileGroup;
|
|
if (id) {
|
|
body['file_group_id'] = id;
|
|
} else if (primary_path) {
|
|
body['file_group_primary_path'] = primary_path;
|
|
} else if (path) {
|
|
body['file_group_primary_path'] = path;
|
|
}
|
|
|
|
const uri = `${API_URI}/files/untag`;
|
|
const response = await apiPost(uri, body)
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Unable to untag');
|
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function saveTag(name, color, id) {
|
|
const body = {name: name, color: color};
|
|
let uri = `${API_URI}/tag`;
|
|
if (id) {
|
|
uri = `${uri}/${id}`;
|
|
}
|
|
const response = await apiPost(uri, body);
|
|
if (id && response.status === 200) {
|
|
toast({
|
|
type: 'info', title: 'Saved tag', description: `Saved tag: ${name}`, time: 2000,
|
|
});
|
|
} else if (response.status === 201) {
|
|
toast({
|
|
type: 'info', title: 'Created new tag', description: `Created new tag: ${name}`, time: 2000,
|
|
});
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Unable to save tag');
|
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function deleteTag(id, name) {
|
|
const uri = `${API_URI}/tag/${id}`;
|
|
const response = await apiDelete(uri);
|
|
if (response.status === 400) {
|
|
const content = await response.json();
|
|
const message = await getErrorMessage(response, 'Cannot delete, Tag is used');
|
|
if (content['code'] === 'USED_TAG') {
|
|
toast({
|
|
type: 'error', title: 'Error!', description: message, time: 5000,
|
|
})
|
|
}
|
|
} else if (!response.ok) {
|
|
console.error('Failed to delete tag');
|
|
const message = await getErrorMessage(response, `Unable to delete tag: ${name}`);
|
|
toast({type: 'error', title: 'Tag Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function sendNotification(message, url) {
|
|
const body = {message, url};
|
|
const response = await apiPost(`${API_URI}/notify`, body);
|
|
if (response.status === 201) {
|
|
toast({type: 'success', title: 'Shared', description: 'Your share was sent', time: 2000});
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Your share failed to send!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function searchDirectories(path) {
|
|
const body = {path: path || ''};
|
|
const response = await apiPost(`${API_URI}/files/search_directories`, body);
|
|
if (response.status === 204) {
|
|
return [];
|
|
} else if (response.status === 200) {
|
|
const content = await response.json();
|
|
return {
|
|
is_dir: content.is_dir,
|
|
directories: content.directories,
|
|
channel_directories: content.channel_directories,
|
|
domain_directories: content.domain_directories,
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to search directories!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the file worker job id of a queued rename (a directory), or null when the rename is already done.
|
|
*/
|
|
export async function renamePath(path, newName) {
|
|
const body = {path, new_name: newName};
|
|
const response = await apiPost(`${API_URI}/files/rename`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to rename!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
const json = await response.json();
|
|
return json['job_id'] || null;
|
|
}
|
|
|
|
/**
|
|
* Returns a file worker job's status ('pending', 'complete', or 'failed'), or null if it is unknown.
|
|
*/
|
|
export async function fetchFileWorkerJobStatus(jobId) {
|
|
const response = await apiGet(`${API_URI}/files/jobs/${encodeURIComponent(jobId)}`);
|
|
if (!response.ok) {
|
|
return null;
|
|
}
|
|
const json = await response.json();
|
|
return json['status'];
|
|
}
|
|
|
|
export async function movePaths(destination, paths) {
|
|
const body = {destination, paths};
|
|
const response = await apiPost(`${API_URI}/files/move`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to move!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function ignoreDirectory(directory) {
|
|
const body = {path: directory};
|
|
const response = await apiPost(`${API_URI}/files/ignore_directory`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to ignore directory!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function unignoreDirectory(directory) {
|
|
const body = {path: directory};
|
|
const response = await apiPost(`${API_URI}/files/unignore_directory`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to unignore directory!');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function fetchZims() {
|
|
const response = await apiGet(`${API_URI}/zim`);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
zims: content['zims'],
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot fetch Zims');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function fetchZimSubscriptions() {
|
|
const response = await apiGet(`${API_URI}/zim/subscribe`);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
subscriptions: content['subscriptions'],
|
|
catalog: content['catalog'],
|
|
iso_639_codes: content['iso_639_codes'],
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot fetch Zim Subscriptions');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function searchZim(offset, limit, searchStr, zimId, activeTags) {
|
|
offset = parseInt(offset || 0);
|
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
|
let body = {offset, limit, search_str: searchStr, tag_names: activeTags || []};
|
|
|
|
console.debug(`Searching Zim ${zimId} for: ${searchStr} tags: ${activeTags}`);
|
|
const response = await apiPost(`${ZIM_API}/search/${zimId}`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
const zim = content['zim'];
|
|
const searchLength = zim['search'].length;
|
|
console.debug(`Got ${searchLength} results for Zim ${zimId}`);
|
|
return content['zim'];
|
|
}
|
|
}
|
|
|
|
export async function tagZimEntry(zim_id, zim_entry, name) {
|
|
const body = {tag_name: name, zim_id: zim_id, zim_entry: zim_entry};
|
|
|
|
const uri = `${API_URI}/zim/tag`;
|
|
const response = await apiPost(uri, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to add zim tag');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function untagZimEntry(zim_id, zim_entry, name) {
|
|
const body = {tag_name: name, zim_id: zim_id, zim_entry: zim_entry};
|
|
|
|
const uri = `${API_URI}/zim/untag`;
|
|
const response = await apiPost(uri, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to untag zim');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function zimSubscribe(name, language) {
|
|
const body = {name, language};
|
|
const response = await apiPost(`${API_URI}/zim/subscribe`, body);
|
|
return response.status === 201;
|
|
}
|
|
|
|
export async function zimUnsubscribe(id) {
|
|
const response = await apiDelete(`${API_URI}/zim/subscribe/${id}`);
|
|
return response.status === 204;
|
|
}
|
|
|
|
export async function setZimAutoSearch(id, auto_search) {
|
|
const body = {auto_search};
|
|
const response = await apiPost(`${API_URI}/zim/${id}/auto_search`, body);
|
|
if (response.status !== 204) {
|
|
throw new Error('Failed to set Zim auto search');
|
|
}
|
|
}
|
|
|
|
export async function fetchDecoded(vinNumber) {
|
|
const body = {vin_number: vinNumber};
|
|
const response = await apiPost(`${API_URI}/vin_number_decoder`, body);
|
|
if (response.status === 200) {
|
|
const content = await response.json();
|
|
return content['vin'];
|
|
} else if (response.status === 400) {
|
|
console.error('Invalid VIN Number');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function searchSuggestions(search_str) {
|
|
const body = {search_str};
|
|
const response = await apiPost(`${API_URI}/search_suggestions`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
|
|
return {
|
|
channels: content.channels,
|
|
domains: content.domains,
|
|
authors: content.authors || [],
|
|
subjects: content.subjects || [],
|
|
repos: content.repos || [],
|
|
}
|
|
} else {
|
|
console.error('Failed to get file search suggestions!');
|
|
}
|
|
}
|
|
|
|
export async function searchEstimateFiles(search_str, tagNames, mimetypes, months, dateRange, anyTag) {
|
|
months = months ? months.map(i => parseInt(i)) : [];
|
|
|
|
const body = {search_str, tag_names: tagNames, mimetypes, months, any_tag: anyTag};
|
|
if (dateRange) {
|
|
body['from_year'] = dateRange[0];
|
|
body['to_year'] = dateRange[1];
|
|
}
|
|
const response = await apiPost(`${API_URI}/search_file_estimates`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
|
|
return {
|
|
fileGroups: content.file_groups,
|
|
fileGroupsDeep: content.file_groups_deep,
|
|
}
|
|
} else {
|
|
console.error('Failed to get file search estimates!');
|
|
}
|
|
}
|
|
|
|
export async function searchEstimateZims(search_str, tagNames) {
|
|
const body = {search_str: search_str, tag_names: tagNames};
|
|
const response = await apiPost(`${API_URI}/zim/search_estimates`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
zimsEstimates: content.zims_estimates,
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function searchEstimateOthers(tagNames, searchStr) {
|
|
const body = {tag_names: tagNames, search_str: searchStr || null};
|
|
const response = await apiPost(`${API_URI}/search_other_estimates`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
others: content.others,
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function searchChannels(tagNames, searchStr) {
|
|
const body = {tag_names: tagNames, search_str: searchStr};
|
|
const response = await apiPost(`${API_URI}/videos/channels/search`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {
|
|
channels: content.channels,
|
|
}
|
|
}
|
|
}
|
|
|
|
// Collections of `kind` whose name matches `searchStr` and/or which have any of the tags.
|
|
export async function searchCollections(kind, tagNames, searchStr) {
|
|
const body = {kind, tag_names: tagNames, search_str: searchStr};
|
|
const response = await apiPost(`${COLLECTIONS_API}/search`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {collections: content.collections};
|
|
}
|
|
}
|
|
|
|
export async function getOutdatedZims() {
|
|
const response = await apiGet(`${API_URI}/zim/outdated`);
|
|
if (response.status === 200) {
|
|
const content = await response.json();
|
|
return {
|
|
outdated: content['outdated'],
|
|
current: content['current'],
|
|
}
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot fetch outdated Zims. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function deleteOutdatedZims() {
|
|
const response = await apiDelete(`${API_URI}/zim/outdated`);
|
|
return response.status === 204;
|
|
}
|
|
|
|
export async function postShutdown() {
|
|
// Call Controller directly for system shutdown
|
|
const {shutdownSystem} = await import('./api/controller');
|
|
try {
|
|
const result = await shutdownSystem();
|
|
if (result.success) {
|
|
return null; // Success
|
|
}
|
|
return {code: 'SHUTDOWN_FAILED', error: result.error};
|
|
} catch (e) {
|
|
return {code: 'SHUTDOWN_FAILED', error: e.message};
|
|
}
|
|
}
|
|
|
|
export async function postRestart() {
|
|
// Call Controller directly for system reboot
|
|
const {rebootSystem} = await import('./api/controller');
|
|
try {
|
|
const result = await rebootSystem();
|
|
if (result.success) {
|
|
return null; // Success
|
|
}
|
|
return {code: 'SHUTDOWN_FAILED', error: result.error};
|
|
} catch (e) {
|
|
return {code: 'SHUTDOWN_FAILED', error: e.message};
|
|
}
|
|
}
|
|
|
|
export async function postVideoFileFormat(video_file_format) {
|
|
const body = {video_file_format};
|
|
return await apiPost(`${API_URI}/videos/file_format`, body);
|
|
}
|
|
|
|
export async function checkUpgrade(force = false) {
|
|
const url = force ? `${API_URI}/upgrade/check?force=true` : `${API_URI}/upgrade/check`;
|
|
const response = await apiGet(url);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// `branch` upgrades from that branch; without it the current branch is upgraded.
|
|
export async function triggerUpgrade(branch = null) {
|
|
const body = branch ? {branch} : undefined;
|
|
const response = await apiPost(`${API_URI}/upgrade/start`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to start upgrade. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Upgrade Error',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function getBulkTagPreview(paths) {
|
|
const body = {paths};
|
|
const response = await apiPost(`${API_URI}/files/bulk_tag/preview`, body);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Failed to get bulk tag preview.');
|
|
toast({type: 'error', title: 'Bulk Tag Error', description: message, time: 5000});
|
|
}
|
|
}
|
|
|
|
export async function applyBulkTags(paths, addTagNames, removeTagNames) {
|
|
const body = {
|
|
paths,
|
|
add_tag_names: addTagNames || [],
|
|
remove_tag_names: removeTagNames || [],
|
|
};
|
|
const response = await apiPost(`${API_URI}/files/bulk_tag/apply`, body);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to apply bulk tags.');
|
|
toast({type: 'error', title: 'Bulk Tag Error', description: message, time: 5000});
|
|
}
|
|
return response;
|
|
}
|
|
|
|
export async function getBulkTagProgress() {
|
|
const response = await apiGet(`${API_URI}/files/bulk_tag/progress`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
// Not toasting because this happens often during polling.
|
|
return null;
|
|
}
|
|
|
|
// Encrypted Cookies API
|
|
|
|
export async function getCookiesStatus() {
|
|
const response = await apiGet(`${VIDEOS_API}/cookies/status`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to get cookies status.');
|
|
toast({type: 'error', title: 'Cookies Error', description: message, time: 5000});
|
|
return null;
|
|
}
|
|
|
|
export async function uploadCookies(cookiesContent, password) {
|
|
const body = {cookies_content: cookiesContent, password};
|
|
const response = await apiPost(`${VIDEOS_API}/cookies`, body);
|
|
if (response.ok) {
|
|
toast({type: 'success', title: 'Cookies Saved', description: 'Cookies encrypted and saved successfully.', time: 3000});
|
|
return {success: true};
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to save cookies.');
|
|
toast({type: 'error', title: 'Cookies Error', description: message, time: 5000});
|
|
return {success: false, error: message};
|
|
}
|
|
|
|
export async function deleteCookies() {
|
|
const response = await apiDelete(`${VIDEOS_API}/cookies`);
|
|
if (response.status === 204) {
|
|
toast({type: 'success', title: 'Cookies Deleted', description: 'Encrypted cookies file deleted.', time: 3000});
|
|
return {success: true};
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to delete cookies.');
|
|
toast({type: 'error', title: 'Cookies Error', description: message, time: 5000});
|
|
return {success: false, error: message};
|
|
}
|
|
|
|
export async function unlockCookies(password) {
|
|
const body = {password};
|
|
const response = await apiPost(`${VIDEOS_API}/cookies/unlock`, body);
|
|
if (response.ok) {
|
|
toast({type: 'success', title: 'Cookies Unlocked', description: 'Cookies decrypted and ready for downloads.', time: 3000});
|
|
return {success: true};
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to unlock cookies.');
|
|
toast({type: 'error', title: 'Cookies Error', description: message, time: 5000});
|
|
return {success: false, error: message};
|
|
}
|
|
|
|
export async function lockCookies() {
|
|
const response = await apiPost(`${VIDEOS_API}/cookies/lock`);
|
|
if (response.ok) {
|
|
toast({type: 'success', title: 'Cookies Locked', description: 'Cookies cleared from memory.', time: 3000});
|
|
return {success: true};
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to lock cookies.');
|
|
toast({type: 'error', title: 'Cookies Error', description: message, time: 5000});
|
|
return {success: false, error: message};
|
|
}
|
|
|
|
export async function fetchSuggestedUserAgent() {
|
|
const response = await apiGet(`${VIDEOS_API}/suggested-user-agent`);
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
return data?.user_agent || '';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
// Docs API
|
|
const DOCS_API = '/api/docs';
|
|
|
|
export async function getDocStatistics() {
|
|
return await apiGet(`${DOCS_API}/statistics`);
|
|
}
|
|
|
|
export async function getDoc(fileGroupId) {
|
|
return await apiGet(`${DOCS_API}/${fileGroupId}`);
|
|
}
|
|
|
|
|
|
export async function searchDocs(offset, limit, searchStr, order, tagNames, author, subject, mimetype, deep, anyTag) {
|
|
offset = parseInt(offset || 0);
|
|
limit = parseInt(limit || DEFAULT_LIMIT);
|
|
let body = {offset, limit};
|
|
if (searchStr) {
|
|
body['search_str'] = searchStr;
|
|
}
|
|
if (order) {
|
|
body['order_by'] = order;
|
|
}
|
|
if (tagNames && tagNames.length > 0) {
|
|
body['tag_names'] = tagNames;
|
|
}
|
|
if (author) {
|
|
body['author'] = author;
|
|
}
|
|
if (subject) {
|
|
body['subject'] = subject;
|
|
}
|
|
if (mimetype) {
|
|
body['mimetype'] = mimetype;
|
|
}
|
|
if (deep) {
|
|
body['deep'] = true;
|
|
}
|
|
if (anyTag) {
|
|
body['any_tag'] = true;
|
|
}
|
|
|
|
console.debug('searching docs', body);
|
|
const response = await apiPost(`${DOCS_API}/search`, body);
|
|
if (response.ok) {
|
|
let data = await response.json();
|
|
return [data['file_groups'], data['totals']['file_groups']];
|
|
} else {
|
|
const message = await getErrorMessage(response, 'Cannot search docs. See server logs.');
|
|
toast({
|
|
type: 'error',
|
|
title: 'Unable to search docs',
|
|
description: message,
|
|
time: 5000,
|
|
});
|
|
throw Error(message);
|
|
}
|
|
}
|
|
|
|
|
|
export async function fetchPlaylists() {
|
|
const response = await apiGet(`${COLLECTIONS_API}?kind=playlist`);
|
|
if (response.ok) {
|
|
return (await response.json())['collections'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to fetch playlists.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function getPlaylist(playlistId) {
|
|
const response = await apiGet(`${COLLECTIONS_API}/${playlistId}`);
|
|
if (response.ok) {
|
|
return (await response.json())['collection'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to fetch playlist.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function createPlaylist(name, description, tagName) {
|
|
// Trailing slash avoids Sanic's 302 redirect on the root POST route (which would drop the body).
|
|
const response = await apiPost(`${COLLECTIONS_API}/`,
|
|
{name, description, tag_name: tagName || null, kind: 'playlist'});
|
|
if (response.ok) {
|
|
return (await response.json())['collection'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to create playlist.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function deletePlaylist(playlistId) {
|
|
const response = await apiDelete(`${COLLECTIONS_API}/${playlistId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to delete playlist.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
}
|
|
|
|
export async function addPlaylistItem(playlistId, item) {
|
|
// item: {item_kind, url?, title?, file_group_id?, zim_id?, zim_entry?, position?}
|
|
const response = await apiPost(`${COLLECTIONS_API}/${playlistId}/items`, item);
|
|
if (response.ok) {
|
|
return (await response.json())['item'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to add item.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function removePlaylistItem(playlistId, itemId) {
|
|
const response = await apiDelete(`${COLLECTIONS_API}/${playlistId}/items/${itemId}`);
|
|
if (!response.ok) {
|
|
const message = await getErrorMessage(response, 'Failed to remove item.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
}
|
|
|
|
export async function reorderPlaylistItems(playlistId, itemIds) {
|
|
const response = await apiPut(`${COLLECTIONS_API}/${playlistId}/items/order`, {item_ids: itemIds});
|
|
if (response.ok) {
|
|
return (await response.json())['collection'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to reorder items.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
// Update a playlist's name, description, and/or custom directory ('' clears the directory).
|
|
export async function updatePlaylist(playlistId, {name, description, directory}) {
|
|
const response = await apiPut(`${COLLECTIONS_API}/${playlistId}`, {name, description, directory});
|
|
if (response.ok) {
|
|
return (await response.json())['collection'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to update playlist.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
// Set (tagName) or clear (tagName='') a playlist's single tag. When `directory` is given, the
|
|
// playlist also moves there (the managed tag location is normalized back to auto-managed).
|
|
export async function setPlaylistTag(playlistId, tagName, directory) {
|
|
const body = {tag_name: tagName || ''};
|
|
if (directory !== null && directory !== undefined) {
|
|
body.directory = directory;
|
|
}
|
|
const response = await apiPut(`${COLLECTIONS_API}/${playlistId}`, body);
|
|
if (response.ok) {
|
|
return (await response.json())['collection'];
|
|
}
|
|
const message = await getErrorMessage(response, 'Failed to update playlist tag.');
|
|
toast({type: 'error', title: 'Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
// Bookmarks: a tree of nodes, a node with `children` being a directory.
|
|
export async function getBookmarks() {
|
|
const response = await apiGet(`${API_URI}/bookmarks`);
|
|
if (response.ok) {
|
|
return (await response.json())['bookmarks'];
|
|
}
|
|
throw new Error('Could not fetch bookmarks');
|
|
}
|
|
|
|
async function bookmarksModify(request, fallbackMessage) {
|
|
const response = await request;
|
|
if (response.ok) {
|
|
return response.status === 204 ? null : await response.json();
|
|
}
|
|
const message = await getErrorMessage(response, fallbackMessage);
|
|
toast({type: 'error', title: 'Bookmarks Error', description: message, time: 5000});
|
|
throw new Error(message);
|
|
}
|
|
|
|
export async function addBookmark({name, url, new_tab = false, parent_id = null, position = null}) {
|
|
const body = {name, url, new_tab, parent_id, position};
|
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks`, body), 'Could not add bookmark');
|
|
}
|
|
|
|
export async function addBookmarkDirectory({name, parent_id = null, position = null}) {
|
|
const body = {name, parent_id, position};
|
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/directory`, body), 'Could not add directory');
|
|
}
|
|
|
|
export async function updateBookmark(nodeId, {name, url, new_tab}) {
|
|
const body = {name, url, new_tab};
|
|
return await bookmarksModify(apiPut(`${API_URI}/bookmarks/${nodeId}`, body), 'Could not update bookmark');
|
|
}
|
|
|
|
export async function moveBookmark(nodeId, parent_id, position = null) {
|
|
const body = {parent_id, position};
|
|
return await bookmarksModify(apiPost(`${API_URI}/bookmarks/${nodeId}/move`, body), 'Could not move bookmark');
|
|
}
|
|
|
|
export async function deleteBookmark(nodeId) {
|
|
return await bookmarksModify(apiDelete(`${API_URI}/bookmarks/${nodeId}`), 'Could not delete bookmark');
|
|
}
|
|
|
|
async function reposError(response, fallbackMessage) {
|
|
const message = await getErrorMessage(response, fallbackMessage);
|
|
toast({type: 'error', title: 'Repos Error', description: message, time: 5000});
|
|
throw Error(message);
|
|
}
|
|
|
|
export async function fetchRepos() {
|
|
const response = await apiGet(REPOS_API);
|
|
if (response.ok) {
|
|
return (await response.json())['repos'];
|
|
}
|
|
await reposError(response, 'Failed to fetch repos.');
|
|
}
|
|
|
|
export async function getRepo(repoId) {
|
|
const response = await apiGet(`${REPOS_API}/${repoId}`);
|
|
if (response.ok) {
|
|
return (await response.json())['repo'];
|
|
}
|
|
await reposError(response, 'Failed to fetch repo.');
|
|
}
|
|
|
|
// `repo`: {url, directory?, name?, tag_name?, frequency?, mode?, branch?, description?}
|
|
export async function createRepo(repo) {
|
|
const response = await apiPost(REPOS_API, repo);
|
|
if (response.ok) {
|
|
return (await response.json())['repo'];
|
|
}
|
|
await reposError(response, 'Failed to add repo.');
|
|
}
|
|
|
|
// `changes`: {description?, frequency?, mode?, branch?}. An empty branch follows the remote's default branch.
|
|
export async function updateRepo(repoId, changes) {
|
|
const response = await apiPut(`${REPOS_API}/${repoId}`, changes);
|
|
if (response.ok) {
|
|
return (await response.json())['repo'];
|
|
}
|
|
await reposError(response, 'Failed to update repo.');
|
|
}
|
|
|
|
export async function deleteRepo(repoId, deleteFiles = false) {
|
|
const response = await apiDelete(`${REPOS_API}/${repoId}?delete_files=${deleteFiles ? 'true' : 'false'}`);
|
|
if (!response.ok) {
|
|
await reposError(response, 'Failed to delete repo.');
|
|
}
|
|
}
|
|
|
|
// Download the repo's updates now.
|
|
export async function updateRepoNow(repoId) {
|
|
const response = await apiPost(`${REPOS_API}/${repoId}/update`);
|
|
if (!response.ok) {
|
|
await reposError(response, 'Failed to start the repo update.');
|
|
}
|
|
}
|
|
|
|
// One directory of a repo's files: {path, entries: [{name, path, is_dir, size}], readme_path}.
|
|
export async function getRepoTree(repoId, path) {
|
|
const query = path ? `?path=${encodeURIComponent(path)}` : '';
|
|
const response = await apiGet(`${REPOS_API}/${repoId}/tree${query}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
await reposError(response, 'Failed to list the repo files.');
|
|
}
|
|
|
|
// Repos matching the search (name and README) and/or the tags. Each has an escaped `readme_headline`.
|
|
export async function searchRepos(searchStr, tagNames) {
|
|
const body = {search_str: searchStr || null, tag_names: tagNames || []};
|
|
const response = await apiPost(`${REPOS_API}/search`, body);
|
|
if (response.ok) {
|
|
const content = await response.json();
|
|
return {repos: content.repos, total: content.totals.repos};
|
|
}
|
|
await reposError(response, 'Failed to search repos.');
|
|
}
|
|
|
|
// The commits of a repo's checked out branch, newest first: {commits: [{sha, author, date, message}], total}.
|
|
export async function getRepoLog(repoId, offset = 0, limit = 50) {
|
|
const response = await apiGet(`${REPOS_API}/${repoId}/log?limit=${limit}&offset=${offset}`);
|
|
if (response.ok) {
|
|
return await response.json();
|
|
}
|
|
await reposError(response, 'Failed to fetch the repo history.');
|
|
}
|
|
|
|
// A ZIP of a repo's checked out files; the browser downloads it.
|
|
export function repoArchiveURL(repoId) {
|
|
return `${REPOS_API}/${repoId}/archive.zip`;
|
|
}
|
|
|
|
// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing.
|
|
export async function inspectRepoImport(directory, name, tagName, url) {
|
|
const body = {directory, name: name || null, tag_name: tagName || null, url: url || null};
|
|
const response = await apiPost(`${REPOS_API}/import/inspect`, body);
|
|
if (response.ok) {
|
|
return {inspection: (await response.json())['inspection']};
|
|
}
|
|
return {error: await getErrorMessage(response, 'Cannot import this directory.')};
|
|
}
|
|
|
|
// Import an existing git clone as a Repo; it stays where it is. `repo`: {directory, confirm, url?, name?, ...}
|
|
export async function importRepo(repo) {
|
|
const response = await apiPost(`${REPOS_API}/import`, repo);
|
|
if (response.ok) {
|
|
return (await response.json())['repo'];
|
|
}
|
|
await reposError(response, 'Failed to import the repo.');
|
|
}
|
|
|
|
// --- Torrents (they reach the Internet only through the VPN) ---
|
|
|
|
const TORRENTS_API = `${API_URI}/torrents`;
|
|
|
|
async function torrentsRequest(response, fallbackMessage) {
|
|
if (!response.ok) {
|
|
throw new Error(await getErrorMessage(response, fallbackMessage));
|
|
}
|
|
return response.status === 204 ? null : response;
|
|
}
|
|
|
|
export async function getTorrents() {
|
|
const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents');
|
|
return await response.json();
|
|
}
|
|
|
|
export async function uploadTorrent(file, destination) {
|
|
const form = new FormData();
|
|
form.append('torrent', file);
|
|
if (destination) {
|
|
form.append('destination', destination);
|
|
}
|
|
const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}),
|
|
'Failed to add the .torrent file');
|
|
return await response.json();
|
|
}
|
|
|
|
export async function pauseTorrent(hash) {
|
|
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent');
|
|
}
|
|
|
|
export async function resumeTorrent(hash) {
|
|
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent');
|
|
}
|
|
|
|
export async function removeTorrent(hash, deleteFiles = false) {
|
|
await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`),
|
|
'Failed to remove the torrent');
|
|
}
|
|
|
|
export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) {
|
|
await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`,
|
|
{seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits');
|
|
}
|
|
|
|
export async function setTorrentSpeedLimits(upload, download) {
|
|
await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}),
|
|
'Failed to save the speed limits');
|
|
}
|
|
|
|
export function torrentFileUrl(hash) {
|
|
return `${TORRENTS_API}/${hash}/torrent`;
|
|
}
|
|
|
|
export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) {
|
|
const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`,
|
|
{path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent');
|
|
return (await response.json()).job_id;
|
|
}
|