Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var $liveChat = angular.module('liveChatModule', ['ngRoute', 'angularFileUpload']);
- $liveChat.initialUrl = 'http://livechattests.azurewebsites.net/';
- $liveChat.hubConnection = $.hubConnection($liveChat.initialUrl);
- $liveChat.chatProxy = $liveChat.hubConnection.createHubProxy('ChatHub');
- $liveChat.connectedUsers = [];
- $liveChat.liveChatGuests = [];
- $liveChat.iAmAdded = false;
- $liveChat._myMediaStream = null;
- $liveChat.isVideoStreamed = false;
- $liveChat.isAudioStreamed = false;
- $liveChat.chatRoom = null;
- $liveChat.selfParticipantId = "";
- $liveChat.chatWithLiveGuests = false;
- $liveChat.rootScopesCalled = false;
- $liveChat.myName = "";
- $liveChat.configuration = {
- 'iceServers': [
- {
- 'url': 'stun:stun.l.google.com:19302'
- },
- {
- 'url': 'turn:192.158.29.39:3478?transport=udp',
- 'credential': 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
- 'username': '28224511:1379330808'
- },
- {
- 'url': 'turn:192.158.29.39:3478?transport=tcp',
- 'credential': 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
- 'username': '28224511:1379330808'
- }
- ]
- }
- $liveChat.factory('UserModel', function(){
- function UserModel(id, firstName, lastName, email, guestIdentification, username, password){
- this.id = id;
- this.firstName = firstName;
- this.lastName = lastName;
- this.email = email;
- this.guestIdentification = guestIdentification;
- this.username = username;
- this.password = password;
- };
- return UserModel;
- });
- $liveChat.factory('ChatRoomModel', function(){
- function ChatRoomModel(id, chatRoomName, startDateTime, endDateTime, agent, usersParticipating, emails, chat, connectionId) {
- this.id = id;
- this.chatRoomName = chatRoomName;
- this.startDateTime = startDateTime;
- this.endDateTime = endDateTime;
- this.creator = agent;
- this.usersParticipating = usersParticipating;
- this.emails = emails;
- this.chat = chat;
- this.connectionId = connectionId;
- }
- return ChatRoomModel;
- });
- $liveChat.factory('ConnectedUser', function(){
- function ConnectedUser(userId, name, userConnectionId, connection, chatIdentification, messages, type) {
- this.userId = userId;
- this.name = name;
- this.userConnectionId = userConnectionId;
- this.connection = connection;
- this.chatIdentification = chatIdentification;
- this.messages = messages;
- this.type = type;
- }
- return ConnectedUser;
- });
- $liveChat.factory('MessageModel', function(){
- function MessageModel(messageBody, senderId, chatId, isFileOrDocument, isImage, fileName, fileSize) {
- this.messageBody = messageBody;
- this.senderId = senderId;
- this.chatId = chatId;
- this.isFileOrDocument = isFileOrDocument;
- this.isImage = isImage;
- this.fileName = fileName;
- this.fileSize = fileSize;
- }
- return MessageModel;
- });
- $liveChat.factory('UserService', function($http, $location){
- var userService = {};
- userService.authLogin = function(username, password, $rootScope, UserService, ConnectedUser){
- var data = "grant_type=password&username=" + username + "&password=" + password;
- return $http.post($liveChat.initialUrl + 'token', data, { headers : {
- 'Content-Type': 'application/x-www-form-urlencoded'
- }
- }).
- then(function(response) {
- localStorage.setItem('chat_token', response.data.access_token);
- userService.getUserRole();
- $liveChat.connectToChatServer($rootScope, UserService, ConnectedUser, username);
- return true;
- }).catch(function(error) {
- alert(error.data);
- return false;
- });
- }
- userService.getUserRole = function() {
- return $http.get($liveChat.initialUrl + 'api/user/role', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- }).then(function(response){
- //enter your logic after retreiving user role
- if(response.data === "Admin"){
- $location.path('/admin');
- }
- else if(response.data === "Agent") {
- $location.path('/agent');
- }
- }).catch(function(error){
- alert("Couldn't retrieve user role." + error);
- });
- }
- userService.setPresenceStatus = function(status) {
- return $http.get($liveChat.initialUrl + '/api/user/agent/presence/' + status, {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.getAllAgents = function() {
- return $http.get($liveChat.initialUrl + 'api/user/agents', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.createAgent = function(agent){
- return $http.post($liveChat.initialUrl + 'api/user/agent/create', agent, {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.deleteAgent = function(id){
- return $http.delete($liveChat.initialUrl + 'api/user/agent/' + id + '/delete', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.getUserInfo = function() {
- return $http.get($liveChat.initialUrl + 'api/user/info', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.updateHubConnection = function(connectionId, username){
- return $http.put($liveChat.initialUrl + 'api/user/hub/' + connectionId + '/' + username + '/connection' , null, {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- userService.disconnectMyself = function(id, room) {
- return $http.get($liveChat.initialUrl + 'api/user/' + id + '/' + room + '/disconnect', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- return userService;
- });
- $liveChat.factory('ChatRoomService', function($http){
- var chatRoomService = {};
- chatRoomService.getAllChatRoomsByUser = function(id){
- return $http.get($liveChat.initialUrl + 'api/chatroom/all/' + id , {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.getAllGuestChats = function(){
- return $http.get($liveChat.initialUrl + 'api/chatroom/guest/all', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.deleteChatRoomById = function(id) {
- return $http.delete($liveChat.initialUrl + 'api/chatroom/delete/' + id, {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.createChatRoom = function(chatRoom) {
- return $http.post($liveChat.initialUrl + 'api/chatroom/new/', JSON.stringify(chatRoom), {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.getChatRoom = function (id) {
- return $http.get($liveChat.initialUrl + 'api/chatroom/info/' + id, {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.endRoom = function(id){
- return $http.get($liveChat.initialUrl + 'api/chatroom/' + id + '/endroom' , {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.getEndedRooms = function(){
- return $http.get($liveChat.initialUrl + 'api/chatroom/ended' , {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.getAllRooms = function(){
- return $http.get($liveChat.initialUrl + 'api/chatroom/all/admin' , {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- chatRoomService.getChatLog = function(guestIdentification){
- return $http.get($liveChat.initialUrl + 'api/chatroom/guest/chat/' + guestIdentification + "/get" , {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- return chatRoomService;
- });
- $liveChat.factory('MessageService', function($http){
- var messageService = {};
- messageService.getChatHistory = function (chatLogId) {
- return $http.get($liveChat.initialUrl + 'api/message/'+ chatLogId + '/history');
- }
- messageService.sendMessageService = function (message, room) {
- return $http.post($liveChat.initialUrl + 'api/message/send/' + room.toString(), JSON.stringify(message));
- }
- messageService.setMediaStatus = function (id, status, room) {
- return $http.get($liveChat.initialUrl + 'api/message/media/' + id + '/' + status + "/" + room
- + '/set', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- messageService.getMediaStatus = function (id) {
- return $http.get($liveChat.initialUrl + 'api/message/media/' + id + '/get', {
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
- 'Content-Type': 'application/json; charset=utf-8'
- }
- });
- }
- return messageService;
- });
- $liveChat.login = function(username, password, $rootScope, UserService, ConnectedUser){
- UserService.authLogin(username, password, $rootScope, UserService, ConnectedUser);
- }
- $liveChat.logout = function($rootScope){
- localStorage.removeItem("chat_token");
- }
- $liveChat.divideChatRooms = function(chatrooms, ChatRoomModel, agentId) {
- var myChatRooms = [];
- var chatRoomsInvitedIn = [];
- for(var i=0; i< chatrooms.length; i++){
- if(chatrooms[i].endDate == null){
- if(chatrooms[i].creator.id === agentId)
- myChatRooms.push(new ChatRoomModel(chatrooms[i].id, chatrooms[i].chatRoomName, chatrooms[i].startDate, null, chatrooms[i].creator, chatrooms[i].usersParticipating, "", chatrooms[i].chat, chatrooms[i].connectionId));
- else
- chatRoomsInvitedIn.push(new ChatRoomModel(chatrooms[i].id, chatrooms[i].chatRoomName, chatrooms[i].startDate, null, chatrooms[i].creator, chatrooms[i].usersParticipating, "", chatrooms[i].chat, chatrooms[i].connectionId));
- }
- }
- return {
- myChatRooms: myChatRooms,
- chatRoomsInvitedIn: chatRoomsInvitedIn
- };
- }
- $liveChat.receiveName = function($rootScope, ConnectedUser){
- $liveChat.chatProxy.on("receiveName", (id, userConnectionId) => {
- if($liveChat.chatRoom == null){
- $liveChat.connectedUsers.push(new ConnectedUser(id, "", userConnectionId, null, null, 0, null));
- }
- else if (id === $liveChat.chatRoom.creator.id) {
- if(id != $liveChat.selfParticipantId){
- var user = $liveChat.connectedUsers.find(x=>x.userConnectionId == userConnectionId);
- if(user === null || user === undefined){
- var check = $liveChat.connectedUsers.find(x=>x.userId == id);
- if(user === null || user === undefined){
- $rootScope.$broadcast('nameReceived', $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, id);
- }
- $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
- $liveChat.connectedUsers.push(new ConnectedUser($liveChat.chatRoom.creator.id, $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, userConnectionId, null, null, 0, null));
- }
- }
- else{
- if ($liveChat.iAmAdded === false){
- $rootScope.$broadcast('nameReceived', $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, id);
- $liveChat.iAmAdded = true;
- }
- }
- }
- else{
- var user = $liveChat.connectedUsers.find(x => x.userConnectionId === userConnectionId);
- if(user === null || user === undefined){
- user = $liveChat.chatRoom.usersParticipating.find(x=> x.id === id);
- if($liveChat.selfParticipantId != user.id){
- var check = $liveChat.connectedUsers.find(x=>x.userId == id);
- $rootScope.$broadcast('nameReceived', user.firstName + " " + user.lastName, id);
- $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
- $liveChat.connectedUsers.push(new ConnectedUser(user.id, user.firstName + " " + user.lastName, userConnectionId, null, null, 0, null));
- }
- else {
- if($liveChat.iAmAdded === false){
- $rootScope.$broadcast('nameReceived', user.firstName + " " + user.lastName, id);
- $liveChat.iAmAdded = true;
- }
- }
- }
- }
- });
- }
- $liveChat.mediaStatus = function($rootScope){
- $liveChat.chatProxy.on("mediaEnabled", (status) => {
- if ($liveChat.chatRoom.creator.id != $liveChat.selfParticipantId) {
- $rootScope.$broadcast('mediaStatus', status);
- }
- });
- }
- $liveChat.pullHistory = function($rootScope){
- $liveChat.chatProxy.on("pullHistory", () => {
- if($liveChat.chatWithLiveGuests){
- $rootScope.$broadcast('pullHistory');
- $liveChat.chatProxy.invoke("askVideo", localStorage.getItem("guestConnectionId"));
- }
- else if ($liveChat.chatRoom.creator.id != $liveChat.selfParticipantId) {
- $rootScope.$broadcast('pullHistory');
- }
- });
- }
- $liveChat.handleUserDisconnection = function($rootScope){
- $liveChat.chatProxy.on("userDisconnected", (userId)=> {
- $rootScope.$broadcast('userDisconnected', userId);
- if(userId === $liveChat.selfParticipantId){
- $liveChat.connectedUsers = [];
- }
- else{
- for(var i = 0; i< $liveChat.connectedUsers.length; i++){
- if($liveChat.connectedUsers[i].userId === userId){
- $liveChat.chatProxy.invoke("removeFromRoom", $liveChat.chatRoom.connectionId, $liveChat.connectedUsers[i].userConnectionId);
- $liveChat.connectedUsers.splice(i, 1);
- }
- }
- }
- });
- }
- $liveChat.receiveMessage = function($rootScope){
- $liveChat.chatProxy.on("sendMessage", (senderName, message, fileSize, messageUrl, type, date, senderConnectionId) => {
- $rootScope.$broadcast('messageSent', senderName, message, fileSize, messageUrl, type, date, senderConnectionId);
- });
- }
- $liveChat.handleRoomDisconnection = function($rootScope){
- $liveChat.chatProxy.on("disconnect", () => {
- if($liveChat._myMediaStream != null){
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, $liveChat.chatRoom.connectionId);
- $('#rtcVideo').hide();
- var guestVideos = document.getElementsByClassName('.guest-video');
- if(!guestVideos != null && !guestVideos != undefined){
- $('.guest-video').remove();
- }
- }
- $liveChat.iAmAdded = false;
- $rootScope.$broadcast('chatRoomClosed', $liveChat.chatRoom.creator.id === $liveChat.selfParticipantId);
- });
- }
- $liveChat.handleVideoCancel = function(){
- $liveChat.chatProxy.on("cancelVideo", (userConnectionId, streamId) => {
- var element = document.getElementById(streamId.toString());
- if(element != null && element != undefined){
- element.remove();
- }
- });
- }
- $liveChat.handleGuestDisconnection = function($rootScope){
- $liveChat.chatProxy.on("disconnectFromRoom", (userConnectionId)=>{
- if(userConnectionId!= $liveChat.hubConnection.id){
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
- if($liveChat.liveChatGuests[i].userConnectionId === userConnectionId){
- $liveChat.liveChatGuests[i].userConnectionId = null;
- }
- }
- if(userConnectionId === localStorage.getItem("guestConnectionId")){
- if($liveChat._myMediaStream!= null)
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, localStorage.getItem("guestConnectionId"));
- localStorage.setItem("guestConnectionId", "");
- $rootScope.$broadcast("guestDisconnectedRoom");
- }
- else{
- $rootScope.$broadcast("agentDisconnectedRoom");
- }
- }
- });
- }
- $liveChat.handleStreamMessage = function(){
- $liveChat.chatProxy.on("streamMessage", (data, senderConnectionId, type) => $liveChat.handleStream(data, senderConnectionId, type));
- }
- $liveChat.askForVideo = function($rootScope){
- $liveChat.chatProxy.on("askVideo", (userConnectionId) => {
- if($liveChat.isVideoStreamed || $liveChat.isAudioStreamed){
- if(userConnectionId != $liveChat.hubConnection.id){
- angular.forEach($liveChat.connectedUsers, function(item){
- if(item.connection == null){
- if($liveChat.isVideoStreamed)
- item.connection = $liveChat.createVideoConnection(item.userConnectionId);
- else
- item.connection = $liveChat.createAudioConnection(item.userConnectionId);
- item.connection.addStream($liveChat._myMediaStream);
- document.getElementById('cancel').addEventListener('click', function () {
- if($liveChat.chatRoom != null)
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, $liveChat.chatRoom.connectionId);
- else
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, localStorage.getItem("guestConnectionId"));
- $('#rtcVideo').hide();
- });
- item.connection.createOffer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- var type = "";
- if($liveChat.isAudioStreamed)
- type = "audio";
- else if($liveChat.isVideoStreamed)
- type = "video";
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, type);
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- });
- }
- }
- });
- }
- $liveChat.handleGuestJoining = function($rootScope, ConnectedUser){
- $liveChat.chatProxy.on("guestJoinedToLiveChat", (userConnectionId, secondArgument, thirdArgument)=>{
- var guest = {};
- if(secondArgument === null){
- var guestExists = $liveChat.liveChatGuests.find(x=>x.chatIdentification === thirdArgument);
- if(guestExists === undefined){
- guest = new ConnectedUser(null, "Guest ", userConnectionId, null, secondArgument, 0, null);
- $liveChat.liveChatGuests.push(guest);
- }
- else {
- if(!guestExists.userConnectionId === userConnectionId)
- guestExists.userConnectionId = userConnectionId;
- }
- }
- else if(thirdArgument === null){
- $liveChat.liveChatGuests.forEach(function(item){
- if(item.chatIdentification === secondArgument.guestIdentification){
- item.userConnectionId = userConnectionId;
- }
- });
- }
- $rootScope.$broadcast("guestListUpdated");
- });
- }
- $liveChat.handleGuestMessage = function($rootScope, ConnectedUser){
- $liveChat.chatProxy.on("guestSentMessage", (userConnectionId, secondArgument, thirdArgument)=> {
- var userExists = null;
- var chatIdentification = "";
- if(secondArgument === null){
- userExists = $liveChat.liveChatGuests.find(x=>x.chatIdentification === thirdArgument);
- chatIdentification = thirdArgument;
- if(userExists === undefined){
- guest = new ConnectedUser(null, "Guest", userConnectionId, null, chatIdentification, 0, null);
- $liveChat.liveChatGuests.push(guest);
- }
- else{
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
- if($liveChat.liveChatGuests[i].chatIdentification === chatIdentification){
- $liveChat.liveChatGuests[i].messages++;
- }
- }
- }
- }
- else if(thirdArgument === null){
- chatIdentification = secondArgument.guestIdentification;
- $liveChat.liveChatGuests.forEach(function(item){
- if(item.chatIdentification === secondArgument.guestIdentification){
- if(item.userConnectionId === null)
- item.userConnectionId = userConnectionId;
- else{
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
- if($liveChat.liveChatGuests[i].chatIdentification === chatIdentification){
- $liveChat.liveChatGuests[i].messages++;
- }
- }
- }
- }
- });
- }
- $rootScope.$broadcast("guestListUpdated");
- });
- }
- $liveChat.handleMessagesClear = function($rootScope){
- $liveChat.chatProxy.on("clearLiveMessages", (chatIdentification)=> {
- $liveChat.clearLiveMessages(chatIdentification, "chatId", $rootScope);
- });
- }
- $liveChat.handleLiveChatJoining = function(ConnectedUser){
- $liveChat.chatProxy.on("joinedToRoom",(userConnectionId, name)=>{
- if(userConnectionId != $liveChat.hubConnection.id){
- var user = $liveChat.connectedUsers.find(x=>x.userConnectionId === userConnectionId);
- if(user === undefined){
- $liveChat.connectedUsers.push(new ConnectedUser(null, "", userConnectionId, null, null, 0));
- $liveChat.chatProxy.invoke("joinedToLiveChat", localStorage.getItem("guestConnectionId"));
- }
- }
- });
- }
- $liveChat.handleDisconnectionFromLiveChat = function($rootScope){
- $liveChat.chatProxy.on("guestDisconnectedFromToLiveChat", (userConnectionId)=>{
- /* if(userConnectionId!= $liveChat.hubConnection.id){
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
- if($liveChat.liveChatGuests[i].userConnectionId === userConnectionId){
- $liveChat.liveChatGuests.splice(i, 1);
- }
- }
- $rootScope.$broadcast("guestListUpdated", null);
- }*/
- $liveChat.clearLiveMessages(userConnectionId, "connectionId", $rootScope);
- });
- }
- $liveChat.handleGuestUpdate = function($rootScope){
- $liveChat.chatProxy.on("guestUpdatedInfo", (chatIdentification, name, hubConnection) => {
- var guestUserInList = $liveChat.liveChatGuests.find(x => x.chatIdentification === chatIdentification);
- guestUserInList.name = name;
- guestUserInList.userConnectionId = hubConnection;
- $rootScope.$broadcast("guestInfoUpdated");
- });
- }
- $liveChat.connectToChatServer = function($rootScope, UserService, ConnectedUser, username){
- $liveChat.receiveName($rootScope, ConnectedUser);
- $liveChat.mediaStatus($rootScope);
- $liveChat.pullHistory($rootScope);
- $liveChat.handleUserDisconnection($rootScope);
- $liveChat.receiveMessage($rootScope);
- $liveChat.handleRoomDisconnection($rootScope);
- $liveChat.handleVideoCancel();
- $liveChat.handleStreamMessage();
- $liveChat.handleGuestDisconnection($rootScope);
- $liveChat.handleGuestJoining($rootScope, ConnectedUser);
- $liveChat.handleGuestMessage($rootScope, ConnectedUser);
- $liveChat.handleMessagesClear($rootScope);
- $liveChat.handleLiveChatJoining(ConnectedUser);
- $liveChat.askForVideo($rootScope);
- $liveChat.handleGuestUpdate($rootScope);
- $liveChat.handleDisconnectionFromLiveChat($rootScope);
- $liveChat.hubConnection.start().done(() => {
- UserService.updateHubConnection($liveChat.hubConnection.id, username);
- UserService.setPresenceStatus(true);
- });
- $liveChat.hubConnection.disconnected(function(){
- UserService.disconnectMyself($liveChat.selfParticipantId, $liveChat.chatRoom.connectionId);
- UserService.setPresenceStatus(false);
- });
- }
- $liveChat.clearLiveMessages = function(firstArgument, secondArgument, $rootScope){
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
- if(secondArgument === "chatId"){
- if($liveChat.liveChatGuests[i].chatIdentification === firstArgument){
- $liveChat.liveChatGuests[i].messages = 0;
- $rootScope.$broadcast("guestListUpdated");
- }
- }
- else if(secondArgument === "connectionId"){
- if ($liveChat.liveChatGuests[i].userConnectionId != null){
- if ($liveChat.liveChatGuests[i].userConnectionId === firstArgument){
- if ($liveChat.liveChatGuests[i].name === "Guest "){
- for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
- if($liveChat.liveChatGuests[i].userConnectionId === firstArgument){
- $liveChat.liveChatGuests.splice(i, 1);
- }
- }
- $rootScope.$broadcast("guestListUpdated");
- }
- else{
- $liveChat.liveChatGuests[i].Messages = 0;
- $rootScope.$broadcast("guestListUpdated");
- }
- }
- }
- }
- }
- }
- $liveChat.enterChatRoom = function(){
- $liveChat.chatProxy.invoke("joinRoom", $liveChat.chatRoom.connectionId);
- $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
- if($liveChat.chatRoom.chat.mediaAllowed){
- $('#startVideo').prop("disabled", false);
- $('#startAudio').prop("disabled", false);
- $liveChat.chatProxy.invoke("askVideo", $liveChat.chatRoom.connectionId);
- }
- }
- $liveChat.videoCall = function($rootScope, cancel, connectionId){
- getUserMedia({
- video: true,
- audio: false
- }, function (stream) {
- $('#' + myvideo.id).show();
- $liveChat._myMediaStream = stream;
- attachMediaStream(myvideo, $liveChat._myMediaStream);
- if(localStorage.getItem('guestConnectionId') != null)
- $liveChat.chatProxy.invoke("callGuest", localStorage.getItem('guestConnectionId'));
- $liveChat.isVideoStreamed = true;
- cancel.addEventListener('click', function () {
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, connectionId);
- $('#' + myvideo.id).hide();
- });
- angular.forEach($liveChat.connectedUsers, function(item){
- if(item.connection == null){
- item.connection = $liveChat.createVideoConnection(item.userConnectionId);
- item.type = "video";
- item.connection.addStream($liveChat._myMediaStream);
- item.connection.createOffer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "video");
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- else if(item.connection != null){
- if (item.type != "video") {
- item.connection = $liveChat.createVideoConnection(item.userConnectionId);
- item.type = "video";
- }
- item.connection.addStream($liveChat._myMediaStream);
- item.connection.createOffer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "video");
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- });
- },
- function (error) {
- alert(JSON.stringify(error));
- });
- }
- $liveChat.audioCall = function($rootScope, cancel, connectionId){
- getUserMedia({
- video: false,
- audio: true
- }, function (stream) {
- $liveChat._myMediaStream = stream;
- cancel.addEventListener('click', function () {
- $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, connectionId);
- });
- $liveChat.isAudioStreamed = true;
- angular.forEach($liveChat.connectedUsers, function(item){
- if(item.connection == null){
- item.connection = $liveChat.createAudioConnection(item.userConnectionId);
- item.type = "audio";
- item.connection.addStream($liveChat._myMediaStream);
- item.connection.createOffer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "audio");
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- else if(item.connection != null){
- if(item.type != "audio") {
- item.connection = $liveChat.createAudioConnection(item.userConnectionId);
- item.type = "audio";
- }
- item.connection.addStream($liveChat._myMediaStream);
- item.connection.createOffer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "audio");
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- });
- },
- function (error) {
- alert(JSON.stringify(error));
- });
- }
- $liveChat.stopVideoStream = function ($rootScope, stream, connectionId) {
- var videos = stream.getVideoTracks();
- if(videos != null && videos != undefined){
- angular.forEach(videos, function (track) {
- track.stop();
- });
- }
- var audios = stream.getAudioTracks();
- if(audios != null && audios != undefined){
- angular.forEach(audios, function (track) {
- track.stop();
- });
- }
- $rootScope.$broadcast('stopVideoStream');
- $liveChat.isAudioStreamed = false;
- $liveChat.isVideoStreamed = false;
- $liveChat.chatProxy.invoke("cancelVideo", connectionId, stream.id);
- }
- $liveChat.createVideoConnection = function(connectionId) {
- var connection = new RTCPeerConnection($liveChat.configuration);
- connection.onicecandidate = function (event) {
- if (event.candidate) {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'candidate': event.candidate }), connectionId, "video");
- }
- };
- connection.onaddstream = function (event) {
- var newVideoElement = document.createElement('video');
- newVideoElement.className = 'guest-video';
- newVideoElement.autoplay = 'autoplay';
- newVideoElement.id = event.stream.id.toString();
- attachMediaStream(newVideoElement, event.stream);
- document.querySelector('.chat-video').appendChild(newVideoElement);
- };
- return connection;
- }
- $liveChat.createAudioConnection = function(connectionId) {
- var connection = new RTCPeerConnection($liveChat.configuration);
- connection.onicecandidate = function (event) {
- if (event.candidate) {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'candidate': event.candidate }), connectionId, "audio");
- }
- };
- connection.onaddstream = function (event) {
- var newAudioElement = document.createElement('audio');
- newAudioElement.className = 'guest-audio';
- newAudioElement.autoplay = 'autoplay';
- newAudioElement.id = event.stream.id.toString();
- attachMediaStream(newAudioElement, event.stream);
- document.querySelector('body').appendChild(newAudioElement);
- };
- return connection;
- }
- $liveChat.handleStream = function (data, senderConnectionId, type) {
- var message = JSON.parse(data);
- angular.forEach($liveChat.connectedUsers, function(item){
- if(item.userConnectionId === senderConnectionId){
- if(item.connection === null || item.type != type){
- if (type === "video"){
- item.connection = $liveChat.createVideoConnection(senderConnectionId);
- item.type = "video";
- }
- else {
- item.connection = $liveChat.createAudioConnection(senderConnectionId);
- item.type = "audio";
- }
- }
- }
- if (message.sdp) {
- item.connection.setRemoteDescription(new RTCSessionDescription(message.sdp), function () {
- if (item.connection.remoteDescription.type == 'offer') {
- console.log('received offer, sending answer...');
- item.connection.createAnswer(function (desc) {
- item.connection.setLocalDescription(desc, function () {
- $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': item.connection.localDescription }), senderConnectionId, type);
- });
- }, function (error) { console.log('Error creating session description: ' + error); });
- }
- else if (item.connection.remoteDescription.type == 'answer') {
- console.log('got an answer');
- }
- });
- }
- else if (message.candidate) {
- console.log('adding ice candidate...');
- item.connection.addIceCandidate(new RTCIceCandidate(message.candidate));
- }
- });
- }
- $liveChat.startUploading = function ($files, uploadedFiles, upload, MessageService, MessageModel, participantId, chatRoomConnectionId, chatId, $upload) {
- for (var i = 0; i < $files.length; i++) {
- var $file = $files[i];
- (function (index) {
- upload[index] = $upload.upload({
- url: "http://livechattests.azurewebsites.net/api/fileupload", // webapi url
- method: "POST",
- file: $file
- }).progress(function (evt) {
- }).success(function (data, status, headers, config) {
- // file is uploaded successfully
- var type = $liveChat.checkFileExtension(data.fileName);
- var newMessage = new MessageModel("http://livechattests.azurewebsites.net/api/Files/" + data.fileName, participantId, chatId, false, false, "", "");
- if(type === "image"){
- newMessage.isImage = true;
- }
- else if(type === "file"){
- newMessage.isFileOrDocument = true;
- }
- newMessage.fileName = data.fileName;
- newMessage.fileSize = $file.size;
- MessageService.sendMessageService(newMessage, chatRoomConnectionId);
- }).error(function (data, status, headers, config) {
- console.log(data);
- });
- })(i);
- }
- }
- $liveChat.checkFileExtension = function(dataFile){
- var lastDot = 0;
- var resultString = "";
- for(var i = 0; i < dataFile.length; i++){
- if(dataFile.charAt(i) === "."){
- lastDot = i;
- }
- }
- resultString = "";
- lastDot++;
- var loop = true;
- while(loop){
- resultString = resultString + dataFile.charAt(lastDot).toString();
- lastDot++;
- if(lastDot === dataFile.length)
- loop = false;
- }
- if(resultString === "png" || resultString === "jpg" || resultString === "jpeg" || resultString === "gif" || resultString === "bmp" )
- resultString = "image";
- else
- resultString = "file";
- return resultString;
- }
- $liveChat.getParameterByName = function(name, url) {
- if (!url) {
- url = window.location.href;
- }
- name = name.replace(/[\[\]]/g, "\\$&");
- var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
- results = regex.exec(url);
- if (!results) return null;
- if (!results[2]) return '';
- return decodeURIComponent(results[2].replace(/\+/g, " "));
- }
- //////events to subscribe on
- /*
- $rootScope.$on('nameReceived', function(event, name, userId) {
- });
- $rootScope.$on('mediaStatus', function(event, status) {
- });
- $rootScope.$on('stopVideoStream', function(event){
- });
- $rootScope.$on('chatRoomClosed', function(event){
- });
- $rootScope.$on('userDisconnected', function(event, userId){
- });
- $rootScope.$on('guestDisconnectedRoom', function(event){
- });
- $rootScope.$on('agentDisconnectedRoom', function(event){
- });
- $rootScope.$on('messageSent', function(event, senderName, message, fileSize, messageUrl, type, date, senderConnectionId){
- });
- $rootScope.$on('pullHistory', function(event){
- });
- $rootScope.$on("guestInfoUpdated"), function(event){
- });
- $rootScope.$on("guestListUpdated", function(event){
- });
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement