diff --git a/app/src/components/Archive.js b/app/src/components/Archive.js index e7b1e2ba..175f3ec8 100644 --- a/app/src/components/Archive.js +++ b/app/src/components/Archive.js @@ -43,6 +43,7 @@ import {useForm} from "../hooks/useForm"; import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal"; import {CollectionTagModal} from "./collections/CollectionTagModal"; import {CollectionReorganizeModal} from "./collections/CollectionReorganizeModal"; +import {ShareCollectionButton} from "./collections/ShareCollectionButton"; import {BatchReorganizeModal} from "./collections/BatchReorganizeModal"; import {useReorganizationStatus} from "../contexts/FileWorkerStatusContext"; import {Link, Route, Routes, useLocation, useNavigate, useParams} from "react-router"; @@ -548,7 +549,7 @@ export function DomainsPage() { export function DomainEditPage() { const {domainId} = useParams(); const navigate = useNavigate(); - const {domain, form, fetchDomain} = useDomain(parseInt(domainId)); + const {domain, savedDirectory, form, fetchDomain} = useDomain(parseInt(domainId)); // Modal state for tagging const [tagEditModalOpen, setTagEditModalOpen] = useState(false); @@ -680,6 +681,7 @@ export function DomainEditPage() { {refreshButton} {tagButton} {reorganizeButton} + ; const [descriptionProps] = form.getCustomProps({name: 'description', path: 'description'}); diff --git a/app/src/components/ChannelEditPage.test.js b/app/src/components/ChannelEditPage.test.js new file mode 100644 index 00000000..13a32551 --- /dev/null +++ b/app/src/components/ChannelEditPage.test.js @@ -0,0 +1,87 @@ +import React from 'react'; +import {createTestForm, render, screen} from '../test-utils'; +import userEvent from '@testing-library/user-event'; +import {ChannelEditPage} from './Channels'; + +jest.mock('react-router', () => ({ + ...jest.requireActual('react-router'), + useParams: () => ({channelId: '1'}), + useNavigate: () => jest.fn(), +})); + +const mockUseChannel = jest.fn(); +jest.mock('../hooks/customHooks', () => ({ + ...jest.requireActual('../hooks/customHooks'), + useChannel: (...args) => mockUseChannel(...args), + // Named here: a circular import leaves the spread above without it when this factory runs. + useWROLMode: () => false, +})); + +jest.mock('./Common', () => ({ + ...jest.requireActual('./Common'), + useTitle: jest.fn(), +})); + +jest.mock('./collections/CollectionEditForm', () => ({ + CollectionEditForm: ({title, actionButtons}) => ( +
+

{title}

