Fixing changes before merge.

Moving FilesRefreshButton and DirectoryRefreshButton out of browser file.

Moving file fetching tino FileBrowser.

Removing sub-folders from Files display when any parent folder is clicked.

Using closed captioning for vtt/srt file icon.

Using my own react-semantic-toasts-2 to use toasts in Node 18.

Fixing bug where more than the last page was displayed.

Upgrading yt-dlp.

Fixing sub-folder file selection.

Adding rowKey to SortableTable to give React a key for each row.

Renaming key to path.

Removing duplicate urls.

Unifying file modals.

Displaying modals for image and text files.

Handling refresh loading in FileBrowser.  Creating refreshing_directory flag.

Removing accidental commit.

Sorting by url_count.

Using SortableTable on Domains page.

Using SortableTable for Channels page.

Created new FileBrowser which allows browsing of files in the media directory.

Using Node 18 in pi-gen.

Creating new FileBrowser to replace outdated react-keyed-file-browser.

Returning mimetype with file list.

Do not display 'Do not download' on Channel download in Dashboard.

Allowing null channel download frequency so user can stop downloading a channel.

Bumping version for Node 18.

Using my own semantic-ui-offline to avoid pulling Google fonts.

Upgrading app docker container to use Node 18.  This requires the removal of several npm packages.  File browser will require re-write.  It now pulls fonts from Google, this will need to be fixed.

Testing DownloadsToggle click.

Testing trinary states of DownloadsToggle.

Installing @testing-library/user-event for testing App.
This commit is contained in:
Roland 2023-01-31 18:08:07 -07:00
parent 5da0fe4f2d
commit 81d80238be
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
43 changed files with 16148 additions and 19032 deletions

View file

@ -1,15 +0,0 @@
os: linux
services:
- docker
language: python
python:
- "3.7"
- "3.8"
- "3.9"
before_install:
- docker-compose -p wrolpi -f docker-compose.dev.yml up -d db
- docker-compose -p wrolpi -f docker-compose.dev.yml run api db upgrade
- docker-compose -p wrolpi -f docker-compose.dev.yml up -d api
- docker-compose -p wrolpi -f docker-compose.dev.yml ps
script:
- docker-compose -p wrolpi -f docker-compose.dev.yml exec api pytest ./api

View file

@ -1,41 +1,43 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `yarn test`
### `npm test`
Launches the test runner in the interactive watch mode.<br />
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
### `npm run build`
Builds the app for production to the `build` folder.<br />
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
@ -45,24 +47,24 @@ To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `yarn build` fails to minify
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

33592
app/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -6,19 +6,20 @@
"@artsy/fresnel": "^6.1.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"lodash": "^4.17.19",
"query-string": "^6.13.0",
"@testing-library/user-event": "^13.5.0",
"lodash": "^4.17.21",
"query-string": "^8.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-dropzone": "^11.4.2",
"react-keyed-file-browser": "^1.14.0",
"react-qr-code": "^2.0.7",
"react-reader": "^0.19.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^3.4.1",
"react-semantic-toasts": "^0.6.5",
"semantic-ui-offline": "^2.4.1-1",
"semantic-ui-react": "^2.1.4"
"react-dropzone": "^14.2.3",
"react-qr-code": "^2.0.11",
"react-reader": "^1.0.2",
"react-router-dom": "^6.8.0",
"react-scripts": "5.0.1",
"react-semantic-toasts-2": "^0.6.7",
"semantic-ui-offline": "^2.5.0",
"semantic-ui-react": "^2.1.4",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
@ -27,7 +28,10 @@
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 127 KiB

Before After
Before After

View file

@ -1,20 +1,20 @@
<!DOCTYPE html>
<html lang="en" style="height: 100% ">
<head>
<meta charset="utf-8"/>
<link rel="icon" href="%PUBLIC_URL%/favicon.ico"/>
<html lang="en" style="height: 100%">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#000000"/>
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="WROLPi is a self-contained collection of software (on a Raspberry Pi) to help you survive the world Without Rule of Law."
name="description"
content="The WROLPI webapp"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo512.png"/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json"/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
@ -25,19 +25,19 @@
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>WROLPi: Create your own off-grid library</title>
</head>
<body style="margin: 0">
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View file

