本地告警页面V0

This commit is contained in:
龚皓
2024-09-04 16:23:57 +08:00
commit c9ba2ad556
29 changed files with 3831 additions and 0 deletions

13
src/utils/Superbox.ts Normal file
View File

@@ -0,0 +1,13 @@
import { SuperboxApi } from "@/utils/superboxApi";
const superbox = new SuperboxApi();
const useSuperbox = (address: string = "", port: number = 0) => {
superbox.setAddress(address);
superbox.setPort(port);
return superbox;
}
export {
useSuperbox,
}

36
src/utils/axios-config.ts Normal file
View File

@@ -0,0 +1,36 @@
// axios-config.ts
import axios from 'axios';
const axiosInstance = axios.create({
// baseURL: 'https://test1.turingvideo.cn/api/v1',
baseURL: 'http://127.0.0.1:8000/api/v1',
timeout: 10000,
});
axiosInstance.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
axiosInstance.interceptors.response.use(
response => {
return response;
},
error => {
if (error.response && error.response.status === 401) {
localStorage.removeItem('token');
window.location.href = '/#/login'; // 重定向到登录页面
}
return Promise.reject(error);
}
);
export default axiosInstance;

View File

@@ -0,0 +1,127 @@
import { ref } from 'vue'
const access_token = ref(null)
const consumerId = ref(null)
const data = ref(null)
// 计数器
let consumeMessageCount = 0
const getAccessToken = async () => {
try {
const response = await fetch('/api/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '88651e249e734a5290b00345961a7458',
client_secret: 'fbd457384ba0423cb5d6b86e4c7d3afc'
})
})
if (!response.ok) throw new Error('Network response was not ok')
const result = await response.json()
console.log("access_token:>>>>>>>>>", result)
access_token.value = result.access_token
} catch (error) {
console.error('Error fetching access token:', error)
}
}
const createConsumer = async () => {
try {
const token = access_token.value
if (!token) throw new Error('Access token not found')
const response = await fetch('/api/api/v1/mq/consumer/group1', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`
}
})
if (!response.ok) throw new Error('Network response was not ok')
const result = await response.json()
console.log("createConsumer:>>>>>>>>>", result.data)
consumerId.value = result.data.consumerId
} catch (error) {
console.error('Error creating consumer:', error)
}
}
const consumeMessage = async () => {
try {
const token = access_token.value
const cid = consumerId.value
if (!token || !cid) throw new Error('Token or Consumer ID not found')
const response = await fetch('/api/api/v1/mq/consumer/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Bearer ${token}`
},
body: new URLSearchParams({
autoCommit: 'true',
consumerId: cid
})
})
if (!response.ok) throw new Error('Network response was not ok')
const result = await response.json()
// 解析 content 数据
const parsedData = result.data.map(item => {
const content = JSON.parse(item.content.replace(/\\/g, '')) // 去除反斜杠
return {
...item,
content
}
})
data.value = parsedData
console.log("consumeMessage:>>>>>>>>>", parsedData)
consumeMessageCount++
console.log(`consumeMessage request count: ${consumeMessageCount}`)
return parsedData
} catch (error) {
console.error('Error consuming message:', error)
return []
}
}
// 定时器管理
let refreshTokenIntervalId = null
let consumeMessageIntervalId = null
const startAutoRefresh = () => {
// 1小时刷新一次 getAccessToken 和 createConsumer
refreshTokenIntervalId = setInterval(async () => {
await getAccessToken()
await createConsumer()
}, 3600000) // 3600000ms = 1小时
// 每25秒触发一次 consumeMessage
consumeMessageIntervalId = setInterval(async () => {
await consumeMessage()
}, 25000) // 25000ms = 25秒
}
const stopAutoRefresh = () => {
if (refreshTokenIntervalId) clearInterval(refreshTokenIntervalId)
if (consumeMessageIntervalId) clearInterval(consumeMessageIntervalId)
}
export {
access_token,
consumerId,
data,
getAccessToken,
createConsumer,
consumeMessage,
startAutoRefresh,
stopAutoRefresh
}

30
src/utils/misc.ts Normal file
View File

@@ -0,0 +1,30 @@
const JWT_TOKEN = 'token';
const useGetToken = (failedProc: () => void) => {
const getToken = (): string => {
const token = sessionStorage.getItem(JWT_TOKEN);
if (!token) {
failedProc();
return ""
}
return token
}
return getToken
}
const useSetToken = () => {
const setToken = (token: string) => {
sessionStorage.setItem(JWT_TOKEN, token);
}
return setToken
}
const useClearToken = () => {
const clearToken = () => {
sessionStorage.removeItem(JWT_TOKEN);
}
return clearToken
}
export { useGetToken, useSetToken, useClearToken }

