合并superbox等控制接口

This commit is contained in:
龚皓 2024-09-30 15:44:17 +08:00
parent 376981cf5e
commit c76d2e498c
4 changed files with 442 additions and 17 deletions

View File

@ -1,15 +1,23 @@
// axios-config.ts
import axios from 'axios'; import axios from 'axios';
// 从 localStorage 中获取地址和端口
const rememberedAddress = localStorage.getItem('rememberedAddress') || '127.0.0.1';
const rememberedPort = localStorage.getItem('rememberedPort') || '8000';
// 动态拼接 baseURL
const baseURL = `http://${rememberedAddress}:${rememberedPort}/api/v1`;
// 创建 axios 实例
const axiosInstance = axios.create({ const axiosInstance = axios.create({
// baseURL: 'https://test1.turingvideo.cn/api/v1', baseURL: baseURL, // 使用动态生成的 baseURL
baseURL: 'http://127.0.0.1:8000/api/v1', timeout: 10000, // 超时时间
timeout: 10000, withCredentials: true, // 使用cookie跨域请求
}); });
// 请求拦截器
axiosInstance.interceptors.request.use( axiosInstance.interceptors.request.use(
config => { config => {
const token = localStorage.getItem('token'); const token = localStorage.getItem('alertToken');
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
@ -20,14 +28,15 @@ axiosInstance.interceptors.request.use(
} }
); );
// 响应拦截器
axiosInstance.interceptors.response.use( axiosInstance.interceptors.response.use(
response => { response => {
return response; return response;
}, },
error => { error => {
if (error.response && error.response.status === 401) { if (error.response && error.response.status === 401) {
localStorage.removeItem('token'); // localStorage.removeItem('alertToken');
window.location.href = '/#/login'; // 重定向到登录页面 // window.location.href = '/#/login';
} }
return Promise.reject(error); return Promise.reject(error);
} }

359
src/utils/boxApi.ts Normal file
View File

@ -0,0 +1,359 @@
import axios from 'axios';
class BoxApi {
private readonly defaultPort: number = 8000;
private readonly apiLogin: string = "/auth/login";
private readonly apiLogout: string = "/auth/logout";
private readonly apiAdduser: string = "/auth/adduser";
private readonly apiRmuser: string = "/auth/rmuser";
private readonly apiAllusers: string = "/auth/allusers";
private readonly apiCameras: string = "/cameras";
private readonly apiEvents: string = "/events";
private readonly apiAlgorithms: string = "/algorithms";
private readonly apiResetUser: string = "/auth/resetuser";
private readonly apiResetPassword: string = "/auth/reset_password";
private readonly loginConfig: object = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
}
private address: string = "";
private port: number = this.defaultPort;
private token: string = "";
private codemap: Map<string, string> = new Map<string, string>();
private axios: any = null;
public constructor(
address: string = "",
port: number = 0
) {
// 获取本地存储的address和port
const rememberedAddress = localStorage.getItem('rememberedAddress') || '127.0.0.1';
const rememberedPort = localStorage.getItem('rememberedPort') || '8000';
this.setAddress(address || rememberedAddress);
this.setPort(port || parseInt(rememberedPort));
// 动态创建axios实例基于当前的address和port
this.createAxiosInstance();
}
private createAxiosInstance() {
// 动态生成baseURL
this.axios = axios.create({
baseURL: `http://${this.address}:${this.port}/api/v1`,
withCredentials: true
});
}
public setAddress(address: string) {
this.address = address === "" ? this._boxAddr() : address;
this.createAxiosInstance();
}
public setPort(port: number) {
this.port = port === 0 ? this.defaultPort : port;
this.createAxiosInstance();
}
public setToken(token: string) {
this.token = token;
}
public async login(username: string, password: string, cookieLess: boolean = false): Promise<any> {
const loginData = {
username: username,
password: password,
cookieless: cookieLess ? "True" : "False"
};
try {
const res = await this.axios.post(this.apiLogin, loginData, this.loginConfig)
console.log(res)
if (res.data.err.ec === 0) {
this.token = res.data.ret.token;
await this.updateCodemap(this.token);
return res.data.ret.token;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async logout(token: string | null = null): Promise<any> {
try {
const res = await this.axios.post(this.apiLogout, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async resetPassword(newPassword: string, token: string | null = null): Promise<any> {
try {
const data = {
new_password: newPassword
};
const res = await this.axios.post(this.apiResetPassword, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async resetUser(username: string, password: string, email: string, token: string | null = null): Promise<any> {
try {
const data = {
username: username,
password: password,
email: email
};
const res = await this.axios.post(this.apiResetUser, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async addUser(username: string, password: string, email: string = "", token: string | null = null): Promise<any> {
try {
const data = {
username: username,
password: password,
email: email
};
const res = await this.axios.post(this.apiAdduser, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw res.data.err;
}
} catch (error: any) {
if (error.response && error.response.data && error.response.data.err) {
throw error.response.data.err;
} else {
throw new Error("网络错误或服务器未响应");
}
}
}
public async rmUser(username: string, token: string | null = null): Promise<any> {
try {
const data = {
username: username
};
const res = await this.axios.post(this.apiRmuser, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getAllUsers(token: string | null = null): Promise<any> {
try {
const res = await this.axios.get(this.apiAllusers, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret.users;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getCamerasByUrl(url: string, token: string | null = null): Promise<any> {
try {
const res = await this.axios.get(url, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getCameras(limit: number, offset: number, token: string | null = null): Promise<any> {
const url = `${this.apiCameras}?limit=${limit}&offset=${offset}`;
return await this.getCamerasByUrl(url, token);
}
public async getEventsByUrl(url: string, token: string | null = null): Promise<any> {
try {
const res = await this.axios.get(url, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
// public async getEvents(limit: number, offset: number, token: string | null = null): Promise<any> {
// const url = `${this.apiEvents}?limit=${limit}&offset=${offset}`;
// return await this.getEventsByUrl(url, token);
// }
// public async getEvents(token: string | null = null, pageSize: number = 10, currentPage: number = 1): Promise<any> {
// const offset = (currentPage - 1) * pageSize;
// const url = `${this.apiEvents}?limit=${pageSize}&offset=${offset}`;
// try {
// const res = await this.axios.get(url, this._authHeader(token));
// if (res.data.err.ec === 0) {
// return res.data.ret;
// } else {
// throw new Error(res.data.err.msg);
// }
// } catch (error) {
// throw error;
// }
// }
public async getEvents(token: string | null = null, pageSize: number = 20, currentPage: number = 1): Promise<any> {
// 计算 offset
const offset = (currentPage - 1) * pageSize;
try {
// 发送请求,携带 limit 和 offset 参数
const res = await this.axios.get(`${this.apiEvents}?limit=${pageSize}&offset=${offset}`, this._authHeader(token));
// 请求成功,返回数据
if (res.data.err.ec === 0) {
return {
tableData: res.data.ret.results, // 告警数据
totalItems: res.data.ret.count // 总条数
};
} else {
// 处理请求失败情况
throw new Error(res.data.err);
}
} catch (error) {
// 抛出异常以便前端捕获
throw error;
}
}
// public async getOneEvent(token: string | null = null): Promise<any> {
// try {
// return await this.getEvents(1, 0, token);
// } catch (error) {
// throw error;
// }
// }
public async getOneEvent(token: string | null = null): Promise<any> {
try {
// 调用 getEvents 方法,设置 pageSize 为 1currentPage 为 1
return await this.getEvents(token, 1, 1);
} catch (error) {
throw error;
}
}
public async setEventStatus(eventId: number, status: string, remark: string | null = null, token: string | null = null): Promise<any> {
const url = `${this.apiEvents}/${eventId}`;
const newRemark = remark ? remark : "";
const data = {
status: status,
remark: newRemark
};
try {
const res = await this.axios.patch(url, data, this._authHeader(token))
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getAlgorithms(token: string | null = null): Promise<any> {
try {
const res = await this.axios.get(this.apiAlgorithms, this._authHeader(token))
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async updateCodemap(token: string | null = null): Promise<boolean> {
try {
this.codemap.clear()
const algorithms = await this.getAlgorithms(token);
algorithms.forEach((algorithm: { code_name: string, name: string }) => {
this.codemap.set(algorithm.code_name, algorithm.name)
});
return true;
} catch (error) {
return false;
}
}
public getAlgorithmName(code_name: string): string {
return this.codemap.get(code_name) || code_name;
}
private _authHeader(token: string | null = null): object {
// const access_token = token === "" ? this.token : token;
const alertToken = localStorage.getItem(`alertToken`) || token || this.token || "" ||"";
return {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${alertToken}`,
// 'Cookie': `jwt=${access_token}`
}
}
}
private _boxAddr() {
return window.location.host.replace(/:\d+/, "");
}
}
export { BoxApi };

View File

@ -6,7 +6,7 @@ export const getSuperboxApiConfig = (address) => {
const LOGIN_ROUTE = BASE_ROUTE + "/auth/login"; const LOGIN_ROUTE = BASE_ROUTE + "/auth/login";
const LOGOUT_ROUTE = BASE_ROUTE + "/auth/logout"; const LOGOUT_ROUTE = BASE_ROUTE + "/auth/logout";
const CAMERA_ROUTE = BASE_ROUTE + "/camera/cameras"; const CAMERA_ROUTE = BASE_ROUTE + "/camera/cameras";
const EVENTS_ROUTE = BASE_ROUTE + "/event/events?limit=300"; const EVENTS_ROUTE = BASE_ROUTE + "/event/events";
const ALGORITHM_ROUTE = BASE_ROUTE + "/algorithms"; const ALGORITHM_ROUTE = BASE_ROUTE + "/algorithms";
let addr = address; let addr = address;
@ -86,11 +86,15 @@ export const getCameras = (token, address = null) => {
}); });
}; };
export const getEvents = (token, address = null) => { export const getEvents = (token, address = null, pageSize = 20, currentPage = 1) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const api = getSuperboxApiConfig(address); const api = getSuperboxApiConfig(address);
const offset = (currentPage - 1) * pageSize;
const params = new URLSearchParams({ limit: pageSize, offset });
const urlWithParams = `${api.events}?${params.toString()}`;
// console.log("urlWithParams>>>>>>>>>>>>>>>>>", urlWithParams);
axios axios
.get(api.events, { .get(urlWithParams, {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -98,7 +102,10 @@ export const getEvents = (token, address = null) => {
}) })
.then((res) => { .then((res) => {
if (res.data.err.ec === 0) { if (res.data.err.ec === 0) {
resolve(res.data.ret.results); resolve({
tableData: res.data.ret.results,
totalItems: res.data.ret.count
});
} }
reject(res.data.err); reject(res.data.err);
}) })

View File

@ -1,4 +1,3 @@
/* eslint-disable no-useless-catch */
import axios from 'axios'; import axios from 'axios';
class SuperboxApi { class SuperboxApi {
@ -7,6 +6,9 @@ class SuperboxApi {
private readonly apiLogin: string = "/auth/login"; private readonly apiLogin: string = "/auth/login";
private readonly apiLogout: string = "/auth/logout"; private readonly apiLogout: string = "/auth/logout";
private readonly apiAdduser: string = "/auth/adduser";
private readonly apiRmuser: string = "/auth/rmuser";
private readonly apiAllusers: string = "/auth/allusers";
private readonly apiCameras: string = "/cameras"; private readonly apiCameras: string = "/cameras";
private readonly apiEvents: string = "/events"; private readonly apiEvents: string = "/events";
private readonly apiAlgorithms: string = "/algorithms"; private readonly apiAlgorithms: string = "/algorithms";
@ -28,7 +30,7 @@ class SuperboxApi {
public constructor( public constructor(
address: string = "", address: string = "",
port: number = 0 port: number = 0
) { ) {
this.setAddress(address); this.setAddress(address);
this.setPort(port); this.setPort(port);
this.axios = axios.create({ this.axios = axios.create({
@ -53,12 +55,11 @@ class SuperboxApi {
const loginData = { const loginData = {
username: username, username: username,
password: password, password: password,
cookieless: cookieLess ? "True" : "False" cookieless: cookieLess ? "true" : "false" // 这里会根据 cookieLess 的值决定是 "true" 还是 "false"
}; };
try { try {
const res = await this.axios.post(this.apiLogin, loginData, this.loginConfig) const res = await this.axios.post(this.apiLogin, loginData, this.loginConfig)
console.log(res)
if (res.data.err.ec === 0) { if (res.data.err.ec === 0) {
this.token = res.data.ret.token; this.token = res.data.ret.token;
await this.updateCodemap(this.token); await this.updateCodemap(this.token);
@ -84,6 +85,55 @@ class SuperboxApi {
} }
} }
public async addUser(username: string, password: string, email: string="", token: string | null = null): Promise<any> {
try {
const data = {
username: username,
password: password,
email: email
};
const res = await this.axios.post(this.apiAdduser, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async rmUser(username: string, token: string | null = null): Promise<any> {
try {
const data = {
username: username
};
const res = await this.axios.post(this.apiRmuser, data, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getAllUsers(token: string | null = null): Promise<any> {
try {
const res = await this.axios.get(this.apiAllusers, this._authHeader(token));
if (res.data.err.ec === 0) {
return res.data.ret.users;
} else {
throw new Error(res.data.err.msg);
}
} catch (error) {
throw error;
}
}
public async getCamerasByUrl(url: string, token: string | null = null): Promise<any> { public async getCamerasByUrl(url: string, token: string | null = null): Promise<any> {
try { try {
const res = await this.axios.get(url, this._authHeader(token)); const res = await this.axios.get(url, this._authHeader(token));
@ -197,4 +247,4 @@ class SuperboxApi {
} }
export { SuperboxApi }; export { SuperboxApi };