diff --git a/UPGRADE.md b/UPGRADE.md index 434c46f8..58a8b8bb 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -14,6 +14,8 @@ * `git pull origin master --ff` 3. Build all docker containers * `docker-compose build --parallel` + * Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet + through the VPN): `docker compose build --pull --no-cache vpn` 4. Create the map volumes * `docker volume create --name=openstreetmap-data` * `docker volume create --name=openstreetmap-rendered-tiles` diff --git a/app/src/App.js b/app/src/App.js index 37c210c8..29911115 100644 --- a/app/src/App.js +++ b/app/src/App.js @@ -4,6 +4,7 @@ import {NavBar} from "./components/Nav"; import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router"; import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos"; import AdminRoute from "./components/admin/AdminRoute"; +import {ExtensionRoute} from "./components/admin/ExtensionPage"; import {Box, Header} from "./components/ui"; import '@mantine/core/styles.css'; import '@mantine/notifications/styles.css'; @@ -125,6 +126,7 @@ export const routes = createRoutesFromElements(}/> }/> }/> + }/> {/* Unknown URLs render inside Root, with the navigation bar and theme. */} }/> ); diff --git a/app/src/api.js b/app/src/api.js index 62579568..ef773bcf 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -2969,3 +2969,63 @@ export async function importRepo(repo) { } await reposError(response, 'Failed to import the repo.'); } + +// --- Torrents (they reach the Internet only through the VPN) --- + +const TORRENTS_API = `${API_URI}/torrents`; + +async function torrentsRequest(response, fallbackMessage) { + if (!response.ok) { + throw new Error(await getErrorMessage(response, fallbackMessage)); + } + return response.status === 204 ? null : response; +} + +export async function getTorrents() { + const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents'); + return await response.json(); +} + +export async function uploadTorrent(file, destination) { + const form = new FormData(); + form.append('torrent', file); + if (destination) { + form.append('destination', destination); + } + const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}), + 'Failed to add the .torrent file'); + return await response.json(); +} + +export async function pauseTorrent(hash) { + await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent'); +} + +export async function resumeTorrent(hash) { + await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent'); +} + +export async function removeTorrent(hash, deleteFiles = false) { + await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`), + 'Failed to remove the torrent'); +} + +export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) { + await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`, + {seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits'); +} + +export async function setTorrentSpeedLimits(upload, download) { + await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}), + 'Failed to save the speed limits'); +} + +export function torrentFileUrl(hash) { + return `${TORRENTS_API}/${hash}/torrent`; +} + +export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) { + const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`, + {path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent'); + return (await response.json()).job_id; +} diff --git a/app/src/api/controller.js b/app/src/api/controller.js index feed933d..5836862f 100644 --- a/app/src/api/controller.js +++ b/app/src/api/controller.js @@ -294,3 +294,29 @@ export async function runSync() { export async function cancelSync() { return controllerFetch('/sync/cancel', {method: 'POST'}); } + +// --- VPN (torrents reach the Internet only through it) --- + +export async function getVpnStatus() { + return controllerFetch('/vpn/status'); +} + +export async function getVpnSettings() { + return controllerFetch('/vpn/settings'); +} + +export async function updateVpnSettings(settings) { + return controllerFetch('/vpn/settings', {method: 'POST', body: JSON.stringify(settings)}); +} + +export async function uploadVpnConfig(filename, content) { + return controllerFetch('/vpn/config', {method: 'POST', body: JSON.stringify({filename, content})}); +} + +export async function deleteVpnConfig() { + return controllerFetch('/vpn/config', {method: 'DELETE'}); +} + +export async function saveVpnAuth(username, password) { + return controllerFetch('/vpn/auth', {method: 'POST', body: JSON.stringify({username, password})}); +} diff --git a/app/src/components/Download.js b/app/src/components/Download.js index 8f115071..a6bea126 100644 --- a/app/src/components/Download.js +++ b/app/src/components/Download.js @@ -1,5 +1,5 @@ import React, {useState} from "react"; -import {fetchVideoDownloadDefaults, getDownloaders, postDownload, putDownload} from "../api"; +import {fetchVideoDownloadDefaults, getDownloaders, getTorrents, postDownload, putDownload, uploadTorrent} from "../api"; import { APIButton, DirectorySearch, @@ -13,8 +13,22 @@ import { validURL, validURLs, } from "./Common"; -import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui"; +import { + Button, + Group, + Header, + Icon, + Message, + MultiSelect, + NumberInput, + Select, + Stack, + TextInput, + Textarea, + toast, +} from "./ui"; import {Link} from "react-router"; +import {VPN_SETTINGS_PATH, VpnStateUnknown} from "./admin/VpnSection"; import {TagsSelector} from "../Tags"; import { commaSeparatedValidator, @@ -1506,6 +1520,116 @@ export function FilesDownloadForm({ } +// One magnet link or .torrent URL per line. +export const validTorrentUrls = (value) => { + const lines = (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean); + return lines.length > 0 && lines.every(i => /^magnet:\?/i.test(i) || /^https?:\/\/\S+$/i.test(i)); +}; + +// The URLs are optional (a .torrent file may be chosen instead); a stable function, as the form registers it. +const optionalTorrentUrls = (value) => !(value || '').trim() || validTorrentUrls(value); + +function TorrentVpnStatus() { + const [status, setStatus] = React.useState(null); + const [failed, setFailed] = React.useState(false); + React.useEffect(() => { + let cancelled = false; + getTorrents() + .then(s => !cancelled && setStatus(s)) + .catch(e => { + console.error('Failed to get torrents', e); + if (!cancelled) { + setFailed(true); + } + }); + return () => { + cancelled = true; + }; + }, []); + + if (failed) { + return ; + } + if (!status) { + return null; + } + const vpn = status.vpn || {}; + if (vpn.state === 'connected') { + return + VPN connected{vpn.public_ip ? <> · peers see {vpn.public_ip} : null} + ; + } + return + Torrents only use the VPN. This torrent will start once the VPN connects.{' '} + Set up the VPN + ; +} + +export function TorrentDownloadForm({download, onCancel, actions = DownloadFormButtons}) { + const [showMessage, setShowMessage] = React.useState(false); + const [file, setFile] = React.useState(null); + const fileInput = React.useRef(null); + + const submitter = async (formData) => { + const urls = (formData.urls || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean); + if (!file && !urls.length) { + throw new Error('Enter a magnet link or .torrent URL, or choose a .torrent file'); + } + if (file) { + try { + await uploadTorrent(file, formData.destination); + } catch (e) { + // The Download button only changes its icon; say why (postDownload toasts its own failures). + toast({type: 'error', title: 'Could not add the .torrent file', description: e.message, time: 6000}); + throw e; + } + setFile(null); + } + if (urls.length) { + await postDownload({downloader: Downloaders.Torrent, destination: formData.destination, urls}); + } + }; + + const emptyFormData = {destination: null, urls: ''}; + + const form = useForm({ + submitter, + defaultFormData: mergeDeep(emptyFormData, download), + emptyFormData, + clearPathsOnSuccess: URL_PATHS, + onSuccess: async () => setShowMessage(true), + }); + + return
e.preventDefault()}> +
Torrent
+

Download (and share) torrents of open data. Torrents only use the VPN, so peers never see this WROLPi's own + address. Saved in the "torrents" directory unless you choose another.

+ + + + {/* Optional: a .torrent file may be chosen instead (or as well). */} + +
+ setFile((e.target.files && e.target.files[0]) || null)}/> + + + {file && {file.name}} + +
+ + {showMessage && } + {/* Download waits for something to download: a URL or a chosen file. */} + {actions({onCancel, form: {...form, ready: form.ready && (!!file || !!(form.formData.urls || '').trim())}})} +
+
+} + const suffixValidator = (value) => { const error = commaSeparatedValidator(value); if (error) { @@ -1659,11 +1783,12 @@ function UrlField({form, required = true, name = 'url', path = 'url', disabled = } /** Multiline URLs field: one URL per line. */ -function UrlsField({name = 'urls', required, form}) { +function UrlsField({name = 'urls', required, form, label = 'URLs', placeholder = 'Enter one URL per line', + valid = validURLs}) { required = required !== undefined; const validator = (value) => { - if (!validURLs(value)) { + if (!valid(value)) { return 'Invalid URLs'; } }; @@ -1687,10 +1812,10 @@ function UrlsField({name = 'urls', required, form}) { }; return
- +