160
src/utils/superbox.js Normal file
View File

@@ -0,0 +1,160 @@
import axios from "axios";
export const getSuperboxApiConfig = (address) => {
const PORT = 8000;
const BASE_ROUTE = "/api/v1";
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 ALGORITHM_ROUTE = BASE_ROUTE + "/algorithms";
let addr = address;
if (!addr) {
addr = window.location.host.replace(/:\d+/, "");
console.log("No address provided, using " + addr);
}
const superboxAddress = "http://" + addr + ":" + PORT.toString();
return {
base: superboxAddress + BASE_ROUTE,
login: superboxAddress + LOGIN_ROUTE,
logout: superboxAddress + LOGOUT_ROUTE,
cameras: superboxAddress + CAMERA_ROUTE,
events: superboxAddress + EVENTS_ROUTE,
algorithms: superboxAddress + ALGORITHM_ROUTE,
};
/*return {
base: "/api/v1",
login: "/api/v1/auth/login",
logout: "/api/v1/auth/logout",
cameras: "/api/v1/camera/cameras",
events: "/api/v1/event/events",
};*/
};
axios.defaults.withCredentials = true;
export const login = (username, password, address = null) => {
return new Promise((resolve, reject) => {
const api = getSuperboxApiConfig(address);
axios
.post(
api.login,
{
username: username,
password: password,
cookieless: false,
},
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((res) => {
if (res.data.err.ec === 0) {
resolve(res.data.ret.token);
}
reject(res.data.err);
})
.catch((err) => {
reject(err);
});
});
};
export const getCameras = (token, address = null) => {
return new Promise((resolve, reject) => {
const api = getSuperboxApiConfig(address);
axios
.get(api.cameras, {
withCredentials: true,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
if (res.data.err.ec === 0) {
resolve(res.data.ret.results);
}
reject(res.data.err);
})
.catch((err) => {
reject(err);
});
});
};
export const getEvents = (token, address = null) => {
return new Promise((resolve, reject) => {
const api = getSuperboxApiConfig(address);
axios
.get(api.events, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
if (res.data.err.ec === 0) {
resolve(res.data.ret.results);
}
reject(res.data.err);
})
.catch((err) => {
reject(err);
});
});
};
export const getAlgorithms = (token, address = null) => {
return new Promise((resolve, reject) => {
const api = getSuperboxApiConfig(address);
axios
.get(api.algorithms, {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
if (res.data.err.ec === 0) {
resolve(res.data.ret);
}
reject(res.data.err);
})
.catch((err) => {
reject(err);
});
});
};
var codeNameMap = {};
export const initCodeNameMap = async (token, address = null) => {
try {
const algorithms = await getAlgorithms(token, address);
algorithms.forEach((algorithm) => {
codeNameMap[algorithm.code_name] = algorithm.name;
});
return true;
} catch (err) {
console.log(err);
return false;
}
};
export const codenameTranslate = (codeName) => {
return codeNameMap[codeName];
};
export default {
login,
getCameras,
getEvents,
getSuperboxApiConfig,
initCodeNameMap,
codenameTranslate,
getAlgorithms,
};

200
src/utils/superboxApi.ts Normal file
View File

@@ -0,0 +1,200 @@
/* eslint-disable no-useless-catch */
import axios from 'axios';
class SuperboxApi {
private readonly defaultPort: number = 8000;
private readonly apiLogin: string = "/auth/login";
private readonly apiLogout: string = "/auth/logout";
private readonly apiCameras: string = "/cameras";
private readonly apiEvents: string = "/events";
private readonly apiAlgorithms: string = "/algorithms";
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
) {
this.setAddress(address);
this.setPort(port);
this.axios = axios.create({
baseURL: `http://${this.address}:${this.port}/api/v1`,
withCredentials: true
})
}
public setAddress(address: string) {
this.address = address === "" ? this._boxAddr() : address;
}
public setPort(port: number) {
this.port = port === 0 ? this.defaultPort : port;
}
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 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 getOneEvent(token: string | null = null): Promise<any> {
try {
return await this.getEvents(1, 0, token);
} 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;
return {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${access_token}`,
}
}
}
private _boxAddr() {
return window.location.host.replace(/:\d+/, "");
}
}
export { SuperboxApi };