+
{actionButtons}
+
+ ), +})); + +jest.mock('./collections/CollectionTagModal', () => ({CollectionTagModal: () => null})); +jest.mock('./collections/CollectionReorganizeModal', () => ({CollectionReorganizeModal: () => null})); + +jest.mock('./admin/Downloads', () => ({ + RecurringDownloadsTable: () =>
, +})); + +// These tests check which directory the page shares, not the modal. +jest.mock('./ShareTorrentModal', () => ({ + ShareTorrentModal: ({open, path}) => open ?
{path}
: null, +})); + +const channel = (overrides = {}) => ({ + id: 1, + collection_id: 11, + name: 'Learn the Sky', + directory: 'videos/Astronomy/Learn the Sky', + tag_name: null, + downloads: [], + ...overrides, +}); + +const renderChannel = (overrides, savedDirectory = 'videos/Astronomy/Learn the Sky') => { + const value = channel(overrides); + mockUseChannel.mockReturnValue({ + channel: value, + savedDirectory, + form: createTestForm(value, {overrides: {ready: true, loading: false}}), + fetchChannel: jest.fn(), + }); + render(); +}; + +describe('ChannelEditPage Share', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('shares the channel directory as a torrent', async () => { + renderChannel(); + const share = screen.getByRole('button', {name: /share/i}); + expect(screen.getByTestId('action-buttons')).toContainElement(share); + await userEvent.click(share); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('videos/Astronomy/Learn the Sky'); + }); + + it('shares the saved directory, not one picked in the form but not saved', async () => { + // The form (channel = form.formData) already holds the picked directory; the server still has the old one. + renderChannel({directory: 'videos/Somewhere Else'}, 'videos/Astronomy/Learn the Sky'); + await userEvent.click(screen.getByRole('button', {name: /share/i})); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('videos/Astronomy/Learn the Sky'); + expect(screen.getByTestId('share-torrent-modal')).not.toHaveTextContent('Somewhere Else'); + }); +}); diff --git a/app/src/components/Channels.js b/app/src/components/Channels.js index dd197f64..769c7684 100644 --- a/app/src/components/Channels.js +++ b/app/src/components/Channels.js @@ -3,6 +3,7 @@ import {useHotkeys} from "react-hotkeys-hook"; import {createChannel, deleteChannel, refreshChannel, tagChannel, tagChannelInfo} from "../api"; import {CollectionTagModal} from "./collections/CollectionTagModal"; import {CollectionReorganizeModal} from "./collections/CollectionReorganizeModal"; +import {ShareCollectionButton} from "./collections/ShareCollectionButton"; import { APIButton, BackButton, @@ -89,7 +90,7 @@ export function ChannelEditPage() { const [downloadModalOpen, setDownloadModalOpen] = useState(false); const [reorganizeModalOpen, setReorganizeModalOpen] = useState(false); - const {channel, form, fetchChannel} = useChannel(channelId); + const {channel, savedDirectory, form, fetchChannel} = useChannel(channelId); useTitle(_.isEmpty(channel) ? null : `${channel.name} Channel`); @@ -203,6 +204,7 @@ export function ChannelEditPage() { {refreshButton} {tagButton} {reorganizeButton} + ; const downloadMissingDataInfo = 'Automatically download missing comments, etc, in the background.'; diff --git a/app/src/components/DomainEditPage.test.js b/app/src/components/DomainEditPage.test.js index e9fce0ca..ed3f6c79 100644 --- a/app/src/components/DomainEditPage.test.js +++ b/app/src/components/DomainEditPage.test.js @@ -67,6 +67,11 @@ jest.mock('./collections/CollectionReorganizeModal', () => ({ }, })); +// Mock ShareTorrentModal: these tests check which directory the page shares, not the modal. +jest.mock('./ShareTorrentModal', () => ({ + ShareTorrentModal: ({open, path}) => open ?
{path}
: null, +})); + // Mock API functions const mockGetCollectionTagInfo = jest.fn(); jest.mock('../api', () => ({ @@ -471,4 +476,42 @@ describe('DomainEditPage', () => { expect(directoryInput).toHaveValue('archive/example.com'); }); }); + + describe('Share', () => { + const renderDomain = (directory, savedDirectory = directory) => { + const mockDomain = createMockDomain({domain: 'example.com', directory}); + mockUseDomain.mockReturnValue({ + domain: mockDomain, + savedDirectory, + form: createTestForm(mockDomain, {overrides: {ready: true, loading: false}}), + fetchDomain: jest.fn(), + }); + render(); + }; + + it('shares the domain directory as a torrent', async () => { + renderDomain('archive/example.com'); + const share = screen.getByRole('button', {name: /share/i}); + expect(screen.getByTestId('action-buttons')).toContainElement(share); + await userEvent.click(share); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('archive/example.com'); + }); + + it('shares the saved directory, not one picked in the form but not saved', async () => { + renderDomain('archive/other.com', 'archive/example.com'); + await userEvent.click(screen.getByRole('button', {name: /share/i})); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('archive/example.com'); + expect(screen.getByTestId('share-torrent-modal')).not.toHaveTextContent('other.com'); + }); + + it('cannot share a domain picked in the form before its directory is saved', () => { + renderDomain('archive/example.com', null); + expect(screen.getByRole('button', {name: /share/i})).toBeDisabled(); + }); + + it('cannot share a domain without a directory', () => { + renderDomain(null); + expect(screen.getByRole('button', {name: /share/i})).toBeDisabled(); + }); + }); }); diff --git a/app/src/components/Playlists.js b/app/src/components/Playlists.js index 49c5d871..4605d72b 100644 --- a/app/src/components/Playlists.js +++ b/app/src/components/Playlists.js @@ -33,6 +33,7 @@ import {useOneQuery, useWROLMode} from "../hooks/customHooks"; import {CollectionTable} from "./collections/CollectionTable"; import {CollectionEditForm} from "./collections/CollectionEditForm"; import {CollectionTagModal} from "./collections/CollectionTagModal"; +import {ShareCollectionButton} from "./collections/ShareCollectionButton"; import { addPlaylistItem, createPlaylist, @@ -494,6 +495,8 @@ export function PlaylistEditPage() { const actionButtons = <> {deleteButton} {tagButton} + {/* The saved directory: the playlist's hard links, as synced, not the field being edited. */} + ; // Minimal form object for CollectionEditForm (mirrors the useForm interface it consumes). diff --git a/app/src/components/Playlists.test.js b/app/src/components/Playlists.test.js index b762b892..b9963efb 100644 --- a/app/src/components/Playlists.test.js +++ b/app/src/components/Playlists.test.js @@ -1,4 +1,28 @@ -import {safeHref} from './Playlists'; +import React from 'react'; +import {Route, Routes} from 'react-router'; +import {act, fireEvent, render, screen} from '../test-utils'; +import {PlaylistEditPage, safeHref} from './Playlists'; +import {getPlaylist} from '../api'; + +jest.mock('../api', () => ({ + ...jest.requireActual('../api'), + getPlaylist: jest.fn(), +})); + +// The edit form's layout is its own spec's concern; these specs need its fields and action row. +jest.mock('./collections/CollectionEditForm', () => ({ + CollectionEditForm: ({title, actionButtons, children}) =>
+

