How do you get the video data? - javascript

I want to take the video data and convert it using cv2. Which part is the video data? It's a code that might be related.
I want to send video data from the client to the server using webrtc, and convert and send the converted video from server to cv2 from the client again.
app.js
from flask import Flask, render_template, request, redirect, url_for, session
from flask_socketio import SocketIO, emit, join_room, leave_room
# Next two lines are for the issue: https://github.com/miguelgrinberg/python-engineio/issues/142
import os
secretKey = os.urandom(24)
app = Flask(__name__)
app.config['SECRET_KEY'] = secretKey
print("secretKey is ",secretKey)
socketio = SocketIO(app)
_users_in_room = {} # stores room wise user list
_room_of_sid = {} # stores room joined by an used
_name_of_sid = {} # stores display name of users
#app.route("/",methods=["GET", "POST"]) #첫번째 로그인화면
def loginPage():
if request.method == "POST":
room_id = request.form['room_id']
return redirect(url_for('enter_room',room_id=room_id))
return render_template("home.html")
#app.route("/<string:room_id>/checkpoint/", methods=["GET", "POST"]) #두번째 화면
def entry_checkpoint(room_id):
if request.method == "POST":
display_name = request.form['display_name']
mute_video = request.form['mute_video']
session[room_id] = {"name": display_name, "mute_video":mute_video}
return redirect(url_for("enter_room", room_id=room_id))
return render_template("chatroom_checkpoint.html", room_id=room_id)
#app.route("/<string:room_id>/") #세번째 스트림화면
def enter_room(room_id):
if room_id not in session:
return redirect(url_for("entry_checkpoint", room_id=room_id))
return render_template("chatroom.html", room_id=room_id, display_name=session[room_id]["name"], mute_video=session[room_id]["mute_video"])
#socketio.on("connect")
def on_connect():
sid = request.sid
print("New socket connected ", sid)
#socketio.on("join-room")
def on_join_room(data):
sid = request.sid
room_id = data["room_id"]
display_name = session[room_id]["name"]
# register sid to the room
join_room(room_id)
_room_of_sid[sid] = room_id
_name_of_sid[sid] = display_name
# broadcast to others in the room
print("[{}] New member joined: {}<{}>".format(room_id, display_name, sid))
emit("user-connect", {"sid": sid, "name": display_name}, broadcast=True, include_self=False, room=room_id)
# add to user list maintained on server
if room_id not in _users_in_room:
_users_in_room[room_id] = [sid]
emit("user-list", {"my_id": sid}) # send own id only
else:
usrlist = {u_id:_name_of_sid[u_id] for u_id in _users_in_room[room_id]}
emit("user-list", {"list": usrlist, "my_id": sid}) # send list of existing users to the new member
_users_in_room[room_id].append(sid) # add new member to user list maintained on server
print("\nusers: ", _users_in_room, "\n")
#socketio.on("disconnect")
def on_disconnect():
sid = request.sid
room_id = _room_of_sid[sid]
display_name = _name_of_sid[sid]
print("[{}] Member left: {}<{}>".format(room_id, display_name, sid))
emit("user-disconnect", {"sid": sid}, broadcast=True, include_self=False, room=room_id)
_users_in_room[room_id].remove(sid)
if len(_users_in_room[room_id]) == 0:
_users_in_room.pop(room_id)
_room_of_sid.pop(sid)
_name_of_sid.pop(sid)
print("\nusers: ", _users_in_room, "\n")
#socketio.on("data")
def on_data(data):
sender_sid = data['sender_id']
target_sid = data['target_id']
if sender_sid != request.sid:
print("[Not supposed to happen!] request.sid and sender_id don't match!!!")
if data["type"] != "new-ice-candidate":
print('{} message from {} to {}'.format(data["type"], sender_sid, target_sid))
socketio.emit('data', data, room=target_sid)
if __name__ == "__main__":
socketio.run(app, host='0.0.0.0', port='5050', debug=True)
chatroom_networking.js
var myID;
var _peer_list = {};
// socketio
var protocol = window.location.protocol;
var socket = io(protocol + '//' + document.domain + ':' + location.port, {autoConnect: false});
document.addEventListener("DOMContentLoaded", (event)=>{
startCamera();
});
var camera_allowed=false;
var mediaConstraints = {
audio: true, // We want an audio track
video: true
}
function startCamera()
{
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then((stream)=>{
myVideo.srcObject = stream;
camera_allowed = true;
//start the socketio connection
socket.connect();
})
.catch((e)=>{
console.log("getUserMedia Error! ", e);
alert("Error! Unable to access camera or mic! ");
});
}
socket.on("connect", ()=>{
console.log("socket connected....");
socket.emit("join-room", {"room_id": myRoomID});
});
socket.on("disconnect", (data)=>{
console.log("disconnect");
});
socket.on("user-connect", (data)=>{
console.log("user-connect ", data);
let peer_id = data["sid"];
let display_name = data["name"];
_peer_list[peer_id] = undefined; // add new user to user list
addVideoElement(peer_id, display_name);
});
socket.on("user-disconnect", (data)=>{
console.log("user-disconnect ", data);
let peer_id = data["sid"];
closeConnection(peer_id);
removeVideoElement(peer_id);
});
socket.on("user-list", (data)=>{
console.log("user list recvd ", data);
myID = data["my_id"];
if( "list" in data) // not the first to connect to room, existing user list recieved
{
let recvd_list = data["list"];
// add existing users to user list
for(peer_id in recvd_list)
{
display_name = recvd_list[peer_id];
_peer_list[peer_id] = undefined;
addVideoElement(peer_id, display_name);
}
start_webrtc();
}
});
function closeConnection(peer_id)
{
if(peer_id in _peer_list)
{
_peer_list[peer_id].onicecandidate = null;
_peer_list[peer_id].ontrack = null;
_peer_list[peer_id].onnegotiationneeded = null;
delete _peer_list[peer_id]; // remove user from user list
}
}
function log_user_list()
{
for(let key in _peer_list)
{
console.log(`${key}: ${_peer_list[key]}`);
}
}
//---------------[ webrtc ]--------------------
var PC_CONFIG = {
iceServers: [
{
urls: ['stun:stun.l.google.com:19302',
'stun:stun1.l.google.com:19302',
'stun:stun2.l.google.com:19302',
'stun:stun3.l.google.com:19302',
'stun:stun4.l.google.com:19302'
]
},
]
};
function log_error(e){console.log("[ERROR] ", e);}
function sendViaServer(data){socket.emit("data", data);}
socket.on("data", (msg)=>{
switch(msg["type"])
{
case "offer":
handleOfferMsg(msg);
break;
case "answer":
handleAnswerMsg(msg);
break;
case "new-ice-candidate":
handleNewICECandidateMsg(msg);
break;
}
});
function start_webrtc()
{
// send offer to all other members
for(let peer_id in _peer_list)
{
invite(peer_id);
}
}
function invite(peer_id)
{
if(_peer_list[peer_id]){console.log("[Not supposed to happen!] Attempting to start a connection that already exists!")}
else if(peer_id === myID){console.log("[Not supposed to happen!] Trying to connect to self!");}
else
{
console.log(`Creating peer connection for <${peer_id}> ...`);
createPeerConnection(peer_id);
let local_stream = myVideo.srcObject;
local_stream.getTracks().forEach((track)=>{_peer_list[peer_id].addTrack(track, local_stream);});
}
}
function createPeerConnection(peer_id)
{
_peer_list[peer_id] = new RTCPeerConnection(PC_CONFIG);
_peer_list[peer_id].onicecandidate = (event) => {handleICECandidateEvent(event, peer_id)};
_peer_list[peer_id].ontrack = (event) => {handleTrackEvent(event, peer_id)};
_peer_list[peer_id].onnegotiationneeded = () => {handleNegotiationNeededEvent(peer_id)};
}
function handleNegotiationNeededEvent(peer_id)
{
_peer_list[peer_id].createOffer()
.then((offer)=>{return _peer_list[peer_id].setLocalDescription(offer);})
.then(()=>{
console.log(`sending offer to <${peer_id}> ...`);
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "offer",
"sdp": _peer_list[peer_id].localDescription
});
})
.catch(log_error);
}
function handleOfferMsg(msg)
{
peer_id = msg['sender_id'];
console.log(`offer recieved from <${peer_id}>`);
createPeerConnection(peer_id);
let desc = new RTCSessionDescription(msg['sdp']);
_peer_list[peer_id].setRemoteDescription(desc)
.then(()=>{
let local_stream = myVideo.srcObject;
local_stream.getTracks().forEach((track)=>{_peer_list[peer_id].addTrack(track, local_stream);});
})
.then(()=>{return _peer_list[peer_id].createAnswer();})
.then((answer)=>{return _peer_list[peer_id].setLocalDescription(answer);})
.then(()=>{
console.log(`sending answer to <${peer_id}> ...`);
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "answer",
"sdp": _peer_list[peer_id].localDescription
});
})
.catch(log_error);
}
function handleAnswerMsg(msg)
{
peer_id = msg['sender_id'];
console.log(`answer recieved from <${peer_id}>`);
let desc = new RTCSessionDescription(msg['sdp']);
_peer_list[peer_id].setRemoteDescription(desc)
}
function handleICECandidateEvent(event, peer_id)
{
if(event.candidate){
sendViaServer({
"sender_id": myID,
"target_id": peer_id,
"type": "new-ice-candidate",
"candidate": event.candidate
});
}
}
function handleNewICECandidateMsg(msg)
{
console.log(`ICE candidate recieved from <${peer_id}>`);
var candidate = new RTCIceCandidate(msg.candidate);
_peer_list[msg["sender_id"]].addIceCandidate(candidate)
.catch(log_error);
}
function handleTrackEvent(event, peer_id)
{
console.log(`track event recieved from <${peer_id}>`);
if(event.streams)
{
getVideoObj(peer_id).srcObject = event.streams[0];
}
}
chatroom_ui.js
var myVideo;
document.addEventListener("DOMContentLoaded", (event)=>{
myVideo = document.getElementById("local_vid");
document.getElementById("room_link").innerHTML=`or the link: <span class="heading-mark">${window.location.href}</span>`;
});
function makeVideoElement(element_id, display_name)
{
let wrapper_div = document.createElement("div");
let vid_wrapper = document.createElement("div");
let vid = document.createElement("video");
let name_text = document.createElement("div");
wrapper_div.id = "div_"+element_id;
vid.id = "vid_"+element_id;
wrapper_div.className = "shadow video-item";
vid_wrapper.className = "vid-wrapper";
vid.autoplay = true;
vid_wrapper.appendChild(vid);
wrapper_div.appendChild(vid_wrapper);
console.log(wrapper_div)
return wrapper_div;
}
function addVideoElement(element_id)
{
document.getElementById("video_grid").appendChild(makeVideoElement(element_id));
}
function removeVideoElement(element_id)
{
let v = getVideoObj(element_id);
if(v.srcObject){
v.srcObject.getTracks().forEach(track => track.stop());
}
v.removeAttribute("srcObject");
v.removeAttribute("src");
document.getElementById("div_"+element_id).remove();
}
function getVideoObj(element_id)
{
return document.getElementById("vid_"+element_id);
}

