WTF IS MODERN JS?!?!
This commit is contained in:
parent
d5cf369a75
commit
9f26ea5963
12 changed files with 2429 additions and 0 deletions
332
crates/librqbit/webui/dist/webui/src/index.jsx
vendored
Normal file
332
crates/librqbit/webui/dist/webui/src/index.jsx
vendored
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
import { Fragment, render } from 'preact';
|
||||
import { useState } from 'preact/hooks';
|
||||
// Define API URL and base path
|
||||
const apiUrl = (window.origin === 'null' || window.origin === 'http://localhost:3031') ? 'http://localhost:3030' : '';
|
||||
// Helper function for making API requests (async/await)
|
||||
async function makeRequest(method, path, data) {
|
||||
const url = apiUrl + path;
|
||||
const options = {
|
||||
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) {
|
||||
return makeRequest('GET', `/torrents/${index}`);
|
||||
}
|
||||
// Function to get detailed statistics about a torrent (async/await)
|
||||
async function getTorrentStats(index) {
|
||||
return makeRequest('GET', `/torrents/${index}/stats`);
|
||||
}
|
||||
function TorrentRow(props) {
|
||||
const { detailsResponse, statsResponse } = this.props;
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
return (<div class="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>);
|
||||
}
|
||||
// Define a Preact component for a column
|
||||
const Column = ({ label, value }) => (<div class={`column-${label.toLowerCase().replace(" ", "-")} me-3 p-2`}>
|
||||
<p class="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 class="column-progress me-3 p-2">
|
||||
<p class="font-weight-bold">{label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" style={`width: ${percentage}%;`}></div>
|
||||
</div>
|
||||
<p class="mb-1">{percentage.toFixed(2)}%</p>
|
||||
</div>);
|
||||
const DeferredTorrent = ({ torrent }) => {
|
||||
const defaultDetails = {
|
||||
files: []
|
||||
};
|
||||
const defaultStats = {
|
||||
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 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);
|
||||
};
|
||||
setTimeout(update, 500);
|
||||
return <TorrentRow detailsResponse={detailsResponse} statsResponse={statsResponse}/>;
|
||||
};
|
||||
// Render function to display all torrents
|
||||
async function displayTorrents() {
|
||||
const response = await makeRequest('GET', '/torrents');
|
||||
const torrents = response.torrents;
|
||||
// Get the torrents container
|
||||
const torrentsContainer = document.getElementById('output');
|
||||
let root = torrents.map((t) => {
|
||||
(<Fragment key={t.id}>
|
||||
<DeferredTorrent torrent={t}/>
|
||||
</Fragment>);
|
||||
});
|
||||
render(root, torrentsContainer);
|
||||
}
|
||||
// Function to update HTML for a torrent row
|
||||
function updateTorrentRow(torrentRow, detailsResponse, statsResponse) {
|
||||
// Calculate download percentage
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
// Display basic information about the torrent
|
||||
const largestFileName = getLargestFileName(detailsResponse);
|
||||
const downloadSpeed = statsResponse.download_speed.human_readable;
|
||||
const eta = getCompletionETA(statsResponse);
|
||||
const peers = `${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`;
|
||||
// Update or create columns in the torrent row
|
||||
updateOrCreateColumnContent(torrentRow, 'Name', largestFileName);
|
||||
updateOrCreateColumnContent(torrentRow, 'Size', `${formatBytesToGB(totalBytes)} GB`);
|
||||
updateOrCreateColumnWithProgressBar(torrentRow, 'Progress', downloadPercentage);
|
||||
updateOrCreateColumnContent(torrentRow, 'Download Speed', downloadSpeed);
|
||||
updateOrCreateColumnContent(torrentRow, 'ETA', eta);
|
||||
updateOrCreateColumnContent(torrentRow, 'Peers', peers);
|
||||
}
|
||||
// Function to update or create the content of a column in a torrent row
|
||||
function updateOrCreateColumnContent(torrentRow, human_label, value) {
|
||||
let label = human_label.toLowerCase().replace(" ", "-");
|
||||
let column = torrentRow.querySelector(`.column-${label}`);
|
||||
// If the column doesn't exist, create a new one
|
||||
if (!column) {
|
||||
column = document.createElement('div');
|
||||
column.classList.add(`column-${label}`, 'me-3', 'p-2');
|
||||
torrentRow.appendChild(column);
|
||||
}
|
||||
// Update the content of the existing or newly created column
|
||||
const contentParagraph = column.querySelector('p:last-child');
|
||||
if (contentParagraph) {
|
||||
contentParagraph.textContent = value;
|
||||
}
|
||||
else {
|
||||
column.innerHTML = `<p class="font-weight-bold">${human_label}</p><p>${value}</p>`;
|
||||
}
|
||||
}
|
||||
// Function to update or create the content of a progress bar column in a torrent row
|
||||
function updateOrCreateColumnWithProgressBar(torrentRow, label, percentage) {
|
||||
let column = torrentRow.querySelector('.column-progress');
|
||||
// If the column doesn't exist, create a new one
|
||||
if (!column) {
|
||||
column = document.createElement('div');
|
||||
column.classList.add('column-progress', 'me-3', 'p-2');
|
||||
torrentRow.appendChild(column);
|
||||
}
|
||||
// Update the value of the progress bar in the existing or newly created column
|
||||
const progressBar = column.querySelector('.progress-bar');
|
||||
const progressPercentage = column.querySelector('p:last-child');
|
||||
if (progressBar && progressPercentage) {
|
||||
progressBar.style.width = `${percentage}%`;
|
||||
progressPercentage.textContent = `${percentage.toFixed(2)}%`;
|
||||
}
|
||||
else {
|
||||
column.innerHTML = `
|
||||
<p class="font-weight-bold">${label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" role="progressbar" style="width: ${percentage}%;"></div>
|
||||
</div>
|
||||
<p class="mb-1">${percentage.toFixed(2)}%</p>`;
|
||||
}
|
||||
}
|
||||
// Function to render HTML for a torrent row
|
||||
function renderTorrentRow(torrentsContainer, torrentId, detailsResponse, statsResponse) {
|
||||
// Check if the torrent row already exists
|
||||
let torrentRow = document.getElementById(`torrent-${torrentId}`);
|
||||
// If the torrent row doesn't exist, create a new one
|
||||
if (!torrentRow) {
|
||||
torrentRow = document.createElement('div');
|
||||
torrentRow.id = `torrent-${torrentId}`;
|
||||
torrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
|
||||
torrentsContainer.appendChild(torrentRow);
|
||||
}
|
||||
// Update columns in the torrent row
|
||||
updateTorrentRow(torrentRow, detailsResponse, statsResponse);
|
||||
return torrentRow;
|
||||
}
|
||||
// Function to create a column div
|
||||
function createColumn(label, value, columnClass) {
|
||||
const columnDiv = document.createElement('div');
|
||||
columnDiv.classList.add(columnClass, 'me-3', 'p-2');
|
||||
columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`;
|
||||
return columnDiv;
|
||||
}
|
||||
// Function to create a column div with a progress bar
|
||||
function createColumnWithProgressBar(label, percentage) {
|
||||
const columnDiv = document.createElement('div');
|
||||
columnDiv.classList.add('column', 'me-3', 'p-2');
|
||||
columnDiv.innerHTML = `
|
||||
<p class="font-weight-bold">${label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" role="progressbar" style="width: ${percentage}%;"></div>
|
||||
</div>
|
||||
<p class="mb-1">${percentage.toFixed(2)}%</p>`;
|
||||
return columnDiv;
|
||||
}
|
||||
// Function to format bytes to GB
|
||||
function formatBytesToGB(bytes) {
|
||||
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) {
|
||||
const largestFile = torrentDetails.files.reduce((prev, current) => (prev.length > current.length) ? prev : current);
|
||||
return largestFile.name;
|
||||
}
|
||||
// Function to get the completion ETA of a torrent
|
||||
function getCompletionETA(stats) {
|
||||
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) {
|
||||
const errorAlert = document.getElementById('error-alert');
|
||||
if (errorAlert) {
|
||||
errorAlert.innerHTML = `
|
||||
<div class="alert alert-danger alert-dismissible fade show" role="alert">
|
||||
<strong>Error ${error.status}:</strong> ${error.statusText}<br>
|
||||
${error.body}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close" onclick="clearErrorAlert()"></button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
// Helper function to clear the error alert
|
||||
function clearErrorAlert() {
|
||||
const errorAlert = document.getElementById('error-alert');
|
||||
if (errorAlert) {
|
||||
errorAlert.innerHTML = ''; // Clear the content
|
||||
}
|
||||
}
|
||||
// List all torrents on page load and set up auto-refresh
|
||||
async function init() {
|
||||
try {
|
||||
await displayTorrents();
|
||||
autoRefreshTorrents(500); // Set the interval (in milliseconds), e.g., 5000 for every 5 seconds
|
||||
}
|
||||
catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
// Function to refresh torrents at a specified interval
|
||||
function autoRefreshTorrents(interval) {
|
||||
setInterval(async () => {
|
||||
await displayTorrents();
|
||||
}, interval);
|
||||
}
|
||||
// Function to add a torrent from a magnet link
|
||||
async function addTorrentFromMagnet() {
|
||||
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() {
|
||||
const fileInput = document.getElementById('file-input');
|
||||
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
|
||||
}
|
||||
}
|
||||
// Add event listeners for buttons
|
||||
document.getElementById('add-magnet-button')?.addEventListener('click', addTorrentFromMagnet);
|
||||
// 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');
|
||||
fileInput.click();
|
||||
});
|
||||
document.getElementById('file-input')?.addEventListener('change', handleFileInputChange);
|
||||
// Call init function on page load
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
9
crates/librqbit/webui/dist/webui/vite.config.js
vendored
Normal file
9
crates/librqbit/webui/dist/webui/vite.config.js
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import preact from '@preact/preset-vite';
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [preact()],
|
||||
server: {
|
||||
port: 3031
|
||||
}
|
||||
});
|
||||
24
crates/librqbit/webui/webui/.gitignore
vendored
Normal file
24
crates/librqbit/webui/webui/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
32
crates/librqbit/webui/webui/index.html
Normal file
32
crates/librqbit/webui/webui/index.html
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>rqbit web 0.0.1-alpha</title>
|
||||
<!-- Include Bootstrap CSS -->
|
||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app-container" class="container text-center">
|
||||
<h1 class="mt-3 mb-4">rqbit web 0.0.1-alpha</h1>
|
||||
<!-- Error Alert Container -->
|
||||
<div id="error-alert"></div>
|
||||
<div id="output" class="output-container"></div>
|
||||
<div id="buttons-container" class="mt-3">
|
||||
<button id="add-magnet-button" class="btn btn-primary mr-2">Add Torrent from Magnet Link</button>
|
||||
<input type="file" id="file-input" accept=".torrent" style="display:none;">
|
||||
<button id="upload-file-button" class="btn btn-secondary">Upload .torrent File</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Include Bootstrap JS and Popper.js (required for Bootstrap) -->
|
||||
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
|
||||
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
|
||||
|
||||
<script type="module" src="src/index.tsx"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
1449
crates/librqbit/webui/webui/package-lock.json
generated
Normal file
1449
crates/librqbit/webui/webui/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
17
crates/librqbit/webui/webui/package.json
Normal file
17
crates/librqbit/webui/webui/package.json
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"preact": "^10.13.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/preset-vite": "^2.5.0",
|
||||
"typescript": "^5.3.2",
|
||||
"vite": "^4.3.2"
|
||||
}
|
||||
}
|
||||
1
crates/librqbit/webui/webui/public/vite.svg
Normal file
1
crates/librqbit/webui/webui/public/vite.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
1
crates/librqbit/webui/webui/src/assets/preact.svg
Normal file
1
crates/librqbit/webui/webui/src/assets/preact.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="27.68" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 296"><path fill="#673AB8" d="m128 0l128 73.9v147.8l-128 73.9L0 221.7V73.9z"></path><path fill="#FFF" d="M34.865 220.478c17.016 21.78 71.095 5.185 122.15-34.704c51.055-39.888 80.24-88.345 63.224-110.126c-17.017-21.78-71.095-5.184-122.15 34.704c-51.055 39.89-80.24 88.346-63.224 110.126Zm7.27-5.68c-5.644-7.222-3.178-21.402 7.573-39.253c11.322-18.797 30.541-39.548 54.06-57.923c23.52-18.375 48.303-32.004 69.281-38.442c19.922-6.113 34.277-5.075 39.92 2.148c5.644 7.223 3.178 21.403-7.573 39.254c-11.322 18.797-30.541 39.547-54.06 57.923c-23.52 18.375-48.304 32.004-69.281 38.441c-19.922 6.114-34.277 5.076-39.92-2.147Z"></path><path fill="#FFF" d="M220.239 220.478c17.017-21.78-12.169-70.237-63.224-110.126C105.96 70.464 51.88 53.868 34.865 75.648c-17.017 21.78 12.169 70.238 63.224 110.126c51.055 39.889 105.133 56.485 122.15 34.704Zm-7.27-5.68c-5.643 7.224-19.998 8.262-39.92 2.148c-20.978-6.437-45.761-20.066-69.28-38.441c-23.52-18.376-42.74-39.126-54.06-57.923c-10.752-17.851-13.218-32.03-7.575-39.254c5.644-7.223 19.999-8.261 39.92-2.148c20.978 6.438 45.762 20.067 69.281 38.442c23.52 18.375 42.739 39.126 54.06 57.923c10.752 17.85 13.218 32.03 7.574 39.254Z"></path><path fill="#FFF" d="M127.552 167.667c10.827 0 19.603-8.777 19.603-19.604c0-10.826-8.776-19.603-19.603-19.603c-10.827 0-19.604 8.777-19.604 19.603c0 10.827 8.777 19.604 19.604 19.604Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.6 KiB |
452
crates/librqbit/webui/webui/src/index.tsx
Normal file
452
crates/librqbit/webui/webui/src/index.tsx
Normal file
|
|
@ -0,0 +1,452 @@
|
|||
import { Fragment, h, render, Component } from 'preact';
|
||||
import { useEffect, useState } from 'preact/hooks';
|
||||
|
||||
// Define API URL and base path
|
||||
const apiUrl = (window.origin === 'null' || window.origin === 'http://localhost:3031') ? 'http://localhost:3030' : '';
|
||||
|
||||
// Interface for the Torrent API response
|
||||
interface Torrent {
|
||||
id: number;
|
||||
info_hash: string;
|
||||
}
|
||||
|
||||
// Interface for the Torrent Details API response
|
||||
interface TorrentDetails {
|
||||
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`);
|
||||
}
|
||||
|
||||
function TorrentRow(props) {
|
||||
const { detailsResponse, statsResponse } = this.props;
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
|
||||
return (
|
||||
<div class="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>
|
||||
);
|
||||
}
|
||||
|
||||
// Define a Preact component for a column
|
||||
const Column = ({ label, value }) => (
|
||||
<div class={`column-${label.toLowerCase().replace(" ", "-")} me-3 p-2`}>
|
||||
<p class="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 class="column-progress me-3 p-2">
|
||||
<p class="font-weight-bold">{label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" style={`width: ${percentage}%;`}></div>
|
||||
</div>
|
||||
<p class="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 [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, 5000);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let timer = setTimeout(update, 0);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
return <TorrentRow detailsResponse={detailsResponse} statsResponse={statsResponse} />
|
||||
}
|
||||
|
||||
const Root = () => {
|
||||
const [torrents, updateTorrents] = useState([]);
|
||||
const update = async () => {
|
||||
let response = await makeRequest('GET', '/torrents');
|
||||
updateTorrents(response.torrents);
|
||||
// setTimeout(update, 500);
|
||||
};
|
||||
useEffect(() => {
|
||||
let timer = setTimeout(update, 0);
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{torrents.map((t: Torrent) => {
|
||||
<Fragment key={t.id}>
|
||||
<DeferredTorrent torrent={t} />
|
||||
</Fragment>
|
||||
})}
|
||||
</>
|
||||
)
|
||||
};
|
||||
|
||||
// Render function to display all torrents
|
||||
async function displayTorrents() {
|
||||
// Get the torrents container
|
||||
const torrentsContainer = document.getElementById('output');
|
||||
render(<Root />, torrentsContainer);
|
||||
}
|
||||
|
||||
// Function to update HTML for a torrent row
|
||||
function updateTorrentRow(torrentRow: HTMLDivElement, detailsResponse: TorrentDetails, statsResponse: TorrentStats) {
|
||||
// Calculate download percentage
|
||||
const totalBytes = statsResponse.snapshot.total_bytes;
|
||||
const downloadedBytes = statsResponse.snapshot.have_bytes;
|
||||
const downloadPercentage = (downloadedBytes / totalBytes) * 100;
|
||||
|
||||
// Display basic information about the torrent
|
||||
const largestFileName = getLargestFileName(detailsResponse);
|
||||
const downloadSpeed = statsResponse.download_speed.human_readable;
|
||||
const eta = getCompletionETA(statsResponse);
|
||||
const peers = `${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`;
|
||||
|
||||
// Update or create columns in the torrent row
|
||||
updateOrCreateColumnContent(torrentRow, 'Name', largestFileName);
|
||||
updateOrCreateColumnContent(torrentRow, 'Size', `${formatBytesToGB(totalBytes)} GB`);
|
||||
updateOrCreateColumnWithProgressBar(torrentRow, 'Progress', downloadPercentage);
|
||||
updateOrCreateColumnContent(torrentRow, 'Download Speed', downloadSpeed);
|
||||
updateOrCreateColumnContent(torrentRow, 'ETA', eta);
|
||||
updateOrCreateColumnContent(torrentRow, 'Peers', peers);
|
||||
}
|
||||
|
||||
// Function to update or create the content of a column in a torrent row
|
||||
function updateOrCreateColumnContent(torrentRow: HTMLDivElement, human_label: string, value: string) {
|
||||
let label = human_label.toLowerCase().replace(" ", "-");
|
||||
let column = torrentRow.querySelector(`.column-${label}`);
|
||||
|
||||
// If the column doesn't exist, create a new one
|
||||
if (!column) {
|
||||
column = document.createElement('div');
|
||||
column.classList.add(`column-${label}`, 'me-3', 'p-2');
|
||||
torrentRow.appendChild(column);
|
||||
}
|
||||
|
||||
// Update the content of the existing or newly created column
|
||||
const contentParagraph = column.querySelector('p:last-child');
|
||||
if (contentParagraph) {
|
||||
contentParagraph.textContent = value;
|
||||
} else {
|
||||
column.innerHTML = `<p class="font-weight-bold">${human_label}</p><p>${value}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Function to update or create the content of a progress bar column in a torrent row
|
||||
function updateOrCreateColumnWithProgressBar(torrentRow: HTMLDivElement, label: string, percentage: number) {
|
||||
let column = torrentRow.querySelector('.column-progress');
|
||||
|
||||
// If the column doesn't exist, create a new one
|
||||
if (!column) {
|
||||
column = document.createElement('div');
|
||||
column.classList.add('column-progress', 'me-3', 'p-2');
|
||||
torrentRow.appendChild(column);
|
||||
}
|
||||
|
||||
// Update the value of the progress bar in the existing or newly created column
|
||||
const progressBar = column.querySelector('.progress-bar') as HTMLElement;
|
||||
const progressPercentage = column.querySelector('p:last-child') as HTMLElement;
|
||||
|
||||
if (progressBar && progressPercentage) {
|
||||
progressBar.style.width = `${percentage}%`;
|
||||
progressPercentage.textContent = `${percentage.toFixed(2)}%`;
|
||||
} else {
|
||||
column.innerHTML = `
|
||||
<p class="font-weight-bold">${label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" role="progressbar" style="width: ${percentage}%;"></div>
|
||||
</div>
|
||||
<p class="mb-1">${percentage.toFixed(2)}%</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Function to render HTML for a torrent row
|
||||
function renderTorrentRow(torrentsContainer: HTMLElement, torrentId: number, detailsResponse: TorrentDetails, statsResponse: TorrentStats) {
|
||||
// Check if the torrent row already exists
|
||||
let torrentRow = document.getElementById(`torrent-${torrentId}`) as HTMLDivElement;
|
||||
|
||||
// If the torrent row doesn't exist, create a new one
|
||||
if (!torrentRow) {
|
||||
torrentRow = document.createElement('div');
|
||||
torrentRow.id = `torrent-${torrentId}`;
|
||||
torrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
|
||||
torrentsContainer.appendChild(torrentRow);
|
||||
}
|
||||
|
||||
// Update columns in the torrent row
|
||||
updateTorrentRow(torrentRow, detailsResponse, statsResponse);
|
||||
|
||||
return torrentRow;
|
||||
}
|
||||
|
||||
|
||||
// Function to create a column div
|
||||
function createColumn(label: string, value: string, columnClass: string): HTMLDivElement {
|
||||
const columnDiv = document.createElement('div');
|
||||
columnDiv.classList.add(columnClass, 'me-3', 'p-2');
|
||||
columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`;
|
||||
return columnDiv;
|
||||
}
|
||||
|
||||
|
||||
// Function to create a column div with a progress bar
|
||||
function createColumnWithProgressBar(label: string, percentage: number): HTMLDivElement {
|
||||
const columnDiv = document.createElement('div');
|
||||
columnDiv.classList.add('column', 'me-3', 'p-2');
|
||||
columnDiv.innerHTML = `
|
||||
<p class="font-weight-bold">${label}</p>
|
||||
<div class="progress mb-1">
|
||||
<div class="progress-bar" role="progressbar" style="width: ${percentage}%;"></div>
|
||||
</div>
|
||||
<p class="mb-1">${percentage.toFixed(2)}%</p>`;
|
||||
return columnDiv;
|
||||
}
|
||||
|
||||
// Function to format bytes to GB
|
||||
function formatBytesToGB(bytes: number): string {
|
||||
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;
|
||||
}
|
||||
|
||||
// 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';
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to display API errors in an alert
|
||||
function displayApiError(error: ApiError): void {
|
||||
const errorAlert = document.getElementById('error-alert');
|
||||
if (errorAlert) {
|
||||
errorAlert.innerHTML = `
|
||||
<div class="alert alert-danger alert-dismissible fade show" role="alert">
|
||||
<strong>Error ${error.status}:</strong> ${error.statusText}<br>
|
||||
${error.body}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close" onclick="clearErrorAlert()"></button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to clear the error alert
|
||||
function clearErrorAlert(): void {
|
||||
const errorAlert = document.getElementById('error-alert');
|
||||
if (errorAlert) {
|
||||
errorAlert.innerHTML = ''; // Clear the content
|
||||
}
|
||||
}
|
||||
|
||||
// List all torrents on page load and set up auto-refresh
|
||||
async function init(): Promise<void> {
|
||||
console.log('init');
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Add event listeners for buttons
|
||||
document.getElementById('add-magnet-button')?.addEventListener('click', addTorrentFromMagnet);
|
||||
|
||||
// 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);
|
||||
82
crates/librqbit/webui/webui/src/style.css
Normal file
82
crates/librqbit/webui/webui/src/style.css
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
: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;
|
||||
}
|
||||
}
|
||||
20
crates/librqbit/webui/webui/tsconfig.json
Normal file
20
crates/librqbit/webui/webui/tsconfig.json
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"noEmit": true,
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
|
||||
/* Preact Config */
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact",
|
||||
"skipLibCheck": true,
|
||||
"paths": {
|
||||
"react": ["./node_modules/preact/compat/"],
|
||||
"react-dom": ["./node_modules/preact/compat/"]
|
||||
}
|
||||
},
|
||||
"include": ["node_modules/vite/client.d.ts", "**/*"]
|
||||
}
|
||||
10
crates/librqbit/webui/webui/vite.config.ts
Normal file
10
crates/librqbit/webui/webui/vite.config.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import preact from '@preact/preset-vite';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [preact()],
|
||||
server: {
|
||||
port: 3031
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue