setup vscode for consistent JS formatting

This commit is contained in:
Igor Katson 2023-12-07 14:11:12 +00:00
parent a641717245
commit ec63e1cef7
No known key found for this signature in database
GPG key ID: B4EC22B66D61A3F5
15 changed files with 1675 additions and 1338 deletions

6
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,6 @@
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}

View file

@ -1,21 +1,27 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>rqbit web 4.0.0-beta.0</title>
<link rel="icon" type="image/svg+xml" href="assets/logo.svg" />
<!-- Include Bootstrap CSS -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css"
integrity="sha384-4LISF5TTJX/fLmGSxO53rV4miRxdg84mZsxmO8Rx5jGtp/LbrixFETvWa5a6sESd"
crossorigin="anonymous"
/>
</head>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>rqbit web 4.0.0-beta.0</title>
<link rel="icon" type="image/svg+xml" href="assets/logo.svg">
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css"
integrity="sha384-4LISF5TTJX/fLmGSxO53rV4miRxdg84mZsxmO8Rx5jGtp/LbrixFETvWa5a6sESd" crossorigin="anonymous">
</head>
<body>
<div id="app"></div>
<script type="module" src="src/main.tsx"></script>
</body>
</html>
<body>
<div id="app"></div>
<script type="module" src="src/main.tsx"></script>
</body>
</html>

View file

@ -304,6 +304,21 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/prettier": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.1.0.tgz",
"integrity": "sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw==",
"dev": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",

View file

@ -12,6 +12,7 @@
"devDependencies": {
"@types/react": "^18.2.38",
"@types/react-dom": "^18.2.16",
"prettier": "3.1.0",
"typescript": "^5.3.2",
"vite": "^4.5.1"
}
@ -653,6 +654,21 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/prettier": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.1.0.tgz",
"integrity": "sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw==",
"dev": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",

View file

@ -14,7 +14,8 @@
"devDependencies": {
"@types/react": "^18.2.38",
"@types/react-dom": "^18.2.16",
"prettier": "3.1.0",
"typescript": "^5.3.2",
"vite": "^4.5.1"
}
}
}

View file

@ -1,131 +1,132 @@
// Interface for the Torrent API response
export interface TorrentId {
id: number;
info_hash: string;
id: number;
info_hash: string;
}
export interface TorrentFile {
name: string;
length: number;
included: boolean;
name: string;
length: number;
included: boolean;
}
// Interface for the Torrent Details API response
export interface TorrentDetails {
info_hash: string,
files: Array<TorrentFile>;
info_hash: string;
files: Array<TorrentFile>;
}
export interface AddTorrentResponse {
id: number | null;
details: TorrentDetails;
output_folder: string,
seen_peers?: Array<string>;
id: number | null;
details: TorrentDetails;
output_folder: string;
seen_peers?: Array<string>;
}
export interface ListTorrentsResponse {
torrents: Array<TorrentId>;
torrents: Array<TorrentId>;
}
export interface Speed {
mbps: number;
human_readable: string;
mbps: number;
human_readable: string;
}
// Interface for the Torrent Stats API response
export interface LiveTorrentStats {
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;
};
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;
};
average_piece_download_time: {
secs: number;
nanos: number;
};
download_speed: Speed;
upload_speed: Speed;
all_time_download_speed: {
mbps: number;
human_readable: string;
};
time_remaining: {
human_readable: string;
duration?: {
secs: number;
};
download_speed: Speed;
upload_speed: Speed;
all_time_download_speed: {
mbps: number;
human_readable: string;
};
time_remaining: {
human_readable: string;
duration?: {
secs: number,
}
} | null;
} | null;
}
export const STATE_INITIALIZING = 'initializing';
export const STATE_PAUSED = 'paused';
export const STATE_LIVE = 'live';
export const STATE_ERROR = 'error';
export const STATE_INITIALIZING = "initializing";
export const STATE_PAUSED = "paused";
export const STATE_LIVE = "live";
export const STATE_ERROR = "error";
export interface TorrentStats {
state: 'initializing' | 'paused' | 'live' | 'error',
error: string | null,
progress_bytes: number,
finished: boolean,
total_bytes: number,
live: LiveTorrentStats | null;
state: "initializing" | "paused" | "live" | "error";
error: string | null;
progress_bytes: number;
finished: boolean;
total_bytes: number;
live: LiveTorrentStats | null;
}
export interface ErrorDetails {
id?: number,
method?: string,
path?: string,
status?: number,
statusText?: string,
text: string,
};
id?: number;
method?: string;
path?: string;
status?: number;
statusText?: string;
text: string;
}
export type Duration = number;
export interface PeerConnectionOptions {
connect_timeout?: Duration | null;
read_write_timeout?: Duration | null;
keep_alive_interval?: Duration | null;
connect_timeout?: Duration | null;
read_write_timeout?: Duration | null;
keep_alive_interval?: Duration | null;
}
export interface AddTorrentOptions {
paused?: boolean;
only_files_regex?: string | null;
only_files?: number[] | null;
overwrite?: boolean;
list_only?: boolean;
output_folder?: string | null;
sub_folder?: string | null;
peer_opts?: PeerConnectionOptions | null;
force_tracker_interval?: Duration | null;
initial_peers?: string[] | null; // Assuming SocketAddr is equivalent to a string in TypeScript
preferred_id?: number | null;
paused?: boolean;
only_files_regex?: string | null;
only_files?: number[] | null;
overwrite?: boolean;
list_only?: boolean;
output_folder?: string | null;
sub_folder?: string | null;
peer_opts?: PeerConnectionOptions | null;
force_tracker_interval?: Duration | null;
initial_peers?: string[] | null; // Assuming SocketAddr is equivalent to a string in TypeScript
preferred_id?: number | null;
}
export interface RqbitAPI {
listTorrents: () => Promise<ListTorrentsResponse>,
getTorrentDetails: (index: number) => Promise<TorrentDetails>,
getTorrentStats: (index: number) => Promise<TorrentStats>;
uploadTorrent: (data: string | File, opts?: AddTorrentOptions) => Promise<AddTorrentResponse>;
listTorrents: () => Promise<ListTorrentsResponse>;
getTorrentDetails: (index: number) => Promise<TorrentDetails>;
getTorrentStats: (index: number) => Promise<TorrentStats>;
uploadTorrent: (
data: string | File,
opts?: AddTorrentOptions
) => Promise<AddTorrentResponse>;
pause: (index: number) => Promise<void>;
start: (index: number) => Promise<void>;
forget: (index: number) => Promise<void>;
delete: (index: number) => Promise<void>;
}
pause: (index: number) => Promise<void>;
start: (index: number) => Promise<void>;
forget: (index: number) => Promise<void>;
delete: (index: number) => Promise<void>;
}

