diff --git a/src/utils/axios-config.ts b/src/utils/axios-config.ts index 7eb172e..aecc6da 100644 --- a/src/utils/axios-config.ts +++ b/src/utils/axios-config.ts @@ -1,15 +1,23 @@ -// axios-config.ts 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({ -// baseURL: 'https://test1.turingvideo.cn/api/v1', - baseURL: 'http://127.0.0.1:8000/api/v1', - timeout: 10000, + baseURL: baseURL, // 使用动态生成的 baseURL + timeout: 10000, // 超时时间 + withCredentials: true, // 使用cookie跨域请求 }); +// 请求拦截器 axiosInstance.interceptors.request.use( config => { - const token = localStorage.getItem('token'); + const token = localStorage.getItem('alertToken'); if (token) { config.headers.Authorization = `Bearer ${token}`; } @@ -20,14 +28,15 @@ axiosInstance.interceptors.request.use( } ); +// 响应拦截器 axiosInstance.interceptors.response.use( response => { return response; }, error => { if (error.response && error.response.status === 401) { - localStorage.removeItem('token'); - window.location.href = '/#/login'; // 重定向到登录页面 + // localStorage.removeItem('alertToken'); + // window.location.href = '/#/login'; } return Promise.reject(error); } diff --git a/src/utils/boxApi.ts b/src/utils/boxApi.ts new file mode 100644 index 0000000..2680e5d --- /dev/null +++ b/src/utils/boxApi.ts @@ -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 = new Map(); + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + const url = `${this.apiCameras}?limit=${limit}&offset=${offset}`; + return await this.getCamerasByUrl(url, token); + } + + public async getEventsByUrl(url: string, token: string | null = null): Promise { + 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 { + // 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 { + // 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 { + // 计算 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 { + // try { + // return await this.getEvents(1, 0, token); + // } catch (error) { + // throw error; + // } + // } + public async getOneEvent(token: string | null = null): Promise { + try { + // 调用 getEvents 方法,设置 pageSize 为 1,currentPage 为 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 { + 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 { + 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 { + 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 }; diff --git a/src/utils/superbox.js b/src/utils/superbox.js index 1db103a..f61b6b3 100644 --- a/src/utils/superbox.js +++ b/src/utils/superbox.js @@ -6,7 +6,7 @@ export const getSuperboxApiConfig = (address) => { const LOGIN_ROUTE = BASE_ROUTE + "/auth/login"; const LOGOUT_ROUTE = BASE_ROUTE + "/auth/logout"; 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"; 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) => { 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 - .get(api.events, { + .get(urlWithParams, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, @@ -98,7 +102,10 @@ export const getEvents = (token, address = null) => { }) .then((res) => { 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); }) diff --git a/src/utils/superboxApi.ts b/src/utils/superboxApi.ts index 1b398ff..4ec17f7 100644 --- a/src/utils/superboxApi.ts +++ b/src/utils/superboxApi.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-useless-catch */ import axios from 'axios'; class SuperboxApi { @@ -7,6 +6,9 @@ class SuperboxApi { 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"; @@ -28,7 +30,7 @@ class SuperboxApi { public constructor( address: string = "", port: number = 0 - ) { + ) { this.setAddress(address); this.setPort(port); this.axios = axios.create({ @@ -53,12 +55,11 @@ class SuperboxApi { const loginData = { username: username, password: password, - cookieless: cookieLess ? "True" : "False" + cookieless: cookieLess ? "true" : "false" // 这里会根据 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); @@ -84,6 +85,55 @@ class SuperboxApi { } } + public async addUser(username: string, password: string, email: string="", token: string | null = null): Promise { + 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 { + 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 { + 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 { try { const res = await this.axios.get(url, this._authHeader(token)); @@ -197,4 +247,4 @@ class SuperboxApi { } -export { SuperboxApi }; \ No newline at end of file +export { SuperboxApi };