Merge pull request #124 from lrnselfreliance/bugfix/121-app-handles-no-api

Wrapping most API requests in trys/catches.
This commit is contained in:
lrnselfreliance 2022-05-01 21:39:15 -06:00 • committed by GitHub
commit 5bd9201e58
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 360 additions and 138 deletions

View file

@ -14,12 +14,13 @@ import {ArchiveRoute, ArchivesList} from "./components/Archive";
import {Saver} from "./components/Upload";
import {MoreButton, PageContainer, SearchInput} from "./components/Common";
import {FilesRoute} from "./components/Files";
import {useSearch, useVersion} from "./hooks/customHooks";
import {useSearch, useUp, useVersion} from "./hooks/customHooks";
import {MapRoute} from "./components/Map";
function Welcome() {
const {searchStr, setSearchStr, archives, videos} = useSearch();
const history = useHistory();
useUp();
let body = (
<>

View file

@ -1,12 +1,4 @@
import {
API_URI,
ARCHIVES_API,
DEFAULT_LIMIT,
emptyToNull,
OTP_API,
secondsToDateTime,
VIDEOS_API
} from "./components/Common";
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) {
@ -111,7 +103,16 @@ export async function deleteChannel(id) {
export async function getChannels() {
let response = await apiGet(`${VIDEOS_API}/channels`);
return (await response.json())['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) {
@ -138,7 +139,12 @@ export async function searchVideos(offset, limit, channel_id, searchStr, order_b
let data = await response.json();
return [data['videos'], data['totals']['videos']];
} else {
throw Error(`Unable to search videos`);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Failed to search videos. See server logs.',
time: 5000,
});
}
}
@ -171,7 +177,16 @@ export async function getDirectories(search_str) {
export async function getSettings() {
let response = await apiGet(`${API_URI}/settings`);
return await response.json();
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) {
@ -180,8 +195,16 @@ export async function saveSettings(settings) {
export async function getDownloads() {
let response = await apiGet(`${API_URI}/download`);
let data = await response.json();
return data;
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get downloads',
time: 5000,
});
}
}
@ -198,7 +221,16 @@ export async function favoriteVideo(video_id, favorite) {
export async function getStatistics() {
let response = await apiGet(`${VIDEOS_API}/statistics`);
return (await response.json())['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 refresh() {
@ -233,51 +265,87 @@ export async function refreshChannel(id) {
export async function encryptOTP(otp, plaintext) {
let body = {otp, plaintext};
let response = await apiPost(`${OTP_API}/encrypt_otp`, body);
if (response.status !== 200) {
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Failed to encrypt OTP',
time: 5000,
});
return;
}
return await response.json();
}
export async function decryptOTP(otp, ciphertext) {
let body = {otp, ciphertext};
let response = await apiPost(`${OTP_API}/decrypt_otp`, body);
if (response.status !== 200) {
if (response.status === 200) {
return await response.json();
} else {
toast({
type: 'error',
title: 'Error!',
description: 'Failed to decrypt OTP',
time: 5000,
});
return;
}
return await response.json();
}
export async function getCategories() {
let response = await apiGet(`${API_URI}/inventory/categories`);
return (await response.json())['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`);
return (await response.json())['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`);
return (await response.json())['inventories'];
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}`);
return await response.json();
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) {
@ -388,7 +456,7 @@ export async function getDownloaders() {
let response = await apiGet(`${API_URI}/downloaders`);
return await response.json();
} catch (e) {
return {};
return {downloaders: []};
}
}
@ -396,7 +464,7 @@ const replaceFileDatetimes = (files) => {
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (file['modified']) {
files[i]['modified'] = secondsToDateTime(file['modified']);
files[i]['modified'] = file['modified'] * 1000;
}
}
return files;
@ -440,8 +508,10 @@ export async function deleteFile(file) {
export async function getVersion() {
let response = await apiGet(`${API_URI}/settings`);
let data = await response.json();
return data['version'];
if (response.status === 200) {
let data = await response.json();
return data['version'];
}
}
export async function getHotspotStatus() {
@ -514,7 +584,16 @@ export async function setThrottle(on) {
export async function getMapImportStatus() {
let response = await apiGet(`${API_URI}/map/files`);
return await response.json();
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) {
@ -559,3 +638,8 @@ export async function clearFailedDownloads() {
});
}
}
export async function getAPIStatus() {
let response = await apiGet(`${API_URI}/echo`);
return response.status === 200;
}

View file

@ -63,19 +63,23 @@ class Settings extends React.Component {
}
async componentDidMount() {
const settings = await getSettings();
this.setState({
ready: true,
disabled: settings.wrol_mode,
download_on_startup: settings.download_on_startup,
hotspot_on_startup: settings.hotspot_on_startup,
hotspot_password: settings.hotspot_password,
hotspot_ssid: settings.hotspot_ssid,
hotspot_status: settings.hotspot_status,
throttle_on_startup: settings.throttle_on_startup,
throttle_status: settings.throttle_status,
timezone: {value: settings.timezone, label: settings.timezone},
}, this.handleHotspotChange);
try {
const settings = await getSettings();
this.setState({
ready: true,
disabled: settings.wrol_mode,
download_on_startup: settings.download_on_startup,
hotspot_on_startup: settings.hotspot_on_startup,
hotspot_password: settings.hotspot_password,
hotspot_ssid: settings.hotspot_ssid,
hotspot_status: settings.hotspot_status,
throttle_on_startup: settings.throttle_on_startup,
throttle_status: settings.throttle_status,
timezone: {value: settings.timezone, label: settings.timezone},
}, this.handleHotspotChange);
} catch (e) {
console.error(e);
}
}
async handleSubmit(e) {
@ -92,7 +96,9 @@ class Settings extends React.Component {
}
handleInputChange = async (e, name, value) => {
if (e) {e.preventDefault()}
if (e) {
e.preventDefault()
}
this.setState({[name]: value});
}
@ -221,8 +227,12 @@ class WROLMode extends React.Component {
}
async componentDidMount() {
let settings = await getSettings();
this.setState({ready: true, WROLMode: settings.wrol_mode});
try {
let settings = await getSettings();
this.setState({ready: true, WROLMode: settings.wrol_mode});
} catch (e) {
console.error(e);
}
}
toggleWROLMode = async () => {
@ -464,12 +474,16 @@ class Downloads extends React.Component {
}
fetchDownloads = async () => {
let data = await getDownloads();
this.setState({
once_downloads: data.once_downloads,
recurring_downloads: data.recurring_downloads,
pending_downloads: data.pending_downloads,
});
try {
let data = await getDownloads();
this.setState({
once_downloads: data.once_downloads,
recurring_downloads: data.recurring_downloads,
pending_downloads: data.pending_downloads,
});
} catch (e) {
console.error(e);
}
}
render() {

View file

@ -17,8 +17,12 @@ class Encrypt extends React.Component {
handleSubmit = async (e) => {
e.preventDefault();
let {otp, plaintext, ciphertext} = await encryptOTP(this.state.otp, this.state.plaintext);
this.setState({otp, plaintext, ciphertext});
try {
let {otp, plaintext, ciphertext} = await encryptOTP(this.state.otp, this.state.plaintext);
this.setState({otp, plaintext, ciphertext});
} catch (e) {
console.error(e);
}
}
handleInputChange = async (event, {name, value}) => {
@ -74,8 +78,12 @@ class Decrypt extends React.Component {
handleSubmit = async (e) => {
e.preventDefault();
let {otp, plaintext, ciphertext} = await decryptOTP(this.state.otp, this.state.ciphertext);
this.setState({otp, plaintext, ciphertext});
try {
let {otp, plaintext, ciphertext} = await decryptOTP(this.state.otp, this.state.ciphertext);
this.setState({otp, plaintext, ciphertext});
} catch (e) {
console.error(e);
}
}
handleInputChange = async (event, {name, value}) => {

View file

@ -18,7 +18,8 @@ import {
downloadChannel,
getChannel,
getChannels,
getDirectories, getSettings,
getDirectories,
getSettings,
refreshChannel,
updateChannel,
validateRegex
@ -442,7 +443,7 @@ class ChannelPage extends APIForm {
<Button color='blue' onClick={this.downloadChannel}>
Download
</Button>
<Button color='inverted blue' onClick={this.refreshChannel}>
<Button inverted color='blue' onClick={this.refreshChannel}>
Refresh
</Button>
</>
@ -565,8 +566,14 @@ export class Channels extends React.Component {
}
async componentDidMount() {
let channels = await getChannels();
this.setState({channels, results: channels});
try {
let channels = await getChannels();
if (channels) {
this.setState({channels, results: channels});
}
} catch (e) {
console.error(e);
}
}
handleSearchChange = async (e, {value}) => {

View file

@ -142,7 +142,7 @@ export function VideoCard({video}) {
let imageLabel = null;
if (video.favorite) {
imageLabel = {as: 'a', corner: 'left', icon: 'heart', color: 'green'};
imageLabel = {corner: 'left', icon: 'heart', color: 'green'};
}
return (
@ -570,8 +570,14 @@ export const useWROLMode = () => {
const [enabled, setEnabled] = useState(false);
const fetchStatus = async () => {
let settings = await getSettings();
setEnabled(settings.wrol_mode);
try {
const settings = await getSettings();
if (settings) {
setEnabled(settings.wrol_mode);
}
} catch (e) {
console.error(e);
}
}
useEffect(() => {

View file

@ -37,11 +37,15 @@ class InventorySummary extends React.Component {
fetchInventory = async () => {
if (this.state.inventory) {
let {by_category, by_subcategory, by_name} = await getInventory(this.state.inventory.id);
by_category = enumerate(by_category);
by_subcategory = enumerate(by_subcategory);
by_name = enumerate(by_name);
this.setState({by_category, by_subcategory, by_name});
try {
let {by_category, by_subcategory, by_name} = await getInventory(this.state.inventory.id);
by_category = enumerate(by_category);
by_subcategory = enumerate(by_subcategory);
by_name = enumerate(by_name);
this.setState({by_category, by_subcategory, by_name});
} catch (e) {
console.error(e);
}
}
}
@ -611,20 +615,24 @@ class InventorySelector extends React.Component {
}
async fetchInventories() {
let inventories = await getInventories();
let options = [];
for (let i = 0; i < inventories.length; i++) {
let inventory = inventories[i];
options = options.concat([{
key: inventory.id,
text: inventory.name,
value: inventory.id,
id: inventory.id,
}])
try {
let inventories = await getInventories();
let options = [];
for (let i = 0; i < inventories.length; i++) {
let inventory = inventories[i];
options = options.concat([{
key: inventory.id,
text: inventory.name,
value: inventory.id,
id: inventory.id,
}])
}
let selected = this.state.selected || inventories[0];
this.setState({inventories, options, selected},
() => this.props.setInventory(selected));
} catch (e) {
console.error(e);
}
let selected = this.state.selected || inventories[0];
this.setState({inventories, options, selected},
() => this.props.setInventory(selected));
}
setInventory = (e, {value}) => {
@ -748,15 +756,19 @@ class CategoryInputs extends React.Component {
}
fetchCategories = async () => {
let categories = await getCategories();
categories = enumerate(categories);
let newCategories = [];
for (let i = 0; i < categories.length; i++) {
let [key, sc] = categories[i];
let [subcategory, category] = sc;
newCategories = newCategories.concat([[key, subcategory, `${subcategory}/${category}`]]);
try {
let categories = await getCategories();
categories = enumerate(categories);
let newCategories = [];
for (let i = 0; i < categories.length; i++) {
let [key, sc] = categories[i];
let [subcategory, category] = sc;
newCategories = newCategories.concat([[key, subcategory, `${subcategory}/${category}`]]);
}
this.setState({categories: newCategories});
} catch (e) {
console.error(e);
}
this.setState({categories: newCategories});
}
clearInputs = () => {
@ -858,14 +870,18 @@ class BrandInput extends React.Component {
}
fetchBrands = async () => {
let brands = await getBrands();
brands = enumerate(brands);
let newBrands = [];
for (let i = 0; i < brands.length; i++) {
let [key, brand] = brands[i];
newBrands = newBrands.concat([[key, brand, brand]]);
try {
let brands = await getBrands();
brands = enumerate(brands);
let newBrands = [];
for (let i = 0; i < brands.length; i++) {
let [key, brand] = brands[i];
newBrands = newBrands.concat([[key, brand, brand]]);
}
this.setState({options: newBrands});
} catch (e) {
console.error(e);
}
this.setState({options: newBrands});
}
handleInputChange = (e, {name, value}) => {

View file

@ -1,5 +1,5 @@
import React from "react";
import {HelpPopup, humanFileSize, minutesToTimestamp, PageContainer, TabLinks, WROLModeMessage} from "./Common";
import {HelpPopup, humanFileSize, PageContainer, TabLinks, WROLModeMessage} from "./Common";
import {Route} from "react-router-dom";
import {getMapImportStatus, importMapFiles} from "../api";
import Table from "semantic-ui-react/dist/commonjs/collections/Table";
@ -28,13 +28,17 @@ class ManageMap extends React.Component {
}
fetchImportStatus = async () => {
const importStatus = await getMapImportStatus();
this.setState({
files: importStatus['files'],
importing: importStatus['importing'],
import_running: importStatus['import_running'],
dockerized: importStatus['dockerized'],
});
try {
const importStatus = await getMapImportStatus();
this.setState({
files: importStatus['files'],
importing: importStatus['importing'],
import_running: importStatus['import_running'],
dockerized: importStatus['dockerized'],
});
} catch (e) {
console.error(e);
}
}
import = async (e) => {

View file

@ -306,10 +306,13 @@ class Videos extends React.Component {
// Pass any enabled filters to the search.
let filtersArr = this.enabledFilters();
let [videos, total] = await searchVideos(offset, limit, channel_id, queryStr, searchOrder, filtersArr);
let totalPages = Math.round(total / this.state.limit) || 1;
this.setState({videos, totalPages});
try {
let [videos, total] = await searchVideos(offset, limit, channel_id, queryStr, searchOrder, filtersArr);
let totalPages = Math.round(total / this.state.limit) || 1;
this.setState({videos, totalPages});
} catch (e) {
console.error(e);
}
}
changePage = async (activePage) => {
@ -573,12 +576,16 @@ class Statistics extends React.Component {
}
async fetchStatistics() {
let stats = await getStatistics();
stats.videos.sum_duration = secondsToString(stats.videos.sum_duration);
stats.videos.sum_size = humanFileSize(stats.videos.sum_size, true);
stats.videos.max_size = humanFileSize(stats.videos.max_size, true);
stats.historical.average_size = humanFileSize(stats.historical.average_size, true);
this.setState({...stats});
try {
let stats = await getStatistics();
stats.videos.sum_duration = secondsToString(stats.videos.sum_duration);
stats.videos.sum_size = humanFileSize(stats.videos.sum_size, true);
stats.videos.max_size = humanFileSize(stats.videos.max_size, true);
stats.historical.average_size = humanFileSize(stats.historical.average_size, true);
this.setState({...stats});
} catch (e) {
console.error(e);
}
}
buildSegment(title, names, stats) {

View file

@ -2,6 +2,7 @@ import {useEffect, useState} from "react";
import {
fetchDomains,
filesSearch,
getAPIStatus,
getDownloaders,
getFiles,
getHotspotStatus,
@ -15,6 +16,7 @@ import {
startDownloads
} from "../api";
import {useHistory} from "react-router-dom";
import {toast} from "react-semantic-toasts";
export const useSearchParam = (key, defaultValue = null) => {
// Get a window.location.search param.
@ -43,14 +45,24 @@ export const useSearch = () => {
const localSearchArchives = async (term) => {
setArchives(null);
const [archives] = await searchArchives(0, 6, null, term);
setArchives(archives);
try {
const [archives] = await searchArchives(0, 6, null, term);
setArchives(archives);
} catch (e) {
console.error(e);
setArchives([]);
}
}
const localSearchVideos = async (term) => {
setVideos(null);
const [videos] = await searchVideos(0, 6, null, term);
setVideos(videos);
try {
const [videos] = await searchVideos(0, 6, null, term);
setVideos(videos);
} catch (e) {
console.error(e);
setVideos([]);
}
}
useEffect(() => {
@ -70,9 +82,14 @@ export const useDomains = () => {
const _fetchDomains = async () => {
setDomains(null);
setTotal(0);
let [domains, total] = await fetchDomains();
setDomains(domains);
setTotal(total);
try {
let [domains, total] = await fetchDomains();
setDomains(domains);
setTotal(total);
} catch (e) {
setDomains([]);
setTotal(0);
}
}
useEffect(() => {
@ -94,9 +111,15 @@ export const useArchives = ({defaultLimit = 20}) => {
const search = async () => {
setArchives(null);
const [archives, total] = await searchArchives(offset, limit, domain, searchStr);
setTotalPages(Math.floor(total / limit) + 1);
setArchives(archives);
try {
const [archives, total] = await searchArchives(offset, limit, domain, searchStr);
setTotalPages(Math.floor(total / limit) + 1);
setArchives(archives);
} catch (e) {
console.error(e);
setTotalPages(0);
setArchives([]);
}
}
useEffect(() => {
@ -133,8 +156,12 @@ export const useVersion = () => {
const [version, setVersion] = useState('');
const fetchVersion = async () => {
let version = await getVersion();
setVersion(version);
try {
let version = await getVersion();
setVersion(version);
} catch (e) {
console.error(e);
}
}
useEffect(() => {
@ -157,9 +184,19 @@ export const useSearchFiles = ({defaultLimit = 50}) => {
setSearchFiles([]);
setTotalPages(0);
if (searchStr) {
let [files, total] = await filesSearch(offset, limit, searchStr);
setSearchFiles(files);
setTotalPages(Math.floor(total / limit) + 1);
try {
let [files, total] = await filesSearch(offset, limit, searchStr);
setSearchFiles(files);
setTotalPages(Math.floor(total / limit) + 1);
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get files',
time: 5000,
});
}
}
}
@ -182,8 +219,13 @@ export const useBrowseFiles = () => {
const [openFolders, setOpenFolders] = useState([]);
const fetchFiles = async () => {
const files = await getFiles(openFolders);
setBrowseFiles(files);
try {
const files = await getFiles(openFolders);
setBrowseFiles(files);
} catch (e) {
console.log(e);
setBrowseFiles([]);
}
}
useEffect(() => {
@ -197,7 +239,12 @@ export const useHotspot = () => {
const [on, setOn] = useState(null);
const fetchHotspotStatus = async () => {
const status = await getHotspotStatus();
let status;
try {
status = await getHotspotStatus();
} catch (e) {
console.error(e);
}
if (status === 'connected') {
// Hotspot is on.
setOn(true);
@ -228,9 +275,13 @@ export const useDownloaders = () => {
const [downloaders, setDownloaders] = useState(null);
const fetchDownloaders = async () => {
let data = await getDownloaders();
setDownloaders(data['downloaders']);
setOn(!data['manager_disabled']);
try {
let data = await getDownloaders();
setDownloaders(data['downloaders']);
setOn(!data['manager_disabled']);
} catch (e) {
console.error(e);
}
}
useEffect(() => {
@ -254,7 +305,12 @@ export const useThrottle = () => {
const [on, setOn] = useState(null);
const fetchThrottleStatus = async () => {
const status = await getThrottleStatus();
let status;
try {
status = await getThrottleStatus();
} catch (e) {
console.error(e);
}
if (status === 'powersave') {
setOn(true);
} else if (status === 'ondemand') {
@ -276,3 +332,22 @@ export const useThrottle = () => {
return {on, setOn, setThrottle: localSetThrottle};
}
export const useUp = () => {
// Checks that the API is up.
const fetchAPIStatus = async () => {
let status = await getAPIStatus();
if (status === false) {
toast({
type: 'error',
title: 'Error!',
description: `API did not respond. Check the server's status.`,
time: 5000,
});
}
}
useEffect(() => {
fetchAPIStatus();
}, []);
}

View file

@ -1,4 +1,4 @@
__version__ = '0.4.6-beta'
__version__ = '0.4.7-beta'
import subprocess