View file

@ -1,103 +1,121 @@
import { AddTorrentResponse, ErrorDetails, ListTorrentsResponse, RqbitAPI, TorrentDetails, TorrentStats } from "./api-types";
import {
AddTorrentResponse,
ErrorDetails,
ListTorrentsResponse,
RqbitAPI,
TorrentDetails,
TorrentStats,
} from "./api-types";
// Define API URL and base path
const apiUrl = (window.origin === 'null' || window.origin === 'http://localhost:3031') ? 'http://localhost:3030' : '';
const apiUrl =
window.origin === "null" || window.origin === "http://localhost:3031"
? "http://localhost:3030"
: "";
const makeRequest = async (method: string, path: string, data?: any): Promise<any> => {
console.log(method, path);
const url = apiUrl + path;
const options: RequestInit = {
method,
headers: {
'Accept': 'application/json',
},
body: data,
};
const makeRequest = async (
method: string,
path: string,
data?: any
): Promise<any> => {
console.log(method, path);
const url = apiUrl + path;
const options: RequestInit = {
method,
headers: {
Accept: "application/json",
},
body: data,
};
let error: ErrorDetails = {
method: method,
path: path,
text: ''
};
let error: ErrorDetails = {
method: method,
path: path,
text: "",
};
let response: Response;
let response: Response;
try {
response = await fetch(url, options);
} catch (e) {
error.text = "network error";
return Promise.reject(error);
}
error.status = response.status;
error.statusText = `${response.status} ${response.statusText}`;
if (!response.ok) {
const errorBody = await response.text();
try {
response = await fetch(url, options);
const json = JSON.parse(errorBody);
error.text =
json.human_readable !== undefined
? json.human_readable
: JSON.stringify(json, null, 2);
} catch (e) {
error.text = 'network error';
return Promise.reject(error);
error.text = errorBody;
}
error.status = response.status;
error.statusText = `${response.status} ${response.statusText}`;
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;
}
return Promise.reject(error);
}
const result = await response.json();
return result;
}
return Promise.reject(error);
}
const result = await response.json();
return result;
};
export const API: RqbitAPI & { getVersion: () => Promise<string> } = {
listTorrents: (): Promise<ListTorrentsResponse> => makeRequest('GET', '/torrents'),
getTorrentDetails: (index: number): Promise<TorrentDetails> => {
return makeRequest('GET', `/torrents/${index}`);
},
getTorrentStats: (index: number): Promise<TorrentStats> => {
return makeRequest('GET', `/torrents/${index}/stats/v1`);
},
listTorrents: (): Promise<ListTorrentsResponse> =>
makeRequest("GET", "/torrents"),
getTorrentDetails: (index: number): Promise<TorrentDetails> => {
return makeRequest("GET", `/torrents/${index}`);
},
getTorrentStats: (index: number): Promise<TorrentStats> => {
return makeRequest("GET", `/torrents/${index}/stats/v1`);
},
uploadTorrent: (data, opts): Promise<AddTorrentResponse> => {
let url = '/torrents?&overwrite=true';
if (opts?.list_only) {
url += '&list_only=true';
}
if (opts?.only_files != null) {
url += `&only_files=${opts.only_files.join(',')}`;
}
if (opts?.peer_opts?.connect_timeout) {
url += `&peer_connect_timeout=${opts.peer_opts.connect_timeout}`;
}
if (opts?.peer_opts?.read_write_timeout) {
url += `&peer_read_write_timeout=${opts.peer_opts.read_write_timeout}`;
}
if (opts?.initial_peers) {
url += `&initial_peers=${opts.initial_peers.join(',')}`;
}
if (opts?.output_folder) {
url += `&output_folder=${opts.output_folder}`;
}
if (typeof data === 'string') {
url += '&is_url=true';
}
return makeRequest('POST', url, data)
},
pause: (index: number): Promise<void> => {
return makeRequest('POST', `/torrents/${index}/pause`);
},
start: (index: number): Promise<void> => {
return makeRequest('POST', `/torrents/${index}/start`);
},
forget: (index: number): Promise<void> => {
return makeRequest('POST', `/torrents/${index}/forget`);
},
delete: (index: number): Promise<void> => {
return makeRequest('POST', `/torrents/${index}/delete`);
},
getVersion: async (): Promise<string> => {
const r = await makeRequest('GET', '/');
return r.version;
uploadTorrent: (data, opts): Promise<AddTorrentResponse> => {
let url = "/torrents?&overwrite=true";
if (opts?.list_only) {
url += "&list_only=true";
}
}
if (opts?.only_files != null) {
url += `&only_files=${opts.only_files.join(",")}`;
}
if (opts?.peer_opts?.connect_timeout) {
url += `&peer_connect_timeout=${opts.peer_opts.connect_timeout}`;
}
if (opts?.peer_opts?.read_write_timeout) {
url += `&peer_read_write_timeout=${opts.peer_opts.read_write_timeout}`;
}
if (opts?.initial_peers) {
url += `&initial_peers=${opts.initial_peers.join(",")}`;
}
if (opts?.output_folder) {
url += `&output_folder=${opts.output_folder}`;
}
if (typeof data === "string") {
url += "&is_url=true";
}
return makeRequest("POST", url, data);
},
pause: (index: number): Promise<void> => {
return makeRequest("POST", `/torrents/${index}/pause`);
},
start: (index: number): Promise<void> => {
return makeRequest("POST", `/torrents/${index}/start`);
},
forget: (index: number): Promise<void> => {
return makeRequest("POST", `/torrents/${index}/forget`);
},
delete: (index: number): Promise<void> => {
return makeRequest("POST", `/torrents/${index}/delete`);
},
getVersion: async (): Promise<string> => {
const r = await makeRequest("GET", "/");
return r.version;
},
};

