diff --git a/app/src/api.js b/app/src/api.js index ed1d8db6..e5abbca1 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -220,7 +220,7 @@ export async function favoriteVideo(video_id, favorite) { return (await response.json())['favorite']; } -export async function getStatistics() { +export async function getVideosStatistics() { let response = await apiGet(`${VIDEOS_API}/statistics`); if (response.status === 200) { return (await response.json())['statistics']; @@ -662,11 +662,11 @@ export async function getAPIStatus() { return response.status === 200; } -export async function getFileStatistics() { - let response = await apiGet(`${API_URI}/files/statistics`); +export async function getStatistics() { + let response = await apiGet(`${API_URI}/statistics`); if (response.status === 200) { const contents = await response.json(); - return contents['statistics']; + return contents; } else { toast({ type: 'error', diff --git a/app/src/components/Apps.js b/app/src/components/Apps.js index b90bcbfa..1ead2f44 100644 --- a/app/src/components/Apps.js +++ b/app/src/components/Apps.js @@ -3,10 +3,10 @@ import {Divider, SegmentGroup, StatisticLabel, StatisticValue} from "semantic-ui import {Link, Route, Routes} from "react-router-dom"; import "../static/wrolpi.css"; import {decryptOTP, encryptOTP} from "../api"; -import {mimetypeColor, PageContainer, toLocaleString, useTitle} from "./Common"; +import {humanFileSize, mimetypeColor, PageContainer, toLocaleString, useTitle} from "./Common"; import {ThemeContext} from "../contexts/contexts"; import {Button, Header, Loader, Segment, Statistic, StatisticGroup, TextArea} from "./Theme"; -import {useFileStatistics} from "../hooks/customHooks"; +import {useStatistics} from "../hooks/customHooks"; class Encrypt extends React.Component { constructor(props) { @@ -146,20 +146,22 @@ function OTP() { > } -function FileStatistics() { - useTitle('File Statistics'); +function StatisticsPage() { + useTitle('Statistics'); const {s} = useContext(ThemeContext); - const {statistics} = useFileStatistics(); - - let body = ; + const {statistics} = useStatistics(); if (statistics === undefined) { - body = Failed to fetch statistics; + return <> + Statistics + Failed to fetch statistics + >; } - if (statistics !== undefined && statistics !== null) { + if (statistics['global_statistics']) { + let {global_statistics, file_statistics} = statistics; const { archive_count, audio_count, @@ -169,14 +171,22 @@ function FileStatistics() { total_count, video_count, zip_count, - } = statistics; - body = <> + total_size, + } = file_statistics; + const {db_size} = global_statistics; + return <> + Statistics + Files {toLocaleString(total_count)} All Files + + {humanFileSize(total_size)} + Total Size + @@ -217,20 +227,31 @@ function FileStatistics() { + + Database + + + + {humanFileSize(db_size)} + Size + + + >; } return <> - File Statistics - {body} - > + Statistics + + >; + } export function AppsRoute(props) { return ( }/> - }/> + }/> ) } diff --git a/app/src/components/Nav.js b/app/src/components/Nav.js index 1a4dccef..18989734 100644 --- a/app/src/components/Nav.js +++ b/app/src/components/Nav.js @@ -16,7 +16,7 @@ const links = [ { key: 'apps', text: 'Apps', links: [ {to: '/apps/otp', text: 'One Time Pad', end: true}, - {to: '/apps/file_statistics', text: 'File Statistics', end: true}, + {to: '/apps/statistics', text: 'Statistics', end: true}, ] }, ]; diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index c89756d0..4b44630d 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -10,10 +10,10 @@ import { getDownloaders, getDownloads, getFiles, - getFileStatistics, + getStatistics, getInventory, getSettings, - getStatistics, + getVideosStatistics, getStatus, getThrottleStatus, getVideo, @@ -675,7 +675,7 @@ export const useVideoStatistics = () => { const fetchStatistics = async () => { try { - let stats = await getStatistics(); + let stats = await getVideosStatistics(); stats.videos.sum_duration = secondsToFullDuration(stats.videos.sum_duration); stats.videos.sum_size = humanFileSize(stats.videos.sum_size); stats.videos.max_size = humanFileSize(stats.videos.max_size); @@ -720,13 +720,13 @@ export const useInventory = (inventoryId) => { return {byCategory, bySubcategory, byName, fetchInventory} } -export const useFileStatistics = () => { +export const useStatistics = () => { const [statistics, setStatistics] = useState(); const fetchFileStatistics = async () => { try { - const statistics = await getFileStatistics(); - setStatistics(statistics || undefined); + const s = await getStatistics(); + setStatistics(s); } catch (e) { console.error(e); setStatistics(undefined); @@ -734,7 +734,7 @@ export const useFileStatistics = () => { } useEffect(() => { - setStatistics(null); + setStatistics({}); fetchFileStatistics(); }, []); diff --git a/wrolpi/common.py b/wrolpi/common.py index 279bcf60..a35127d6 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -1044,3 +1044,14 @@ def get_warn_once(message: str, logger__: logging.Logger, level=logging.ERROR): def ordered_unique_list(lst: Iterable) -> List: """Return a new list that contains only the first occurrence of each item.""" return list(dict.fromkeys(lst)) + + +def get_global_statistics(): + from wrolpi.db import get_db_curs + with get_db_curs() as curs: + curs.execute('select pg_database_size(current_database())') + db_size = curs.fetchall()[0][0] + + return dict( + db_size=db_size, + ) diff --git a/wrolpi/files/api.py b/wrolpi/files/api.py index 56d5dd28..7b8b72c4 100644 --- a/wrolpi/files/api.py +++ b/wrolpi/files/api.py @@ -135,12 +135,3 @@ def post_directories(_, body: schema.DirectoriesRequest): body = {'directories': dirs, 'exists': path.exists(), 'is_dir': path.is_dir(), 'is_file': path.is_file()} return response.json(body) - - -@bp.get('/statistics') -@openapi.definition( - summary='Get summary statistics of all files', -) -async def get_statistics(_): - statistics = await lib.get_file_statistics() - return json_response({'statistics': statistics}) diff --git a/wrolpi/files/lib.py b/wrolpi/files/lib.py index 137b7cd2..4d219fed 100644 --- a/wrolpi/files/lib.py +++ b/wrolpi/files/lib.py @@ -622,7 +622,7 @@ def split_file_name_words(name: str) -> List[str]: return [name] -async def get_file_statistics(): +def get_file_statistics(): with get_db_curs() as curs: curs.execute(''' SELECT @@ -631,7 +631,8 @@ async def get_file_statistics(): COUNT(path) FILTER (WHERE file.mimetype = 'application/pdf') AS "pdf_count", COUNT(path) FILTER (WHERE file.mimetype LIKE 'image/%' AND file.associated = FALSE) AS "image_count", COUNT(path) FILTER (WHERE file.mimetype = 'application/zip') AS "zip_count", - COUNT(path) FILTER (WHERE file.mimetype LIKE 'audio/%' AND file.associated = FALSE) AS "audio_count" + COUNT(path) FILTER (WHERE file.mimetype LIKE 'audio/%' AND file.associated = FALSE) AS "audio_count", + SUM(size)::BIGINT AS "total_size" FROM file ''') diff --git a/wrolpi/files/test/test_api.py b/wrolpi/files/test/test_api.py index 6ec958cb..682c1988 100644 --- a/wrolpi/files/test/test_api.py +++ b/wrolpi/files/test/test_api.py @@ -247,10 +247,9 @@ def test_refresh_files_list(test_session, test_client, make_files_structure): def test_file_statistics(test_session, test_client, example_pdf, example_mobi, example_epub, video_file): """A summary of File statistics can be fetched.""" # Statistics can be fetched while empty. - request, response = test_client.get('/api/files/statistics') + request, response = test_client.get('/api/statistics') assert response.status_code == HTTPStatus.OK - assert response.json == { - 'statistics': { + assert response.json['file_statistics'] == { 'archive_count': 0, 'audio_count': 0, 'ebook_count': 0, @@ -258,15 +257,14 @@ def test_file_statistics(test_session, test_client, example_pdf, example_mobi, e 'pdf_count': 0, 'total_count': 0, 'video_count': 0, - 'zip_count': 0}, + 'zip_count': 0, } test_client.post('/api/files/refresh') - request, response = test_client.get('/api/files/statistics') + request, response = test_client.get('/api/statistics') assert response.status_code == HTTPStatus.OK - assert response.json == { - 'statistics': { + assert response.json['file_statistics'] == { 'archive_count': 0, 'audio_count': 0, 'ebook_count': 2, @@ -274,5 +272,5 @@ def test_file_statistics(test_session, test_client, example_pdf, example_mobi, e 'pdf_count': 1, 'total_count': 5, 'video_count': 1, - 'zip_count': 0}, + 'zip_count': 0, } diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 27f4f805..c041fd34 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -19,10 +19,11 @@ from sanic_ext.extensions.openapi import openapi from wrolpi import admin, status from wrolpi.admin import HotspotStatus from wrolpi.common import logger, get_config, wrol_mode_enabled, Base, get_media_directory, \ - wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode + wrol_mode_check, native_only, disable_wrol_mode, enable_wrol_mode, get_global_statistics from wrolpi.dates import set_timezone from wrolpi.downloader import download_manager from wrolpi.errors import WROLModeEnabled, InvalidTimezone, API_ERRORS, APIError, ValidationError, HotspotError +from wrolpi.files.lib import get_file_statistics from wrolpi.schema import RegexRequest, RegexResponse, SettingsRequest, SettingsResponse, DownloadRequest, EchoResponse from wrolpi.vars import API_HOST, API_PORT, DOCKERIZED, API_DEBUG, API_ACCESS_LOG, API_WORKERS, API_AUTO_RELOAD, \ truthy_arg @@ -359,6 +360,19 @@ async def get_status(_: Request): return json_response(ret) +@api_bp.get('/statistics') +@openapi.definition( + summary='Get summary statistics of all files', +) +async def get_statistics(_): + file_statistics = get_file_statistics() + global_statistics = get_global_statistics() + return json_response({ + 'file_statistics': file_statistics, + 'global_statistics': global_statistics, + }) + + class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): diff --git a/wrolpi/test/test_root_api.py b/wrolpi/test/test_root_api.py index 087a571d..12332c77 100644 --- a/wrolpi/test/test_root_api.py +++ b/wrolpi/test/test_root_api.py @@ -351,3 +351,8 @@ def test_get_downloaders(test_client): assert 'downloaders' in response.json, 'Downloaders not returned' assert isinstance(response.json['downloaders'], list) and len(response.json['downloaders']), \ 'No downloaders returned' + + +def test_get_global_statistics(test_session, test_client): + request, response = test_client.get('/api/statistics') + assert response.json['global_statistics']['db_size'] > 1
Failed to fetch statistics