84 lines
2.4 KiB
TypeScript
Raw Permalink Normal View History

2023-07-28 20:12:34 +08:00
import {Method} from "axios";
2022-12-02 11:04:17 +08:00
import axios from "axios";
2023-07-28 20:12:34 +08:00
import querystring from "querystring";
2023-10-11 17:34:26 +08:00
import QbConfigDto from "../entity/dto/QbConfigDto";
2022-12-02 11:04:17 +08:00
import GlobalService from '../service/GlobalConfigService';
2023-10-11 17:34:26 +08:00
let qbInfo: QbConfigDto = null;
let cookie: any = null;
2022-12-02 11:04:17 +08:00
2023-10-11 17:34:26 +08:00
export function updateQbInfo(info: QbConfigDto) {
2023-07-28 20:12:34 +08:00
qbInfo = info;
2022-12-02 11:04:17 +08:00
}
2023-07-28 20:12:34 +08:00
export function getQbInfo() {
return qbInfo;
2022-12-02 11:04:17 +08:00
}
2023-10-11 17:34:26 +08:00
export async function get(url: string, data: object) {
return await request("get", url, data, null, false);
2022-12-02 11:04:17 +08:00
}
2023-10-11 17:34:26 +08:00
export async function post(url: string, data: object, isForm = false) {
return await request("post", url, null, data, isForm);
2022-12-02 11:04:17 +08:00
}
async function request(method: Method, url: string, query: any, body: any, isForm = false) {
2023-07-28 20:12:34 +08:00
if (!qbInfo.valid) {
throw new Error("qbittorrent无法连接请检查配置");
}
let isTryLogin = false;
while (true) {
let headers = {"Cookie": cookie};
if (isForm) {
headers['content-type'] = "multipart/form-data";
} else if (method == "post") {
headers['content-type'] = "application/json";
}
let res = await axios.request({
baseURL: qbInfo.address,
2023-10-11 17:34:26 +08:00
url: "/api/v2" + url,
2023-07-28 20:12:34 +08:00
method,
params: query,
data: body,
headers,
});
if (res.status == 200) {
return res.data;
}
if (res.status == 403) {
if (isTryLogin) {
throw new Error("qb用户名密码设置有误");
} else {
await tryLogin();
isTryLogin = true;
}
} else {
throw new Error("请求报错:" + res.data);
}
}
2022-12-02 11:04:17 +08:00
}
2023-07-28 20:12:34 +08:00
export async function tryLogin(): Promise<boolean> {
if (qbInfo == null || qbInfo.address == null || qbInfo.address == "") {
return false;
}
let body = {username: qbInfo.username, password: qbInfo.password};
try {
let res = await axios.post(qbInfo.address + `/api/v2/auth/login`, querystring.stringify(body), {
headers: {"Content-Type": "application/x-www-form-urlencoded"}
});
let success = res.data.toLocaleLowerCase().indexOf('ok') > -1;
if (success) {
2023-10-11 17:34:26 +08:00
cookie = res.headers['set-cookie'];
2023-07-28 20:12:34 +08:00
}
qbInfo.valid = success;
return success;
} catch (error) {
console.error("登录报错:", error);
return false;
}
2022-12-02 11:04:17 +08:00
}