View file

@ -1,27 +1,33 @@
import { StrictMode, useEffect, useState } from "react";
import ReactDOM from 'react-dom/client';
import ReactDOM from "react-dom/client";
import { RqbitWebUI, APIContext, customSetInterval } from "./rqbit-web";
import { API } from "./http-api";
const RootWithVersion = () => {
let [title, setTitle] = useState<string>("rqbit web UI");
useEffect(() => {
const refreshVersion = () => API.getVersion().then((version) => {
setTitle(`rqbit web UI - v${version}`);
return 10000;
}, (e) => {
return 1000;
});
return customSetInterval(refreshVersion, 0)
}, [])
let [title, setTitle] = useState<string>("rqbit web UI");
useEffect(() => {
const refreshVersion = () =>
API.getVersion().then(
(version) => {
setTitle(`rqbit web UI - v${version}`);
return 10000;
},
(e) => {
return 1000;
}
);
return customSetInterval(refreshVersion, 0);
}, []);
return <StrictMode>
<APIContext.Provider value={API}>
<RqbitWebUI title={title} />
</APIContext.Provider>
</StrictMode>;
}
return (
<StrictMode>
<APIContext.Provider value={API}>
<RqbitWebUI title={title} />
</APIContext.Provider>
</StrictMode>
);
};
ReactDOM.createRoot(document.getElementById('app') as HTMLInputElement).render(
<RootWithVersion />
ReactDOM.createRoot(document.getElementById("app") as HTMLInputElement).render(
<RootWithVersion />
);

File diff suppressed because it is too large Load diff

View file

@ -1,19 +1,17 @@
<!doctype html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>rqbit web 4.0.0-beta.0</title>
<link rel="icon" type="image/svg+xml" href="assets/logo.svg" />
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="/src/styles/bootstrap.min.css" />
<link rel="stylesheet" href="/src/styles/bootstrap-icons.css" />
</head>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>rqbit web 4.0.0-beta.0</title>
<link rel="icon" type="image/svg+xml" href="assets/logo.svg">
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="/src/styles/bootstrap.min.css" />
<link rel="stylesheet" href="/src/styles/bootstrap-icons.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View file

@ -1,90 +1,107 @@
import { AddTorrentResponse, ListTorrentsResponse, RqbitAPI, TorrentDetails, TorrentStats, ErrorDetails } from "./rqbit-webui-src/api-types";
import {
AddTorrentResponse,
ListTorrentsResponse,
RqbitAPI,
TorrentDetails,
TorrentStats,
ErrorDetails,
} from "./rqbit-webui-src/api-types";
import { InvokeArgs, invoke } from "@tauri-apps/api/tauri"
import { InvokeArgs, invoke } from "@tauri-apps/api/tauri";
interface InvokeErrorResponse {
error_kind: string,
human_readable: string,
status: number,
status_text: string,
error_kind: string;
human_readable: string;
status: number;
status_text: string;
}
function errorToUIError(path: string): (e: InvokeErrorResponse) => Promise<never> {
return (e: InvokeErrorResponse) => {
console.log(e);
let reason: ErrorDetails = {
method: 'INVOKE',
path: path,
text: e.human_readable,
status: e.status,
statusText: e.status_text
};
return Promise.reject(reason);
}
function errorToUIError(
path: string
): (e: InvokeErrorResponse) => Promise<never> {
return (e: InvokeErrorResponse) => {
console.log(e);
let reason: ErrorDetails = {
method: "INVOKE",
path: path,
text: e.human_readable,
status: e.status,
statusText: e.status_text,
};
return Promise.reject(reason);
};
}
export async function invokeAPI<Response>(name: string, params?: InvokeArgs): Promise<Response> {
console.log("invoking", name, params);
const result = await invoke<Response>(name, params).catch(errorToUIError(name));
console.log(result);
return result;
export async function invokeAPI<Response>(
name: string,
params?: InvokeArgs
): Promise<Response> {
console.log("invoking", name, params);
const result = await invoke<Response>(name, params).catch(
errorToUIError(name)
);
console.log(result);
return result;
}
async function readFileAsBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function (event) {
const base64String = (event?.target?.result as string)?.split(',')[1];
if (base64String) {
resolve(base64String);
} else {
reject(new Error('Failed to read file as base64.'));
}
};
reader.onload = function (event) {
const base64String = (event?.target?.result as string)?.split(",")[1];
if (base64String) {
resolve(base64String);
} else {
reject(new Error("Failed to read file as base64."));
}
};
reader.onerror = function (error) {
console.log(error);
reject(error);
};
reader.onerror = function (error) {
console.log(error);
reject(error);
};
reader.readAsDataURL(file);
});
reader.readAsDataURL(file);
});
}
export const API: RqbitAPI = {
listTorrents: async function (): Promise<ListTorrentsResponse> {
return await invokeAPI<ListTorrentsResponse>("torrents_list");
},
getTorrentDetails: async function (id: number): Promise<TorrentDetails> {
return await invokeAPI<TorrentDetails>("torrent_details", { id });
},
getTorrentStats: async function (id: number): Promise<TorrentStats> {
return await invokeAPI<TorrentStats>("torrent_stats", { id });
},
uploadTorrent: async function (data, opts): Promise<AddTorrentResponse> {
if (data instanceof File) {
let contents = await readFileAsBase64(data);
return await invokeAPI<AddTorrentResponse>("torrent_create_from_base64_file", {
contents,
opts: opts ?? {},
});
listTorrents: async function (): Promise<ListTorrentsResponse> {
return await invokeAPI<ListTorrentsResponse>("torrents_list");
},
getTorrentDetails: async function (id: number): Promise<TorrentDetails> {
return await invokeAPI<TorrentDetails>("torrent_details", { id });
},
getTorrentStats: async function (id: number): Promise<TorrentStats> {
return await invokeAPI<TorrentStats>("torrent_stats", { id });
},
uploadTorrent: async function (data, opts): Promise<AddTorrentResponse> {
if (data instanceof File) {
let contents = await readFileAsBase64(data);
return await invokeAPI<AddTorrentResponse>(
"torrent_create_from_base64_file",
{
contents,
opts: opts ?? {},
}
return await invokeAPI<AddTorrentResponse>("torrent_create_from_url", {
url: data,
opts: opts ?? {},
});
},
pause: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_pause", { id });
},
start: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_start", { id });
},
forget: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_forget", { id });
},
delete: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_delete", { id });
);
}
}
return await invokeAPI<AddTorrentResponse>("torrent_create_from_url", {
url: data,
opts: opts ?? {},
});
},
pause: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_pause", { id });
},
start: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_start", { id });
},
forget: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_forget", { id });
},
delete: function (id: number): Promise<void> {
return invokeAPI<void>("torrent_action_delete", { id });
},
};