Related

When Im sending message to specific user in SignalR chat im getting back message that i wrote

Screenshot how this problem looks in chat - https://imgur.com/a/2y7cImC
I immediately received the same text that i sent to user(sending time is randomized, dont look at it)
User that must receive the message get it without problem, but every time when method is invoked, all users get message text that was written in the input
Here`s the code of method that creating message
[HttpPost("create"), DisableRequestSizeLimit]
public async Task<ActionResult> CreateMessage(CreateMessageDto createMessageDto)
{
try
{
var authJWT = Request.Cookies["accessToken"];
var validatedJWT = _jwtService.ValidateJWT(authJWT);
Message messageToCreate;
if (createMessageDto.Type == "image" || createMessageDto.Type == "video" || createMessageDto.Type == "document")
{
var uploadFile = await UploadFile(createMessageDto.File);
if (uploadFile.Code == "error")
{
return Ok(new { code = "error", message = uploadFile.Message });
}
messageToCreate = new()
{
MessageId = Guid.NewGuid(),
Uid = createMessageDto.Uid,
Username = createMessageDto.Username,
Avatar = createMessageDto.Avatar,
Content = uploadFile.FileName,
Type = createMessageDto.Type,
CreatedAt = DateTime.Now,
InboxRefId = createMessageDto.InboxRefId
};
}
else
{
messageToCreate = new()
{
MessageId = Guid.NewGuid(),
Uid = createMessageDto.Uid,
Username = createMessageDto.Username,
Avatar = createMessageDto.Avatar,
Content = createMessageDto.Content,
Type = createMessageDto.Type,
CreatedAt = DateTime.Now,
InboxRefId = createMessageDto.InboxRefId
};
}
await _messageRepository.CreateMessage(messageToCreate);
await _chatHub.Clients.All.ReceiveMessage(messageToCreate);
return Ok(new { code = "success", message = messageToCreate });
} catch (Exception ex) {
return Unauthorized(new { code = "error", message = "Unauthorized" });
}
}
and from front-end part:
const connection = new HubConnectionBuilder()
.withUrl(`https://chatapitest.azurewebsites.net/hubs/chat`)
.withAutomaticReconnect()
.build();
connection
.start()
.then(() => {
console.log("connect");
// Receive message event listener
connection.on("ReceiveMessage", (message) => {
console.log("Receive!");
// console.log(message);
messageObj = {
id: chatMessages.length + 1,
message: message.content,
time: "00:" + n,
userType: "receiver",
// image: avatar4,
isFileMessage: false,
isImageMessage: false,
};
// console.log(messageObj);
setchatMessages((prev) => [...prev, messageObj]);
```

webrtc - connecting multiple clients to one specific client - python & javascript

I am currently working on webrtc project with multiple clients (5 - 4 with input video streams and 1 for showing them) and signaling server. Main goal is to connect clients on this way:
Every client with input video stream should be connected to client that will show all of video streams. It should be connected like that because I want to use webrtc so I can have low latency. I would also like to use web sockets for signaling server. Server is written in Python and clients in Javascript. Does anyone know how to accomplish that?
Server:
from aiohttp import web
import socketio
ROOM = 'room'
sessionIDs = []
sio = socketio.AsyncServer(cors_allowed_origins='*', ping_timeout=35)
app = web.Application()
sio.attach(app)
#sio.event
async def connect(sid, environ):
print('Connected', sid)
sessionIDs.append(sid)
await sio.emit('ready', room=ROOM, skip_sid=sid)
sio.enter_room(sid, ROOM)
#sio.event
def disconnect(sid):
sio.leave_room(sid, ROOM)
print('Disconnected', sid)
#sio.event
async def data(sid, data):
print('Message from {}: {}'.format(sid, data))
await sio.emit('data', data, room=ROOM, skip_sid=sid)
if __name__ == '__main__':
web.run_app(app, port=9999)
Client:
const SIGNALING_SERVER_URL = 'http://localhost:9999';
const TURN_SERVER_URL = 'localhost:3478';
const TURN_SERVER_USERNAME = 'username';
const TURN_SERVER_CREDENTIAL = 'credential';
const PC_CONFIG = {
iceServers: [
{
urls: 'turn:' + TURN_SERVER_URL + '?transport=tcp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL
},
{
urls: 'turn:' + TURN_SERVER_URL + '?transport=udp',
username: TURN_SERVER_USERNAME,
credential: TURN_SERVER_CREDENTIAL
}
]
};
// Signaling methods
let socket = io(SIGNALING_SERVER_URL, { autoConnect: false }, /*{query: 'loggeduser=finalClient'}*/ /*{auth: {token: 'my-token'}}*/);
socket.on('data', (data) => {
console.log('Data received: ', data);
handleSignalingData(data);
});
socket.on('ready', () => {
console.log('Ready');
// Connection with signaling server is ready, and so is local stream
createPeerConnection();
sendOffer();
});
let sendData = (data) => {
socket.emit('data', data);
};
// WebRTC methods
let pc;
let localStream;
let remoteStreamElement = document.querySelector('#remoteStream');
let getLocalStream = () => {
socket.connect();
}
let createPeerConnection = () => {
try {
pc = new RTCPeerConnection(PC_CONFIG);
pc.onicecandidate = onIceCandidate;
pc.ontrack = onTrack;
pc.addStream(localStream);
console.log('PeerConnection created');
} catch (error) {
console.error('PeerConnection failed: ', error);
}
};
let sendOffer = () => {
console.log('Send offer');
pc.createOffer().then(
setAndSendLocalDescription,
(error) => { console.error('Send offer failed: ', error); }
);
};
let sendAnswer = () => {
console.log('Send answer');
pc.createAnswer().then(
setAndSendLocalDescription,
(error) => { console.error('Send answer failed: ', error); }
);
};
let setAndSendLocalDescription = (sessionDescription) => {
pc.setLocalDescription(sessionDescription);
console.log('Local description set');
sendData(sessionDescription);
};
let onIceCandidate = (event) => {
if (event.candidate) {
console.log('ICE candidate');
sendData({
type: 'candidate',
candidate: event.candidate
});
}
};
let onTrack = (event) => {
console.log('Add track');
remoteStreamElement.srcObject = event.streams[0];
};
let handleSignalingData = (data) => {
switch (data.type) {
case 'offer':
createPeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(data));
sendAnswer();
break;
case 'answer':
pc.setRemoteDescription(new RTCSessionDescription(data));
break;
case 'candidate':
pc.addIceCandidate(new RTCIceCandidate(data.candidate));
break;
}
};
// Start connection
getLocalStream();
Currently main functionality is peer to peer connection between them, but I want to make new peer to peer connection (for every client - with input stream - connected to server) with specific client that will show all of them.

django channels custom token authenticated Websocket keeps disconnecting ERR_CONNECTION_RESET

i using react as my front end and django as my backend , as such , it requires me to use token based authentication with django channels. The method i am employing is by sending the authentication token as a cookie header. The methodology was taken from this git hub post here
So far , i have gotten most of the working parts together , however i don't seem to be able to persist the connection , it will always return an error in my console:
ERR_CONNECTION_RESET
Here is my code:
FRONTEND: Websocket.js
class WebSocketService{
static instance = null;
callbacks = {};
static getInstance(){
if (!WebSocketService.instance){
WebSocketService.instance = new WebSocketService();
}
return WebSocketService.instance;
}
constructor(){
this.socketRef = null;
}
connect(token){
var loc = window.location
var wsStart = 'ws://'
if (loc.protocol === 'https'){
wsStart = 'wss://'
}
const path = wsStart + 'localhost:8000'+ loc.pathname
// console.log(path)
// console.log(path + "?token=" + token)
document.cookie = 'authorization=' + token + ';'
console.log(document.cookie)
this.socketRef = new WebSocket(path)
this.socketRef.onmessage = e => {
console.log('in on message')
this.socketNewMessage(e.data);
};
this.socketRef.onopen = () => {
console.log(this.props.token)
console.log("WebSocket open");
};
this.socketRef.onerror = e => {
console.log('error happ')
console.log(e.message);
};
this.socketRef.onclose = () => {
console.log("WebSocket closed, restarting..");
this.connect(token);
};
}
socketNewMessage(data){
const parsedData = JSON.parse(data);
const command = parsedData.command;
if(Object.keys(this.callbacks).length === 0){
return;
}
if(command === 'messages'){
this.callbacks[command](parsedData.messages);
}
if(command === 'new_message'){
console.log("okay so this was called")
this.callbacks[command](parsedData.message);
}
}
state(){
return this.socketRef.readyState;
}
waitForSocketConnection(callback){
const socket = this.socketRef;
const recursion = this.waitForSocketConnection;
setTimeout(
function(){
if(socket.readyState === 1){
console.log("Connection is made");
if(callback != null){
callback();
}
return;
}
else{
console.log("Wait for connection..");
recursion(callback);
}
}, 1);
}
}
let WebSocketInstance = WebSocketService.getInstance();
export default WebSocketInstance;
FRONTEND: Apps.js
class App extends Component {
componentDidMount() {
console.log('app mounting..')
this.props.onTryAutoSignup();
console.log(this.props.isAuthenticated)
if (this.props.isAuthenticated) {
WebSocketInstance.connect()
}
}
componentDidUpdate(oldProps) {
console.log('app updating props..')
if (this.props.token !== oldProps.token ) {
console.log(this.props.token)
WebSocketInstance.connect(this.props.token)
}
}
render() {
return (
<div>
<Router>
<CustomLayout {...this.props}>
<BaseRouter/>
</CustomLayout>
</Router>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuthenticated: state.token !== null ,
token : state.token
}
}
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
BACKEND: token_auth.py ( A custom middleware)
#database_sync_to_async
def get_user(token_key):
try:
return Token.objects.get(key=token_key).user
except Token.DoesNotExist:
return AnonymousUser()
class TokenAuthMiddleware:
"""
Token authorization middleware for Django Channels 2
see:
https://channels.readthedocs.io/en/latest/topics/authentication.html#custom-authentication
"""
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
return TokenAuthMiddlewareInstance(scope, self)
class TokenAuthMiddlewareInstance:
def __init__(self, scope, middleware):
self.middleware = middleware
self.scope = dict(scope)
self.inner = self.middleware.inner
async def __call__(self, receive, send):
headers = dict(self.scope["headers"])
print(headers[b"cookie"])
if b"authorization" in headers[b"cookie"]:
print('still good here')
cookies = headers[b"cookie"].decode()
token_key = re.search("authorization=(.*)(; )?", cookies).group(1)
if token_key:
self.scope["user"] = await get_user(token_key)
return self.inner(self.scope)
BACKEND : Router.py
application = ProtocolTypeRouter({
"websocket": TokenAuthMiddlewareStack(
URLRouter([
path("", NotificationConsumer),
]),
),
})
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
Here is my the items that were printed out in my cmd prompt:
WebSocket HANDSHAKING / [127.0.0.1:59931]
b'authorization=xxxxxxxxxxxx' #<-- token from the cookie header
still good here #<--- passed first validation
user1 #<---- went into the get_user function i declared within my middleware
WebSocket DISCONNECT / [127.0.0.1:59931] #<---- disconnects...
Please help! Im lost!
the issue was with the middleware instance , it should be :
class TokenAuthMiddlewareInstance:
def __init__(self, scope, middleware):
self.middleware = middleware
self.scope = dict(scope)
self.inner = self.middleware.inner
async def __call__(self, receive, send):
close_old_connections()
headers = dict(self.scope["headers"])
print(headers[b"cookie"])
if b"authorization" in headers[b"cookie"]:
print('still good here')
cookies = headers[b"cookie"].decode()
token_key = re.search("authorization=(.*)(; )?", cookies).group(1)
if token_key:
self.scope["user"] = await get_user(token_key)
inner = self.inner(self.scope)
return await inner(receive, send)
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
thanks!

how to do websocket connection event inside of express`s get request?

im trying to get websocket in express`s router.get request
here the code
app.js
const { createServer } = require("http");
const mongoose = require('mongoose');
const config = require('./config');
const WebSocket = require('ws');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const server = createServer(app);
app.use("/RegisterApi", require("./Routes/RegisterApi/RegisterApi"));
const wss = new WebSocket.Server({ server });
app.wss = wss;
app.locals.clients = [];
server.listen(config.PORT, function () {
console.log(`im listening at ${config.PORT}`);
mongoose.connect(config.MONGODB_URI, {
useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true,
useFindAndModify: false
})
RegisterApi.js
const router = express.Router();
const nodemailer = require("nodemailer");
const Users = require("../../Models/YakutGamesUserModel");
const WebSocket = require('ws');
//const jwt = require("jsonwebtoken");
router.get('/login'/*,verifyToken*/, async (req, res) => {
console.log(req.query.name);
const currentUser = await Users.findOne({ name: req.query.name });
const userunchecked = false;
if (!currentUser) {
res.send("invalid user ");
userunchecked = true;
}
else if (!currentUser.confirmed) {
res.send("confirm your email " + currentUser.name); userunchecked = true;
}
else if (currentUser.password !== req.query.password) { res.send("password is wrong"); userunchecked = true; }
const wss = req.app.wss;
const clients = req.app.locals.clients;
await wss.once("connection", (ws, request) => {
console.log("Total connected clients:", wss.clients.size);
const ip = request.connection.remoteAddress;
console.log(ip);
if (userunchecked) { ws.delete; console.log('wtf'); return; }
const userObject = { id: currentUser._id, object: ws };
clients.push(userObject);
ws.send("ID= " + currentUser._id);
});
});
those are server side
as a client im using unity
unity code C#
async void Login()
{
newUser.name = namefield.text;
newUser.password = passfield.text;
string url = String.Format("http://localhost:7989/RegisterApi/login?name={0}&password={1}", newUser.name, newUser.password);
StartCoroutine(LoginUser(url, () => { Debug.Log("login req done"); }));
websocket = new WebSocket("ws://localhost:7989/RegisterApi/login");
websocket.OnOpen += () =>
{
Debug.Log("Connection open!");
};
websocket.OnError += (e) =>
{
Debug.Log("Error! " + e);
};
websocket.OnClose += (e) =>
{
Debug.Log("Connection closed!");
};
websocket.OnMessage += (bytes) =>
{
var message = System.Text.Encoding.UTF8.GetString(bytes);
Debug.Log("OnMessage! " + message);
};
await websocket.Connect();
}
problem is server do not get console.log("Total connected clients:", wss.clients.size); at first time when i fire login function from unity. but if i fire login second time server get that but this time wss.clients.size will be 2 .
what am i doing wrong?
I think you are trying to log in ,with http request you can do once.
This code worked for me.
IEnumerator LoginUser(string url, Action onSuccess)
{
UnityWebRequest req = UnityWebRequest.Get(url);
yield return req.SendWebRequest();
while (!req.isDone)
yield return null;
string result = req.downloadHandler.text;
string[] resultArray = result.Split(' ');
if (resultArray[0] == "yourCode")
{
myTempID = resultArray[1];
Debug.Log(myTempID);
Wss(myTempID);
LoginLog.GetComponent<TextMeshProUGUI>().text = "login done";
mainMenuButtonHandlersGO.GetComponent<MainMenuButtonHandlers>().OpenFirstCanvasButtons();
messageHandlerGO.GetComponent<WssMessageHandler>().MessageHandlerFunction();
}
else LoginLog.GetComponent<TextMeshProUGUI>().text = result;
onSuccess();
}
async void Wss(string code)
{
websocket = new WebSocket(String.Format("ws://{1}:7989/RegisterApi/login?parentID={0}", code, mainAddress));
websocket.OnOpen += () =>
{
Debug.Log("Connection open!");
};
websocket.OnError += (e) =>
{
Debug.Log("Error! " + e);
};
websocket.OnClose += (e) =>
{
Debug.Log("Connection closed!");
};
// Keep sending messages at every 0.3s
//InvokeRepeating("SendWebSocketMessage", 0.0f, 5.0f);
// waiting for messages
await websocket.Connect();
}

How to pass dynamic `groupID` from one js file to another js file

I have attached my code for reference, In that I want to pass dynamic groupID from teamgroupapi.js to teamCategoryApi.js
Code is working fine when I try to pass manually groupID from ApiCategory.js file.
File name teamgroupapi.js
import { getGeneratedApi } from '#test/bender-executor-simple-api-generator';
import ApiGroup from '../_support/ApiGroup.js';
const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;
const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-s10938402.cc-staging.test.com/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'JTFihw2GJbJ87duTihoGW3vBi8MErxTbBJsD4dw6k5MsPmfI0J8lsf9-mRFXufFYYMzEVcEdK8kXEi3EVkojHQ';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-s10938402.cc-staging.test.com');
const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};
describe('Create Group all api generated', () => {
let api;
let groupID;
let apiGroup;
const groupName = "Test_" + new Date().getTime();
const groupName_rename = "Rename_" + new Date().getTime();
//const groupJson = { "name": groupName };
//const grouprenameJson = { "name": groupName_rename };
beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiGroup = new ApiGroup();
});
beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});
//Create Group API
test('Create Group', async() => {
try
{
jest.setTimeout(10000);
console.log("Create Group");
//const payload = readJsonTestFile('e2e/example.json');
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName);
const createGroup = await api.postTeamGroups(groupJson);
//const listofGroups = JSON.parse(JSON.stringify(createGroup));
//expect(result.response.statusCode).toBe(201);
expect(createGroup).to.have.status(201);
console.log("Create group successfully executed");
} catch(e){
console.log("Failed to create group");
throw e;
}
});
//Get Group API
test('Get Group API', async() => {
try
{
jest.setTimeout(10000);
console.log("Get Created Group");
let foundIndex = -1;
console.log("Running get group and attempting to get ::: " + groupName);
//Check if previously created Group exists using the GET Group API
//Check the response payload and loop through the response to find the workspace that was created earlier
const getGroup = await api.getTeamGroups(false,false);
//const listofGroups = JSON.parse(JSON.stringify(getGroup));
//console.log("list of groups" + getGroup.body.length);
expect(getGroup).to.have.status(200);
for(var i = 0; i < getGroup.body.length;i++){
if((getGroup.body[i].name == groupName) && (getGroup.body[i].id != '') ) {
foundIndex = i;
break;
}
}
groupID = getGroup.body[i].id;
console.log("Group ID ---->>>>" + getGroup.body[i].id);
console.log("Group Name ---->>>>" + getGroup.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get group successfully executed");
} catch(e){
console.log("Failed to get group");
throw e;
}
});
// Rename Group API
test.skip('Rename Group API with Group ID', async()=> {
try
{
jest.setTimeout(10000);
console.log("Rename already created group");
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apigroup = await api.postTeamGroupsWithGroupID(groupID,groupJson);
expect(apigroup).to.have.status(200);
console.log("Rename group successfully executed");
} catch(e){
console.log("Failed to rename group");
throw e;
}
});
//Delete Group API
test.skip('Delete Group API', async()=> {
try
{
jest.setTimeout(10000);
console.log("Delete Created Group");
console.log("Running delete group and attemptin to delete ::: " + groupID);
const apigroup = await api.deleteTeamGroupsWithGroupID(groupID);
expect(apigroup).to.have.status(200);
console.log("Delete group successfully executed");
} catch(e){
console.log("Failed to delete group");
throw e;
}
});
});
Separate Json Functions for teamgroupapi.js File name ApiGroup.js
class ApiGroup {
constructor()
{
//super();
}
generateCreateGroupJsonObject(groupName) {
return {
"name": groupName
}
}
}
module.exports = ApiGroup;
File name teamCategoryApi.js
import { getGeneratedApi } from '#test/bender-executor-simple-api-generator';
import ApiCategory from '../_support/ApiCategory.js';
import teamgroupapi from './teamgroupapi.js';
const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;
const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-s10938402.cc-staging.test.com/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'JTFihw2GJbJ87duTihoGW3vBi8MErxTbBJsD4dw6k5MsPmfI0J8lsf9-mRFXufFYYMzEVcEdK8kXEi3EVkojHQ';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-s10938402.cc-staging.test.com');
const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};
describe('Create category all api generated', () => {
let api;
let categoryID;
let apiCategory;
let groupID;
//let teamGroup;
const categoryName = "Test_" + new Date().getTime();
const categoryName_rename = "Rename_" + new Date().getTime();
//const categoryrenameJson = { "name": categoryName_rename };
beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiCategory = new ApiCategory();
//teamGroup = new teamgroupapi();
//console.log(api);
});
beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});
//Create Category API
test('Create Category', async () => {
jest.setTimeout(20000);
try {
console.log("Create Category");
/*const groupID = teamGroupApi.groupID;
let api = teamGroupApi.api;*/
/*groupID = teamgroupapi.groupID;
console.log(groupID);*/
const categoryJson = apiCategory.generateCreateCategoryJsonObject(categoryName,groupID);
//const categoryJson = { "name": categoryName, "groupId": groupID, "parent": 0 };
const createCategory = await api.postTeamCategories(categoryJson);
//const listofCategories = JSON.parse(JSON.stringify(createCategory));
//expect(result.response.statusCode).toBe(201);
expect(createCategory).to.have.status(201);
console.log("Create category successfully executed");
}
catch (e)
{
console.log("Failed to create category");
throw e;
}
});
//Get Category API
test.skip('Get Category API', async() => {
jest.setTimeout(20000);
try {
console.log("Get Created Category");
let foundIndex = -1;
//const categoryName = "Test_" + new Date().getTime();
console.log("Running get category and attempting to get ::: " + categoryName);
//Check if previously created Group exists using the GET Group API
//Check the response payload and loop through the response to find the workspace that was created earlier
//let api = teamGroupApi.api;
const getCategory = await api.getTeamCategories();
//const listofCategories = JSON.parse(JSON.stringify(apicategory));
//console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//console.log("list of category" + apicategory.body.length);
expect(getCategory).to.have.status(200);
for(var i = 0; i < getCategory.body.length;i++){
if((getCategory.body[i].name == categoryName) && (getCategory.body[i].id != '') ) {
foundIndex = i;
break;
}
}
categoryID = getCategory.body[i].id;
console.log("Category Name ---->>>>" + getCategory.body[i].id);
console.log("Category Name ---->>>>" + getCategory.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get Category successfully executed");
}
catch (e)
{
console.log("Failed to get category");
throw e;
}
});
//Rename Category API
test.skip('Rename Category API with categoryID', async()=> {
jest.setTimeout(20000);
try {
console.log("Rename already created category");
const renameCategoryJson = apiCategory.renameCreateCategoryJsonObject(categoryName_rename);
//const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,renameCategoryJson);
//const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,categoryrenameJson);
expect(apicategory).to.have.status(200);
console.log("Rename category successfully executed");
}
catch (e)
{
console.log("Failed to Rename category");
throw e;
}
});
//Delete Category API
test.skip('Delete Category API', async()=> {
jest.setTimeout(20000);
try {
console.log("Delete Created Cateory");
console.log("Running delete category and attemptin to delete ::: " + categoryID);
const apicategory = await api.deleteTeamCategoriesWithCategoryID(categoryID);
expect(apicategory).to.have.status(200);
console.log("Delete category successfully executed");
}
catch (e)
{
console.log("Failed to delete category");
throw e;
}
});
});
Separate Json Functions for teamCategory.js File name ApiCategory.js
class ApiCategory {
constructor()
{
//super();
}
generateCreateCategoryJsonObject(categoryName,groupID) {
return{
"name": categoryName,
"groupId": groupID, //if you pass manually groupId here and run the code then code is executed successfully.
"parent": 0
}
}
renameCreateCategoryJsonObject(categoryName_rename) {
return{
"name": categoryName_rename
}
}
}
module.exports = ApiCategory;
A simple pub sub module might help you here
const topics = {};
const hOP = topics.hasOwnProperty;
export default class Events {
/**
*
* #param topic
* #param listener
* #returns {{remove: remove}}
*/
subscribe(topic, listener) {
if (!hOP.call(topics, topic)) topics[topic] = [];
const index = topics[topic].push(listener) - 1;
return {
remove: function() {
delete topics[topic][index];
}
};
}
/**
*
* #param topic
* #param info
*/
publish(topic, info) {
if (!hOP.call(topics, topic)) return;
topics[topic].forEach(function(item) {
item(info != undefined ? info : {});
});
}
}
Create this in a js file somewhere. then import it into each of your js files. When you want to pass the value from one script to another you can first publish in the teamgroupapi file and subscribe to the event in the teamCategoryApi file.
self.events.publish('/eventId', groupId);
events.subscribe('/eventId', (groupId) => {
console.log(groupId);
// do stuff
});
Issue is getting resolve after add this lines to teamgroupapi.js file
export let groupID;
exports.groupID = groupID;
After add above two lines in teamgroupapi.js file.
import { getGeneratedApi } from '#test/bender-executor-simple-api-generator';
import ApiGroup from '../_support/ApiGroup.js';
const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;
const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-slurmhourly.hourly.cc.altus.bblabs/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'ju7WkQItxRMFdMtghlGEVz5CZdC1b4umwLId16591CbK00hWs1a1_lT63cBr8xkvBhPK_vWO-fJTUBdP99LFVw';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-slurmhourly.hourly.cc.altus.bblabs');
const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};
export var groupID;
describe('Create Group all api generated', () => {
let api;
let apiGroup;
//let groupID;
const groupName = "Test_" + new Date().getTime();
const groupName_rename = "Rename_" + new Date().getTime();
//const groupJson = { "name": groupName };
//const grouprenameJson = { "name": groupName_rename };
beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiGroup = new ApiGroup();
});
beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});
//Create Group API
test('Create Group', async() => {
try
{
jest.setTimeout(10000);
console.log("Create Group");
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName);
const createGroup = await api.postTeamGroups(groupJson);
expect(createGroup).to.have.status(201);
console.log("Create group successfully executed");
} catch(e){
console.log("Failed to create group");
throw e;
}
});
//Get Group API
test('Get Group API', async() => {
try
{
jest.setTimeout(10000);
console.log("Get Created Group");
let foundIndex = -1;
console.log("Running get group and attempting to get ::: " + groupName);
const getGroup = await api.getTeamGroups(false,false);
expect(getGroup).to.have.status(200);
for(var i = 0; i < getGroup.body.length;i++){
if((getGroup.body[i].name == groupName) && (getGroup.body[i].id != '') ) {
foundIndex = i;
break;
}
}
groupID = getGroup.body[i].id;
console.log("Group ID ---->>>>" + getGroup.body[i].id);
console.log("Group Name ---->>>>" + getGroup.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get group successfully executed");
} catch(e){
console.log("Failed to get group");
throw e;
}
});
// Rename Group API
test.skip('Rename Group API with Group ID', async()=> {
try
{
jest.setTimeout(10000);
console.log("Rename already created group");
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apigroup = await api.postTeamGroupsWithGroupID(groupID,groupJson);
expect(apigroup).to.have.status(200);
console.log("Rename group successfully executed");
} catch(e){
console.log("Failed to rename group");
throw e;
}
});
//Delete Group API
test.skip('Delete Group API', async()=> {
try
{
jest.setTimeout(10000);
console.log("Delete Created Group");
console.log("Running delete group and attemptin to delete ::: " + groupID);
const apigroup = await api.deleteTeamGroupsWithGroupID(groupID);
expect(apigroup).to.have.status(200);
console.log("Delete group successfully executed");
} catch(e){
console.log("Failed to delete group");
throw e;
}
});
});
exports.groupID = groupID;
In teamCategoryApi.js file add this two lines.
var teamgroupapi = require('./teamgroupapi.js');
groupID = teamgroupapi.groupID;
After Add above two lines in teamCategoryApi.js file issue is getting resolved.
import { getGeneratedApi } from '#test/bender-executor-simple-api-generator';
import ApiCategory from '../_support/ApiCategory.js';
var teamgroupapi = require('./teamgroupapi.js');
const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;
const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-slurmhourly.hourly.cc.altus.bblabs/documentation/api.json';
const token = process.env.BENDER_LOGIN_TOKEN || 'ju7WkQItxRMFdMtghlGEVz5CZdC1b4umwLId16591CbK00hWs1a1_lT63cBr8xkvBhPK_vWO-fJTUBdP99LFVw';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-slurmhourly.hourly.cc.altus.bblabs');
const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};
describe('Create category all api generated', () => {
let api;
let categoryID;
let apiCategory;
let groupID;
//let teamGroup;
const categoryName = "Test_" + new Date().getTime();
const categoryName_rename = "Rename_" + new Date().getTime();
//const categoryrenameJson = { "name": categoryName_rename };
beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiCategory = new ApiCategory();
//teamGroup = new teamgroupapi();
//console.log(api);
});
beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});
//Create Category API
test('Create Category', async () => {
jest.setTimeout(20000);
try {
console.log("Create Category");
groupID = teamgroupapi.groupID;
const categoryJson = apiCategory.generateCreateCategoryJsonObject(categoryName,groupID);
//const categoryJson = { "name": categoryName, "groupId": groupID, "parent": 0 };
const createCategory = await api.postTeamCategories(categoryJson);
//const listofCategories = JSON.parse(JSON.stringify(createCategory));
//expect(result.response.statusCode).toBe(201);
expect(createCategory).to.have.status(201);
console.log("Create category successfully executed");
}
catch (e)
{
console.log("Failed to create category");
throw e;
}
});
//Get Category API
test('Get Category API', async() => {
jest.setTimeout(20000);
try {
console.log("Get Created Category");
let foundIndex = -1;
//const categoryName = "Test_" + new Date().getTime();
console.log("Running get category and attempting to get ::: " + categoryName);
//Check if previously created Group exists using the GET Group API
//Check the response payload and loop through the response to find the workspace that was created earlier
//let api = teamGroupApi.api;
const getCategory = await api.getTeamCategories();
//const listofCategories = JSON.parse(JSON.stringify(apicategory));
//console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//console.log("list of category" + apicategory.body.length);
expect(getCategory).to.have.status(200);
for(var i = 0; i < getCategory.body.length;i++){
if((getCategory.body[i].name == categoryName) && (getCategory.body[i].id != '') ) {
foundIndex = i;
break;
}
}
categoryID = getCategory.body[i].id;
console.log("Category Name ---->>>>" + getCategory.body[i].id);
console.log("Category Name ---->>>>" + getCategory.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get Category successfully executed");
}
catch (e)
{
console.log("Failed to get category");
throw e;
}
});
//Rename Category API
test('Rename Category API with categoryID', async()=> {
jest.setTimeout(20000);
try {
console.log("Rename already created category");
const renameCategoryJson = apiCategory.renameCreateCategoryJsonObject(categoryName_rename);
//const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,renameCategoryJson);
//const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,categoryrenameJson);
expect(apicategory).to.have.status(200);
console.log("Rename category successfully executed");
}
catch (e)
{
console.log("Failed to Rename category");
throw e;
}
});
//Delete Category API
test('Delete Category API', async()=> {
jest.setTimeout(20000);
try {
console.log("Delete Created Cateory");
console.log("Running delete category and attemptin to delete ::: " + categoryID);
const apicategory = await api.deleteTeamCategoriesWithCategoryID(categoryID);
expect(apicategory).to.have.status(200);
console.log("Delete category successfully executed");
}
catch (e)
{
console.log("Failed to delete category");
throw e;
}
});
});

Categories