{title}

+
{actionButtons}
+ {children} +
, +})); +jest.mock('./collections/CollectionTagModal', () => ({CollectionTagModal: () => null})); + +// Which directory is shared is this spec's concern; the modal has its own. +jest.mock('./ShareTorrentModal', () => ({ + ShareTorrentModal: ({open, path}) => open ?
{path}
: null, +})); // safeHref is the only thing standing between a stored playlist url item and an executable href, // so every dangerous-scheme vector must return null. @@ -41,3 +65,29 @@ describe('safeHref', () => { expect(safeHref('javascript%3Aalert(1)')).toBe('javascript%3Aalert(1)'); }); }); + +describe('PlaylistEditPage Share', () => { + it("shares the playlist's hardlink directory, not an unsaved directory", async () => { + getPlaylist.mockResolvedValue({ + id: 3, collection_id: 3, name: 'Astronomy 101', kind: 'playlist', tag_name: 'Learning', + directory: 'playlists/Learning/Astronomy 101', description: null, items: [], + }); + render( + }/> + , {route: '/playlists/3/edit'}); + await act(async () => { + }); + + // Commit a new directory to the form the way the field does (it calls onSelect on blur), without saving. + const directoryInput = screen.getByPlaceholderText('Search directory names...'); + fireEvent.change(directoryInput, {target: {value: 'somewhere/else'}}); + fireEvent.blur(directoryInput); + await act(async () => { + }); + expect(screen.getByPlaceholderText('Search directory names...')).toHaveValue('somewhere/else'); + + fireEvent.click(screen.getByRole('button', {name: /share/i})); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('playlists/Learning/Astronomy 101'); + expect(screen.getByTestId('share-torrent-modal')).not.toHaveTextContent('somewhere/else'); + }); +}); diff --git a/app/src/components/Repos.js b/app/src/components/Repos.js index f7f20760..4052d18e 100644 --- a/app/src/components/Repos.js +++ b/app/src/components/Repos.js @@ -38,6 +38,7 @@ import { import {useOneQuery, useWROLMode} from "../hooks/customHooks"; import {CollectionTable} from "./collections/CollectionTable"; import {CollectionTagModal} from "./collections/CollectionTagModal"; +import {ShareCollectionButton} from "./collections/ShareCollectionButton"; import { createRepo, deleteRepo, @@ -1028,6 +1029,7 @@ export function RepoEditPage() { +
diff --git a/app/src/components/Repos.test.js b/app/src/components/Repos.test.js index 5485ce3f..fbf3186e 100644 --- a/app/src/components/Repos.test.js +++ b/app/src/components/Repos.test.js @@ -44,6 +44,11 @@ jest.mock('./MarkdownPreview', () => ({ MarkdownPreview: ({url}) =>
{url}
, })); +// Which directory is shared is this spec's concern; the modal has its own. +jest.mock('./ShareTorrentModal', () => ({ + ShareTorrentModal: ({open, path}) => open ?
{path}
: null, +})); + const repoFixture = (overrides = {}) => ({ id: 1, collection_id: 10, name: 'kiwix-tools', tag_name: null, description: null, url: 'https://github.com/kiwix/kiwix-tools', mode: 'full', branch: null, default_branch: 'main', @@ -305,6 +310,13 @@ describe('RepoEditPage', () => { expect(updateRepo).toHaveBeenCalledWith('1', expect.objectContaining({frequency: 0})); }); + it('shares the repo directory as a torrent', async () => { + renderEditPage(repoFixture()); + await flush(); + fireEvent.click(screen.getByRole('button', {name: /share/i})); + expect(screen.getByTestId('share-torrent-modal')).toHaveTextContent('repos/kiwix-tools'); + }); + it('deletes the repo, and its files only when asked', async () => { deleteRepo.mockResolvedValue(undefined); renderEditPage(repoFixture()); diff --git a/app/src/components/ShareTorrentModal.js b/app/src/components/ShareTorrentModal.js index 892a3ba1..4b5dcaad 100644 --- a/app/src/components/ShareTorrentModal.js +++ b/app/src/components/ShareTorrentModal.js @@ -6,6 +6,8 @@ import {JobProgress, useJob} from './VideoEditMenu'; import {VPN_SETTINGS_PATH, VpnStateUnknown} from './admin/VpnSection'; const lines = (value) => (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean); +// qBittorrent names a torrent after the file or directory it is made of (the directories above it are not in it). +const torrentName = (path) => (path || '').replace(/\/+$/, '').split('/').pop(); /** * Make a torrent of a file or directory in the library, and seed it. qBittorrent hashes the files, which takes @@ -76,8 +78,8 @@ export function ShareTorrentModal({path, open, onClose}) { {!jobId ?

- Make a torrent of {path} and seed it, so others can download it from this WROLPi (through - the VPN). A large file takes a while to prepare: about an hour for hundreds of gigabytes on a + Make a torrent named {torrentName(path)} of {path} and seed it, so others can + download it from this WROLPi (through the VPN). A large file takes a while to prepare: about an hour for hundreds of gigabytes on a Raspberry Pi.

{vpnFailed && } diff --git a/app/src/components/ShareTorrentModal.test.js b/app/src/components/ShareTorrentModal.test.js index 52267812..cc1757e8 100644 --- a/app/src/components/ShareTorrentModal.test.js +++ b/app/src/components/ShareTorrentModal.test.js @@ -35,6 +35,13 @@ describe('ShareTorrentModal', () => { expect(screen.getByText('maps/planet.pmtiles')).toBeInTheDocument(); }); + test('names the torrent after the last part of the path, not the directories above it', async () => { + render(); + await waitFor(() => expect(getTorrents).toHaveBeenCalled()); + expect(screen.getByText('Sigint')).toBeInTheDocument(); + expect(screen.getByText('playlists/Radio/Sigint')).toBeInTheDocument(); + }); + test('warns while the VPN is down', async () => { getTorrents.mockResolvedValue({vpn: {state: 'stopped'}, trackers: [], torrents: []}); render(); diff --git a/app/src/components/collections/ShareCollectionButton.js b/app/src/components/collections/ShareCollectionButton.js new file mode 100644 index 00000000..6613b5f2 --- /dev/null +++ b/app/src/components/collections/ShareCollectionButton.js @@ -0,0 +1,28 @@ +import React from 'react'; +import {Button} from '../ui'; +import {ShareTorrentModal} from '../ShareTorrentModal'; +import {useWROLMode} from '../../hooks/customHooks'; + +/** + * Share a Collection's directory (relative to the media directory) as a torrent. A Collection without a directory + * (e.g. some Domains) has nothing to share. A Playlist's directory is its hard-linked copy of its items, in order, + * so it can be shared whatever the receiver's library looks like. + */ +export function ShareCollectionButton({directory, size = 'small'}) { + const [open, setOpen] = React.useState(false); + const wrolModeEnabled = useWROLMode(); + + return <> + + {directory && setOpen(false)} path={directory}/>} + ; +} + +export default ShareCollectionButton; diff --git a/app/src/components/collections/ShareCollectionButton.test.js b/app/src/components/collections/ShareCollectionButton.test.js new file mode 100644 index 00000000..48f0d2aa --- /dev/null +++ b/app/src/components/collections/ShareCollectionButton.test.js @@ -0,0 +1,49 @@ +import React from 'react'; +import {screen, waitFor} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {render} from '../../test-utils'; +import {settingsFixture} from '../../test-fixtures'; +import {ShareCollectionButton} from './ShareCollectionButton'; +import {getTorrents} from '../../api'; + +// Listed, not spread from the real module (see ShareTorrentModal.test.js). +jest.mock('../../api', () => ({ + getTorrents: jest.fn(), + shareTorrent: jest.fn(), + getJob: jest.fn(), + cancelJob: jest.fn(), + fetchVideoDownloadDefaults: jest.fn(), + transcodeVideo: jest.fn(), + updateVideo: jest.fn(), +})); + +describe('ShareCollectionButton', () => { + beforeEach(() => { + jest.clearAllMocks(); + getTorrents.mockResolvedValue({vpn: {state: 'connected'}, trackers: [], torrents: []}); + }); + + test('opens Share as Torrent for the collection directory', async () => { + render(); + await userEvent.click(screen.getByRole('button', {name: /share/i})); + expect(await screen.findByText('Share as Torrent')).toBeInTheDocument(); + expect(screen.getByText('videos/Learn the Sky')).toBeInTheDocument(); + await waitFor(() => expect(getTorrents).toHaveBeenCalled()); + }); + + test('is not a submit button (it sits in the collection edit form)', () => { + render(); + expect(screen.getByRole('button', {name: /share/i})).toHaveAttribute('type', 'button'); + }); + + test('is disabled without a directory', () => { + render(); + expect(screen.getByRole('button', {name: /share/i})).toBeDisabled(); + }); + + test('is disabled in WROL Mode', () => { + render(, + {settings: {settings: settingsFixture({wrol_mode: true})}}); + expect(screen.getByRole('button', {name: /share/i})).toBeDisabled(); + }); +}); diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index 6fb3e05c..4473c6df 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -443,6 +443,8 @@ export const useDomain = (domainId) => { description: '', tag_name: null, }; + // The directory the server has; the form's may be a pick not yet saved. + const [savedDirectory, setSavedDirectory] = React.useState(null); const fetchDomain = async () => { if (!domainId) { @@ -450,6 +452,7 @@ export const useDomain = (domainId) => { return; } const d = await getDomain(domainId); + setSavedDirectory(d.directory || null); // Prevent controlled to uncontrolled d.directory = d.directory || ''; d.description = d.description || ''; @@ -480,7 +483,7 @@ export const useDomain = (domainId) => { const domain = form.formData; - return {domain, form, fetchDomain: form.fetcher}; + return {domain, savedDirectory, form, fetchDomain: form.fetcher}; } export const useArchive = (fileGroupId) => { @@ -865,6 +868,8 @@ export const useChannel = (channel_id) => { tag_name: null, download_missing_data: null, }; + // The directory the server has; the form's may be a pick not yet saved (its files are not there until Save). + const [savedDirectory, setSavedDirectory] = React.useState(null); const fetchChannel = async () => { if (!channel_id) { @@ -877,6 +882,7 @@ export const useChannel = (channel_id) => { c['download_frequency'] = c['download_frequency'] || ''; c['match_regex'] = c['match_regex'] || ''; c['download_missing_data'] = c['download_missing_data'] ?? true; + setSavedDirectory(c.directory || null); return c; } @@ -911,6 +917,7 @@ export const useChannel = (channel_id) => { return { channel: form.formData, + savedDirectory, form, fetchChannel: form.fetcher, }; diff --git a/app/src/hooks/customHooks.test.js b/app/src/hooks/customHooks.test.js index 7d1259ed..af639901 100644 --- a/app/src/hooks/customHooks.test.js +++ b/app/src/hooks/customHooks.test.js @@ -2,11 +2,11 @@ import React from 'react'; import {act, renderHook} from '@testing-library/react'; import {render, screen} from '../test-utils'; import { - useBrowseFiles, usePages, useDriveTemperature, useDriveHealth, useSearchArchives, useSearchChannels, + useBrowseFiles, useChannel, useDomain, usePages, useDriveTemperature, useDriveHealth, useSearchArchives, useSearchChannels, useSearchDocs, useSearchFiles, useSearchRecentFiles, useSearchVideos, useSettings, useStatistics, useStatus, useVideoExtras, } from './customHooks'; import { - ApiDownError, fetchDomains, filesSearch, getFiles, getSettings, getStatistics, getStatus, getVideoComments, + ApiDownError, fetchDomains, filesSearch, getChannel, getDomain, getFiles, getSettings, getStatistics, getStatus, getVideoComments, getVideoDescription, searchArchives, searchChannels, searchDocs, searchVideos, } from '../api'; import {getControllerStats} from '../api/controller'; @@ -53,6 +53,8 @@ jest.mock('../api', () => ({ filesSearch: jest.fn(), getFiles: jest.fn(), fetchDomains: jest.fn(), + getChannel: jest.fn(), + getDomain: jest.fn(), searchArchives: jest.fn(), searchDocs: jest.fn(), searchVideos: jest.fn(), @@ -842,3 +844,48 @@ describe('useSearchFiles', () => { expect(filesSearch).not.toHaveBeenCalled(); }); }); + +// Share uses the directory the server has, never one picked in the edit form but not yet saved (the files are not +// there until Save). +describe('saved directory', () => { + beforeEach(() => jest.clearAllMocks()); + + it('useChannel: an edited directory is not the saved one until it is fetched again', async () => { + getChannel.mockResolvedValue({id: 1, name: 'Learn the Sky', directory: 'videos/Astronomy/Learn the Sky'}); + const {result} = renderHook(() => useChannel(1)); + await act(async () => { + }); + expect(result.current.savedDirectory).toBe('videos/Astronomy/Learn the Sky'); + + act(() => result.current.form.setValue('directory', 'videos/Somewhere Else')); + expect(result.current.channel.directory).toBe('videos/Somewhere Else'); + expect(result.current.savedDirectory).toBe('videos/Astronomy/Learn the Sky'); + + // Saved: the next fetch has it. + getChannel.mockResolvedValue({id: 1, name: 'Learn the Sky', directory: 'videos/Somewhere Else'}); + await act(async () => { + await result.current.fetchChannel(); + }); + expect(result.current.savedDirectory).toBe('videos/Somewhere Else'); + }); + + it('useDomain: an edited directory is not the saved one until it is fetched again', async () => { + getDomain.mockResolvedValue({id: 2, domain: 'example.com', directory: 'archive/example.com'}); + const {result} = renderHook(() => useDomain(2)); + await act(async () => { + }); + expect(result.current.savedDirectory).toBe('archive/example.com'); + + act(() => result.current.form.setValue('directory', 'archive/other.com')); + expect(result.current.domain.directory).toBe('archive/other.com'); + expect(result.current.savedDirectory).toBe('archive/example.com'); + }); + + it('useDomain: no saved directory', async () => { + getDomain.mockResolvedValue({id: 3, domain: 'yahoo.com', directory: null}); + const {result} = renderHook(() => useDomain(3)); + await act(async () => { + }); + expect(result.current.savedDirectory).toBeFalsy(); + }); +});