@ -1,6 +1,6 @@
{
"short_name": "WROLPi",
"name": "WROLPi web interface",
"short_name": "WROLPi App",
"name": "WROLPi App",
"icons": [
{
"src": "favicon.ico",
@ -10,16 +10,16 @@
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
"sizes": "191x191"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
"sizes": "512x509"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
"background_color": "#000000"
}

View file

@ -111,3 +111,25 @@ input:checked + .slider:before {
-ms-transform: translateX(26px);
transform: translateX(26px);
}
div.full-height {
overflow: hidden;
padding-top: 100%;
position: relative;
}
td.file-path {
cursor: pointer;
}
/* Necessary until react-semantic-toasts is upgraded to Node 18 */
.ui-alerts {
position: fixed;
z-index: 2060;
padding: 24px;
}
.ui-alerts.top-right {
top: 20px;
right: 20px;
}

View file

@ -6,8 +6,6 @@ import {VideosRoute, VideoWrapper} from "./components/Videos";
import Admin from "./components/admin/Admin";
import {Container} from "semantic-ui-react";
import 'semantic-ui-offline/semantic.min.css';
import {SemanticToastContainer} from 'react-semantic-toasts';
import 'react-semantic-toasts/styles/react-semantic-alert.css';
import {MoreRoute} from "./components/Apps";
import {InventoryRoute} from "./components/Inventory";
import {ArchiveRoute} from "./components/Archive";
@ -19,6 +17,7 @@ import {Header, ThemeWrapper} from "./components/Theme";
import {Dashboard} from "./Dashboard";
import {Donate} from "./components/Donate";
import {useEventsInterval} from "./Events";
import {SemanticToastContainer} from "react-semantic-toasts-2";
function PageNotFound() {
const {t} = useContext(ThemeContext);
@ -53,29 +52,26 @@ function Root() {
</header>
<Outlet/>
<Footer/>
<SemanticToastContainer position="top-right"/>
</>
}
const router = createBrowserRouter(createRoutesFromElements(
<Route
path='/'
element={<Root/>}
errorElement={<PageNotFound/>}
>
<Route index element={<Dashboard/>}/>
<Route path='donate' element={<Donate/>}/>
<Route path='videos/video/:videoId' exact element={<VideoWrapper/>}/>
<Route path='videos/channel/:channelId/video/:videoId' exact element={<VideoWrapper/>}/>
<Route path="videos/*" element={<VideosRoute/>}/>
<Route path="admin/*" element={<Admin/>}/>
<Route path="more/*" element={<MoreRoute/>}/>
<Route path="inventory/*" element={<InventoryRoute/>}/>
<Route path='archive/*' element={<ArchiveRoute/>}/>
<Route path='map/*' element={<MapRoute/>}/>
<Route path='files/*' element={<FilesRoute/>}/>
</Route>
));
const router = createBrowserRouter(createRoutesFromElements(<Route
path='/'
element={<Root/>}
errorElement={<PageNotFound/>}
>
<Route index element={<Dashboard/>}/>
<Route path='donate' element={<Donate/>}/>
<Route path='videos/video/:videoId' exact element={<VideoWrapper/>}/>
<Route path='videos/channel/:channelId/video/:videoId' exact element={<VideoWrapper/>}/>
<Route path="videos/*" element={<VideosRoute/>}/>
<Route path="admin/*" element={<Admin/>}/>
<Route path="more/*" element={<MoreRoute/>}/>
<Route path="inventory/*" element={<InventoryRoute/>}/>
<Route path='archive/*' element={<ArchiveRoute/>}/>
<Route path='map/*' element={<MapRoute/>}/>
<Route path='files/*' element={<FilesRoute/>}/>
</Route>));
export default function App() {
const status = useStatusInterval();
@ -84,6 +80,7 @@ export default function App() {
return <ThemeWrapper>
{/* Context and style to handle switching between mobile/computer. */}
<style>{mediaStyles}</style>
<SemanticToastContainer position='top-right'/>
<MediaContextProvider>
<StatusContext.Provider value={status}>
<RouterProvider router={router}/>

View file

@ -3,13 +3,6 @@ import {render} from '@testing-library/react';
import '@testing-library/jest-dom';
import App from "./App";
Object.defineProperty(window, 'matchMedia', {
writable: true, value: jest.fn().mockImplementation(query => ({
matches: false, media: query, onchange: null, addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(),
})),
});
test('renders without crashing', () => {
render(<App/>);

View file

@ -4,7 +4,7 @@ import React, {useContext, useState} from "react";
import {StatusContext} from "./contexts/contexts";
import {DownloadMenu} from "./components/Download";
import {FilesSearchView} from "./components/Files";
import {Header, Segment, Statistic, StatisticGroup} from "./components/Theme";
import {Button, Header, Segment, Statistic, StatisticGroup} from "./components/Theme";
import {Link} from "react-router-dom";
import {BandwidthProgressCombined, CPUUsageProgress} from "./components/admin/Status";
import {ProgressPlaceholder} from "./components/Placeholder";
@ -12,6 +12,7 @@ import {Divider, Icon, Message} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {refreshFiles} from "./api";
import _ from "lodash";
import {toast} from "react-semantic-toasts-2";
function FlagsMessages({flags}) {
if (!flags) {

View file

@ -1,7 +1,7 @@
import React, {useEffect} from 'react';
import {toast} from "react-semantic-toasts";
import {useRecurringTimeout} from "./hooks/customHooks";
import {getEvents} from "./api";
import {toast} from "react-semantic-toasts-2";
const apiEventName = 'apiEvent';

View file

@ -1,5 +1,5 @@
import {API_URI, ARCHIVES_API, DEFAULT_LIMIT, emptyToNull, OTP_API, VIDEOS_API} from "./components/Common";
import {toast} from 'react-semantic-toasts';
import {toast} from "react-semantic-toasts-2";
function timeoutPromise(ms, promise) {
// Create a timeout wrapper around a promise. If the timeout is reached, throw an error. Otherwise, return

View file

@ -10,10 +10,7 @@ import {
Input,
PlaceholderHeader,
PlaceholderLine,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {
@ -41,7 +38,8 @@ import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
import _ from "lodash";
import {ThemeContext} from "../contexts/contexts";
import {Button, Card, CardIcon, Header, Loader, Placeholder, Segment, Table} from "./Theme";
import {Button, Card, CardIcon, Header, Loader, Placeholder, Segment} from "./Theme";
import {SortableTable} from "./SortableTable";
function ArchivePage() {
const [deleteOpen, setDeleteOpen] = useState(false);
@ -262,6 +260,11 @@ export function Domains() {
</TableRow>
}
const headers = [
{key: 'domain', text: 'Domain', sortBy: 'domain', width: 12},
{key: 'archives', text: 'Archives', sortBy: 'url_count', width: 2},
];
return <>
<Input
icon='search'
@ -269,18 +272,13 @@ export function Domains() {
placeholder='Search...'
onChange={(e, {value}) => setSearchStr(value)}
/>
<Table celled>
<TableHeader>
<TableRow>
<TableHeaderCell>Domain</TableHeaderCell>
<TableHeaderCell>Archives</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{filteredDomains.map(row)}
</TableBody>
</Table>
<SortableTable
tableProps={{unstackable: true}}
data={filteredDomains}
rowFunc={(i, sortData) => row(i)}
rowKey='domain'
tableHeaders={headers}
/>
</>;
}

View file

@ -28,10 +28,8 @@ import {
import {Link, useNavigate, useParams} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import Confirm from "semantic-ui-react/dist/commonjs/addons/Confirm";
import {ChannelPlaceholder} from "./Placeholder";
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {useChannel, useChannels} from "../hooks/customHooks";
import {toast} from "react-semantic-toasts";
import _ from "lodash";
import {
Accordion,
@ -48,6 +46,9 @@ import {
} from "./Theme";
import Dropdown from "semantic-ui-react/dist/commonjs/modules/Dropdown";
import {Media} from "../contexts/contexts";
import {SortableTable} from "./SortableTable";
import {ChannelPlaceholder} from "./Placeholder";
import {toast} from "react-semantic-toasts-2";
function ChannelStatistics({statistics}) {
@ -325,7 +326,7 @@ function ChannelPage({create, header}) {
<FormGroup>
<FormField>
<label>Download Frequency</label>
<Dropdown selection
<Dropdown selection clearable
name='download_frequency'
placeholder='Frequency'
error={errors.download_frequency}
@ -517,28 +518,32 @@ export function Channels() {
</Grid>
</div>;
let tableHeader = <TableHeader>
<TableRow>
<TableHeaderCell width={8}>Name</TableHeaderCell>
<TableHeaderCell width={2}>Videos</TableHeaderCell>
<TableHeaderCell width={2}>Last Update</TableHeaderCell>
<TableHeaderCell width={2}>Frequency</TableHeaderCell>
<TableHeaderCell width={2} colSpan={3} textAlign='center'>Manage</TableHeaderCell>
</TableRow>
</TableHeader>;
const headers = [
{key: 'name', text: 'Name', sortBy: 'name', width: 8},
{key: 'video_count', text: 'Videos', sortBy: 'video_count', width: 2},
{key: 'last_update', text: 'Last Update', sortBy: 'info_date', width: 2},
{key: 'download_frequency', text: 'Download Frequency', sortBy: 'download_frequency', width: 2},
{key: 'manage', text: 'Manage', width: 2},
];
const mobileHeaders = [
{key: 'name', text: 'Name', sortBy: 'name'},
{key: 'video_count', text: 'Videos', sortBy: 'video_count'},
{key: 'manage', text: 'Manage'},
];
if (channels === null) {
// Placeholders while fetching
return <>
{header}
<Table compact striped basic size='large'>
{tableHeader}
<Table compact striped basic sortable size='large'>
<TableHeader>
<TableRow>
{headers.map(i => <TableHeaderCell key={i['key']}>{i['text']}</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
<TableRow>
<TableCell><ChannelPlaceholder/></TableCell>
<TableCell/>
<TableCell/>
<TableCell/>
<TableCell colSpan={5}><ChannelPlaceholder/></TableCell>
</TableRow>
</TableBody>
</Table>
@ -562,19 +567,24 @@ export function Channels() {
return <>
{header}
<Media at='mobile'>
<Table striped unstackable size='small'>
<TableBody>
{filteredChannels.map(channel => <MobileChannelRow key={channel.id} channel={channel}/>)}
</TableBody>
</Table>
<SortableTable
tableProps={{striped: true, size: 'small', unstackable: true}}
data={filteredChannels}
tableHeaders={mobileHeaders}
defaultSortColumn='name'
rowKey='id'
rowFunc={(i, sortData) => <MobileChannelRow key={i.id} channel={i} sortData={sortData}/>}
/>
</Media>
<Media greaterThanOrEqual='tablet'>
<Table compact unstackable striped size='large'>
{tableHeader}
<TableBody>
{filteredChannels.map(channel => <ChannelRow key={channel.id} channel={channel}/>)}
</TableBody>
</Table>
<SortableTable
tableProps={{striped: true, size: 'large', unstackable: true, compact: true}}
data={filteredChannels}
tableHeaders={headers}
defaultSortColumn='name'
rowKey='id'
rowFunc={(i, sortData) => <ChannelRow key={i.id} channel={i} sortData={sortData}/>}
/>
</Media>
</>
}

View file

@ -148,9 +148,9 @@ export function RequiredAsterisk() {
export let defaultVideoOrder = '-upload_date';
export let defaultSearchOrder = 'rank';
export const frequencyOptions = [{key: 'daily', text: 'Daily', value: 86400}, {
key: 'weekly', text: 'Weekly', value: 604800
}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, {
export const frequencyOptions = [{key: null, text: '', value: null}, {
key: 'daily', text: 'Daily', value: 86400
}, {key: 'weekly', text: 'Weekly', value: 604800}, {key: 'biweekly', text: 'Biweekly', value: 1209600}, {
key: '30days', text: '30 Days', value: 2592000
}, {key: '90days', text: '90 Days', value: 7776000},];
@ -515,7 +515,8 @@ export function Toggle({label, checked, disabled, onChange, icon}) {
style['color'] = '#888888';
}
let onMouseUp;
let onMouseUp = () => {
};
if (onChange) {
onMouseUp = (e) => {
if (disabled) {
@ -534,10 +535,11 @@ export function Toggle({label, checked, disabled, onChange, icon}) {
return <>
<div className='toggle' onMouseUp={onMouseUp}>
<input type="checkbox" className={inputClassName} checked={checked} onChange={onMouseUp}/>
<input type="checkbox" className={inputClassName} checked={checked} onChange={onMouseUp}
data-testid='toggle'/>
<span className={sliderClassName}></span>
</div>
<span style={style}>
<span style={style} data-testid='toggle-label'>
{icon}
{label}
</span>
@ -547,11 +549,11 @@ export function Toggle({label, checked, disabled, onChange, icon}) {
export function DisableDownloadsToggle() {
let {on, setDownloads} = useDownloaders();
return <Form>
<Toggle toggle
label={on ? 'Downloading Enabled' : 'Downloading Disabled'}
disabled={on === null}
checked={on === true}
onChange={setDownloads}
<Toggle
label={on ? 'Downloading Enabled' : 'Downloading Disabled'}
disabled={on === null}
checked={on === true}
onChange={setDownloads}
/>
</Form>;
}
@ -568,18 +570,21 @@ export function emptyToNull(obj) {
}
export function mimetypeColor(mimetype) {
if (!mimetype) {
return 'grey';
}
try {
if (mimetype === 'application/pdf') {
return 'red'
} else if (mimetype && mimetype.startsWith('video/')) {
} else if (mimetype.startsWith('video/')) {
return 'blue'
} else if (mimetype && mimetype.startsWith('image/')) {
} else if (mimetype.startsWith('image/')) {
return 'pink'
} else if (mimetype && mimetype.startsWith('text/html')) {
} else if (mimetype.startsWith('text/html')) {
return 'green'
} else if (mimetype && mimetype.startsWith('application/zip')) {
} else if (mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib') || mimetype.startsWith('application/x-7z-compressed') || mimetype.startsWith('application/x-bzip2') || mimetype.startsWith('application/x-xz')) {
return 'purple'
} else if (mimetype && (mimetype.startsWith('application/epub') || mimetype.startsWith('application/x-mobipocket-ebook'))) {
} else if (mimetype.startsWith('application/epub') || mimetype.startsWith('application/x-mobipocket-ebook')) {
return 'yellow'
}
} catch (e) {
@ -591,7 +596,8 @@ export function mimetypeColor(mimetype) {
export function FileIcon({file, disabled = true, size = 'huge', ...props}) {
// Default to a grey file icon.
const {mimetype} = file;
const {mimetype, path} = file;
const lowerPath = path.toLowerCase();
props['name'] = 'file';
props['color'] = mimetypeColor(mimetype);
if (mimetype) {
@ -605,12 +611,16 @@ export function FileIcon({file, disabled = true, size = 'huge', ...props}) {
props['name'] = 'image';
} else if (mimetype.startsWith('video/')) {
props['name'] = 'film';
} else if (mimetype.startsWith('application/zip')) {
} else if (mimetype.startsWith('application/zip') || mimetype.startsWith('application/zlib') || mimetype.startsWith('application/x-7z-compressed') || mimetype.startsWith('application/x-bzip2') || mimetype.startsWith('application/x-xz')) {
props['name'] = 'file archive';
} else if (mimetype.startsWith('application/x-iso9660-image')) {
props['name'] = 'dot circle';
} else if (mimetype.startsWith('application/epub') || mimetype.startsWith('application/x-mobipocket-ebook')) {
props['name'] = 'book';
} else if (mimetype.startsWith('text/vtt') || mimetype.startsWith('text/srt')) {
props['name'] = 'closed captioning';
} else if (mimetype.startsWith('application/octet-stream') && (lowerPath.endsWith('.stl') || lowerPath.endsWith('.blend'))) {
props['name'] = 'cube';
}
}
return <Icon disabled={disabled} size={size} {...props}/>

View file

@ -0,0 +1,58 @@
import React from "react";
import {getByTestId, render, screen} from '@testing-library/react';
import {DisableDownloadsToggle} from "./Common";
import {useDownloaders} from "../hooks/customHooks";
import user from '@testing-library/user-event';
jest.mock('../hooks/customHooks', () => ({useDownloaders: jest.fn()}));
test('DownloadsToggle is off when loading', async () => {
useDownloaders.mockImplementation(() => ({on: null}));
const {container} = render(<DisableDownloadsToggle/>);
let toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Disabled while loading.
expect(toggle).toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is off if downloading is Off', async () => {
useDownloaders.mockImplementation(() => ({on: false}));
const {container} = render(<DisableDownloadsToggle/>);
const toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is on if downloading is On', async () => {
useDownloaders.mockImplementation(() => ({on: true}));
const {container} = render(<DisableDownloadsToggle/>);
const toggle = screen.getByRole('checkbox');
expect(toggle).toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "enabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Enabled');
});
test('DownloadsToggle click', async () => {
const mock = jest.fn();
useDownloaders.mockImplementation(() => ({on: true, setDownloads: mock}));
render(<DisableDownloadsToggle/>);
// Downloads is toggled when DownloadsToggle is clicked.
const toggle = screen.getByRole('checkbox');
user.click(toggle);
expect(mock).toHaveBeenCalled();
expect(mock).toHaveBeenLastCalledWith(false);
})

View file

@ -111,7 +111,7 @@ class ChannelDownload extends React.Component {
this.state = {
url: '', frequency: 604800, pending: false, disabled: false, ready: false, error: null, success: null,
};
this.freqOptions = [{key: 'once', text: 'Once', value: 0}, ...frequencyOptions,];
this.freqOptions = [{key: 'once', text: 'Once', value: 0}, ...frequencyOptions.slice(1),];
this.handleUrlChange = this.handleUrlChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleFrequencyChange = this.handleFrequencyChange.bind(this);

View file

@ -0,0 +1,254 @@
import {Button, Icon, Placeholder} from "./Theme";
import {
Button as SButton,
Checkbox,
Confirm,
Image,
Modal,
ModalActions,
ModalContent,
PlaceholderLine,
TableCell,
TableFooter,
TableHeaderCell,
TableRow
} from "semantic-ui-react";
import {FileIcon, humanFileSize} from "./Common";
import React from "react";
import {deleteFile} from "../api";
import _ from 'lodash';
import {SortableTable} from "./SortableTable";
import {useBrowseFiles} from "../hooks/customHooks";
import {DirectoryRefreshButton, FilesRefreshButton} from "./Files";
function depthIndentation(path) {
// Repeated spaces for every folder a path is in.
const depth = (path.match(/\//g) || []).length;
return '\xa0\xa0\xa0\xa0'.repeat(depth);
}
function Folder({folder, onFolderClick, sortData, selectedPath, onFileClick, onSelect}) {
// Creates a single table row for a folder, or a row for itself and indented rows for its children.
let {path, children} = folder;
const pathWithNoTrailingSlash = path.substring(0, path.length - 1);
const name = path.substring(pathWithNoTrailingSlash.lastIndexOf('/') + 1);
const f = <TableRow key={path}>
<TableCell collapsing>
<Checkbox checked={selectedPath === folder['path']} onChange={() => onSelect(folder['path'])}/>
</TableCell>
<TableCell onClick={() => onFolderClick(path)} className='file-path'>
{depthIndentation(pathWithNoTrailingSlash)}
<Icon name='folder'/>
{name}
</TableCell>
<TableCell/>
</TableRow>;
if (children && !_.isEmpty(children)) {
// Folder has children, recursively display them.
children = sortData(children);
let childPaths = [];
_.forEach(children, (p, k) => {
childPaths = [...childPaths,
<Path key={k} path={p} onFolderClick={onFolderClick} sortData={sortData} onFileClick={onFileClick}
selectedPath={selectedPath} onSelect={onSelect}/>];
});
return <React.Fragment>
{f}
{childPaths}
</React.Fragment>
} else {
// Folder has no children.
return f;
}
}
function File({file, onFileClick, selectedPath, onSelect}) {
const {path, size} = file;
const name = path.substring(path.lastIndexOf('/') + 1);
return <TableRow key={path}>
<TableCell collapsing>
<Checkbox checked={selectedPath === path} onChange={() => onSelect(path)}/>
</TableCell>
<TableCell onClick={() => onFileClick(file)} className='file-path'>
{depthIndentation(path)}
{/*null size to make icon the correct size*/}
<FileIcon file={file} size={null}/>
{name}
</TableCell>
<TableCell collapsing textAlign='right'>
{humanFileSize(size)}
</TableCell>
</TableRow>
}
function Path({path, onFolderClick, onFileClick, sortData, selectedPath, onSelect}) {
if (path['path'].endsWith('/')) {
return <Folder
folder={path}
onFolderClick={onFolderClick}
sortData={sortData}
selectedPath={selectedPath}
onSelect={onSelect}
onFileClick={onFileClick}
/>
} else {
return <File
file={path}
onFileClick={onFileClick}
selectedPath={selectedPath}
onSelect={onSelect}
/>
}
}
export function FileBrowser() {
const [selectedPath, setSelectedPath] = React.useState(null);
const [deleteOpen, setDeleteOpen] = React.useState(false);
const [fileSelected, setFileSelected] = React.useState(false);
const [folderSelected, setFolderSelected] = React.useState(false);
const {browseFiles, openFolders, setOpenFolders, fetchFiles} = useBrowseFiles();
const headers = [{key: 'select', text: ''}, {
key: 'path', text: 'Path', sortBy: i => i['path'].toLowerCase()
}, {key: 'size', text: 'Size', sortBy: 'size'},];
const [modal, setModal] = React.useState(null);
const onFileClick = (path) => {
const {mimetype} = path;
const url = `/media/${path['path']}`;
let modalBody;
if (mimetype === 'text/plain' || mimetype === 'text/html') {
modalBody = <ModalContent>
<div className='full-height'>
<iframe title='textModal' src={url}
style={{
height: '100%',
width: '100%',
border: 'none',
position: 'absolute',
top: 0,
}}/>
</div>
</ModalContent>;
} else if (mimetype.startsWith('image/')) {
modalBody = <ModalContent>
<a href={url}>
<Image src={url}/>
</a>
</ModalContent>;
}
if (modalBody) {
// Create modal that will instantly display the file.
setModal(<Modal closeIcon
size='fullscreen'
open={true}
onClose={() => setModal(null)}
>
{modalBody}
<ModalActions>
<SButton color='blue' onClick={() => window.open(url)}>Open</SButton>
<SButton onClick={() => setModal(null)}>Close</SButton>
</ModalActions>
</Modal>)
} else {
// No special handler for this file type, just open it.
setModal(null);
window.open(url);
}
}
const onSelect = (path) => {
if (path.endsWith('/') && selectedPath === path) {
// Deselect folder.
setFileSelected(false);
setFolderSelected(false);
setSelectedPath(null);
} else if (path.endsWith('/')) {
// Select folder.
setFileSelected(false);
setFolderSelected(true);
setSelectedPath(path);
} else if (selectedPath === path) {
// Deselect file.
setFileSelected(false);
setFolderSelected(false);
setSelectedPath(null);
} else {
// Select file.
setFileSelected(true);
setFolderSelected(false);
setSelectedPath(path);
}
}
const onDelete = async () => {
await deleteFile(selectedPath);
setDeleteOpen(false);
await fetchFiles();
};
const footer = <TableFooter fullWidth>
<TableRow>
<TableHeaderCell colSpan={3}>
{folderSelected ? <DirectoryRefreshButton directory={selectedPath}/> : <FilesRefreshButton/>}
<Button
color='red'
onClick={() => setDeleteOpen(true)}
disabled={!fileSelected}
>
<Icon name='close'/>
Delete
</Button>
<Confirm
open={deleteOpen}
content='Are you sure you want to delete these files?'
onConfirm={onDelete}
onCancel={() => setDeleteOpen(false)}
/>
</TableHeaderCell>
</TableRow>
</TableFooter>;
const onFolderClick = async (folder) => {
let newFolders;
if (openFolders.indexOf(folder) >= 0) {
// Remove the folder that was clicked on, as well as its sub-folders.
newFolders = openFolders.filter(i => !i.startsWith(folder));
} else {
// Add the new folder to the opened folders.
newFolders = [...openFolders, folder];
}
console.debug(`newFolders=${newFolders}`);
setOpenFolders(newFolders);
}
if (browseFiles === null) {
return <Placeholder>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>;
}
return <>
<SortableTable
tableProps={{unstackable: true}}
data={browseFiles}
tableHeaders={headers}
defaultSortColumn='path'
rowKey='path'
rowFunc={(i, sortData) => <Path
key={i['key']}
path={i}
onFolderClick={onFolderClick}
onFileClick={onFileClick}
sortData={sortData}
selectedPath={selectedPath}
onSelect={onSelect}
/>}
footer={footer}
/>
{modal}
</>
}

View file

@ -1,14 +1,11 @@
import React, {useContext} from "react";
import FileBrowser from 'react-keyed-file-browser';
import {
Button as SButton,
CardContent,
CardDescription,
CardHeader,
CardMeta,
Confirm,
Container,
Divider,
Dropdown,
Header as SHeader,
Image,
@ -17,8 +14,6 @@ import {
TableCell,
TableHeaderCell,
} from "semantic-ui-react";
import 'react-keyed-file-browser/dist/react-keyed-file-browser.css';
import {deleteFile, refreshDirectoryFiles, refreshFiles} from "../api";
import {
CardGroupCentered,
CardLink,
@ -34,7 +29,7 @@ import {
textEllipsis,
useTitle
} from "./Common";
import {useBrowseFiles, useQuery, useSearchFiles} from "../hooks/customHooks";
import {useQuery, useSearchFiles} from "../hooks/customHooks";
import {Route, Routes} from "react-router-dom";
import {CardPlacholder} from "./Placeholder";
import {ArchiveCard, ArchiveRowCells} from "./Archive";
@ -44,118 +39,15 @@ import {Button, Card, CardIcon, Icon, Placeholder, Segment} from "./Theme";
import {SelectableTable} from "./Tables";
import {VideoCard, VideoRowCells} from "./Videos";
import _ from 'lodash';
import {useSubscribeEvents, useSubscribeEventName} from "../Events";
import {FileBrowser} from "./FileBrowser";
import {refreshDirectoryFiles, refreshFiles} from "../api";
import {useSubscribeEventName} from "../Events";
const icons = {
File: <Icon name='file'/>,
Folder: <Icon name='folder'/>,
FolderOpen: <Icon name='folder open'/>,
Image: <Icon name='file image'/>,
PDF: <Icon name='file pdf'/>,
};
export function Files() {
export function FilesPage() {
useTitle('Files');
const {t} = useContext(ThemeContext);
const {browseFiles, setOpenFolders, fetchFiles} = useBrowseFiles();
const [deleteOpen, setDeleteOpen] = React.useState(false);
const [selectedFile, setSelectedFile] = React.useState(null);
const [selectedDirectory, setSelectedDirectory] = React.useState(null);
const handleFolderChange = async (file, browserProps) => {
let openFolders = Object.keys(browserProps.openFolders);
setOpenFolders(openFolders);
}
const onSelect = async (file) => {
// A user can only select one file or one directory.
if (file.key.endsWith('/')) {
setSelectedFile(null);
setSelectedDirectory(file);
} else {
setSelectedDirectory(null);
setSelectedFile(file);
}
}
const onDeleteFile = async () => {
await deleteFile(selectedFile.key);
await fetchFiles();
}
const openDelete = () => {
setDeleteOpen(true);
}
const closeDelete = () => {
setDeleteOpen(false);
}
const clearSelection = async (e) => {
e.preventDefault();
setOpenFolders(null);
setSelectedDirectory(null);
setSelectedFile(null);
await fetchFiles();
}
let clearButton = <Button
onClick={clearSelection}
disabled={!!!selectedFile && !!!selectedDirectory}>
Clear
</Button>;
let buttons;
if (selectedFile) {
buttons = <>
<ExternalCardLink to={`/download/${selectedFile.key}`}>
<Button primary>Open</Button>
</ExternalCardLink>
<Confirm
open={deleteOpen}
onCancel={closeDelete}
onConfirm={onDeleteFile}
content={`Are you sure you want to delete: ${selectedFile.key}`}
confirmButton='Delete'
/>
<Button floated='right' color='red' onClick={openDelete}>Delete</Button>
</>;
} else if (selectedDirectory) {
buttons = <>
<DirectoryFilesRefreshButton directory={selectedDirectory.key}/>
</>;
} else {
buttons = <FilesRefreshButton/>;
}
let body = <Placeholder>
<PlaceholderLine/>
<PlaceholderLine/>
</Placeholder>;
if (_.isArray(browseFiles)) {
body = <FileBrowser
showActionBar={false}
canFilter={false}
files={browseFiles}
icons={icons}
onFolderOpen={handleFolderChange}
onFolderClose={handleFolderChange}
onSelect={onSelect}
detailRenderer={() => <></>} // Hide the preview that the 3rd party provided.
/>;
}
return <>
{clearButton}
{buttons}
<Divider/>
<div {...t}>
{body}
</div>
</>
return <FileBrowser/>;
}
function EbookCard({file}) {
@ -560,10 +452,18 @@ export function FilesSearchView({
/>
}
function FilesRefreshButton() {
const {t} = useContext(ThemeContext);
export function FilesRoute() {
return <PageContainer>
<Routes>
<Route path='/' exact element={<FilesPage/>}/>
</Routes>
</PageContainer>;
}
export function FilesRefreshButton() {
const {status} = useContext(StatusContext);
const refreshing = status && status['flags'] && status['flags'].indexOf('refreshing') >= 0;
const refreshingDirectory = status && status['flags'] && status['flags'].indexOf('refreshing_directory') >= 0;
const [loading, setLoading] = React.useState(false);
@ -575,26 +475,20 @@ function FilesRefreshButton() {
// Clear loading when global refresh event completes.
useSubscribeEventName('global_refresh_completed', () => setLoading(false));
return <>
<Button icon
labelPosition='left'
loading={loading || refreshing}
id='refresh_files'
onClick={handleClick}
disabled={loading || refreshing}>
<Icon name='refresh'/>
Refresh Files
</Button>
<label htmlFor='refresh_files' {...t}>
Find and index all files in the media directory.
</label>
</>;
return <Button icon
labelPosition='left'
loading={loading || refreshing || refreshingDirectory}
onClick={handleClick}
disabled={loading || refreshing}>
<Icon name='refresh'/>
Refresh All
</Button>;
}
function DirectoryFilesRefreshButton({directory}) {
const {t} = useContext(ThemeContext);
export function DirectoryRefreshButton({directory}) {
const {status} = useContext(StatusContext);
const refreshing = status && status['flags'] && status['flags'].indexOf('refreshing') >= 0;
const refreshingDirectory = status && status['flags'] && status['flags'].indexOf('refreshing_directory') >= 0;
const [loading, setLoading] = React.useState(false);
@ -603,29 +497,17 @@ function DirectoryFilesRefreshButton({directory}) {
await refreshDirectoryFiles(directory);
}
// Clear loading when directory refresh event completes.
// Clear loading when global refresh event completes.
useSubscribeEventName('global_refresh_completed', () => setLoading(false));
useSubscribeEventName('directory_refresh_completed', () => setLoading(false));
return <>
<Button icon primary
labelPosition='left'
loading={loading || refreshing}
id='refresh_files'
onClick={handleClick}
disabled={loading || refreshing}>
<Icon name='refresh'/>
Refresh Directory
</Button>
<label htmlFor='refresh_files' {...t}>
Find and index all files in the directory.
</label>
</>;
}
export function FilesRoute() {
return (<PageContainer>
<Routes>
<Route path='/' exact element={<Files/>}/>
</Routes>
</PageContainer>);
return <Button icon
labelPosition='left'
loading={loading || refreshing || refreshingDirectory}
onClick={handleClick}
disabled={loading || refreshing || refreshingDirectory}
>
<Icon name='refresh'/>
Refresh Directory
</Button>
}

View file

@ -25,12 +25,12 @@ import {
TableRow
} from "semantic-ui-react";
import {Route, Routes} from "react-router-dom";
import {toast} from 'react-semantic-toasts';
import {arraysEqual, enumerate, PageContainer, replaceNullValues, TabLinks, useTitle} from './Common';
import _ from 'lodash';
import {ThemeContext} from "../contexts/contexts";
import {useInventory} from "../hooks/customHooks";
import {Button, FormGroup, FormInput, Header, Segment, Table} from "./Theme";
import {toast} from "react-semantic-toasts-2";
function InventorySummary() {
const {t} = useContext(ThemeContext);

View file

@ -0,0 +1,73 @@
import React from "react";
import _ from "lodash";
import {TableBody, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Table} from "./Theme";
export class SortableTable extends React.Component {
constructor(props) {
super(props);
this.state = {sortColumn: null, direction: 'ascending'};
}
changeSort = (key) => {
const {sortColumn, direction} = this.state;
if (key === sortColumn) {
this.setState({direction: direction === 'ascending' ? 'descending' : 'ascending'});
} else {
this.setState({sortColumn: key, direction: 'ascending'});
}
}
sortData = (data) => {
let {tableHeaders, defaultSortColumn} = this.props;
let {sortColumn, direction} = this.state;
const sortKey = sortColumn || defaultSortColumn;
const sortHeader = _.find(tableHeaders, {key: sortKey});
if (sortHeader === undefined) {
// No sort header, probably no default defined.
return data;
}
data = _.sortBy(data, sortHeader['sortBy']);
data = direction === 'descending' ? data.reverse() : data;
return data;
}
render() {
let {rowFunc, tableHeaders, rowKey} = this.props;
let {direction} = this.state;
rowKey = rowKey || 'key';
const data = this.sortData(this.props['data']);
const tableHeader = (spec) => {
const {key, text, sortBy, width} = spec;
if (sortBy) {
return <TableHeaderCell
key={key}
sorted={this.state['sortColumn'] === key ? direction : null}
onClick={() => this.changeSort(key)}
width={width || undefined}
>
{text}
</TableHeaderCell>;
} else {
return <TableHeaderCell key={key} width={width}>{text}</TableHeaderCell>
}
}
const rows = data.map(i => <React.Fragment key={i[rowKey]}>{rowFunc(i, this.sortData)}</React.Fragment>);
return <Table sortable {...this.props.tableProps}>
<TableHeader>
<TableRow>
{tableHeaders.map(tableHeader)}
</TableRow>
</TableHeader>
<TableBody>
{rows}
</TableBody>
{this.props.footer}
</Table>
}
}

View file

@ -25,16 +25,16 @@ import {
startDownloads
} from "../api";
import {createSearchParams, useSearchParams} from "react-router-dom";
import {toast} from "react-semantic-toasts";
import {enumerate, filterToMimetypes, humanFileSize, secondsToFullDuration} from "../components/Common";
import {StatusContext} from "../contexts/contexts";
import {toast} from "react-semantic-toasts-2";
const calculatePage = (offset, limit) => {
return offset && limit ? Math.round((offset / limit) + 1) : 1;
}
const calculateTotalPages = (total, limit) => {
return total && limit ? Math.round(total / limit) + 1 : 1;
return total && limit ? Math.round(total / limit) : 1;
}
export const useRecurringTimeout = (callback, delay) => {

View file

@ -1,33 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
html, body, #root {
height: 100%;
margin: 0;
}
.vwrapper, html, body {
height: 100%;
margin: 0;
}
.vwrapper {
display: flex;
flex-direction: column;
}
.full-page {
flex: 2;
display: flex;
}

View file

@ -1,14 +1,7 @@
import React from 'react';
import {createRoot} from 'react-dom/client';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
const container = document.getElementById('root');
const root = createRoot(container);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

Before After
Before After

View file

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View file

@ -1,135 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}

14
app/src/setupTests.js Normal file
View file

@ -0,0 +1,14 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
window.matchMedia = window.matchMedia || function() {
return {
matches: false,
addListener: function() {},
addEventListener: function() {},
removeListener: function() {}
};
};

View file

@ -60,6 +60,9 @@ services:
healthcheck:
test: [ 'CMD-SHELL', 'curl http://127.0.0.1:3000' ]
user: '${UID-1000}:${GID-1000}'
environment:
# Force React to use nginx port to connect to it's websocket.
- WDS_SOCKET_PORT=0
map:
# https://github.com/Overv/openstreetmap-tile-server

View file

@ -1,5 +1,5 @@
# base image
FROM node:13-buster
FROM node:18-bullseye
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
@ -7,10 +7,10 @@ ENV PATH /app/node_modules/.bin:$PATH
# install and cache app dependencies
COPY app/public /app/public
COPY app/src /app/src
COPY app/package.json /app/
RUN rm -rf /app/node_modules /app/package-lock.json
COPY app/package.json app/package-lock.json /app/
RUN npm install
RUN npm install -g serve
RUN chown -R node:node /app
# Run the production build
CMD ["serve", "-s", "build"]

View file

@ -332,7 +332,7 @@ def test_channel_by_id(test_session, test_client, simple_channel, simple_video):
assert response.status_code == HTTPStatus.OK
def test_channel_crud(test_session, test_client, test_directory):
def test_channel_crud(test_session, test_client, test_directory, test_download_manager):
channel_directory = test_directory / 'channel directory'
channel_directory.mkdir()
@ -372,19 +372,35 @@ def test_channel_crud(test_session, test_client, test_directory):
request, response = test_client.post('/api/videos/channels', content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.BAD_REQUEST
def put_and_fetch(new_channel_):
request, response = test_client.put(location, content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
request, response = test_client.get(location)
assert response.status_code == HTTPStatus.OK
channel = response.json['channel']
return channel
# Update it
new_channel['name'] = 'Example Channel 2'
new_channel['directory'] = str(new_channel['directory']) # noqa
request, response = test_client.put(location, content=json.dumps(new_channel))
assert response.status_code == HTTPStatus.NO_CONTENT, response.status_code
request, response = test_client.get(location)
assert response.status_code == HTTPStatus.OK
channel = response.json['channel']
new_channel['download_frequency'] = 60
channel = put_and_fetch(new_channel)
assert channel['id'] == 1
assert channel['name'] == 'Example Channel 2'
assert channel['directory'] == channel_directory.name
assert channel['match_regex'] == 'asdf'
assert channel['url'] == 'https://example.com/channel1'
# Download was created.
assert channel['download_frequency']
assert (downloads := test_download_manager.get_downloads(test_session)) and len(downloads) == 1 and downloads[
0].url == new_channel['url']
# Update with no download frequency.
new_channel['download_frequency'] = None
channel = put_and_fetch(new_channel)
assert channel['download_frequency'] is None
# Download was deleted.
assert len(test_download_manager.get_downloads(test_session)) == 0
# Can't update channel that doesn't exist
request, response = test_client.put('/api/videos/channels/doesnt_exist',

View file

@ -32,7 +32,7 @@ http {
rewrite $1 break;
}
location /sockjs-node {
location /ws {
proxy_pass http://app:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;

View file

@ -1,2 +1,2 @@
# Install Node 14 repo.
npm --version || curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
# Install Node 18 repo.
npm --version || curl -fsSL https://deb.nodesource.com/setup_18.x | bash -

View file

@ -24,4 +24,4 @@ selenium==4.1.0
srt==3.5.1
websockets==10.1
webvtt-py==0.4.6
yt-dlp==2022.9.1
yt-dlp==2023.1.6

View file

@ -4,14 +4,18 @@ echo "Debian 11 install start: $(date '+%Y-%m-%d %H:%M:%S')"
set -x
set -e
# Install npm repos.
npm --version || curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
# Update if we haven't updated in the last day.
[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -1)" ] && apt update
# Install dependencies
apt install -y apt-transport-https ca-certificates curl gnupg-agent gcc libpq-dev software-properties-common \
postgresql-13 nginx-full nginx-doc python3-full python3-dev python3-doc python3-venv htop vim ffmpeg hostapd \
chromium chromium-driver cpufrequtils network-manager npm
chromium chromium-driver cpufrequtils network-manager nodejs
# Install serve, and archiving tools.
sudo npm i -g serve@12.0.1 single-file-cli@1.0.15 'git+https://github.com/pirate/readability-extractor' &
sudo npm i -g serve single-file-cli@1.0.33 'git+https://github.com/lrnselfreliance/readability-extractor' &
# Setup the virtual environment that main.py expects
pip3 --version || (

View file

@ -5,7 +5,8 @@ set -x
set -e
# Install npm repos.
npm --version || curl -fsSL https://deb.nodesource.com/setup_14.x | bash -
npm --version || curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
# Update if we haven't updated in the last day.
[ -z "$(find -H /var/lib/apt/lists -maxdepth 0 -mtime -1)" ] && apt update
# Install dependencies
@ -14,7 +15,7 @@ apt install -y apt-transport-https ca-certificates curl gnupg-agent gcc libpq-de
ffmpeg hostapd nodejs chromium-browser chromium-chromedriver cpufrequtils network-manager
# Install serve, and archiving tools.
sudo npm i -g serve@12.0.1 single-file-cli@1.0.15 'git+https://github.com/pirate/readability-extractor' &
sudo npm i -g serve single-file-cli@1.0.33 'git+https://github.com/lrnselfreliance/readability-extractor' &
# Setup the virtual environment that main.py expects
pip3 --version || (

View file

@ -17,34 +17,6 @@ from ..vars import PYTEST
bp = get_blueprint('Files', '/api/files')
def paths_to_files(paths: List[pathlib.Path]):
"""Convert Paths to what the React UI expects."""
media_directory = get_media_directory()
new_files = []
for path in paths:
stat = path.stat()
key = path.relative_to(media_directory)
modified = stat.st_mtime
if path.is_dir():
key = f'{key}/'
new_files.append(dict(
key=key,
modified=modified,
url=key,
name=path.name,
))
else:
# A File should know it's size.
new_files.append(dict(
key=key,
modified=modified,
size=stat.st_size,
url=key,
name=path.name,
))
return new_files
@bp.post('/')
@openapi.definition(
summary='List files in a directory',
@ -54,8 +26,7 @@ def paths_to_files(paths: List[pathlib.Path]):
async def get_files(_: Request, body: schema.FilesRequest):
directories = body.directories or []
files = lib.list_files(directories)
files = paths_to_files(files)
files = lib.list_directories_contents(directories)
return json_response({'files': files})

View file

@ -7,7 +7,7 @@ import pathlib
import re
import subprocess
from pathlib import Path
from typing import List, Tuple, Union
from typing import List, Tuple, Union, Dict
import psycopg2
from sqlalchemy.orm import Session
@ -35,7 +35,8 @@ except ImportError:
logger = logger.getChild(__name__)
__all__ = ['list_files', 'delete_file', 'split_path_stem_and_suffix', 'refresh_files', 'search_files', 'get_mimetype',
__all__ = ['list_directories_contents', 'delete_file', 'split_path_stem_and_suffix', 'refresh_files', 'search_files',
'get_mimetype',
'split_file_name_words']
@ -59,24 +60,54 @@ def filter_parent_directories(directories: List[Path]) -> List[Path]:
return new_directories
def list_files(directories: List[str]) -> List[Path]:
"""List all files down to the directories provided. This includes all parent directories of the directories."""
def _get_file_dict(file: pathlib.Path) -> Dict:
media_directory = get_media_directory()
return dict(
path=file.relative_to(media_directory),
size=file.stat().st_size,
mimetype=get_mimetype(file),
)
# Always display the media_directory files.
paths = list(media_directory.iterdir())
if directories:
directories = [media_directory / i for i in directories if i]
directories = filter_parent_directories(directories)
for directory in directories:
directory = media_directory / directory
for parent in directory.parents:
is_relative_to = str(media_directory).startswith(str(parent))
if parent == Path('') or is_relative_to:
continue
paths.extend(parent.iterdir())
paths.extend(directory.iterdir())
def _get_directory_dict(directory: pathlib.Path, directories: List[pathlib.Path]) -> Dict:
media_directory = get_media_directory()
d = dict(
path=f'{directory.relative_to(media_directory)}/',
)
if directory in directories:
children = dict()
for path in directory.iterdir():
if path.is_dir() and path in directories:
children[f'{path.name}/'] = _get_directory_dict(path, directories)
elif path.is_dir():
children[f'{path.name}/'] = dict(path=f'{path.relative_to(media_directory)}/')
else:
children[path.name] = _get_file_dict(path)
d['children'] = children
return d
def list_directories_contents(directories_: List[str]) -> Dict:
"""List all files down to (and within) the directories provided.
This should only be used by the frontend for it's FileBrowser."""
media_directory = get_media_directory()
# Convert all directories to pathlib.Path.
directories = {media_directory / i for i in directories_}
if invalid_directories := [i for i in directories if not i.is_dir()]:
raise FileNotFoundError(f'Invalid directories: {invalid_directories}')
# Get all unique parents for each directory, but not if they are above the media directory.
parents = {j for i in directories for j in i.parents if j not in media_directory.parents}
# Add unique parents onto the requested directories.
directories = list(directories | parents)
paths = dict()
for path in media_directory.iterdir():
if path.is_dir():
paths[f'{path.name}/'] = _get_directory_dict(path, directories)
else:
paths[path.name] = _get_file_dict(path)
return paths
@ -127,6 +158,7 @@ def _mimetype_suffix_map(path: Path, mimetype: str):
return mimetype
@functools.lru_cache(maxsize=1000)
def get_mimetype(path: Path) -> str:
"""Get the mimetype of a file, prefer using `magic`, fallback to builtin `file` command."""
if magic is None:
@ -367,37 +399,38 @@ async def refresh_directory_files_recursively(directory: Union[pathlib.Path, str
if directory.is_file():
raise ValueError(f'Cannot refresh files of a file: {directory=}')
relative_path = str(get_relative_to_media_directory(directory))
if send_events:
Events.send_directory_refresh_started(f'Refresh of {repr(relative_path)} has started.')
with flags.refreshing_directory:
relative_path = str(get_relative_to_media_directory(directory))
if send_events:
Events.send_directory_refresh_started(f'Refresh of {repr(relative_path)} has started.')
# All Files older than this will be removed.
idempotency = now()
# All Files older than this will be removed.
idempotency = now()
refresh_logger.info(f'Recursively refreshing all files in {directory}')
refresh_logger.info(f'Recursively refreshing all files in {directory}')
await _refresh_directory_files_recursively(directory, idempotency)
await _refresh_directory_files_recursively(directory, idempotency)
# Remove any records where the file no longer exists.
with get_db_curs(commit=True) as curs:
refresh_logger.debug(f'Deleting files no longer in {directory}')
params = dict(
directory=f'{directory}/%', # trailing / is important!
idempotency=idempotency,
)
stmt = '''
DELETE FROM file
WHERE
(idempotency < %(idempotency)s OR idempotency IS NULL)
AND path LIKE %(directory)s'''
curs.execute(stmt, params)
# Remove any records where the file no longer exists.
with get_db_curs(commit=True) as curs:
refresh_logger.debug(f'Deleting files no longer in {directory}')
params = dict(
directory=f'{directory}/%', # trailing / is important!
idempotency=idempotency,
)
stmt = '''
DELETE FROM file
WHERE
(idempotency < %(idempotency)s OR idempotency IS NULL)
AND path LIKE %(directory)s'''
curs.execute(stmt, params)
apply_after_refresh()
await apply_indexers()
apply_after_refresh()
await apply_indexers()
if send_events:
Events.send_directory_refresh_completed(f'Refresh of {repr(relative_path)} has completed.')
refresh_logger.info(f'Done refreshing files in {directory}')
if send_events:
Events.send_directory_refresh_completed(f'Refresh of {repr(relative_path)} has completed.')
refresh_logger.info(f'Done refreshing files in {directory}')
def search_files(search_str: str, limit: int, offset: int, mimetypes: List[str] = None, model: str = None) -> \

View file

@ -27,54 +27,83 @@ def test_list_files_api(test_client, make_files_structure, test_directory):
def check_get_files(directories, expected_files):
request, response = test_client.post('/api/files', content=json.dumps({'directories': directories}))
assert not response.json.get('errors')
results = sorted(response.json['files'], key=lambda i: i['key'])
for f1, f2 in zip_longest(results, expected_files):
for key in f2.keys():
assert f1[key] == f2[key], f'{f1} != {f2}'
# The first dict is the media directory.
children = response.json['files']
assert children == expected_files
# Requesting no directories results in the top-level results.
expected = [dict(key='archives/'), dict(key='empty directory/'), dict(key='videos/')]
expected = {
'archives/': {'path': 'archives/'},
'empty directory/': {'path': 'empty directory/'},
'videos/': {'path': 'videos/'}
}
check_get_files([], expected)
# empty directory is empty
expected = {
'archives/': {'path': 'archives/'},
'empty directory/': {'path': 'empty directory/', 'children': {}},
'videos/': {'path': 'videos/'}
}
check_get_files(['empty directory'], expected)
expected = [
dict(key='archives/'),
dict(key='archives/bar.txt', size=12),
dict(key='archives/baz/'),
dict(key='archives/foo.txt'),
dict(key='empty directory/'),
dict(key='videos/'),
]
expected = {
'archives/': {
'path': 'archives/',
'children': {
'foo.txt': {'path': 'archives/foo.txt', 'size': 0, 'mimetype': 'inode/x-empty'},
'bar.txt': {'path': 'archives/bar.txt', 'size': 12, 'mimetype': 'text/plain'},
'baz/': {'path': 'archives/baz/'},
}
},
'empty directory/': {'path': 'empty directory/'},
'videos/': {'path': 'videos/'}
}
check_get_files(['archives'], expected)
# Sub-directories are supported.
expected = [
dict(key='archives/'),
dict(key='archives/bar.txt', size=12),
dict(key='archives/baz/'),
dict(key='archives/baz/bar.txt'),
dict(key='archives/baz/foo.txt'),
dict(key='archives/foo.txt'),
dict(key='empty directory/'),
dict(key='videos/'),
]
expected = {
'archives/': {
'path': 'archives/',
'children': {
'foo.txt': {'path': 'archives/foo.txt', 'size': 0, 'mimetype': 'inode/x-empty'},
'bar.txt': {'path': 'archives/bar.txt', 'size': 12, 'mimetype': 'text/plain'},
'baz/': {
'path': 'archives/baz/',
'children': {
'bar.txt': {'path': 'archives/baz/bar.txt', 'size': 0, 'mimetype': 'inode/x-empty'},
'foo.txt': {'path': 'archives/baz/foo.txt', 'size': 0, 'mimetype': 'inode/x-empty'},
}
}
}
},
'empty directory/': {'path': 'empty directory/'},
'videos/': {'path': 'videos/'},
}
check_get_files(['archives', 'archives/baz'], expected)
# Requesting only a subdirectory also returns `archives` contents.
check_get_files(['archives/baz'], expected)
expected = [
dict(key='archives/'),
dict(key='archives/bar.txt', size=12),
dict(key='archives/baz/'),
dict(key='archives/foo.txt'),
dict(key='empty directory/'),
dict(key='videos/'),
dict(key='videos/other video.mp4'),
dict(key='videos/some video.mp4'),
]
expected = {
'archives/': {
'path': 'archives/',
'children': {
'foo.txt': {'path': 'archives/foo.txt', 'size': 0, 'mimetype': 'inode/x-empty'},
'bar.txt': {'path': 'archives/bar.txt', 'size': 12, 'mimetype': 'text/plain'},
'baz/': {'path': 'archives/baz/'},
}
},
'empty directory/': {'path': 'empty directory/'},
'videos/': {
'path': 'videos/',
'children': {
'other video.mp4': {'path': 'videos/other video.mp4', 'size': 0, 'mimetype': 'inode/x-empty'},
'some video.mp4': {'path': 'videos/some video.mp4', 'size': 0, 'mimetype': 'inode/x-empty'},
}
}
}
check_get_files(['archives', 'videos'], expected)
# Order does not matter.
check_get_files(['archives', 'videos', 'empty directory'], expected)
check_get_files(['archives', 'empty directory', 'videos'], expected)
check_get_files(['videos', 'archives'], expected)
def test_delete_file(test_client, make_files_structure, test_directory):
@ -250,15 +279,15 @@ def test_file_statistics(test_session, test_client, example_pdf, example_mobi, e
request, response = test_client.get('/api/statistics')
assert response.status_code == HTTPStatus.OK
assert response.json['file_statistics'] == {
'archive_count': 0,
'total_size': 0,
'audio_count': 0,
'ebook_count': 0,
'image_count': 0,
'pdf_count': 0,
'total_count': 0,
'video_count': 0,
'zip_count': 0,
'archive_count': 0,
'total_size': 0,
'audio_count': 0,
'ebook_count': 0,
'image_count': 0,
'pdf_count': 0,
'total_count': 0,
'video_count': 0,
'zip_count': 0,
}
test_client.post('/api/files/refresh')
@ -268,12 +297,12 @@ def test_file_statistics(test_session, test_client, example_pdf, example_mobi, e
stats = response.json['file_statistics']
stats.pop('total_size')
assert stats == {
'archive_count': 0,
'audio_count': 0,
'ebook_count': 2,
'image_count': 0,
'pdf_count': 1,
'total_count': 5,
'video_count': 1,
'zip_count': 0,
'archive_count': 0,
'audio_count': 0,
'ebook_count': 2,
'image_count': 0,
'pdf_count': 1,
'total_count': 5,
'video_count': 1,
'zip_count': 0,
}

View file

@ -25,82 +25,6 @@ def assert_files(session: Session, expected):
assert files == set(expected)
def test_list_files(make_files_structure, test_directory):
files = [
'archives/bar.txt',
'archives/baz/bar.txt',
'archives/baz/foo.txt',
'archives/foo.txt',
'empty directory/',
'videos/other video.mp4',
'videos/some video.mp4',
]
make_files_structure(files)
def check_list_files(path, expected):
result = lib.list_files(path)
result = sorted(result)
assert [str(i.relative_to(test_directory)) for i in result] == expected
check_list_files([], ['archives', 'empty directory', 'videos'])
# Falsey directories are ignored.
check_list_files([None, ''], ['archives', 'empty directory', 'videos'])
check_list_files(['empty directory'], ['archives', 'empty directory', 'videos'])
check_list_files(['empty directory'], ['archives', 'empty directory', 'videos'])
# Trailing slash is ignored.
check_list_files(['empty directory/'], ['archives', 'empty directory', 'videos'])
check_list_files(['archives'], [
'archives',
'archives/bar.txt',
'archives/baz',
'archives/foo.txt',
'empty directory',
'videos',
])
check_list_files(['archives/baz'], [
'archives',
'archives/bar.txt',
'archives/baz',
'archives/baz/bar.txt',
'archives/baz/foo.txt',
'archives/foo.txt',
'empty directory',
'videos',
])
# Including duplicate directories does not change results.
check_list_files(['archives/baz', 'archives'], [
'archives',
'archives/bar.txt',
'archives/baz',
'archives/baz/bar.txt',
'archives/baz/foo.txt',
'archives/foo.txt',
'empty directory',
'videos',
])
check_list_files(['videos'], [
'archives',
'empty directory',
'videos',
'videos/other video.mp4',
'videos/some video.mp4',
])
# All files and directories are listed.
check_list_files(['videos', 'archives/baz'], [
'archives',
'archives/bar.txt',
'archives/baz',
'archives/baz/bar.txt',
'archives/baz/foo.txt',
'archives/foo.txt',
'empty directory',
'videos',
'videos/other video.mp4',
'videos/some video.mp4',
])
@pytest.mark.parametrize(
'directories,expected', [
([Path('foo')], [Path('foo')]),
@ -210,11 +134,6 @@ async def test_refresh_many_files(test_session, make_files_structure):
assert test_session.query(File).count() == count
@pytest.mark.asyncio
async def test_refresh_files_flags(test_session):
pass
@pytest.mark.asyncio
async def test_refresh_files_list(test_session, make_files_structure, test_directory):
make_files_structure(['foo.txt', 'bar.txt'])

View file

@ -100,6 +100,8 @@ class Flag:
db_up = Flag('db_up')
# The global refresh is running.
refreshing = Flag('refreshing')
# Refreshing single directory.
refreshing_directory = Flag('refreshing_directory')
# The global refresh has been performed. This is False on a fresh instance of WROLPi.
refresh_complete = Flag('refresh_complete', store_db=True)
# Third party packages that may be required. See `cmd.py`
@ -119,6 +121,8 @@ def get_flags() -> List[str]:
flags.append('db_up')
if refreshing.is_set():
flags.append('refreshing')
if refreshing_directory.is_set():
flags.append('refreshing_directory')
if refresh_complete.is_set():
flags.append('refresh_complete')
if chromium_installed.is_set():

View file

@ -1,4 +1,4 @@
__version__ = '0.8.3-beta'
__version__ = '0.9.0-beta'
import subprocess