View file

@ -3,48 +3,48 @@ type Duration = string;
type SocketAddr = string;
interface RqbitDesktopConfigDht {
disable: boolean;
disable_persistence: boolean;
persistence_filename: PathLike;
disable: boolean;
disable_persistence: boolean;
persistence_filename: PathLike;
}
interface RqbitDesktopConfigTcpListen {
disable: boolean;
min_port: number;
max_port: number;
disable: boolean;
min_port: number;
max_port: number;
}
interface RqbitDesktopConfigPersistence {
disable: boolean;
filename: PathLike;
disable: boolean;
filename: PathLike;
}
interface RqbitDesktopConfigPeerOpts {
connect_timeout: Duration;
read_write_timeout: Duration;
connect_timeout: Duration;
read_write_timeout: Duration;
}
interface RqbitDesktopConfigHttpApi {
disable: boolean;
listen_addr: SocketAddr;
read_only: boolean;
disable: boolean;
listen_addr: SocketAddr;
read_only: boolean;
}
interface RqbitDesktopConfigUpnp {
disable: boolean;
disable: boolean;
}
export interface RqbitDesktopConfig {
default_download_location: PathLike;
dht: RqbitDesktopConfigDht;
tcp_listen: RqbitDesktopConfigTcpListen;
upnp: RqbitDesktopConfigUpnp;
persistence: RqbitDesktopConfigPersistence;
peer_opts: RqbitDesktopConfigPeerOpts;
http_api: RqbitDesktopConfigHttpApi;
default_download_location: PathLike;
dht: RqbitDesktopConfigDht;
tcp_listen: RqbitDesktopConfigTcpListen;
upnp: RqbitDesktopConfigUpnp;
persistence: RqbitDesktopConfigPersistence;
peer_opts: RqbitDesktopConfigPeerOpts;
http_api: RqbitDesktopConfigHttpApi;
}
export interface CurrentDesktopState {
config: RqbitDesktopConfig | null,
configured: boolean,
}
config: RqbitDesktopConfig | null;
configured: boolean;
}

