Browse Source

左侧菜单右键事件

master
chendingwei 2 years ago
parent
commit
18daa00ca6
  1. 2
      components.d.ts
  2. 6
      src/App.vue
  3. 8
      src/store/index.ts
  4. 317
      src/utils/webrtc-streamer/webrtcstreamer.js
  5. 60
      src/views/page/aside/cameraLeftMenu.vue
  6. 92
      src/views/page/cameraCenter.vue

2
components.d.ts

@ -8,6 +8,7 @@ export {}
declare module '@vue/runtime-core' { declare module '@vue/runtime-core' {
export interface GlobalComponents { export interface GlobalComponents {
AButton: typeof import('ant-design-vue/es')['Button'] AButton: typeof import('ant-design-vue/es')['Button']
ADirectoryTree: typeof import('ant-design-vue/es')['DirectoryTree']
ADropdown: typeof import('ant-design-vue/es')['Dropdown'] ADropdown: typeof import('ant-design-vue/es')['Dropdown']
AForm: typeof import('ant-design-vue/es')['Form'] AForm: typeof import('ant-design-vue/es')['Form']
AFormItem: typeof import('ant-design-vue/es')['FormItem'] AFormItem: typeof import('ant-design-vue/es')['FormItem']
@ -20,6 +21,7 @@ declare module '@vue/runtime-core' {
ARow: typeof import('ant-design-vue/es')['Row'] ARow: typeof import('ant-design-vue/es')['Row']
ASelect: typeof import('ant-design-vue/es')['Select'] ASelect: typeof import('ant-design-vue/es')['Select']
ATree: typeof import('ant-design-vue/es')['Tree'] ATree: typeof import('ant-design-vue/es')['Tree']
ATreeNode: typeof import('ant-design-vue/es')['TreeNode']
Draggable: typeof import('./src/components/Draggable.vue')['default'] Draggable: typeof import('./src/components/Draggable.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink'] RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']

6
src/App.vue

@ -14,7 +14,7 @@ import { useStore } from '@/store';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import MqttUnit from "@/utils/mqttunit"; import MqttUnit from "@/utils/mqttunit";
import { onMounted } from 'vue'; import { onMounted } from 'vue';
import {WebRtcStreamer} from '@/utils/webrtc-streamer/webrtcstreamer.js' // import {WebRtcStreamer} from '@/utils/webrtc-streamer/webrtcstreamer.js'
let pinia = useStore() let pinia = useStore()
@ -22,9 +22,9 @@ onMounted(() => {
// //
document.oncontextmenu = new Function("event.returnValue=false"); document.oncontextmenu = new Function("event.returnValue=false");
// let client = new MqttUnit().mqttInit(); // let client = new MqttUnit().mqttInit();
let WebRtcStreamerRt=WebRtcStreamer() // let WebRtcStreamerRt=WebRtcStreamer()
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') { if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
window.WebRtcStreamer = WebRtcStreamerRt; // window.WebRtcStreamer = WebRtcStreamerRt;
} }
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = WebRtcStreamerRt; module.exports = WebRtcStreamerRt;

8
src/store/index.ts

@ -4,14 +4,19 @@ export const useStore = defineStore('Index', {
return { return {
//当前相机id //当前相机id
curSelectKey: "", curSelectKey: "",
//右键关闭视频
closeVideoKey:"",
//存放相机数组 //存放相机数组
cameraMap: new Map<string, any>(), cameraMap: new Map<string, any>(),
//左侧菜单树状结构
treeData: <any[]>[], treeData: <any[]>[],
audioCount: 0, audioCount: 0,
audioCurrentCount: 0, audioCurrentCount: 0,
editType: 0, editType: 0,
addLabel: { cmMarkGroupId: 0, labelType: "", isAddLabel: false }, addLabel: { cmMarkGroupId: 0, labelType: "", isAddLabel: false },
//当前选中的树节点
curTreeKey: "", curTreeKey: "",
//标签组类
labelGroupList: [] labelGroupList: []
} }
}, },
@ -30,6 +35,9 @@ export const useStore = defineStore('Index', {
updateCurSelectKey(key: string) { updateCurSelectKey(key: string) {
this.curSelectKey = key this.curSelectKey = key
}, },
updateCloseVideoKey(key: string) {
this.closeVideoKey = key
},
updateCurTreeKey(key: string) { updateCurTreeKey(key: string) {
this.curTreeKey = key this.curTreeKey = key
}, },

317
src/utils/webrtc-streamer/webrtcstreamer.js

@ -1,317 +0,0 @@
export let WebRtcStreamer = function () {
/**
* Interface with WebRTC-streamer API
* @constructor
* @param {string} videoElement - id of the video element tag
* @param {string} srvurl - url of webrtc-streamer (default is current location)
*/
var WebRtcStreamer = function WebRtcStreamer(videoElement, srvurl) {
if (typeof videoElement === "string") {
this.videoElement = document.getElementById(videoElement);
} else {
this.videoElement = videoElement;
}
this.srvurl = srvurl || location.protocol + "//" + window.location.hostname + ":" + window.location.port;
this.pc = null;
this.mediaConstraints = {offerToReceiveAudio: true, offerToReceiveVideo: true};
this.iceServers = null;
this.earlyCandidates = [];
}
WebRtcStreamer.prototype._handleHttpErrors = function (response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
/**
* Connect a WebRTC Stream to videoElement
* @param {string} videourl - id of WebRTC video stream
* @param {string} audiourl - id of WebRTC audio stream
* @param {string} options - options of WebRTC call
* @param {string} stream - local stream to send
*/
WebRtcStreamer.prototype.connect = function (videourl, audiourl, options, localstream) {
this.disconnect();
// getIceServers is not already received
if (!this.iceServers) {
console.log("Get IceServers");
fetch(this.srvurl + "/api/getIceServers")
.then(this._handleHttpErrors)
.then((response) => (response.json()))
.then((response) => this.onReceiveGetIceServers.call(this, response, videourl, audiourl, options, localstream))
.catch((error) => this.onError("getIceServers " + error))
} else {
this.onReceiveGetIceServers(this.iceServers, videourl, audiourl, options, localstream);
}
}
/**
* Disconnect a WebRTC Stream and clear videoElement source
*/
WebRtcStreamer.prototype.disconnect = function () {
if (this.videoElement?.srcObject) {
this.videoElement.srcObject.getTracks().forEach(track => {
track.stop()
this.videoElement.srcObject.removeTrack(track);
});
}
if (this.pc) {
fetch(this.srvurl + "/api/hangup?peerid=" + this.pc.peerid)
.then(this._handleHttpErrors)
.catch((error) => this.onError("hangup " + error))
try {
this.pc.close();
} catch (e) {
console.log("Failure close peer connection:" + e);
}
this.pc = null;
}
}
/*
* GetIceServers callback
*/
WebRtcStreamer.prototype.onReceiveGetIceServers = function (iceServers, videourl, audiourl, options, stream) {
this.iceServers = iceServers;
this.pcConfig = iceServers || {"iceServers": []};
try {
this.createPeerConnection();
var callurl = this.srvurl + "/api/call?peerid=" + this.pc.peerid + "&url=" + encodeURIComponent(videourl);
if (audiourl) {
callurl += "&audiourl=" + encodeURIComponent(audiourl);
}
if (options) {
callurl += "&options=" + encodeURIComponent(options);
}
if (stream) {
this.pc.addStream(stream);
}
// clear early candidates
this.earlyCandidates.length = 0;
// create Offer
var bind = this;
this.pc.createOffer(this.mediaConstraints).then(function (sessionDescription) {
console.log("Create offer:" + JSON.stringify(sessionDescription));
bind.pc.setLocalDescription(sessionDescription
, function () {
fetch(callurl, {method: "POST", body: JSON.stringify(sessionDescription)})
.then(bind._handleHttpErrors)
.then((response) => (response.json()))
.catch((error) => bind.onError("call " + error))
.then((response) => bind.onReceiveCall.call(bind, response))
.catch((error) => bind.onError("call " + error))
}
, function (error) {
console.log("setLocalDescription error:" + JSON.stringify(error));
});
}, function (error) {
alert("Create offer error:" + JSON.stringify(error));
});
} catch (e) {
this.disconnect();
alert("connect error: " + e);
}
}
WebRtcStreamer.prototype.getIceCandidate = function () {
fetch(this.srvurl + "/api/getIceCandidate?peerid=" + this.pc.peerid)
.then(this._handleHttpErrors)
.then((response) => (response.json()))
.then((response) => this.onReceiveCandidate.call(this, response))
.catch((error) => bind.onError("getIceCandidate " + error))
}
/*
* create RTCPeerConnection
*/
WebRtcStreamer.prototype.createPeerConnection = function () {
console.log("createPeerConnection config: " + JSON.stringify(this.pcConfig));
this.pc = new RTCPeerConnection(this.pcConfig);
var pc = this.pc;
pc.peerid = Math.random();
var bind = this;
pc.onicecandidate = function (evt) {
bind.onIceCandidate.call(bind, evt);
};
pc.onaddstream = function (evt) {
bind.onAddStream.call(bind, evt);
};
pc.oniceconnectionstatechange = function (evt) {
console.log("oniceconnectionstatechange state: " + pc.iceConnectionState);
if (bind.videoElement) {
if (pc.iceConnectionState === "connected") {
bind.videoElement.style.opacity = "1.0";
} else if (pc.iceConnectionState === "disconnected") {
bind.videoElement.style.opacity = "0.25";
} else if ((pc.iceConnectionState === "failed") || (pc.iceConnectionState === "closed")) {
bind.videoElement.style.opacity = "0.5";
} else if (pc.iceConnectionState === "new") {
bind.getIceCandidate.call(bind)
}
}
}
pc.ondatachannel = function (evt) {
console.log("remote datachannel created:" + JSON.stringify(evt));
evt.channel.onopen = function () {
console.log("remote datachannel open");
this.send("remote channel openned");
}
evt.channel.onmessage = function (event) {
console.log("remote datachannel recv:" + JSON.stringify(event.data));
}
}
pc.onicegatheringstatechange = function () {
if (pc.iceGatheringState === "complete") {
const recvs = pc.getReceivers();
recvs.forEach((recv) => {
if (recv.track && recv.track.kind === "video") {
console.log("codecs:" + JSON.stringify(recv.getParameters().codecs))
}
});
}
}
try {
var dataChannel = pc.createDataChannel("ClientDataChannel");
dataChannel.onopen = function () {
console.log("local datachannel open");
this.send("local channel openned");
}
dataChannel.onmessage = function (evt) {
console.log("local datachannel recv:" + JSON.stringify(evt.data));
}
} catch (e) {
console.log("Cannor create datachannel error: " + e);
}
console.log("Created RTCPeerConnnection with config: " + JSON.stringify(this.pcConfig));
return pc;
}
/*
* RTCPeerConnection IceCandidate callback
*/
WebRtcStreamer.prototype.onIceCandidate = function (event) {
if (event.candidate) {
if (this.pc.currentRemoteDescription) {
this.addIceCandidate(this.pc.peerid, event.candidate);
} else {
this.earlyCandidates.push(event.candidate);
}
} else {
console.log("End of candidates.");
}
}
WebRtcStreamer.prototype.addIceCandidate = function (peerid, candidate) {
fetch(this.srvurl + "/api/addIceCandidate?peerid=" + peerid, {method: "POST", body: JSON.stringify(candidate)})
.then(this._handleHttpErrors)
.then((response) => (response.json()))
.then((response) => {
console.log("addIceCandidate ok:" + response)
})
.catch((error) => this.onError("addIceCandidate " + error))
}
/*
* RTCPeerConnection AddTrack callback
*/
WebRtcStreamer.prototype.onAddStream = function (event) {
console.log("Remote track added:" + JSON.stringify(event));
this.videoElement.srcObject = event.stream;
var promise = this.videoElement.play();
if (promise !== undefined) {
var bind = this;
promise.catch(function (error) {
console.warn("error:" + error);
bind.videoElement.setAttribute("controls", true);
});
}
}
/*
* AJAX /call callback
*/
WebRtcStreamer.prototype.onReceiveCall = function (dataJson) {
var bind = this;
console.log("offer: " + JSON.stringify(dataJson));
var descr = new RTCSessionDescription(dataJson);
this.pc.setRemoteDescription(descr
, function () {
console.log("setRemoteDescription ok");
while (bind.earlyCandidates.length) {
var candidate = bind.earlyCandidates.shift();
bind.addIceCandidate.call(bind, bind.pc.peerid, candidate);
}
bind.getIceCandidate.call(bind)
}
, function (error) {
console.log("setRemoteDescription error:" + JSON.stringify(error));
});
}
/*
* AJAX /getIceCandidate callback
*/
WebRtcStreamer.prototype.onReceiveCandidate = function (dataJson) {
console.log("candidate: " + JSON.stringify(dataJson));
if (dataJson) {
for (var i = 0; i < dataJson.length; i++) {
var candidate = new RTCIceCandidate(dataJson[i]);
console.log("Adding ICE candidate :" + JSON.stringify(candidate));
this.pc.addIceCandidate(candidate
, function () {
console.log("addIceCandidate OK");
}
, function (error) {
console.log("addIceCandidate error:" + JSON.stringify(error));
});
}
this.pc.addIceCandidate();
}
}
/*
* AJAX callback for Error
*/
WebRtcStreamer.prototype.onError = function (status) {
console.log("onError:" + status);
}
return WebRtcStreamer;
};
if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
window.WebRtcStreamer = WebRtcStreamer;
}
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = WebRtcStreamer;
}

60
src/views/page/aside/cameraLeftMenu.vue

@ -12,8 +12,8 @@
</div> </div>
<div class="container clearfix"> <div class="container clearfix">
<a-tree :tree-data="treeData" v-model:expandedKeys="expandedKeys" :expandAction="'click'" <a-tree :tree-data="treeData" v-model:expandedKeys="expandedKeys" :expandAction="'click'"
@select="selectCamera"> @select="selectCamera" @rightClick="onRightClick">
<template #title="{ key: treeKey, title }"> <template #title="{ key: treeKey, title: title }">
<a-dropdown :trigger="['contextmenu']"> <a-dropdown :trigger="['contextmenu']">
<span>{{ title }}</span> <span>{{ title }}</span>
<template #overlay> <template #overlay>
@ -35,6 +35,9 @@ import { ref, onMounted, onUnmounted, watch } from "vue";
import { useStore } from '@/store/index'; import { useStore } from '@/store/index';
import * as cameraApi from '@/axios/cameraBase/cameraApi'; import * as cameraApi from '@/axios/cameraBase/cameraApi';
let piniaStore = useStore(); let piniaStore = useStore();
const NodeTreeItem = ref()
let searchStr = ref('');
const expandedKeys = ref<any[]>([]);
const treeData = ref<any>([ const treeData = ref<any>([
// { // {
// title: '', // title: '',
@ -52,25 +55,8 @@ const treeData = ref<any>([
// ], // ],
// } // }
]); ]);
const onContextMenuClick = (treeKey: string, menuKey: string) => {
console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);
//key
if (menuKey == "open") {
let arr = [...expandedKeys.value]
arr.push(treeKey)
arr = [...new Set(arr)]
expandedKeys.value = arr
} else if (menuKey == "close") {
expandedKeys.value = expandedKeys.value.filter((item: any) => {
return item != treeKey
})
} else if (menuKey == "delete") {
}
};
let searchStr = ref('');
const expandedKeys = ref<any[]>([]);
onMounted(() => { onMounted(() => {
init() init()
@ -90,14 +76,44 @@ watch(searchStr, (newVal, oldVal) => {
}); });
expandedKeys.value = expandedKeyArr expandedKeys.value = expandedKeyArr
}) })
//
function onRightClick({ node }: any) {
NodeTreeItem.value = {
cbCameraId: node.cbCameraId,
isGroup: node.isGroup,
id: node.key,
title: node.title,
key: node.key,
};
}
const onContextMenuClick = (treeKey: string, menuKey: string) => {
console.log(`treeKey: ${treeKey}, menuKey: ${menuKey},NodeTreeItem.value:`,NodeTreeItem.value);
//key
if (menuKey == "open") {
let arr = [...expandedKeys.value]
arr.push(treeKey)
arr = [...new Set(arr)]
expandedKeys.value = arr
} else if (menuKey == "close") {
expandedKeys.value = expandedKeys.value.filter((item: any) => {
return item != treeKey
})
} else if (menuKey == "delete") {
}
};
// //
function selectCamera(treeKeyArr: any, item: any) { function selectCamera(treeKeyArr: any, item: any) {
if (treeKeyArr.length != 0) { if (treeKeyArr.length != 0) {
console.log(treeKeyArr);
piniaStore.updateCurTreeKey(treeKeyArr[0].toString()) piniaStore.updateCurTreeKey(treeKeyArr[0].toString())
} }
if (!item.node.isGroup) { // if (!item.node.isGroup) {
piniaStore.updateCurSelectKey(item.node.cbCameraId.toString()) piniaStore.updateCurSelectKey(item.node.cbCameraId.toString())
} // }
} }
// //
function searchFn(newVal: string, arr: any[]): any { function searchFn(newVal: string, arr: any[]): any {

92
src/views/page/cameraCenter.vue

@ -87,13 +87,13 @@ let canvasWidth = ref(0)
let canvasHeight = ref(0) let canvasHeight = ref(0)
let curSelectKey = storeToRefs(piniaStore).curSelectKey let curSelectKey = storeToRefs(piniaStore).curSelectKey
let cameraMap = storeToRefs(piniaStore).cameraMap let cameraMap = storeToRefs(piniaStore).cameraMap
let webRtcServer: any = ref()
let isActiveChoose = ref(false) let isActiveChoose = ref(false)
let labelList = ref<any[]>([]) let labelList = ref<any[]>([])
let addLabel = storeToRefs(piniaStore).addLabel let addLabel = storeToRefs(piniaStore).addLabel
let addLabelLeft = ref(0); let addLabelLeft = ref(0);
let addLabelTop = ref(0); let addLabelTop = ref(0);
var jessibuca = ref(); var jessibuca = ref();
const curVideoKey=ref()
onMounted(() => { onMounted(() => {
{ {
player = <HTMLVideoElement>document.querySelector('#videoPlayer'); player = <HTMLVideoElement>document.querySelector('#videoPlayer');
@ -108,9 +108,7 @@ onMounted(() => {
watch(curSelectKey, (newVal, oldVal) => { watch(curSelectKey, (newVal, oldVal) => {
labelList.value = []
switchCamera(newVal) switchCamera(newVal)
jessibuca.value.play("ws://192.168.1.119:8080/jessica/live/test.flv")
}) })
watch(addLabel, (newVal, oldVal) => { watch(addLabel, (newVal, oldVal) => {
if (newVal.isAddLabel) { if (newVal.isAddLabel) {
@ -123,36 +121,36 @@ watch(addLabel, (newVal, oldVal) => {
} }
}) })
// //
function create(){ function create() {
var showOperateBtns = false; // var showOperateBtns = false; //
var forceNoOffscreen = true; // var forceNoOffscreen = true; //
jessibuca.value = new Jessibuca({ jessibuca.value = new Jessibuca({
container: player, container: player,
videoBuffer: 1, // videoBuffer: 1, //
isResize: false, isResize: false,
text: "", text: "",
loadingText: "", loadingText: "",
useMSE: false, useMSE: false,
debug: false, debug: false,
showBandwidth: showOperateBtns, // showBandwidth: showOperateBtns, //
operateBtns: { operateBtns: {
fullscreen: showOperateBtns, fullscreen: showOperateBtns,
screenshot: showOperateBtns, screenshot: showOperateBtns,
play: showOperateBtns, play: showOperateBtns,
audio: false, audio: false,
recorder: false recorder: false
}, },
forceNoOffscreen: forceNoOffscreen, forceNoOffscreen: forceNoOffscreen,
isNotMute: false, isNotMute: false,
},); },);
jessibuca.value.onLog = (msg:any) => console.error(msg); jessibuca.value.onLog = (msg: any) => console.error(msg);
jessibuca.value.onRecord = (status:any) => console.log('onRecord', status); jessibuca.value.onRecord = (status: any) => console.log('onRecord', status);
jessibuca.value.onPause = () => console.log('onPause'); jessibuca.value.onPause = () => console.log('onPause');
jessibuca.value.onPlay = () => console.log('onPlay'); jessibuca.value.onPlay = () => console.log('onPlay');
jessibuca.value.onFullscreen = (msg:any) => console.log('onFullscreen', msg); jessibuca.value.onFullscreen = (msg: any) => console.log('onFullscreen', msg);
jessibuca.value.onMute = (msg:any) => console.log('onMute', msg); jessibuca.value.onMute = (msg: any) => console.log('onMute', msg);
} }
// //
@ -190,7 +188,7 @@ const onContextMenuClick = (item: any, menuKey: string,) => {
// console.log(item); // console.log(item);
//key //key
if (menuKey == "edit") { if (menuKey == "edit") {
popup("编辑标签", [h(LabelEditModel,{ modelData: item})], "editLabel"); popup("编辑标签", [h(LabelEditModel, { modelData: item })], "editLabel");
} else if (menuKey == "delete") { } else if (menuKey == "delete") {
Modal.confirm({ Modal.confirm({
zIndex: 10000, zIndex: 10000,
@ -315,20 +313,15 @@ function switchCamera(cameraId: string) {
if (!cameraObj) { if (!cameraObj) {
console.log('camera obj not found.'); console.log('camera obj not found.');
return; return;
} }
// object to proxy, ? jessibuca.value.destroy();
console.log(cameraObj, '111111'); create()
labelList.value = []
// step2, get camera rtsp url.
console.log('get camera rtsp url.');
let rtspUrl = getRtspUrl(cameraObj);
// step3, connect webrtc-steamer.
console.log('connect webrtc-steamer.'); console.log('connect webrtc-steamer.');
// webRtcServer.value.disconnect(); jessibuca.value.play("ws://192.168.1.119:8080/jessica/live/test.flv")
// webRtcServer.value.connect(rtspUrl); curVideoKey.value=cameraId
// step4, active camera searcher. // step4, active camera searcher.
markSearchApi.IsExistsSearcher({ markSearchApi.IsExistsSearcher({
'cameraId': cameraObj.id 'cameraId': cameraObj.id
@ -432,16 +425,13 @@ function drawMarkLabels(markLabels: Array<any>) {
ctx.closePath(); ctx.closePath();
} }
} }
//
window.onbeforeunload = () => {
jessibuca.value.destroy()
};
onUnmounted(() => { onUnmounted(() => {
{ {
console.log('beforeUnmount.');
// webRtcServer
if (!webRtcServer.value) return;
console.log(123);
jessibuca.value.destroy() jessibuca.value.destroy()
// webRtcServer.value.disconnect();
// webRtcServer.value = null;
} }
}) })
</script> </script>

Loading…
Cancel
Save