wrolpi/app/src/api.js
dependabot[bot] d4ed5fa5ce Fixing JS warnings.
Handling all combinations of toggle in light and dark.

Changing CPUUsageProgress colors to be more readable in dark mode.

Moving theme handling into Theme.js.  Importing element wrappers from Theme.js to handle element theming.

Changing video menu to dark mode.

Creating ThemeContext to share Dark Mode setting.

Removing duplicate code for search functions.

Displaying X when downloads are disabled.

Using react context to share settings across components.

Refusing to start workers when WROL Mode is enabled.

Changing warning to debug.

Queuing recurring downloads first.

Adding Video.url index.

Adding special handling for youtube shorts to videos.

Reworking Downloads to have one worker per process.

Testing creating downloads and getting downloaders.

Testing video validation and poster generation.  Testing video statistics.

Increasing inventory test coverage.

Adding pytest.ini to automatically detect async test.

Adding more archive test coverage.

Testing Archive CRUD.

Catching and logging when encountering error during indexing.

Using FileIcon when Archive has no screenshot.

A Video will be assigned to a Channel by its info json first, then to its directory.

Including suffix in File json.

Adding index for File.suffix.

Gathering suffix during indexing.

Passing entire file down to FileIcon.

Moving logging up.

Returning File.associated in file json.

Associated files are last in file search.

Removing duplicate refreshing code by creating new _refresh_directory function.

Changing File.idempotency to a datetime to avoid having to clear idempotency.

Truncating indexes to avoid error with large files.

Don't overwrite video data when info json is empty.

Using already_downloaded for channel videos.

Awaiting refresh in Channel.refresh.

Testing that videos already downloaded aren't downloaded again.

Adding indexes for video/archive referenced paths.

Changing grid width for mobile or computer.

Adding button to refresh specific directories.

Restoring Channel edit link.

Fixing caption path in video_modeler.

Adding ZIP files to mimetype colors.

Using model instead of first file's model.

Fetching File models in batches to avoid issuing a SELECT for every File with a model.

Flushing generated poster file.

Getting Channel in VideoPage, relying on Video.channl_id, falling back to URL's channel_id.

Attaching Video to it's Channel during download.

Using ExternalCardLink for ArchivePage singlefile link.

Validating and indexing videos after download.

Handling glob when file name contains matching characters.

Reworking and testing split_path_stem_and_suffix and glob_shared_stem.

Adding associated video files to DB during upsert.

Adding pending downloads to dashboard.

Hiding status when download is open.

Handling when load is empty.

Adding load statistics to Dashboard.

Limiting concurrent after_refresh functions.

Handling when no onSelect is declared.

Adding ImageRow for FileTable.

Moving image date into Card.Meta.

Using ExternalLink for FileCard.

Using ExternalLink for ImageCard.

Handling when error occurs during refresh of a directory.  Committing during refresh to avoid losing all files if an error occurs.

Removing api health check to avoid spamming logs.

Creating ImageCard to display image posters when they aren't too large.

Removing archive.domain_id not null.

Reworking file refresh to process all files in a single directory.

Bumping version for major file rework.

No longer checking for video corruption.

Adding duration by default to speed up tests.

Using register_indexer for all indexers.

Adding CPU usage progress bar in Welcome.

Modifying TextIndexer to ignore large text files.

Counting all files during refresh.

Adding refresh_logger to clarify logging.  Checking for wrol_mode before refresh functions.

Removing unused idempotency from video/channel tables.

Using magic module to speed up mimetype identification.

All tests pass.

Archive tests pass.

Changing video get endpoint to return 'file' to avoid ambiguity.

Video tests pass.

Simplifying regex filtering.

Using regex to ignore case when filtering.

Converting all channel classes to functions.

Restoring channel refresh and download buttons.

Matching format of Archive and Video pages.

Adding sorting to Archives search.

Reworking video orders for file search.  Using SearchInput for videos search.

Archives can be searched on the Archives page.  Domains can be filtered.

Reworking Archive search to use Files.  Videos, Archives and Global search use the FilesView.

Videos are claimed by their Channel based on the Channel's directory.  Prev and Next video cards are displayed on the VideoPage.

Creating useVideo for reworked VideoWrapper and VideoPage.

Adding Paginator to FilesView.

Moving file refresh button out of manage tab.  Removing Files page tabs.  Limiting refresh to one at a time.

Adding class for card icon to match poster height.

Video and Archives always re-claim their files on refresh.

Archive files are indexed and claimed.

FileView table is compact and striped.

Videos page uses FileView.

Updated navlinks to router v6.

Removing ! character from file names.

Disabling select button when cards are visible.

Adding show/hide button for FileTable selection.

