Adding database size and total file size to statistics page.

This commit is contained in:
Roland 2022-12-16 11:10:01 -07:00
parent 45e6bf859f
commit 5cbd4c755c
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
10 changed files with 88 additions and 47 deletions

View file

@ -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',

View file

@ -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 = <Segment><Loader inline active/></Segment>;
const {statistics} = useStatistics();
if (statistics === undefined) {
body = <Segment><p {...s}>Failed to fetch statistics</p></Segment>;
return <>
<Header as='h1'>Statistics</Header>
<Segment><p {...s}>Failed to fetch statistics</p></Segment>
</>;
}
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 <>
<Header as='h1'>Statistics</Header>
<Header as='h2'>Files</Header>
<Segment>
<StatisticGroup>
<Statistic>
<StatisticValue>{toLocaleString(total_count)}</StatisticValue>
<StatisticLabel>All Files</StatisticLabel>
</Statistic>
<Statistic>
<StatisticValue>{humanFileSize(total_size)}</StatisticValue>
<StatisticLabel>Total Size</StatisticLabel>
</Statistic>
</StatisticGroup>
</Segment>
<Segment>
@ -217,20 +227,31 @@ function FileStatistics() {
</Statistic>
</StatisticGroup>
</Segment>
<Header as='h2'>Database</Header>
<Segment>
<StatisticGroup>
<Statistic>
<StatisticValue>{humanFileSize(db_size)}</StatisticValue>
<StatisticLabel>Size</StatisticLabel>
</Statistic>
</StatisticGroup>
</Segment>
</>;
}
return <>
<Header as='h1'>File Statistics</Header>
{body}
</>
<Header as='h1'>Statistics</Header>
<Segment><Loader inline active/></Segment>
</>;
}
export function AppsRoute(props) {
return (<PageContainer>
<Routes>
<Route path='otp' exact element={<OTP/>}/>
<Route path='file_statistics' exact element={<FileStatistics/>}/>
<Route path='statistics' exact element={<StatisticsPage/>}/>
</Routes>
</PageContainer>)
}

View file

@ -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},
]
},
];

View file

@ -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();
}, []);

View file

@ -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,
)

View file

@ -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})

View file

@ -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
''')

View file

@ -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,
}

View file

@ -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):

View file

@ -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