Webui starting to work a bit better
This commit is contained in:
parent
e5d96243d4
commit
795ae82439
5 changed files with 415 additions and 404 deletions
7
Makefile
7
Makefile
|
|
@ -5,7 +5,12 @@ all: sign-release sign-debug
|
|||
@PHONY: webui-dev
|
||||
webui-dev:
|
||||
cd crates/librqbit/webui && \
|
||||
tsc --watch
|
||||
npm run dev
|
||||
|
||||
@PHONY: webui-build
|
||||
webui-build:
|
||||
cd crates/librqbit/webui && \
|
||||
npm run build
|
||||
|
||||
@PHONY: clean
|
||||
clean:
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ impl HttpApi {
|
|||
"GET /torrents/{index}/peer_stats": "Per peer stats",
|
||||
// This is kind of not secure as it just reads any local file that it has access to,
|
||||
// or any URL, but whatever, ok for our purposes / threat model.
|
||||
"POST /torrents": "Add a torrent here. magnet: or http:// or a local file."
|
||||
"POST /torrents": "Add a torrent here. magnet: or http:// or a local file.",
|
||||
"GET /web/": "Web UI",
|
||||
},
|
||||
"server": "rqbit",
|
||||
}))
|
||||
|
|
|
|||
20
crates/librqbit/webui/dist/app.js
vendored
20
crates/librqbit/webui/dist/app.js
vendored
File diff suppressed because one or more lines are too long
|
|
@ -1,385 +1,472 @@
|
|||
import { Fragment, createContext, useContext, useEffect, useRef, useState } from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
import { StrictMode, createContext, memo, useContext, useEffect, useRef, useState } from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
|
||||
// Define API URL and base path
|
||||
const apiUrl = (window.origin === 'null' || window.origin === 'http://localhost:3031') ? 'http://localhost:3030' : '';
|
||||
|
||||
interface ErrorType {
|
||||
status: number,
|
||||
statusText: number,
|
||||
body: number,
|
||||
id?: number,
|
||||
method?: string,
|
||||
path?: string,
|
||||
status?: number,
|
||||
statusText?: string,
|
||||
text: string,
|
||||
};
|
||||
|
||||
let defaultContext: {
|
||||
setError: any,
|
||||
} = {
|
||||
setError: null,
|
||||
};
|
||||
interface ContextType {
|
||||
setCloseableError: (error: ErrorType) => void,
|
||||
setOtherError: (error: ErrorType) => void,
|
||||
makeRequest: (method: string, path: string, data: any, showError: boolean) => Promise<any>,
|
||||
requests: {
|
||||
getTorrentDetails: any,
|
||||
getTorrentStats: any,
|
||||
},
|
||||
refreshTorrents: () => void,
|
||||
}
|
||||
|
||||
const AppContext = createContext(defaultContext);
|
||||
const AppContext = createContext<ContextType>(null);
|
||||
|
||||
// Interface for the Torrent API response
|
||||
interface Torrent {
|
||||
id: number;
|
||||
info_hash: string;
|
||||
interface TorrentId {
|
||||
id: number;
|
||||
info_hash: string;
|
||||
}
|
||||
|
||||
// Interface for the Torrent Details API response
|
||||
interface TorrentDetails {
|
||||
files: {
|
||||
name: string;
|
||||
length: number;
|
||||
included: boolean;
|
||||
}[];
|
||||
files: {
|
||||
name: string;
|
||||
length: number;
|
||||
included: boolean;
|
||||
}[];
|
||||
}
|
||||
|
||||
// Interface for the Torrent Stats API response
|
||||
interface TorrentStats {
|
||||
snapshot: {
|
||||
have_bytes: number;
|
||||
downloaded_and_checked_bytes: number;
|
||||
downloaded_and_checked_pieces: number;
|
||||
fetched_bytes: number;
|
||||
uploaded_bytes: number;
|
||||
initially_needed_bytes: number;
|
||||
remaining_bytes: number;
|
||||
total_bytes: number;
|
||||
total_piece_download_ms: number;
|
||||
peer_stats: {
|
||||
queued: number;
|
||||
connecting: number;
|
||||
live: number;
|
||||
seen: number;
|
||||
dead: number;
|
||||
not_needed: number;
|
||||
};
|
||||
};
|
||||
average_piece_download_time: {
|
||||
secs: number;
|
||||
nanos: number;
|
||||
};
|
||||
download_speed: {
|
||||
mbps: number;
|
||||
human_readable: string;
|
||||
};
|
||||
all_time_download_speed: {
|
||||
mbps: number;
|
||||
human_readable: string;
|
||||
};
|
||||
time_remaining: {
|
||||
human_readable: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
|
||||
// Interface for the API error response
|
||||
interface ApiError {
|
||||
status: number;
|
||||
statusText: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
// Helper function for making API requests (async/await)
|
||||
async function makeRequest(method: string, path: string, data?: any): Promise<any> {
|
||||
const url = apiUrl + path;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: data,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.text();
|
||||
try {
|
||||
const json = JSON.parse(errorBody);
|
||||
displayApiError({
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
body: json.human_readable !== undefined ? json.human_readable : errorBody,
|
||||
});
|
||||
} catch (e) {
|
||||
displayApiError({
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
body: errorBody,
|
||||
});
|
||||
}
|
||||
return Promise.reject(errorBody);
|
||||
}
|
||||
const result = await response.json();
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
displayApiError({
|
||||
status: error.status,
|
||||
statusText: error.statusText,
|
||||
body: error.toString(),
|
||||
});
|
||||
return Promise.reject(`Error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Function to get detailed information about a torrent (async/await)
|
||||
async function getTorrentDetails(index: number): Promise<TorrentDetails> {
|
||||
return makeRequest('GET', `/torrents/${index}`);
|
||||
}
|
||||
|
||||
// Function to get detailed statistics about a torrent (async/await)
|
||||
async function getTorrentStats(index: number): Promise<TorrentStats> {
|
||||
return makeRequest('GET', `/torrents/${index}/stats`);
|
||||
snapshot: {
|
||||
have_bytes: number;
|
||||
downloaded_and_checked_bytes: number;
|
||||
downloaded_and_checked_pieces: number;
|
||||
fetched_bytes: number;
|
||||
uploaded_bytes: number;
|
||||
initially_needed_bytes: number;
|
||||
remaining_bytes: number;
|
||||
total_bytes: number;
|
||||
total_piece_download_ms: number;
|
||||
peer_stats: {
|
||||
queued: number;
|
||||
connecting: number;
|
||||
live: number;
|
||||
seen: number;
|
||||
dead: number;
|
||||
not_needed: number;
|
||||
};
|
||||
};
|
||||
average_piece_download_time: {
|
||||
secs: number;
|
||||
nanos: number;
|
||||
};
|
||||
download_speed: {
|
||||
mbps: number;
|
||||
human_readable: string;
|
||||
};
|
||||
all_time_download_speed: {
|
||||
mbps: number;
|
||||
human_readable: string;
|
||||
};
|
||||
time_remaining: {
|
||||
human_readable: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function TorrentRow({ detailsResponse, statsResponse }) {
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
|
||||
return (
|
||||
<div className="torrent-row d-flex flex-row p-3 bg-light rounded mb-3">
|
||||
{/* Create and render columns */}
|
||||
<Column label="Name" value={getLargestFileName(detailsResponse)} />
|
||||
<Column label="Size" value={`${formatBytesToGB(totalBytes)} GB`} />
|
||||
<ColumnWithProgressBar label="Progress" percentage={downloadPercentage} />
|
||||
<Column label="Download Speed" value={statsResponse.download_speed.human_readable} />
|
||||
<Column label="ETA" value={getCompletionETA(statsResponse)} />
|
||||
<Column label="Peers" value={`${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`} />
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className="torrent-row d-flex flex-row p-3 bg-light rounded mb-3">
|
||||
<Column label="Name" value={getLargestFileName(detailsResponse)} />
|
||||
<Column label="Size" value={`${formatBytesToGB(totalBytes)} GB`} />
|
||||
<ColumnWithProgressBar label="Progress" percentage={downloadPercentage} />
|
||||
<Column label="Download Speed" value={statsResponse.download_speed.human_readable} />
|
||||
<Column label="ETA" value={getCompletionETA(statsResponse)} />
|
||||
<Column label="Peers" value={`${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Define a Preact component for a column
|
||||
const Column = ({ label, value }) => (
|
||||
<div className={`column-${label.toLowerCase().replace(" ", "-")} me-3 p-2`}>
|
||||
<p className="font-weight-bold">{label}</p>
|
||||
<p>{value}</p>
|
||||
</div>
|
||||
<div className={`column-${label.toLowerCase().replace(" ", "-")} me-3 p-2`}>
|
||||
<p className="font-weight-bold">{label}</p>
|
||||
<p>{value}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Define a Preact component for a column with a progress bar
|
||||
const ColumnWithProgressBar = ({ label, percentage }) => (
|
||||
<div className="column-progress me-3 p-2">
|
||||
<p className="font-weight-bold">{label}</p>
|
||||
<div className="progress mb-1">
|
||||
<div className="progress-bar" style={{ width: `${percentage}%` }}></div>
|
||||
</div>
|
||||
<p className="mb-1">{percentage.toFixed(2)}%</p>
|
||||
</div >
|
||||
<div className="column-progress me-3 p-2">
|
||||
<p className="font-weight-bold">{label}</p>
|
||||
<div className="progress mb-1">
|
||||
<div className="progress-bar" style={{ width: `${percentage}%` }}></div>
|
||||
</div>
|
||||
<p className="mb-1">{percentage.toFixed(2)}%</p>
|
||||
</div >
|
||||
);
|
||||
|
||||
const DeferredTorrent = ({ torrent }) => {
|
||||
const defaultDetails: TorrentDetails = {
|
||||
files: []
|
||||
};
|
||||
const defaultStats: TorrentStats = {
|
||||
snapshot: {
|
||||
have_bytes: 0,
|
||||
downloaded_and_checked_bytes: 0,
|
||||
downloaded_and_checked_pieces: 0,
|
||||
fetched_bytes: 0,
|
||||
uploaded_bytes: 0,
|
||||
initially_needed_bytes: 0,
|
||||
remaining_bytes: 0,
|
||||
total_bytes: 0,
|
||||
total_piece_download_ms: 0,
|
||||
peer_stats: {
|
||||
queued: 0,
|
||||
connecting: 0,
|
||||
live: 0,
|
||||
seen: 0,
|
||||
dead: 0,
|
||||
not_needed: 0
|
||||
}
|
||||
},
|
||||
average_piece_download_time: {
|
||||
secs: 0,
|
||||
nanos: 0
|
||||
},
|
||||
download_speed: {
|
||||
mbps: 0,
|
||||
human_readable: ''
|
||||
},
|
||||
all_time_download_speed: {
|
||||
mbps: 0,
|
||||
human_readable: ''
|
||||
},
|
||||
time_remaining: {
|
||||
human_readable: ''
|
||||
}
|
||||
};
|
||||
const Torrent = ({ torrent }) => {
|
||||
const defaultDetails: TorrentDetails = {
|
||||
files: []
|
||||
};
|
||||
const defaultStats: TorrentStats = {
|
||||
snapshot: {
|
||||
have_bytes: 0,
|
||||
downloaded_and_checked_bytes: 0,
|
||||
downloaded_and_checked_pieces: 0,
|
||||
fetched_bytes: 0,
|
||||
uploaded_bytes: 0,
|
||||
initially_needed_bytes: 0,
|
||||
remaining_bytes: 0,
|
||||
total_bytes: 0,
|
||||
total_piece_download_ms: 0,
|
||||
peer_stats: {
|
||||
queued: 0,
|
||||
connecting: 0,
|
||||
live: 0,
|
||||
seen: 0,
|
||||
dead: 0,
|
||||
not_needed: 0
|
||||
}
|
||||
},
|
||||
average_piece_download_time: {
|
||||
secs: 0,
|
||||
nanos: 0
|
||||
},
|
||||
download_speed: {
|
||||
mbps: 0,
|
||||
human_readable: ''
|
||||
},
|
||||
all_time_download_speed: {
|
||||
mbps: 0,
|
||||
human_readable: ''
|
||||
},
|
||||
time_remaining: {
|
||||
human_readable: ''
|
||||
}
|
||||
};
|
||||
|
||||
const [detailsResponse, updateDetailsResponse] = useState(defaultDetails);
|
||||
const [statsResponse, updateStatsResponse] = useState(defaultStats);
|
||||
const [detailsResponse, updateDetailsResponse] = useState(defaultDetails);
|
||||
const [statsResponse, updateStatsResponse] = useState(defaultStats);
|
||||
|
||||
const update = async () => {
|
||||
let a = getTorrentDetails(torrent.id).then((details) => {
|
||||
updateDetailsResponse(details);
|
||||
});
|
||||
let b = getTorrentStats(torrent.id).then((stats) => {
|
||||
updateStatsResponse(stats);
|
||||
});
|
||||
await Promise.all([a, b]);
|
||||
setTimeout(update, 500);
|
||||
};
|
||||
let ctx = useContext(AppContext);
|
||||
|
||||
useEffect(() => {
|
||||
let timer = setTimeout(update, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
const update = async () => {
|
||||
return await Promise.all([
|
||||
ctx.requests.getTorrentDetails(torrent.id).then((details) => {
|
||||
updateDetailsResponse(details);
|
||||
return details;
|
||||
}),
|
||||
ctx.requests.getTorrentStats(torrent.id).then((stats) => {
|
||||
updateStatsResponse(stats);
|
||||
return stats;
|
||||
})
|
||||
]).then(([_, stats]) => {
|
||||
return torrentIsDone(stats) ? 10000 : 500;
|
||||
}, (e) => {
|
||||
return 5000;
|
||||
})
|
||||
};
|
||||
|
||||
return <TorrentRow detailsResponse={detailsResponse} statsResponse={statsResponse} />
|
||||
useEffect(() => {
|
||||
let clear = customSetInterval(update, 0);
|
||||
return clear;
|
||||
}, []);
|
||||
|
||||
return <TorrentRow detailsResponse={detailsResponse} statsResponse={statsResponse} />
|
||||
}
|
||||
|
||||
var globalCtx = null;
|
||||
const Spinner = () => (
|
||||
<div className="spinner-border" role="status">
|
||||
<span className="sr-only">Loading...</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
const TorrentsList = () => {
|
||||
const [torrents, updateTorrents] = useState([]);
|
||||
globalCtx = useContext(AppContext);
|
||||
const update = async () => {
|
||||
let response = await makeRequest('GET', '/torrents');
|
||||
updateTorrents(response.torrents);
|
||||
setTimeout(update, 500);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let timer = setTimeout(update, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
let torrentsComponents = torrents.map((t: Torrent) =>
|
||||
<DeferredTorrent key={t.id} torrent={t} />
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{torrentsComponents}
|
||||
</div>
|
||||
)
|
||||
const TorrentsList = (props: { torrents: Array<TorrentId>, loading: boolean }) => {
|
||||
if (props.torrents === null && props.loading) {
|
||||
return <Spinner />
|
||||
}
|
||||
let torrents = props.torrents === null ? [] : props.torrents;
|
||||
if (torrents.length === 0) {
|
||||
return (
|
||||
<div className="text-center">
|
||||
<p>No existing torrents found. Add them through buttons below.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
{torrents.map((t: TorrentId) =>
|
||||
<Torrent key={t.id} torrent={t} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
};
|
||||
|
||||
const Root = () => {
|
||||
const [error, setError] = useState(null);
|
||||
const [closeableError, setCloseableError] = useState<ErrorType>(null);
|
||||
const [otherError, setOtherError] = useState<ErrorType>(null);
|
||||
|
||||
const Error = ({ error }) => {
|
||||
if (error == null) {
|
||||
return null;
|
||||
}
|
||||
const [torrents, setTorrents] = useState<Array<TorrentId>>(null);
|
||||
const [torrentsLoading, setTorrentsLoading] = useState(false);
|
||||
|
||||
let ctx = useContext(AppContext);
|
||||
const makeRequest = async (method: string, path: string, data: any, showError: boolean): Promise<any> => {
|
||||
console.log(method, path);
|
||||
const url = apiUrl + path;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: data,
|
||||
};
|
||||
|
||||
return (<div className="alert alert-danger alert-dismissible fade show" role="alert">
|
||||
<strong>Error ${error.status}:</strong> {error.statusText}<br />
|
||||
{error.body}
|
||||
<button type="button" className="btn-close" data-bs-dismiss="alert" aria-label="Close" onClick={() => ctx.setError(null)}>Close</button>
|
||||
</div>);
|
||||
};
|
||||
const maybeShowError = (e: ErrorType) => {
|
||||
if (showError) {
|
||||
setCloseableError(e);
|
||||
}
|
||||
}
|
||||
|
||||
const FileInput = () => {
|
||||
const inputRef = useRef();
|
||||
let error: ErrorType = {
|
||||
method: method,
|
||||
path: path,
|
||||
text: ''
|
||||
};
|
||||
|
||||
const inputOnChange = (e) => {
|
||||
let file = e.target.files[0];
|
||||
makeRequest('POST', '/torrents?overwrite=true', file);
|
||||
// e.target.clear();
|
||||
}
|
||||
let response: Response;
|
||||
|
||||
const onClick = (e) => {
|
||||
inputRef.current.click();
|
||||
}
|
||||
try {
|
||||
response = await fetch(url, options);
|
||||
} catch (e) {
|
||||
error.text = 'unknown error: ' + e.toString();
|
||||
maybeShowError(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
return (<div>
|
||||
<input type="file" ref={inputRef} id="file-input" accept=".torrent" onChange={inputOnChange} style={{ display: 'none' }} />
|
||||
<button id="upload-file-button" className="btn btn-secondary" onClick={onClick}>Upload .torrent File</button>
|
||||
</div>);
|
||||
};
|
||||
error.status = response.status;
|
||||
error.statusText = response.statusText;
|
||||
|
||||
const Buttons = () => {
|
||||
return (
|
||||
<div id="buttons-container" className="mt-3">
|
||||
<button id="add-magnet-button" className="btn btn-primary mr-2" onClick={addTorrentFromMagnet}>Add Torrent from Magnet Link</button>
|
||||
<FileInput />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.text();
|
||||
try {
|
||||
const json = JSON.parse(errorBody);
|
||||
error.text = json.human_readable !== undefined ? json.human_readable : JSON.stringify(json, null, 2);
|
||||
} catch (e) {
|
||||
error.text = errorBody;
|
||||
}
|
||||
maybeShowError(error);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const result = await response.json();
|
||||
return result;
|
||||
}
|
||||
|
||||
return <AppContext.Provider value={{ setError: setError }}>
|
||||
<Error error={error} />
|
||||
<TorrentsList />
|
||||
<Buttons />
|
||||
</AppContext.Provider >
|
||||
const requests = {
|
||||
getTorrentDetails: (index: number): Promise<TorrentDetails> => {
|
||||
return makeRequest('GET', `/torrents/${index}`, null, false);
|
||||
},
|
||||
getTorrentStats: (index: number): Promise<TorrentStats> => {
|
||||
return makeRequest('GET', `/torrents/${index}/stats`, null, false);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshTorrents = async () => {
|
||||
setTorrentsLoading(true);
|
||||
let torrents: { torrents: Array<TorrentId> } = await makeRequest('GET', '/torrents', null, false).finally(() => setTorrentsLoading(false));
|
||||
setTorrents(torrents.torrents);
|
||||
return torrents;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let interval = 500;
|
||||
let clear = customSetInterval(async () => {
|
||||
try {
|
||||
await refreshTorrents();
|
||||
setOtherError(null);
|
||||
return interval;
|
||||
} catch (e) {
|
||||
setOtherError(e);
|
||||
console.error(e);
|
||||
return 5000;
|
||||
}
|
||||
}, interval);
|
||||
return clear;
|
||||
}, []);
|
||||
|
||||
const context: ContextType = {
|
||||
setCloseableError,
|
||||
setOtherError,
|
||||
makeRequest,
|
||||
requests,
|
||||
refreshTorrents,
|
||||
}
|
||||
|
||||
return <AppContext.Provider value={context}>
|
||||
<RootContent closeableError={closeableError} otherError={otherError} torrents={torrents} torrentsLoading={torrentsLoading} />
|
||||
</AppContext.Provider >
|
||||
}
|
||||
|
||||
const Error = (props: { error: ErrorType, remove?: () => void }) => {
|
||||
let { error, remove } = props;
|
||||
|
||||
if (error == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (<div className="alert alert-danger fade show" role="alert">
|
||||
{error.method && (
|
||||
<strong>Error calling {error.method} {error.path}: </strong>
|
||||
)}
|
||||
{error.status && (
|
||||
<strong>{error.status} {error.statusText}: </strong>
|
||||
)}
|
||||
{error.text}
|
||||
{
|
||||
remove && (
|
||||
<button type="button" className="close" data-dismiss="alert" aria-label="Close" onClick={remove}>
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
</div >);
|
||||
};
|
||||
|
||||
const MagnetInput = () => {
|
||||
let ctx = useContext(AppContext);
|
||||
|
||||
// Function to add a torrent from a magnet link
|
||||
async function addTorrentFromMagnet(): Promise<void> {
|
||||
const magnetLink = prompt('Enter magnet link:');
|
||||
if (magnetLink) {
|
||||
await ctx.makeRequest('POST', '/torrents?overwrite=true', magnetLink, true);
|
||||
ctx.refreshTorrents();
|
||||
}
|
||||
}
|
||||
|
||||
return <button id="add-magnet-button" className="btn btn-primary mr-2" onClick={addTorrentFromMagnet}>Add Torrent from Magnet Link</button>
|
||||
};
|
||||
|
||||
const FileInput = () => {
|
||||
const inputRef = useRef<HTMLInputElement>();
|
||||
|
||||
let ctx = useContext(AppContext);
|
||||
|
||||
const inputOnChange = async (e) => {
|
||||
let file = e.target.files[0];
|
||||
await ctx.makeRequest('POST', '/torrents?overwrite=true', file, true);
|
||||
ctx.refreshTorrents();
|
||||
}
|
||||
|
||||
const onClick = () => {
|
||||
inputRef.current.click();
|
||||
}
|
||||
|
||||
return (<>
|
||||
<input type="file" ref={inputRef} id="file-input" accept=".torrent" onChange={inputOnChange} className='d-none' />
|
||||
<button id="upload-file-button" className="btn btn-secondary" onClick={onClick}>Upload .torrent File</button>
|
||||
</>);
|
||||
};
|
||||
|
||||
const Buttons = () => {
|
||||
return (
|
||||
<div id="buttons-container" className="mt-3">
|
||||
<MagnetInput />
|
||||
<FileInput />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const LastErrors = (props: { lastErrors: Array<ErrorType> }) => {
|
||||
return <div>
|
||||
{props.lastErrors.map((e: ErrorType) => (
|
||||
<div className="alert alert-primary" role="alert"></div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
|
||||
const RootContent = (props: { closeableError: ErrorType, otherError: ErrorType, torrents: Array<TorrentId>, torrentsLoading: boolean }) => {
|
||||
let ctx = useContext(AppContext);
|
||||
return <>
|
||||
<Error error={props.closeableError} remove={() => ctx.setCloseableError(null)} />
|
||||
<Error error={props.otherError} />
|
||||
<TorrentsList torrents={props.torrents} loading={props.torrentsLoading} />
|
||||
<Buttons />
|
||||
</>
|
||||
};
|
||||
|
||||
function torrentIsDone(stats: TorrentStats): boolean {
|
||||
return stats.snapshot.have_bytes == stats.snapshot.total_bytes;
|
||||
}
|
||||
|
||||
// Render function to display all torrents
|
||||
async function displayTorrents() {
|
||||
// Get the torrents container
|
||||
const torrentsContainer = document.getElementById('output');
|
||||
ReactDOM.render(<Root />, torrentsContainer);
|
||||
// Get the torrents container
|
||||
const torrentsContainer = document.getElementById('output');
|
||||
const RootMemo = memo(Root, (prev, next) => true);
|
||||
ReactDOM.createRoot(torrentsContainer).render(<StrictMode><RootMemo /></StrictMode>);
|
||||
}
|
||||
|
||||
// Function to format bytes to GB
|
||||
function formatBytesToGB(bytes: number): string {
|
||||
const GB = bytes / (1024 * 1024 * 1024);
|
||||
return GB.toFixed(2);
|
||||
const GB = bytes / (1024 * 1024 * 1024);
|
||||
return GB.toFixed(2);
|
||||
}
|
||||
|
||||
// Function to get the name of the largest file in a torrent
|
||||
function getLargestFileName(torrentDetails: TorrentDetails): string {
|
||||
if (torrentDetails.files.length == 0) {
|
||||
return 'Loading...';
|
||||
}
|
||||
const largestFile = torrentDetails.files.reduce((prev: any, current: any) => (prev.length > current.length) ? prev : current);
|
||||
return largestFile.name;
|
||||
if (torrentDetails.files.length == 0) {
|
||||
return 'Loading...';
|
||||
}
|
||||
const largestFile = torrentDetails.files.reduce((prev: any, current: any) => (prev.length > current.length) ? prev : current);
|
||||
return largestFile.name;
|
||||
}
|
||||
|
||||
// Function to get the completion ETA of a torrent
|
||||
function getCompletionETA(stats: TorrentStats): string {
|
||||
if (stats.time_remaining) {
|
||||
return stats.time_remaining.human_readable;
|
||||
} else {
|
||||
return 'N/A';
|
||||
}
|
||||
if (stats.time_remaining) {
|
||||
return stats.time_remaining.human_readable;
|
||||
} else {
|
||||
return 'N/A';
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to display API errors in an alert
|
||||
function displayApiError(error: ApiError): void {
|
||||
globalCtx.setError(error);
|
||||
function customSetInterval(asyncCallback: any, interval: number) {
|
||||
let timeoutId: number;
|
||||
let currentInterval: number = interval;
|
||||
|
||||
const executeCallback = async () => {
|
||||
currentInterval = await asyncCallback();
|
||||
if (currentInterval === null || currentInterval === undefined) {
|
||||
throw 'asyncCallback returned null or undefined';
|
||||
}
|
||||
scheduleNext();
|
||||
}
|
||||
|
||||
let scheduleNext = () => {
|
||||
timeoutId = setTimeout(executeCallback, currentInterval);
|
||||
}
|
||||
|
||||
scheduleNext();
|
||||
|
||||
let clearCustomInterval = () => {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
|
||||
return clearCustomInterval;
|
||||
}
|
||||
|
||||
// List all torrents on page load and set up auto-refresh
|
||||
async function init(): Promise<void> {
|
||||
await displayTorrents();
|
||||
await displayTorrents();
|
||||
}
|
||||
|
||||
// Function to add a torrent from a magnet link
|
||||
async function addTorrentFromMagnet(): Promise<void> {
|
||||
const magnetLink = prompt('Enter magnet link:');
|
||||
if (magnetLink) {
|
||||
await makeRequest('POST', '/torrents?overwrite=true', magnetLink);
|
||||
// await displayTorrents(); // Refresh the torrent list after adding a new torrent
|
||||
}
|
||||
}
|
||||
|
||||
// Function to handle file input change
|
||||
async function handleFileInputChange(): Promise<void> {
|
||||
const fileInput = document.getElementById('file-input') as HTMLInputElement;
|
||||
const file = fileInput.files?.[0];
|
||||
if (file) {
|
||||
await makeRequest('POST', '/torrents?overwrite=true', file);
|
||||
// await displayTorrents(); // Refresh the torrent list after adding a new torrent
|
||||
}
|
||||
}
|
||||
|
||||
// Update the event listener for the file input button
|
||||
const fileInputButton = document.getElementById('upload-file-button');
|
||||
fileInputButton?.addEventListener('click', () => {
|
||||
const fileInput = document.getElementById('file-input') as HTMLInputElement;
|
||||
fileInput.click();
|
||||
});
|
||||
|
||||
document.getElementById('file-input')?.addEventListener('change', handleFileInputChange);
|
||||
|
||||
// Call init function on page load
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
:root {
|
||||
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color: #222;
|
||||
background-color: #ffffff;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
#app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
img {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
img:hover {
|
||||
filter: drop-shadow(0 0 2em #673ab8aa);
|
||||
}
|
||||
|
||||
section {
|
||||
margin-top: 5rem;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
column-gap: 1.5rem;
|
||||
}
|
||||
|
||||
.resource {
|
||||
padding: 0.75rem 1.5rem;
|
||||
border-radius: 0.5rem;
|
||||
text-align: left;
|
||||
text-decoration: none;
|
||||
color: #222;
|
||||
background-color: #f1f1f1;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.resource:hover {
|
||||
border: 1px solid #000;
|
||||
box-shadow: 0 25px 50px -12px #673ab888;
|
||||
}
|
||||
|
||||
@media (max-width: 639px) {
|
||||
#app {
|
||||
margin: 2rem;
|
||||
}
|
||||
section {
|
||||
margin-top: 5rem;
|
||||
grid-template-columns: 1fr;
|
||||
row-gap: 1rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
color: #ccc;
|
||||
background-color: #1a1a1a;
|
||||
}
|
||||
.resource {
|
||||
color: #ccc;
|
||||
background-color: #161616;
|
||||
}
|
||||
.resource:hover {
|
||||
border: 1px solid #bbb;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue