Skip to content

Commit

Permalink
Add universal url-with-credentials parser (cross-seed#510)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmgoodnow authored Oct 3, 2023
1 parent cf275d2 commit fe8f1ce
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 53 deletions.
11 changes: 7 additions & 4 deletions src/Result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ export interface Result<T, U> {
isErr(): boolean;
mapOk<R>(mapper: (t: T) => R): Result<R, U>;
mapErr<R>(mapper: (u: U) => R): Result<T, R>;
unwrapOrThrow(): T;
unwrapOrThrow(errToThrow?: Error): T;
unwrapErrOrThrow(): U;
}

Expand All @@ -26,11 +26,13 @@ class OkResult<T, U> implements Result<T, U> {
return new OkResult(mapper(this.contents));
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
mapErr<R>(mapper: (u: U) => R): Result<T, R> {
return this as unknown as Result<T, R>;
}

unwrapOrThrow(): T {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
unwrapOrThrow(errToThrow?: Error): T {
return this.contents;
}

Expand All @@ -54,6 +56,7 @@ class ErrResult<T, U> implements Result<T, U> {
return true;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
mapOk<R>(mapper: (t: T) => R): Result<R, U> {
return this as unknown as Result<R, U>;
}
Expand All @@ -62,8 +65,8 @@ class ErrResult<T, U> implements Result<T, U> {
return new ErrResult(mapper(this.contents));
}

unwrapOrThrow(): T {
throw new Error("Tried to unwrap an ErrResult's error");
unwrapOrThrow(errToThrow?: Error): T {
throw errToThrow ?? new Error("Tried to unwrap an ErrResult's error");
}

unwrapErrOrThrow(): U {
Expand Down
38 changes: 13 additions & 25 deletions src/clients/QBittorrent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Label, logger, logOnce } from "../logger.js";
import { Metafile } from "../parseTorrent.js";
import { getRuntimeConfig } from "../runtimeConfig.js";
import { Searchee } from "../searchee.js";
import { extractCredentialsFromUrl } from "../utils.js";
import { TorrentClient } from "./TorrentClient.js";

const X_WWW_FORM_URLENCODED = {
Expand Down Expand Up @@ -85,36 +86,21 @@ interface Category {
}

export default class QBittorrent implements TorrentClient {
url: URL;
cookie: string;

constructor() {
const { qbittorrentUrl } = getRuntimeConfig();
try {
this.url = new URL(`${qbittorrentUrl}/api/v2`);
} catch (e) {
throw new CrossSeedError("qBittorrent url must be percent-encoded");
}
}

async login(): Promise<void> {
const { origin, pathname, username, password } = this.url;

let searchParams;
try {
searchParams = new URLSearchParams({
username: decodeURIComponent(username),
password: decodeURIComponent(password),
});
} catch (e) {
throw new CrossSeedError("qBittorrent url must be percent-encoded");
}
const { qbittorrentUrl } = getRuntimeConfig();
const { username, password, href } = extractCredentialsFromUrl(
qbittorrentUrl
).unwrapOrThrow(
new CrossSeedError("qBittorrent url must be percent-encoded")
);

let response: Response;
try {
response = await fetch(`${origin}${pathname}/auth/login`, {
response = await fetch(`${href}/api/v2/auth/login`, {
method: "POST",
body: searchParams,
body: new URLSearchParams({ username, password }),
});
} catch (e) {
throw new CrossSeedError(`qBittorrent login failed: ${e.message}`);
Expand Down Expand Up @@ -151,8 +137,10 @@ export default class QBittorrent implements TorrentClient {
label: Label.QBITTORRENT,
message: `Making request to ${path} with body ${body.toString()}`,
});
const { origin, pathname } = this.url;
const response = await fetch(`${origin}${pathname}${path}`, {
const { qbittorrentUrl } = getRuntimeConfig();
const { href } =
extractCredentialsFromUrl(qbittorrentUrl).unwrapOrThrow();
const response = await fetch(`${href}/api/v2${path}`, {
method: "post",
headers: { Cookie: this.cookie, ...headers },
body,
Expand Down
39 changes: 17 additions & 22 deletions src/clients/RTorrent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Metafile } from "../parseTorrent.js";
import { Result, resultOf, resultOfErr } from "../Result.js";
import { getRuntimeConfig } from "../runtimeConfig.js";
import { File, Searchee } from "../searchee.js";
import { wait } from "../utils.js";
import { extractCredentialsFromUrl, wait } from "../utils.js";
import { TorrentClient } from "./TorrentClient.js";

interface LibTorrentResumeFileEntry {
Expand Down Expand Up @@ -80,30 +80,25 @@ export default class RTorrent implements TorrentClient {
constructor() {
const { rtorrentRpcUrl } = getRuntimeConfig();

try {
const { origin, username, password, protocol, pathname } = new URL(
rtorrentRpcUrl
);
const { href, username, password } = extractCredentialsFromUrl(
rtorrentRpcUrl
).unwrapOrThrow(
new CrossSeedError("rTorrent url must be percent-encoded")
);

const clientCreator =
protocol === "https:"
? xmlrpc.createSecureClient
: xmlrpc.createClient;
const clientCreator =
new URL(href).protocol === "https:"
? xmlrpc.createSecureClient
: xmlrpc.createClient;

const shouldUseAuth = Boolean(username && password);
const shouldUseAuth = Boolean(username && password);

this.client = clientCreator({
url: origin + pathname,
basic_auth: shouldUseAuth
? {
user: decodeURIComponent(username),
pass: decodeURIComponent(password),
}
: undefined,
});
} catch (e) {
throw new CrossSeedError("rTorrent url must be percent-encoded");
}
this.client = clientCreator({
url: href,
basic_auth: shouldUseAuth
? { user: username, pass: password }
: undefined,
});
}

private async methodCallP<R>(method: string, args): Promise<R> {
Expand Down
7 changes: 5 additions & 2 deletions src/clients/Transmission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Metafile } from "../parseTorrent.js";
import { Result, resultOf, resultOfErr } from "../Result.js";
import { getRuntimeConfig } from "../runtimeConfig.js";
import { Searchee } from "../searchee.js";
import { extractCredentialsFromUrl } from "../utils.js";
import { TorrentClient } from "./TorrentClient.js";

const XTransmissionSessionId = "X-Transmission-Session-Id";
Expand Down Expand Up @@ -46,8 +47,10 @@ export default class Transmission implements TorrentClient {
): Promise<T> {
const { transmissionRpcUrl } = getRuntimeConfig();

const { username, password, origin, pathname } = new URL(
const { username, password, href } = extractCredentialsFromUrl(
transmissionRpcUrl
).unwrapOrThrow(
new CrossSeedError("Transmission rpc url must be percent-encoded")
);

const headers = new Headers();
Expand All @@ -62,7 +65,7 @@ export default class Transmission implements TorrentClient {
headers.set("Authorization", `Basic ${credentials}`);
}

const response = await fetch(origin + pathname, {
const response = await fetch(href, {
method: "POST",
body: JSON.stringify({ method, arguments: args }),
headers,
Expand Down
16 changes: 16 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
SEASON_REGEX,
VIDEO_EXTENSIONS,
} from "./constants.js";
import { Result, resultOf, resultOfErr } from "./Result.js";

export enum MediaType {
EPISODE = "episode",
Expand Down Expand Up @@ -93,3 +94,18 @@ export function fallback<T>(...args: T[]): T {
}
return undefined;
}

export function extractCredentialsFromUrl(
url: string
): Result<{ username: string; password: string; href: string }, "invalid URL"> {
try {
const { origin, pathname, username, password } = new URL(url);
return resultOf({
username: decodeURIComponent(username),
password: decodeURIComponent(password),
href: origin + pathname,
});
} catch (e) {
return resultOfErr("invalid URL");
}
}

0 comments on commit fe8f1ce

Please sign in to comment.