This commit is contained in:
Igor Katson 2023-11-20 22:47:12 +00:00
parent 3a171c92e1
commit 994c890be6
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
2 changed files with 94 additions and 85 deletions

View file

@ -1,6 +1,5 @@
// Define API URL and base path // Define API URL and base path
const apiUrl = window.origin == 'null' ? 'http://localhost:3030' : ''; const apiUrl = window.origin == 'null' ? 'http://localhost:3030' : '';
// Helper function for making API requests (async/await) // Helper function for making API requests (async/await)
async function makeRequest(method, path, data) { async function makeRequest(method, path, data) {
const url = apiUrl + path; const url = apiUrl + path;
@ -45,13 +44,6 @@ async function makeRequest(method, path, data) {
return Promise.reject(`Error: ${error.message}`); return Promise.reject(`Error: ${error.message}`);
} }
} }
// Helper function to display the API response
function displayResult(result) {
const outputDiv = document.getElementById('output');
if (outputDiv) {
outputDiv.innerHTML = `<pre>${result}</pre>`;
}
}
// Function to get detailed information about a torrent (async/await) // Function to get detailed information about a torrent (async/await)
async function getTorrentDetails(index) { async function getTorrentDetails(index) {
return makeRequest('GET', `/torrents/${index}`); return makeRequest('GET', `/torrents/${index}`);
@ -65,50 +57,57 @@ async function displayTorrents() {
try { try {
const response = await makeRequest('GET', '/torrents'); const response = await makeRequest('GET', '/torrents');
const torrents = response.torrents; const torrents = response.torrents;
// Create a container for all torrents using Bootstrap classes // Get the torrents container
const torrentsContainer = document.createElement('div'); const torrentsContainer = document.getElementById('output');
torrentsContainer.classList.add('d-flex', 'flex-column', 'torrents-container'); // Array to hold promises for torrent details and stats
for (const torrent of torrents) { const promises = torrents.map(async (torrent) => {
const detailsResponse = await getTorrentDetails(torrent.id); const detailsPromise = getTorrentDetails(torrent.id);
const statsResponse = await getTorrentStats(torrent.id); const statsPromise = getTorrentStats(torrent.id);
const totalBytes = detailsResponse.files.reduce((total, file) => total + file.length, 0); const [detailsResponse, statsResponse] = await Promise.all([detailsPromise, statsPromise]);
const totalBytes = statsResponse.snapshot.total_bytes;
const downloadedBytes = statsResponse.snapshot.have_bytes; const downloadedBytes = statsResponse.snapshot.have_bytes;
// Calculate download percentage // Calculate download percentage
const downloadPercentage = (downloadedBytes / totalBytes) * 100; const downloadPercentage = (downloadedBytes / totalBytes) * 100;
// Create a container for each torrent using Bootstrap classes
const torrentContainer = document.createElement('div');
torrentContainer.classList.add('torrent-container', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
// Display basic information about the torrent // Display basic information about the torrent
const largestFileName = getLargestFileName(detailsResponse); const largestFileName = getLargestFileName(detailsResponse);
const downloadSpeed = statsResponse.download_speed.human_readable; const downloadSpeed = statsResponse.download_speed.human_readable;
const eta = getCompletionETA(statsResponse); const eta = getCompletionETA(statsResponse);
// Create and append divs for concise information as columns const peers = `${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`;
const nameColumn = createColumn('Name', largestFileName); // Check if the torrent row already exists
const sizeColumn = createColumn('Size', `${formatBytesToGB(totalBytes)} GB`); let torrentRow = document.getElementById(`torrent-${torrent.id}`);
const progressColumn = createColumnWithProgressBar('Progress', downloadPercentage); if (!torrentRow) {
const downloadSpeedColumn = createColumn('Download Speed', downloadSpeed); console.log("not found!");
const etaColumn = createColumn('ETA', eta); // If the torrent row doesn't exist, create a new one
// Append columns to the torrent container torrentRow = document.createElement('div');
torrentContainer.appendChild(nameColumn); torrentRow.id = `torrent-${torrent.id}`;
torrentContainer.appendChild(sizeColumn); torrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
torrentContainer.appendChild(progressColumn); // Append the new torrent row to the torrentsContainer
torrentContainer.appendChild(downloadSpeedColumn); torrentsContainer.appendChild(torrentRow);
torrentContainer.appendChild(etaColumn); }
// Append the torrent container to the torrentsContainer // Create a detached element to replace torrentRow.innerHTML atomically
torrentsContainer.appendChild(torrentContainer); const newTorrentRow = document.createElement('div');
} newTorrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
// Replace the old content with the new one newTorrentRow.appendChild(createColumn('Name', largestFileName, 'name-column'));
const outputDiv = document.getElementById('output'); newTorrentRow.appendChild(createColumn('Size', `${formatBytesToGB(totalBytes)} GB`, 'size-column'));
outputDiv.replaceChildren(torrentsContainer); newTorrentRow.appendChild(createColumnWithProgressBar('Progress', downloadPercentage));
newTorrentRow.appendChild(createColumn('Download Speed', downloadSpeed, 'download-speed-column'));
newTorrentRow.appendChild(createColumn('ETA', eta, 'eta-column'));
newTorrentRow.appendChild(createColumn('Peers', peers, 'peers-column'));
// Replace torrentRow.innerHTML with the new content
torrentRow.replaceChildren(newTorrentRow);
});
// Wait for all promises to resolve
await Promise.all(promises);
} }
catch (error) { catch (error) {
console.error(error); console.error(error);
// Handle errors as needed
} }
} }
// Function to create a column div // Function to create a column div
function createColumn(label, value) { function createColumn(label, value, columnClass) {
const columnDiv = document.createElement('div'); const columnDiv = document.createElement('div');
columnDiv.classList.add('me-3', 'p-2'); columnDiv.classList.add(columnClass, 'me-3', 'p-2');
columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`; columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`;
return columnDiv; return columnDiv;
} }

View file

@ -20,17 +20,41 @@ interface TorrentDetails {
interface TorrentStats { interface TorrentStats {
snapshot: { snapshot: {
have_bytes: number; 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; 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: { download_speed: {
mbps: number; mbps: number;
human_readable: string; human_readable: string;
}; };
time_remaining?: { all_time_download_speed: {
mbps: number;
human_readable: string; human_readable: string;
}; };
time_remaining: {
human_readable: string;
} | null;
} }
// Interface for the API error response // Interface for the API error response
interface ApiError { interface ApiError {
status: number; status: number;
@ -82,14 +106,6 @@ async function makeRequest(method: string, path: string, data?: any): Promise<an
} }
} }
// Helper function to display the API response
function displayResult(result: string): void {
const outputDiv = document.getElementById('output');
if (outputDiv) {
outputDiv.innerHTML = `<pre>${result}</pre>`;
}
}
// Function to get detailed information about a torrent (async/await) // Function to get detailed information about a torrent (async/await)
async function getTorrentDetails(index: number): Promise<TorrentDetails> { async function getTorrentDetails(index: number): Promise<TorrentDetails> {
return makeRequest('GET', `/torrents/${index}`); return makeRequest('GET', `/torrents/${index}`);
@ -106,13 +122,8 @@ async function displayTorrents() {
const response = await makeRequest('GET', '/torrents'); const response = await makeRequest('GET', '/torrents');
const torrents = response.torrents; const torrents = response.torrents;
// Create a container for all torrents using Bootstrap classes // Get the torrents container
const torrentsContainer = document.createElement('div'); const torrentsContainer = document.getElementById('output');
torrentsContainer.id = 'torrents-container';
torrentsContainer.classList.add('d-flex', 'flex-column', 'torrents-container');
// Map to store existing elements
const existingElementsMap = new Map();
// Array to hold promises for torrent details and stats // Array to hold promises for torrent details and stats
const promises = torrents.map(async (torrent) => { const promises = torrents.map(async (torrent) => {
@ -120,64 +131,63 @@ async function displayTorrents() {
const statsPromise = getTorrentStats(torrent.id); const statsPromise = getTorrentStats(torrent.id);
const [detailsResponse, statsResponse] = await Promise.all([detailsPromise, statsPromise]); const [detailsResponse, statsResponse] = await Promise.all([detailsPromise, statsPromise]);
const totalBytes = detailsResponse.files.reduce((total, file) => total + file.length, 0); const totalBytes = statsResponse.snapshot.total_bytes;
const downloadedBytes = statsResponse.snapshot.have_bytes; const downloadedBytes = statsResponse.snapshot.have_bytes;
// Calculate download percentage // Calculate download percentage
const downloadPercentage = (downloadedBytes / totalBytes) * 100; const downloadPercentage = (downloadedBytes / totalBytes) * 100;
// Check if the torrent container already exists
let torrentContainer = existingElementsMap.get(torrent.id);
if (!torrentContainer) {
torrentContainer = document.createElement('div');
torrentContainer.id = `torrent-${torrent.id}`;
torrentContainer.classList.add('torrent-container', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
existingElementsMap.set(torrent.id, torrentContainer);
}
// Display basic information about the torrent // Display basic information about the torrent
const largestFileName = getLargestFileName(detailsResponse); const largestFileName = getLargestFileName(detailsResponse);
const downloadSpeed = statsResponse.download_speed.human_readable; const downloadSpeed = statsResponse.download_speed.human_readable;
const eta = getCompletionETA(statsResponse); const eta = getCompletionETA(statsResponse);
const peers = `${statsResponse.snapshot.peer_stats.live} / ${statsResponse.snapshot.peer_stats.seen}`;
// Update or append columns to the torrent container // Check if the torrent row already exists
torrentContainer.innerHTML = ''; // Clear existing content let torrentRow = document.getElementById(`torrent-${torrent.id}`);
torrentContainer.appendChild(createColumn('Name', largestFileName, 'name-column'));
torrentContainer.appendChild(createColumn('Size', `${formatBytesToGB(totalBytes)} GB`, 'size-column'));
torrentContainer.appendChild(createColumnWithProgressBar('Progress', downloadPercentage, 'progress-column'));
torrentContainer.appendChild(createColumn('Download Speed', downloadSpeed, 'download-speed-column'));
torrentContainer.appendChild(createColumn('ETA', eta, 'eta-column'));
// Append the torrent container to the torrentsContainer if (!torrentRow) {
torrentsContainer.appendChild(torrentContainer); console.log("not found!");
// If the torrent row doesn't exist, create a new one
torrentRow = document.createElement('div');
torrentRow.id = `torrent-${torrent.id}`;
torrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
// Append the new torrent row to the torrentsContainer
torrentsContainer.appendChild(torrentRow);
}
// Create a detached element to replace torrentRow.innerHTML atomically
const newTorrentRow = document.createElement('div');
newTorrentRow.classList.add('torrent-row', 'd-flex', 'flex-row', 'p-3', 'bg-light', 'rounded', 'mb-3');
newTorrentRow.appendChild(createColumn('Name', largestFileName, 'name-column'));
newTorrentRow.appendChild(createColumn('Size', `${formatBytesToGB(totalBytes)} GB`, 'size-column'));
newTorrentRow.appendChild(createColumnWithProgressBar('Progress', downloadPercentage,));
newTorrentRow.appendChild(createColumn('Download Speed', downloadSpeed, 'download-speed-column'));
newTorrentRow.appendChild(createColumn('ETA', eta, 'eta-column'));
newTorrentRow.appendChild(createColumn('Peers', peers, 'peers-column'));
// Replace torrentRow.innerHTML with the new content
torrentRow.replaceChildren(newTorrentRow);
}); });
// Replace the old content with loading spinners
const outputDiv = document.getElementById('output') || document.createElement('div');
outputDiv.id = 'output';
outputDiv.innerHTML = `<div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div>`;
// Wait for all promises to resolve // Wait for all promises to resolve
await Promise.all(promises); await Promise.all(promises);
// Replace the loading spinners with the new content
outputDiv.replaceChildren(torrentsContainer);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
// Handle errors as needed // Handle errors as needed
} }
} }
// Function to create a column div // Function to create a column div
function createColumn(label: string, value: string): HTMLDivElement { function createColumn(label: string, value: string, columnClass: string): HTMLDivElement {
const columnDiv = document.createElement('div'); const columnDiv = document.createElement('div');
columnDiv.classList.add('me-3', 'p-2'); columnDiv.classList.add(columnClass, 'me-3', 'p-2');
columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`; columnDiv.innerHTML = `<p class="font-weight-bold">${label}</p><p>${value}</p>`;
return columnDiv; return columnDiv;
} }
// Function to create a column div with a progress bar // Function to create a column div with a progress bar
function createColumnWithProgressBar(label: string, percentage: number): HTMLDivElement { function createColumnWithProgressBar(label: string, percentage: number): HTMLDivElement {
const columnDiv = document.createElement('div'); const columnDiv = document.createElement('div');