View file

@ -6,310 +6,314 @@ import { invokeAPI } from "./api";
import { ErrorDetails } from "./rqbit-webui-src/api-types";
const FormCheck: React.FC<{
label: string,
name: string,
checked: boolean,
onChange: (e: any) => void,
disabled?: boolean,
help?: string,
label: string;
name: string;
checked: boolean;
onChange: (e: any) => void;
disabled?: boolean;
help?: string;
}> = ({ label, name, checked, onChange, disabled, help }) => {
return <Form.Group as={Row} controlId={name} className="mb-3">
<Form.Label className="col-4">{label}</Form.Label>
<div className="col-8">
<Form.Check
type="switch"
name={name}
checked={checked}
onChange={onChange}
disabled={disabled}
/>
</div>
{help && <div className="form-text">{help}</div>}
return (
<Form.Group as={Row} controlId={name} className="mb-3">
<Form.Label className="col-4">{label}</Form.Label>
<div className="col-8">
<Form.Check
type="switch"
name={name}
checked={checked}
onChange={onChange}
disabled={disabled}
/>
</div>
{help && <div className="form-text">{help}</div>}
</Form.Group>
}
);
};
const FormInput: React.FC<{
label: string,
name: string,
value: string | number,
inputType: string,
onChange: (e: any) => void,
disabled?: boolean,
help?: string
label: string;
name: string;
value: string | number;
inputType: string;
onChange: (e: any) => void;
disabled?: boolean;
help?: string;
}> = ({ label, name, value, inputType, onChange, disabled, help }) => {
return <Form.Group as={Row} controlId={name} className="mb-3">
<Form.Label className="col-4 col-form-label">{label}</Form.Label>
<div className="col-8">
<Form.Control
type={inputType}
name={name}
value={value}
onChange={onChange}
disabled={disabled}
/>
</div>
{help && <div className="form-text">{help}</div>}
return (
<Form.Group as={Row} controlId={name} className="mb-3">
<Form.Label className="col-4 col-form-label">{label}</Form.Label>
<div className="col-8">
<Form.Control
type={inputType}
name={name}
value={value}
onChange={onChange}
disabled={disabled}
/>
</div>
{help && <div className="form-text">{help}</div>}
</Form.Group>
}
);
};
export const ConfigModal: React.FC<{
show: boolean,
handleStartReconfigure: () => void,
handleConfigured: (config: RqbitDesktopConfig) => void,
handleCancel?: () => void,
initialConfig: RqbitDesktopConfig,
defaultConfig: RqbitDesktopConfig,
}> = ({ show, handleStartReconfigure, handleConfigured, handleCancel, initialConfig, defaultConfig }) => {
let [config, setConfig] = useState<RqbitDesktopConfig>(initialConfig);
let [loading, setLoading] = useState<boolean>(false);
show: boolean;
handleStartReconfigure: () => void;
handleConfigured: (config: RqbitDesktopConfig) => void;
handleCancel?: () => void;
initialConfig: RqbitDesktopConfig;
defaultConfig: RqbitDesktopConfig;
}> = ({
show,
handleStartReconfigure,
handleConfigured,
handleCancel,
initialConfig,
defaultConfig,
}) => {
let [config, setConfig] = useState<RqbitDesktopConfig>(initialConfig);
let [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<any | null>(null);
const [error, setError] = useState<any | null>(null);
const handleInputChange = (e: any) => {
const name: string = e.target.name;
const value: any = e.target.value;
const [mainField, subField] = name.split('.', 2);
const handleInputChange = (e: any) => {
const name: string = e.target.name;
const value: any = e.target.value;
const [mainField, subField] = name.split(".", 2);
if (subField) {
setConfig((prevConfig: any) => ({
...prevConfig,
[mainField]: {
...prevConfig[mainField],
[subField]: value,
},
}));
} else {
setConfig((prevConfig) => ({
...prevConfig,
[name]: value,
}));
}
};
if (subField) {
setConfig((prevConfig: any) => ({
...prevConfig,
[mainField]: {
...prevConfig[mainField],
[subField]: value,
},
}));
} else {
setConfig((prevConfig) => ({
...prevConfig,
[name]: value,
}));
}
};
const handleToggleChange = (e: any) => {
const name: string = e.target.name;
const [mainField, subField] = name.split('.', 2);
const handleToggleChange = (e: any) => {
const name: string = e.target.name;
const [mainField, subField] = name.split(".", 2);
if (subField) {
setConfig((prevConfig: any) => ({
...prevConfig,
[mainField]: {
...prevConfig[mainField],
[subField]: !prevConfig[mainField][subField],
},
}));
} else {
setConfig((prevConfig: any) => ({
...prevConfig,
[name]: !prevConfig[name],
}));
}
};
if (subField) {
setConfig((prevConfig: any) => ({
...prevConfig,
[mainField]: {
...prevConfig[mainField],
[subField]: !prevConfig[mainField][subField],
},
}));
} else {
setConfig((prevConfig: any) => ({
...prevConfig,
[name]: !prevConfig[name],
}));
}
};
const handleOkClick = () => {
setError(null);
handleStartReconfigure();
setLoading(true);
invokeAPI<{}>("config_change", { config }).then(
() => {
setLoading(false);
handleConfigured(config);
},
(e: ErrorDetails) => {
setLoading(false);
setError({
text: "Error saving configuration",
details: e,
});
}
)
};
return (
<Modal show={show} size='xl' onHide={handleCancel}>
<Modal.Header closeButton>
<Modal.Title>Configure Rqbit desktop</Modal.Title>
</Modal.Header>
<Modal.Body>
<ErrorComponent error={error}></ErrorComponent>
<Tabs
defaultActiveKey="home"
id="rqbit-config"
className="mb-3">
<Tab className="mb-3" eventKey="home" title="Home">
<FormInput
label="Default download folder"
name="default_download_location"
value={config.default_download_location}
inputType="text"
onChange={handleInputChange}
help="Where to download torrents by default. You can override this per torrent."
/>
</Tab>
<Tab className="mb-3" eventKey="dht" title="DHT">
<legend>DHT config</legend>
<FormCheck
label="Enable DHT"
name="dht.disable"
checked={!config.dht.disable}
onChange={handleToggleChange}
help="DHT is required to read magnet links. There's no good reason to disable it, unless you know what you are doing."
/>
<FormCheck
label="Enable DHT persistence"
name="dht.disable_persistence"
checked={!config.dht.disable_persistence}
onChange={handleToggleChange}
disabled={config.dht.disable}
help="Enable to store DHT state in a file periodically. If disabled, DHT will bootstrap from scratch on restart."
/>
<FormInput
label="Persistence filename"
name="dht.persistence_filename"
value={config.dht.persistence_filename}
inputType="text"
disabled={config.dht.disable}
onChange={handleInputChange}
help="The filename to store DHT state into"
/>
</Tab>
<Tab className="mb-3" eventKey="tcp_listen" title="TCP">
<legend>TCP Listener config</legend>
<FormCheck
label="Listen on TCP"
name="tcp_listen.disable"
checked={!config.tcp_listen.disable}
onChange={handleToggleChange}
help="Listen for torrent requests on TCP. Required for peers to be able to connect to you, mainly for uploading."
/>
<FormCheck
label="Advertise over UPnP"
name="tcp_listen.disable"
checked={!config.tcp_listen.disable}
onChange={handleToggleChange}
help="Advertise your port over UPnP. This is required for peers to be able to connect to you from the internet. Will only work if your router has a static IP."
/>
<FormInput
inputType="number"
label="Min port"
name="tcp_listen.min_port"
value={config.tcp_listen.min_port}
disabled={config.tcp_listen.disable}
onChange={handleInputChange}
help="The min port to try to listen on. First successful is taken."
/>
<FormInput
inputType="number"
label="Max port"
name="tcp_listen.max_port"
value={config.tcp_listen.max_port}
disabled={config.tcp_listen.disable}
onChange={handleInputChange}
help="The max port to try to listen on."
/>
</Tab>
<Tab className="mb-3" eventKey="session_persistence" title="Session">
<legend>Session persistence</legend>
<FormCheck
label="Enable persistence"
name="persistence.disable"
checked={!config.persistence.disable}
onChange={handleToggleChange}
help="If you disable session persistence, rqbit won't remember the torrents you had before restart."
/>
<FormInput
label="Persistence filename"
name="persistence.filename"
inputType="text"
value={config.persistence.filename}
onChange={handleInputChange}
disabled={config.persistence.disable}
/>
</Tab>
<Tab className="mb-3" eventKey="peer_opts" title="Peer options">
<legend>Peer connection options</legend>
<FormInput
label="Connect timeout (seconds)"
inputType="number"
name="peer_opts.connect_timeout"
value={config.peer_opts.connect_timeout}
onChange={handleInputChange}
help="How much to wait for outgoing connections to connect. Default is low to prefer faster peers."
/>
<FormInput
label="Read/write timeout (seconds)"
inputType="number"
name="peer_opts.read_write_timeout"
value={config.peer_opts.read_write_timeout}
onChange={handleInputChange}
help="Peer socket read/write timeout."
/>
</Tab>
<Tab className="mb-3" eventKey="http_api" title="HTTP API">
<legend>HTTP API config</legend>
<FormCheck
label="Enable HTTP API"
name="http_api.disable"
checked={!config.http_api.disable}
onChange={handleToggleChange}
help="If enabled you can access the HTTP API at the address below"
/>
<FormCheck
label="Read only"
name="http_api.read_only"
checked={config.http_api.read_only}
disabled={config.http_api.disable}
onChange={handleToggleChange}
help="If enabled, only GET requests will be allowed through the API"
/>
<FormInput
label="Listen address"
inputType="text"
name="http_api.listen_addr"
value={config.http_api.listen_addr}
disabled={config.http_api.disable}
onChange={handleInputChange}
help={`You'll access the API at http://${config.http_api.listen_addr}`}
/>
</Tab>
</Tabs>
</Modal.Body>
<Modal.Footer>
{!!handleCancel &&
<Button variant="secondary" onClick={handleCancel}>
Cancel
</Button>
}
<Button variant="secondary" onClick={() => setConfig(defaultConfig)}>
Reset to defaults
</Button>
<Button variant="primary" onClick={handleOkClick} disabled={loading}>
OK
</Button>
</Modal.Footer>
</Modal>
const handleOkClick = () => {
setError(null);
handleStartReconfigure();
setLoading(true);
invokeAPI<{}>("config_change", { config }).then(
() => {
setLoading(false);
handleConfigured(config);
},
(e: ErrorDetails) => {
setLoading(false);
setError({
text: "Error saving configuration",
details: e,
});
}
);
};
return (
<Modal show={show} size="xl" onHide={handleCancel}>
<Modal.Header closeButton>
<Modal.Title>Configure Rqbit desktop</Modal.Title>
</Modal.Header>
<Modal.Body>
<ErrorComponent error={error}></ErrorComponent>
<Tabs defaultActiveKey="home" id="rqbit-config" className="mb-3">
<Tab className="mb-3" eventKey="home" title="Home">
<FormInput
label="Default download folder"
name="default_download_location"
value={config.default_download_location}
inputType="text"
onChange={handleInputChange}
help="Where to download torrents by default. You can override this per torrent."
/>
</Tab>
<Tab className="mb-3" eventKey="dht" title="DHT">
<legend>DHT config</legend>
<FormCheck
label="Enable DHT"
name="dht.disable"
checked={!config.dht.disable}
onChange={handleToggleChange}
help="DHT is required to read magnet links. There's no good reason to disable it, unless you know what you are doing."
/>
<FormCheck
label="Enable DHT persistence"
name="dht.disable_persistence"
checked={!config.dht.disable_persistence}
onChange={handleToggleChange}
disabled={config.dht.disable}
help="Enable to store DHT state in a file periodically. If disabled, DHT will bootstrap from scratch on restart."
/>
<FormInput
label="Persistence filename"
name="dht.persistence_filename"
value={config.dht.persistence_filename}
inputType="text"
disabled={config.dht.disable}
onChange={handleInputChange}
help="The filename to store DHT state into"
/>
</Tab>
<Tab className="mb-3" eventKey="tcp_listen" title="TCP">
<legend>TCP Listener config</legend>
<FormCheck
label="Listen on TCP"
name="tcp_listen.disable"
checked={!config.tcp_listen.disable}
onChange={handleToggleChange}
help="Listen for torrent requests on TCP. Required for peers to be able to connect to you, mainly for uploading."
/>
<FormCheck
label="Advertise over UPnP"
name="tcp_listen.disable"
checked={!config.tcp_listen.disable}
onChange={handleToggleChange}
help="Advertise your port over UPnP. This is required for peers to be able to connect to you from the internet. Will only work if your router has a static IP."
/>
<FormInput
inputType="number"
label="Min port"
name="tcp_listen.min_port"
value={config.tcp_listen.min_port}
disabled={config.tcp_listen.disable}
onChange={handleInputChange}
help="The min port to try to listen on. First successful is taken."
/>
<FormInput
inputType="number"
label="Max port"
name="tcp_listen.max_port"
value={config.tcp_listen.max_port}
disabled={config.tcp_listen.disable}
onChange={handleInputChange}
help="The max port to try to listen on."
/>
</Tab>
<Tab className="mb-3" eventKey="session_persistence" title="Session">
<legend>Session persistence</legend>
<FormCheck
label="Enable persistence"
name="persistence.disable"
checked={!config.persistence.disable}
onChange={handleToggleChange}
help="If you disable session persistence, rqbit won't remember the torrents you had before restart."
/>
<FormInput
label="Persistence filename"
name="persistence.filename"
inputType="text"
value={config.persistence.filename}
onChange={handleInputChange}
disabled={config.persistence.disable}
/>
</Tab>
<Tab className="mb-3" eventKey="peer_opts" title="Peer options">
<legend>Peer connection options</legend>
<FormInput
label="Connect timeout (seconds)"
inputType="number"
name="peer_opts.connect_timeout"
value={config.peer_opts.connect_timeout}
onChange={handleInputChange}
help="How much to wait for outgoing connections to connect. Default is low to prefer faster peers."
/>
<FormInput
label="Read/write timeout (seconds)"
inputType="number"
name="peer_opts.read_write_timeout"
value={config.peer_opts.read_write_timeout}
onChange={handleInputChange}
help="Peer socket read/write timeout."
/>
</Tab>
<Tab className="mb-3" eventKey="http_api" title="HTTP API">
<legend>HTTP API config</legend>
<FormCheck
label="Enable HTTP API"
name="http_api.disable"
checked={!config.http_api.disable}
onChange={handleToggleChange}
help="If enabled you can access the HTTP API at the address below"
/>
<FormCheck
label="Read only"
name="http_api.read_only"
checked={config.http_api.read_only}
disabled={config.http_api.disable}
onChange={handleToggleChange}
help="If enabled, only GET requests will be allowed through the API"
/>
<FormInput
label="Listen address"
inputType="text"
name="http_api.listen_addr"
value={config.http_api.listen_addr}
disabled={config.http_api.disable}
onChange={handleInputChange}
help={`You'll access the API at http://${config.http_api.listen_addr}`}
/>
</Tab>
</Tabs>
</Modal.Body>
<Modal.Footer>
{!!handleCancel && (
<Button variant="secondary" onClick={handleCancel}>
Cancel
</Button>
)}
<Button variant="secondary" onClick={() => setConfig(defaultConfig)}>
Reset to defaults
</Button>
<Button variant="primary" onClick={handleOkClick} disabled={loading}>
OK
</Button>
</Modal.Footer>
</Modal>
);
};

View file

@ -1,5 +1,5 @@
import { StrictMode } from "react";
import ReactDOM from 'react-dom/client';
import ReactDOM from "react-dom/client";
import { APIContext } from "./rqbit-webui-src/rqbit-web";
import { API } from "./api";
import { invoke } from "@tauri-apps/api";
@ -7,23 +7,29 @@ import { CurrentDesktopState, RqbitDesktopConfig } from "./configuration";
import { RqbitDesktop } from "./rqbit-desktop";
async function get_version(): Promise<string> {
return invoke<string>("get_version");
return invoke<string>("get_version");
}
async function get_default_config(): Promise<RqbitDesktopConfig> {
return invoke<RqbitDesktopConfig>("config_default");
return invoke<RqbitDesktopConfig>("config_default");
}
async function get_current_config(): Promise<CurrentDesktopState> {
return invoke<CurrentDesktopState>("config_current");
return invoke<CurrentDesktopState>("config_current");
}
Promise.all([get_version(), get_default_config(), get_current_config()]).then(([version, defaultConfig, currentState]) => {
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<StrictMode>
<APIContext.Provider value={API}>
<RqbitDesktop version={version} defaultConfig={defaultConfig} currentState={currentState} />
</APIContext.Provider>
</StrictMode>
Promise.all([get_version(), get_default_config(), get_current_config()]).then(
([version, defaultConfig, currentState]) => {
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<StrictMode>
<APIContext.Provider value={API}>
<RqbitDesktop
version={version}
defaultConfig={defaultConfig}
currentState={currentState}
/>
</APIContext.Provider>
</StrictMode>
);
})
}
);

View file

@ -3,41 +3,49 @@ import { RqbitWebUI } from "./rqbit-webui-src/rqbit-web";
import { CurrentDesktopState, RqbitDesktopConfig } from "./configuration";
import { ConfigModal } from "./configure";
export const RqbitDesktop: React.FC<{
version: string,
defaultConfig: RqbitDesktopConfig,
currentState: CurrentDesktopState,
version: string;
defaultConfig: RqbitDesktopConfig;
currentState: CurrentDesktopState;
}> = ({ version, defaultConfig, currentState }) => {
let [configured, setConfigured] = useState<boolean>(currentState.configured);
let [config, setConfig] = useState<RqbitDesktopConfig>(currentState.config ?? defaultConfig);
let [configurationOpened, setConfigurationOpened] = useState<boolean>(false);
let [configured, setConfigured] = useState<boolean>(currentState.configured);
let [config, setConfig] = useState<RqbitDesktopConfig>(
currentState.config ?? defaultConfig
);
let [configurationOpened, setConfigurationOpened] = useState<boolean>(false);
return <>
{configured && <RqbitWebUI title={`Rqbit Desktop v${version}`}></RqbitWebUI>}
{configured && <a
className="bi bi-sliders2 position-absolute top-0 start-0 p-3 text-primary"
onClick={(e) => {
e.stopPropagation();
setConfigurationOpened(true);
}}
href="#"
aria-label="Settings" />}
<ConfigModal
show={!configured || configurationOpened}
handleStartReconfigure={() => {
setConfigured(false);
}}
handleCancel={() => {
setConfigurationOpened(false);
}}
handleConfigured={(config) => {
setConfig(config);
setConfigurationOpened(false);
setConfigured(true);
}}
initialConfig={config}
defaultConfig={defaultConfig}
return (
<>
{configured && (
<RqbitWebUI title={`Rqbit Desktop v${version}`}></RqbitWebUI>
)}
{configured && (
<a
className="bi bi-sliders2 position-absolute top-0 start-0 p-3 text-primary"
onClick={(e) => {
e.stopPropagation();
setConfigurationOpened(true);
}}
href="#"
aria-label="Settings"
/>
)}
<ConfigModal
show={!configured || configurationOpened}
handleStartReconfigure={() => {
setConfigured(false);
}}
handleCancel={() => {
setConfigurationOpened(false);
}}
handleConfigured={(config) => {
setConfig(config);
setConfigurationOpened(false);
setConfigured(true);
}}
initialConfig={config}
defaultConfig={defaultConfig}
/>
</>
}
);
};