The Archive Page is displayed.

Adding mimetype dropdown.

Upgrading to React Router v6 for useSearchParams.

Validating video during modeling.  Removing screenshot during corruption check because it was very slow.  Updating app to use video files as search results.

Updating video search to return Files.

Video and WROLPi tests pass.

Creating function to refresh files within a channel's directory.

Removing troubleshooting print.  Updating result order in test.

Reworking video_factory to handle a specific video file location.

Returning video model on file search.

Getting session using video_file.

Screenshotting when checking for video corruption.

Reducing ffmpeg calls by gathering duration during poster generation.

Moving video file matching into model.

VideoIndexer is moved into video module.  Video files are validated.

Moving files module into wrolpi in preparation to use it in modules.

Title and contents are indexed for text file.

Files are indexed on refresh by using their indexer.

Zip files are indexed using their contents.

Testing multiple zip files.

Adding unique to file.path.  Checking that the correct indexer is used.

Adding index to file.modification_datetime and file.size.

Handling file info gathering in File.do_index.  Only reading contents of file if file.indexed is False.

Video model is found during file refresh.  A Video record is created that has the associated files.

Videos without associated files are found.

Videos are found using registered video_modeler() rather than in refresh code.

Removing old video columns.

Handling video info json files.

Trying to import each module individually.  Will continue to import modules even if one fails.

Reworking refresh so it performs less DB calls.

Converting file.path to primary key.

file.path is always a pathlib.Path.

Updating video_factory to use new file system, testing it.

Bump sanic from 21.9.1 to 21.12.2 in /docker/archive

Bumps [sanic](https://github.com/sanic-org/sanic) from 21.9.1 to 21.12.2.
- [Release notes](https://github.com/sanic-org/sanic/releases)
- [Changelog](https://github.com/sanic-org/sanic/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/sanic-org/sanic/compare/v21.9.1...v21.12.2)

---
updated-dependencies:
- dependency-name: sanic
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-09-23 11:25:55 -06:00

683 lines
20 KiB
JavaScript

import {API_URI, ARCHIVES_API, DEFAULT_LIMIT, emptyToNull, OTP_API, VIDEOS_API} from "./components/Common";
import {toast} from 'react-semantic-toasts';
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);
}
);
})
}
async function apiCall(url, method, body, ms = 20000) {
let init = {method};
if (body !== undefined) {
init.body = JSON.stringify(body);
}
// Create a fetch promise, this will be awaited by the timeout.
let promise = fetch(url, init);
try {
// await the response or error.
let response = await timeoutPromise(ms, promise);
if (200 <= response.status && response.status < 300) {
// Request was successful.
return response;
}
// Request encountered an error.
let copy = response.clone();
let code = (await copy.json())['code'];
if (response.status === 403 && code === 17) {
toast({
type: 'error',
title: 'WROL Mode is enabled!',
description: 'This functionality is disabled while WROL Mode is enabled!',
time: 5000,
});
}
return response;
} catch (e) {
// Timeout, or some other exception.
if (e.message === 'promise timeout') {
toast({
type: 'error',
title: 'Server failed to respond!',
description: 'Timeout while waiting for server response. See server logs.',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Error!',
description: 'See client logs',
time: 5000,
});
}
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)
};
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) {
return apiDelete(`${VIDEOS_API}/channels/${channelId}`);
}
export async function getChannels() {
let response = await apiGet(`${VIDEOS_API}/channels`);
if (response.status === 200) {
return (await response.json())['channels'];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Failed to get channels. See server logs.',
time: 5000,
});
}
}
export async function getChannel(id) {
let response = await apiGet(`${VIDEOS_API}/channels/${id}`);
return (await response.json())['channel'];
}
export async function searchVideos(offset, limit, channelId, searchStr, order_by, filters = []) {
// 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, filters, order_by: order_by || 'rank'};
if (searchStr) {
body['search_str'] = searchStr;
}
if (channelId) {
body['channel_id'] = parseInt(channelId);
}
console.debug('searching videos', body);
let response = await apiPost(`${VIDEOS_API}/search`, body);
if (response.status === 200) {
let data = await response.json();
return [data['files'], data['totals']['files']];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Failed to search videos. See server logs.',
time: 5000,
});
return [[], 0];
}
}
export async function getVideo(video_id) {
let response = await apiGet(`${VIDEOS_API}/video/${video_id}`);
let data = await response.json();
return [data['file'], data['prev'], data['next']];
}
export async function deleteVideo(video_id) {
let response = await apiDelete(`${VIDEOS_API}/video/${video_id}`);
if (response.status !== 204) {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Failed to delete video. See server logs.',
time: 5000,
});
}
}
export async function getDirectories(search_str) {
let form_data = {'search_str': search_str || null};
let response = await apiPost(`${VIDEOS_API}/directories`, form_data);
if (response.status === 200) {
return (await response.json())['directories'];
}
return [];
}
export async function getStatus() {
let response = await apiGet(`${API_URI}/status`);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get server status',
time: 5000,
});
}
}
export async function getSettings() {
let response = await apiGet(`${API_URI}/settings`);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get settings',
time: 5000,
});
}
}
export async function saveSettings(settings) {
return await apiPatch(`${API_URI}/settings`, settings);
}
export async function getDownloads() {
let response = await apiGet(`${API_URI}/download`);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get downloads',
time: 5000,
});
}
}
export async function validateRegex(regex) {
let response = await apiPost(`${API_URI}/valid_regex`, {regex});
return (await response.json())['valid'];
}
export async function favoriteVideo(video_id, favorite) {
let body = {favorite: favorite, video_id};
let response = await apiPost(`${VIDEOS_API}/favorite`, body);
return (await response.json())['favorite'];
}
export async function getStatistics() {
let response = await apiGet(`${VIDEOS_API}/statistics`);
if (response.status === 200) {
return (await response.json())['statistics'];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get statistics',
time: 5000,
});
}
}
export async function downloadChannel(channelId) {
let url = `${VIDEOS_API}/channels/download/${channelId}`;
let response = await apiPost(url);
let json = await response.json();
if (response.status === 400 && json['code'] === 30) {
toast({
type: 'error',
title: 'Cannot Download!',
description: 'This channel does not have a download record. Modify the frequency.',
time: 5000,
});
}
}
export async function refreshChannel(channelId) {
let url = `${VIDEOS_API}/channels/refresh/${channelId}`;
await fetch(url, {method: 'POST'});
}
export async function encryptOTP(otp, plaintext) {
let body = {otp, plaintext};
let response = await apiPost(`${OTP_API}/encrypt_otp`, body);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Failed to encrypt OTP',
time: 5000,
});
}
}
export async function decryptOTP(otp, ciphertext) {
let body = {otp, ciphertext};
let response = await apiPost(`${OTP_API}/decrypt_otp`, body);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Failed to decrypt OTP',
time: 5000,
});
}
}
export async function getCategories() {
let response = await apiGet(`${API_URI}/inventory/categories`);
if (response.status === 200) {
return (await response.json())['categories'];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get categories',
time: 5000,
});
}
}
export async function getBrands() {
let response = await apiGet(`${API_URI}/inventory/brands`);
if (response.status === 200) {
return (await response.json())['brands'];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get brands',
time: 5000,
});
}
}
export async function getInventories() {
let response = await apiGet(`${API_URI}/inventory`);
if (response.status === 200) {
return (await response.json())['inventories'];
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get inventories',
time: 5000,
});
}
}
export async function getInventory(inventoryId) {
let response = await apiGet(`${API_URI}/inventory/${inventoryId}`);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get inventory',
time: 5000,
});
}
}
export async function saveInventory(inventory) {
return await apiPost(`${API_URI}/inventory`, inventory);
}
export async function updateInventory(inventoryId, inventory) {
delete inventory['id'];
return await apiPut(`${API_URI}/inventory/${inventoryId}`, inventory);
}
export async function deleteInventory(inventoryId) {
return await apiDelete(`${API_URI}/inventory/${inventoryId}`);
}
export async function getItems(inventoryId) {
let response = await apiGet(`${API_URI}/inventory/${inventoryId}/item`);
return await response.json();
}
export async function saveItem(inventoryId, item) {
return await apiPost(`${API_URI}/inventory/${inventoryId}/item`, item);
}
export async function updateItem(itemId, item) {
item = emptyToNull(item);
return await apiPut(`${API_URI}/inventory/item/${itemId}`, item);
}
export async function deleteItems(itemIds) {
let i = itemIds.join(',');
await apiDelete(`${API_URI}/inventory/item/${i}`);
}
export async function deleteArchive(archive_id) {
return await apiDelete(`${API_URI}/archive/${archive_id}`);
}
export async function searchArchives(offset, limit, domain, searchStr, order) {
// 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;
}
console.debug('searching archives', body);
let response = await apiPost(`${ARCHIVES_API}/search`, body);
if (response.status === 200) {
let data = await response.json();
return [data['archives'], data['totals']['archives']];
} else {
toast({
type: 'error',
title: 'Unable to search archives',
description: 'Cannot search archives. See server logs.',
time: 5000,
});
}
}
export async function fetchDomains() {
let response = await apiGet(`${ARCHIVES_API}/domains`);
if (response.status === 200) {
let data = await response.json();
return [data['domains'], data['totals']['domains']];
} else {
toast({
type: 'error',
title: 'Domains Error',
description: 'Unable to fetch Domains. See server logs.',
time: 5000,
});
}
}
export async function getArchive(archiveId) {
const response = await apiGet(`${ARCHIVES_API}/${archiveId}`);
if (response.status === 200) {
const data = await response.json();
return [data['file'], data['alternatives']];
} else {
toast({
type: 'error',
title: 'Archive Error',
description: 'Unable to get Archive. See server logs.',
time: 5000,
});
}
}
export async function postDownload(urls, downloader, frequency, sub_downloader) {
let body = {urls: urls, downloader: downloader, frequency: frequency || null};
if (sub_downloader) {
body['sub_downloader'] = sub_downloader;
}
let response = await apiPost(`${API_URI}/download`, body);
return response;
}
export async function killDownload(download_id) {
let response = await apiPost(`${API_URI}/download/${download_id}/kill`);
return response;
}
export async function killDownloads() {
let response = await apiPost(`${API_URI}/download/kill`);
return response;
}
export async function startDownloads() {
let response = await apiPost(`${API_URI}/download/enable`);
return response;
}
export async function getDownloaders() {
try {
let response = await apiGet(`${API_URI}/downloaders`);
return await response.json();
} catch (e) {
return {downloaders: []};
}
}
const replaceFileDatetimes = (files) => {
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (file['modified']) {
files[i]['modified'] = file['modified'] * 1000;
}
}
return files;
}
export async function filesSearch(offset, limit, searchStr, mimetype, model) {
const body = {search_str: searchStr, offset: parseInt(offset), limit: parseInt(limit)};
if (mimetype) {
body['mimetype'] = mimetype;
}
if (model) {
body['model'] = model;
}
console.debug('searching files', body);
const response = await apiPost(`${API_URI}/files/search`, body);
if (response.status === 200) {
let data = await response.json();
let [files, total] = [data['files'], data['totals']['files']];
files = replaceFileDatetimes(files);
return [files, total];
} else {
toast({
type: 'error',
title: 'Unable to search files',
description: 'Cannot search files. See server logs.',
time: 5000,
});
return [null, null];
}
}
export async function refreshFiles() {
return await apiPost(`${API_URI}/files/refresh`);
}
export async function refreshDirectoryFiles(directory) {
let body = {directory};
try {
return await apiPost(`${API_URI}/files/refresh/directory`, body);
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unable to refresh directory',
description: 'Cannot refresh the files in the directory. See server logs.',
time: 5000,
});
}
}
export async function getFiles(directories) {
let body = {directories: directories || []};
let response = await apiPost(`${API_URI}/files`, body);
let {files} = await response.json();
files = replaceFileDatetimes(files);
return files;
}
export async function deleteFile(file) {
let body = {file: file};
await apiPost(`${API_URI}/files/delete`, body);
}
export async function getHotspotStatus() {
let response = await getSettings();
return response['hotspot_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.status === 204) {
return null;
} else {
let code = (await response.json())['code'];
if (code === 34) {
toast({
type: 'error',
title: 'Unsupported!',
description: 'Hotspot is only supported on a Raspberry Pi!',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Could not modify hotspot. See server logs.',
time: 5000,
});
}
}
}
export async function getThrottleStatus() {
let response = await getSettings();
return response['throttle_status'];
}
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.status === 204) {
return null;
} else {
let code = (await response.json())['code'];
if (code === 34) {
toast({
type: 'error',
title: 'Unsupported!',
description: 'Throttle is only supported on a Raspberry Pi!',
time: 5000,
});
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Could not modify throttle. See server logs.',
time: 5000,
});
}
}
}
export async function getMapImportStatus() {
let response = await apiGet(`${API_URI}/map/files`);
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get import status',
time: 5000,
});
}
}
export async function importMapFiles(paths) {
let body = {'files': paths};
let response = await apiPost(`${API_URI}/map/import`, body);
if (response.status === 204) {
return null;
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Could not start import! See server logs.',
time: 5000,
});
}
}
export async function clearCompletedDownloads() {
let response = await apiPost(`${API_URI}/download/clear_completed`);
if (response.status === 204) {
return null
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Could not clear completed downloads! See server logs.',
time: 5000,
});
}
}
export async function clearFailedDownloads() {
let response = await apiPost(`${API_URI}/download/clear_failed`);
if (response.status === 204) {
return null
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Could not clear failed downloads! See server logs.',
time: 5000,
});
}
}
export async function getAPIStatus() {
let response = await apiGet(`${API_URI}/echo`);
return response.status === 200;
}