Advertisement
Guest User

Untitled

a guest
May 13th, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.76 KB | None | 0 0
  1. var $liveChat = angular.module('liveChatModule', ['ngRoute', 'angularFileUpload']);
  2.  
  3. $liveChat.initialUrl = 'http://livechattests.azurewebsites.net/';
  4. $liveChat.hubConnection = $.hubConnection($liveChat.initialUrl);
  5. $liveChat.chatProxy = $liveChat.hubConnection.createHubProxy('ChatHub');
  6. $liveChat.connectedUsers = [];
  7. $liveChat.liveChatGuests = [];
  8. $liveChat.iAmAdded = false;
  9. $liveChat._myMediaStream = null;
  10. $liveChat.isVideoStreamed = false;
  11. $liveChat.isAudioStreamed = false;
  12. $liveChat.chatRoom = null;
  13. $liveChat.selfParticipantId = "";
  14. $liveChat.chatWithLiveGuests = false;
  15. $liveChat.rootScopesCalled = false;
  16. $liveChat.myName = "";
  17. $liveChat.configuration = {
  18. 'iceServers': [
  19. {
  20. 'url': 'stun:stun.l.google.com:19302'
  21. },
  22. {
  23. 'url': 'turn:192.158.29.39:3478?transport=udp',
  24. 'credential': 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
  25. 'username': '28224511:1379330808'
  26. },
  27. {
  28. 'url': 'turn:192.158.29.39:3478?transport=tcp',
  29. 'credential': 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
  30. 'username': '28224511:1379330808'
  31. }
  32. ]
  33. }
  34.  
  35. $liveChat.factory('UserModel', function(){
  36. function UserModel(id, firstName, lastName, email, guestIdentification, username, password){
  37. this.id = id;
  38. this.firstName = firstName;
  39. this.lastName = lastName;
  40. this.email = email;
  41. this.guestIdentification = guestIdentification;
  42. this.username = username;
  43. this.password = password;
  44. };
  45.  
  46. return UserModel;
  47. });
  48. $liveChat.factory('ChatRoomModel', function(){
  49. function ChatRoomModel(id, chatRoomName, startDateTime, endDateTime, agent, usersParticipating, emails, chat, connectionId) {
  50. this.id = id;
  51. this.chatRoomName = chatRoomName;
  52. this.startDateTime = startDateTime;
  53. this.endDateTime = endDateTime;
  54. this.creator = agent;
  55. this.usersParticipating = usersParticipating;
  56. this.emails = emails;
  57. this.chat = chat;
  58. this.connectionId = connectionId;
  59. }
  60.  
  61. return ChatRoomModel;
  62. });
  63. $liveChat.factory('ConnectedUser', function(){
  64. function ConnectedUser(userId, name, userConnectionId, connection, chatIdentification, messages, type) {
  65. this.userId = userId;
  66. this.name = name;
  67. this.userConnectionId = userConnectionId;
  68. this.connection = connection;
  69. this.chatIdentification = chatIdentification;
  70. this.messages = messages;
  71. this.type = type;
  72. }
  73.  
  74. return ConnectedUser;
  75. });
  76. $liveChat.factory('MessageModel', function(){
  77. function MessageModel(messageBody, senderId, chatId, isFileOrDocument, isImage, fileName, fileSize) {
  78. this.messageBody = messageBody;
  79. this.senderId = senderId;
  80. this.chatId = chatId;
  81. this.isFileOrDocument = isFileOrDocument;
  82. this.isImage = isImage;
  83. this.fileName = fileName;
  84. this.fileSize = fileSize;
  85. }
  86.  
  87. return MessageModel;
  88. });
  89.  
  90. $liveChat.factory('UserService', function($http, $location){
  91. var userService = {};
  92.  
  93. userService.authLogin = function(username, password, $rootScope, UserService, ConnectedUser){
  94. var data = "grant_type=password&username=" + username + "&password=" + password;
  95.  
  96. return $http.post($liveChat.initialUrl + 'token', data, { headers : {
  97. 'Content-Type': 'application/x-www-form-urlencoded'
  98. }
  99. }).
  100. then(function(response) {
  101. localStorage.setItem('chat_token', response.data.access_token);
  102. userService.getUserRole();
  103. $liveChat.connectToChatServer($rootScope, UserService, ConnectedUser, username);
  104. return true;
  105. }).catch(function(error) {
  106. alert(error.data);
  107. return false;
  108. });
  109. }
  110. userService.getUserRole = function() {
  111. return $http.get($liveChat.initialUrl + 'api/user/role', {
  112. headers: {
  113. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  114. 'Content-Type': 'application/json; charset=utf-8'
  115. }
  116. }).then(function(response){
  117. //enter your logic after retreiving user role
  118. if(response.data === "Admin"){
  119. $location.path('/admin');
  120. }
  121. else if(response.data === "Agent") {
  122. $location.path('/agent');
  123. }
  124. }).catch(function(error){
  125. alert("Couldn't retrieve user role." + error);
  126. });
  127. }
  128. userService.setPresenceStatus = function(status) {
  129. return $http.get($liveChat.initialUrl + '/api/user/agent/presence/' + status, {
  130. headers: {
  131. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  132. 'Content-Type': 'application/json; charset=utf-8'
  133. }
  134. });
  135. }
  136. userService.getAllAgents = function() {
  137. return $http.get($liveChat.initialUrl + 'api/user/agents', {
  138. headers: {
  139. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  140. 'Content-Type': 'application/json; charset=utf-8'
  141. }
  142. });
  143. }
  144.  
  145. userService.createAgent = function(agent){
  146. return $http.post($liveChat.initialUrl + 'api/user/agent/create', agent, {
  147. headers: {
  148. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  149. 'Content-Type': 'application/json; charset=utf-8'
  150. }
  151. });
  152. }
  153.  
  154. userService.deleteAgent = function(id){
  155. return $http.delete($liveChat.initialUrl + 'api/user/agent/' + id + '/delete', {
  156. headers: {
  157. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  158. 'Content-Type': 'application/json; charset=utf-8'
  159. }
  160. });
  161. }
  162.  
  163. userService.getUserInfo = function() {
  164. return $http.get($liveChat.initialUrl + 'api/user/info', {
  165. headers: {
  166. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  167. 'Content-Type': 'application/json; charset=utf-8'
  168. }
  169. });
  170. }
  171.  
  172. userService.updateHubConnection = function(connectionId, username){
  173. return $http.put($liveChat.initialUrl + 'api/user/hub/' + connectionId + '/' + username + '/connection' , null, {
  174. headers: {
  175. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  176. 'Content-Type': 'application/json; charset=utf-8'
  177. }
  178. });
  179. }
  180. userService.disconnectMyself = function(id, room) {
  181. return $http.get($liveChat.initialUrl + 'api/user/' + id + '/' + room + '/disconnect', {
  182. headers: {
  183. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  184. 'Content-Type': 'application/json; charset=utf-8'
  185. }
  186. });
  187. }
  188.  
  189. return userService;
  190. });
  191. $liveChat.factory('ChatRoomService', function($http){
  192. var chatRoomService = {};
  193.  
  194. chatRoomService.getAllChatRoomsByUser = function(id){
  195. return $http.get($liveChat.initialUrl + 'api/chatroom/all/' + id , {
  196. headers: {
  197. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  198. 'Content-Type': 'application/json; charset=utf-8'
  199. }
  200. });
  201. }
  202. chatRoomService.getAllGuestChats = function(){
  203. return $http.get($liveChat.initialUrl + 'api/chatroom/guest/all', {
  204. headers: {
  205. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  206. 'Content-Type': 'application/json; charset=utf-8'
  207. }
  208. });
  209. }
  210.  
  211. chatRoomService.deleteChatRoomById = function(id) {
  212. return $http.delete($liveChat.initialUrl + 'api/chatroom/delete/' + id, {
  213. headers: {
  214. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  215. 'Content-Type': 'application/json; charset=utf-8'
  216. }
  217. });
  218. }
  219. chatRoomService.createChatRoom = function(chatRoom) {
  220. return $http.post($liveChat.initialUrl + 'api/chatroom/new/', JSON.stringify(chatRoom), {
  221. headers: {
  222. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  223. 'Content-Type': 'application/json; charset=utf-8'
  224. }
  225. });
  226. }
  227. chatRoomService.getChatRoom = function (id) {
  228. return $http.get($liveChat.initialUrl + 'api/chatroom/info/' + id, {
  229. headers: {
  230. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  231. 'Content-Type': 'application/json; charset=utf-8'
  232. }
  233. });
  234. }
  235.  
  236. chatRoomService.endRoom = function(id){
  237. return $http.get($liveChat.initialUrl + 'api/chatroom/' + id + '/endroom' , {
  238. headers: {
  239. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  240. 'Content-Type': 'application/json; charset=utf-8'
  241. }
  242. });
  243. }
  244. chatRoomService.getEndedRooms = function(){
  245. return $http.get($liveChat.initialUrl + 'api/chatroom/ended' , {
  246. headers: {
  247. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  248. 'Content-Type': 'application/json; charset=utf-8'
  249. }
  250. });
  251. }
  252. chatRoomService.getAllRooms = function(){
  253. return $http.get($liveChat.initialUrl + 'api/chatroom/all/admin' , {
  254. headers: {
  255. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  256. 'Content-Type': 'application/json; charset=utf-8'
  257. }
  258. });
  259. }
  260. chatRoomService.getChatLog = function(guestIdentification){
  261. return $http.get($liveChat.initialUrl + 'api/chatroom/guest/chat/' + guestIdentification + "/get" , {
  262. headers: {
  263. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  264. 'Content-Type': 'application/json; charset=utf-8'
  265. }
  266. });
  267. }
  268.  
  269. return chatRoomService;
  270. });
  271. $liveChat.factory('MessageService', function($http){
  272. var messageService = {};
  273.  
  274. messageService.getChatHistory = function (chatLogId) {
  275. return $http.get($liveChat.initialUrl + 'api/message/'+ chatLogId + '/history');
  276. }
  277.  
  278. messageService.sendMessageService = function (message, room) {
  279. return $http.post($liveChat.initialUrl + 'api/message/send/' + room.toString(), JSON.stringify(message));
  280. }
  281.  
  282. messageService.setMediaStatus = function (id, status, room) {
  283. return $http.get($liveChat.initialUrl + 'api/message/media/' + id + '/' + status + "/" + room
  284. + '/set', {
  285. headers: {
  286. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  287. 'Content-Type': 'application/json; charset=utf-8'
  288. }
  289. });
  290. }
  291.  
  292. messageService.getMediaStatus = function (id) {
  293. return $http.get($liveChat.initialUrl + 'api/message/media/' + id + '/get', {
  294. headers: {
  295. 'Authorization': 'Bearer ' + localStorage.getItem("chat_token").toString(),
  296. 'Content-Type': 'application/json; charset=utf-8'
  297. }
  298. });
  299. }
  300.  
  301. return messageService;
  302. });
  303.  
  304. $liveChat.login = function(username, password, $rootScope, UserService, ConnectedUser){
  305. UserService.authLogin(username, password, $rootScope, UserService, ConnectedUser);
  306. }
  307. $liveChat.logout = function($rootScope){
  308. localStorage.removeItem("chat_token");
  309. }
  310. $liveChat.divideChatRooms = function(chatrooms, ChatRoomModel, agentId) {
  311. var myChatRooms = [];
  312. var chatRoomsInvitedIn = [];
  313. for(var i=0; i< chatrooms.length; i++){
  314. if(chatrooms[i].endDate == null){
  315. if(chatrooms[i].creator.id === agentId)
  316. 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));
  317. else
  318. 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));
  319. }
  320. }
  321. return {
  322. myChatRooms: myChatRooms,
  323. chatRoomsInvitedIn: chatRoomsInvitedIn
  324. };
  325. }
  326. $liveChat.receiveName = function($rootScope, ConnectedUser){
  327. $liveChat.chatProxy.on("receiveName", (id, userConnectionId) => {
  328. if($liveChat.chatRoom == null){
  329. $liveChat.connectedUsers.push(new ConnectedUser(id, "", userConnectionId, null, null, 0, null));
  330. }
  331. else if (id === $liveChat.chatRoom.creator.id) {
  332. if(id != $liveChat.selfParticipantId){
  333. var user = $liveChat.connectedUsers.find(x=>x.userConnectionId == userConnectionId);
  334. if(user === null || user === undefined){
  335. var check = $liveChat.connectedUsers.find(x=>x.userId == id);
  336. if(user === null || user === undefined){
  337. $rootScope.$broadcast('nameReceived', $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, id);
  338. }
  339. $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
  340. $liveChat.connectedUsers.push(new ConnectedUser($liveChat.chatRoom.creator.id, $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, userConnectionId, null, null, 0, null));
  341. }
  342. }
  343. else{
  344. if ($liveChat.iAmAdded === false){
  345. $rootScope.$broadcast('nameReceived', $liveChat.chatRoom.creator.firstName + " " + $liveChat.chatRoom.creator.lastName, id);
  346. $liveChat.iAmAdded = true;
  347. }
  348. }
  349. }
  350. else{
  351. var user = $liveChat.connectedUsers.find(x => x.userConnectionId === userConnectionId);
  352. if(user === null || user === undefined){
  353. user = $liveChat.chatRoom.usersParticipating.find(x=> x.id === id);
  354. if($liveChat.selfParticipantId != user.id){
  355. var check = $liveChat.connectedUsers.find(x=>x.userId == id);
  356. $rootScope.$broadcast('nameReceived', user.firstName + " " + user.lastName, id);
  357. $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
  358. $liveChat.connectedUsers.push(new ConnectedUser(user.id, user.firstName + " " + user.lastName, userConnectionId, null, null, 0, null));
  359. }
  360. else {
  361. if($liveChat.iAmAdded === false){
  362. $rootScope.$broadcast('nameReceived', user.firstName + " " + user.lastName, id);
  363. $liveChat.iAmAdded = true;
  364. }
  365. }
  366. }
  367. }
  368. });
  369. }
  370. $liveChat.mediaStatus = function($rootScope){
  371. $liveChat.chatProxy.on("mediaEnabled", (status) => {
  372. if ($liveChat.chatRoom.creator.id != $liveChat.selfParticipantId) {
  373. $rootScope.$broadcast('mediaStatus', status);
  374. }
  375. });
  376. }
  377. $liveChat.pullHistory = function($rootScope){
  378. $liveChat.chatProxy.on("pullHistory", () => {
  379. if($liveChat.chatWithLiveGuests){
  380. $rootScope.$broadcast('pullHistory');
  381. $liveChat.chatProxy.invoke("askVideo", localStorage.getItem("guestConnectionId"));
  382. }
  383. else if ($liveChat.chatRoom.creator.id != $liveChat.selfParticipantId) {
  384. $rootScope.$broadcast('pullHistory');
  385. }
  386. });
  387. }
  388. $liveChat.handleUserDisconnection = function($rootScope){
  389. $liveChat.chatProxy.on("userDisconnected", (userId)=> {
  390. $rootScope.$broadcast('userDisconnected', userId);
  391. if(userId === $liveChat.selfParticipantId){
  392. $liveChat.connectedUsers = [];
  393. }
  394. else{
  395. for(var i = 0; i< $liveChat.connectedUsers.length; i++){
  396. if($liveChat.connectedUsers[i].userId === userId){
  397. $liveChat.chatProxy.invoke("removeFromRoom", $liveChat.chatRoom.connectionId, $liveChat.connectedUsers[i].userConnectionId);
  398. $liveChat.connectedUsers.splice(i, 1);
  399. }
  400. }
  401. }
  402. });
  403. }
  404. $liveChat.receiveMessage = function($rootScope){
  405. $liveChat.chatProxy.on("sendMessage", (senderName, message, fileSize, messageUrl, type, date, senderConnectionId) => {
  406. $rootScope.$broadcast('messageSent', senderName, message, fileSize, messageUrl, type, date, senderConnectionId);
  407. });
  408. }
  409. $liveChat.handleRoomDisconnection = function($rootScope){
  410. $liveChat.chatProxy.on("disconnect", () => {
  411. if($liveChat._myMediaStream != null){
  412. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, $liveChat.chatRoom.connectionId);
  413. $('#rtcVideo').hide();
  414. var guestVideos = document.getElementsByClassName('.guest-video');
  415. if(!guestVideos != null && !guestVideos != undefined){
  416. $('.guest-video').remove();
  417. }
  418. }
  419. $liveChat.iAmAdded = false;
  420. $rootScope.$broadcast('chatRoomClosed', $liveChat.chatRoom.creator.id === $liveChat.selfParticipantId);
  421. });
  422. }
  423. $liveChat.handleVideoCancel = function(){
  424. $liveChat.chatProxy.on("cancelVideo", (userConnectionId, streamId) => {
  425. var element = document.getElementById(streamId.toString());
  426. if(element != null && element != undefined){
  427. element.remove();
  428. }
  429. });
  430. }
  431. $liveChat.handleGuestDisconnection = function($rootScope){
  432. $liveChat.chatProxy.on("disconnectFromRoom", (userConnectionId)=>{
  433. if(userConnectionId!= $liveChat.hubConnection.id){
  434. for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
  435. if($liveChat.liveChatGuests[i].userConnectionId === userConnectionId){
  436. $liveChat.liveChatGuests[i].userConnectionId = null;
  437. }
  438. }
  439. if(userConnectionId === localStorage.getItem("guestConnectionId")){
  440. if($liveChat._myMediaStream!= null)
  441. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, localStorage.getItem("guestConnectionId"));
  442.  
  443. localStorage.setItem("guestConnectionId", "");
  444.  
  445. $rootScope.$broadcast("guestDisconnectedRoom");
  446. }
  447. else{
  448. $rootScope.$broadcast("agentDisconnectedRoom");
  449. }
  450. }
  451. });
  452. }
  453. $liveChat.handleStreamMessage = function(){
  454. $liveChat.chatProxy.on("streamMessage", (data, senderConnectionId, type) => $liveChat.handleStream(data, senderConnectionId, type));
  455. }
  456. $liveChat.askForVideo = function($rootScope){
  457. $liveChat.chatProxy.on("askVideo", (userConnectionId) => {
  458. if($liveChat.isVideoStreamed || $liveChat.isAudioStreamed){
  459. if(userConnectionId != $liveChat.hubConnection.id){
  460. angular.forEach($liveChat.connectedUsers, function(item){
  461. if(item.connection == null){
  462. if($liveChat.isVideoStreamed)
  463. item.connection = $liveChat.createVideoConnection(item.userConnectionId);
  464. else
  465. item.connection = $liveChat.createAudioConnection(item.userConnectionId);
  466. item.connection.addStream($liveChat._myMediaStream);
  467. document.getElementById('cancel').addEventListener('click', function () {
  468. if($liveChat.chatRoom != null)
  469. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, $liveChat.chatRoom.connectionId);
  470. else
  471. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, localStorage.getItem("guestConnectionId"));
  472. $('#rtcVideo').hide();
  473. });
  474. item.connection.createOffer(function (desc) {
  475. item.connection.setLocalDescription(desc, function () {
  476. var type = "";
  477. if($liveChat.isAudioStreamed)
  478. type = "audio";
  479. else if($liveChat.isVideoStreamed)
  480. type = "video";
  481. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, type);
  482. });
  483. }, function (error) { console.log('Error creating session description: ' + error); });
  484. }
  485. });
  486. }
  487. }
  488. });
  489. }
  490. $liveChat.handleGuestJoining = function($rootScope, ConnectedUser){
  491. $liveChat.chatProxy.on("guestJoinedToLiveChat", (userConnectionId, secondArgument, thirdArgument)=>{
  492. var guest = {};
  493. if(secondArgument === null){
  494. var guestExists = $liveChat.liveChatGuests.find(x=>x.chatIdentification === thirdArgument);
  495. if(guestExists === undefined){
  496. guest = new ConnectedUser(null, "Guest ", userConnectionId, null, secondArgument, 0, null);
  497. $liveChat.liveChatGuests.push(guest);
  498. }
  499. else {
  500. if(!guestExists.userConnectionId === userConnectionId)
  501. guestExists.userConnectionId = userConnectionId;
  502. }
  503. }
  504. else if(thirdArgument === null){
  505. $liveChat.liveChatGuests.forEach(function(item){
  506. if(item.chatIdentification === secondArgument.guestIdentification){
  507. item.userConnectionId = userConnectionId;
  508. }
  509. });
  510. }
  511. $rootScope.$broadcast("guestListUpdated");
  512. });
  513. }
  514. $liveChat.handleGuestMessage = function($rootScope, ConnectedUser){
  515. $liveChat.chatProxy.on("guestSentMessage", (userConnectionId, secondArgument, thirdArgument)=> {
  516. var userExists = null;
  517. var chatIdentification = "";
  518. if(secondArgument === null){
  519. userExists = $liveChat.liveChatGuests.find(x=>x.chatIdentification === thirdArgument);
  520. chatIdentification = thirdArgument;
  521. if(userExists === undefined){
  522. guest = new ConnectedUser(null, "Guest", userConnectionId, null, chatIdentification, 0, null);
  523. $liveChat.liveChatGuests.push(guest);
  524. }
  525. else{
  526. for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
  527. if($liveChat.liveChatGuests[i].chatIdentification === chatIdentification){
  528. $liveChat.liveChatGuests[i].messages++;
  529. }
  530. }
  531. }
  532. }
  533. else if(thirdArgument === null){
  534. chatIdentification = secondArgument.guestIdentification;
  535. $liveChat.liveChatGuests.forEach(function(item){
  536. if(item.chatIdentification === secondArgument.guestIdentification){
  537. if(item.userConnectionId === null)
  538. item.userConnectionId = userConnectionId;
  539. else{
  540. for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
  541. if($liveChat.liveChatGuests[i].chatIdentification === chatIdentification){
  542. $liveChat.liveChatGuests[i].messages++;
  543. }
  544. }
  545. }
  546. }
  547. });
  548. }
  549. $rootScope.$broadcast("guestListUpdated");
  550. });
  551. }
  552. $liveChat.handleMessagesClear = function($rootScope){
  553. $liveChat.chatProxy.on("clearLiveMessages", (chatIdentification)=> {
  554. $liveChat.clearLiveMessages(chatIdentification, "chatId", $rootScope);
  555. });
  556. }
  557. $liveChat.handleLiveChatJoining = function(ConnectedUser){
  558. $liveChat.chatProxy.on("joinedToRoom",(userConnectionId, name)=>{
  559. if(userConnectionId != $liveChat.hubConnection.id){
  560. var user = $liveChat.connectedUsers.find(x=>x.userConnectionId === userConnectionId);
  561. if(user === undefined){
  562. $liveChat.connectedUsers.push(new ConnectedUser(null, "", userConnectionId, null, null, 0));
  563. $liveChat.chatProxy.invoke("joinedToLiveChat", localStorage.getItem("guestConnectionId"));
  564. }
  565. }
  566. });
  567. }
  568. $liveChat.handleDisconnectionFromLiveChat = function($rootScope){
  569. $liveChat.chatProxy.on("guestDisconnectedFromToLiveChat", (userConnectionId)=>{
  570. /* if(userConnectionId!= $liveChat.hubConnection.id){
  571. for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
  572. if($liveChat.liveChatGuests[i].userConnectionId === userConnectionId){
  573. $liveChat.liveChatGuests.splice(i, 1);
  574. }
  575. }
  576.  
  577. $rootScope.$broadcast("guestListUpdated", null);
  578. }*/
  579. $liveChat.clearLiveMessages(userConnectionId, "connectionId", $rootScope);
  580. });
  581. }
  582. $liveChat.handleGuestUpdate = function($rootScope){
  583. $liveChat.chatProxy.on("guestUpdatedInfo", (chatIdentification, name, hubConnection) => {
  584. var guestUserInList = $liveChat.liveChatGuests.find(x => x.chatIdentification === chatIdentification);
  585. guestUserInList.name = name;
  586. guestUserInList.userConnectionId = hubConnection;
  587.  
  588. $rootScope.$broadcast("guestInfoUpdated");
  589. });
  590. }
  591. $liveChat.connectToChatServer = function($rootScope, UserService, ConnectedUser, username){
  592. $liveChat.receiveName($rootScope, ConnectedUser);
  593. $liveChat.mediaStatus($rootScope);
  594. $liveChat.pullHistory($rootScope);
  595. $liveChat.handleUserDisconnection($rootScope);
  596. $liveChat.receiveMessage($rootScope);
  597. $liveChat.handleRoomDisconnection($rootScope);
  598. $liveChat.handleVideoCancel();
  599. $liveChat.handleStreamMessage();
  600. $liveChat.handleGuestDisconnection($rootScope);
  601. $liveChat.handleGuestJoining($rootScope, ConnectedUser);
  602. $liveChat.handleGuestMessage($rootScope, ConnectedUser);
  603. $liveChat.handleMessagesClear($rootScope);
  604. $liveChat.handleLiveChatJoining(ConnectedUser);
  605. $liveChat.askForVideo($rootScope);
  606. $liveChat.handleGuestUpdate($rootScope);
  607. $liveChat.handleDisconnectionFromLiveChat($rootScope);
  608. $liveChat.hubConnection.start().done(() => {
  609. UserService.updateHubConnection($liveChat.hubConnection.id, username);
  610. UserService.setPresenceStatus(true);
  611. });
  612. $liveChat.hubConnection.disconnected(function(){
  613. UserService.disconnectMyself($liveChat.selfParticipantId, $liveChat.chatRoom.connectionId);
  614. UserService.setPresenceStatus(false);
  615. });
  616. }
  617. $liveChat.clearLiveMessages = function(firstArgument, secondArgument, $rootScope){
  618. for(var i = 0; i < $liveChat.liveChatGuests.length; i++){
  619. if(secondArgument === "chatId"){
  620. if($liveChat.liveChatGuests[i].chatIdentification === firstArgument){
  621. $liveChat.liveChatGuests[i].messages = 0;
  622. $rootScope.$broadcast("guestListUpdated");
  623. }
  624. }
  625. else if(secondArgument === "connectionId"){
  626. if ($liveChat.liveChatGuests[i].userConnectionId != null){
  627. if ($liveChat.liveChatGuests[i].userConnectionId === firstArgument){
  628. if ($liveChat.liveChatGuests[i].name === "Guest "){
  629. for(var i = 0; i < $liveChat.liveChatGuests.length; i++) {
  630. if($liveChat.liveChatGuests[i].userConnectionId === firstArgument){
  631. $liveChat.liveChatGuests.splice(i, 1);
  632. }
  633. }
  634. $rootScope.$broadcast("guestListUpdated");
  635. }
  636. else{
  637. $liveChat.liveChatGuests[i].Messages = 0;
  638. $rootScope.$broadcast("guestListUpdated");
  639. }
  640. }
  641. }
  642. }
  643. }
  644. }
  645. $liveChat.enterChatRoom = function(){
  646. $liveChat.chatProxy.invoke("joinRoom", $liveChat.chatRoom.connectionId);
  647. $liveChat.chatProxy.invoke("sendName", $liveChat.chatRoom.connectionId, $liveChat.selfParticipantId);
  648. if($liveChat.chatRoom.chat.mediaAllowed){
  649. $('#startVideo').prop("disabled", false);
  650. $('#startAudio').prop("disabled", false);
  651. $liveChat.chatProxy.invoke("askVideo", $liveChat.chatRoom.connectionId);
  652. }
  653. }
  654. $liveChat.videoCall = function($rootScope, cancel, connectionId){
  655. getUserMedia({
  656. video: true,
  657. audio: false
  658. }, function (stream) {
  659. $('#' + myvideo.id).show();
  660. $liveChat._myMediaStream = stream;
  661. attachMediaStream(myvideo, $liveChat._myMediaStream);
  662.  
  663. if(localStorage.getItem('guestConnectionId') != null)
  664. $liveChat.chatProxy.invoke("callGuest", localStorage.getItem('guestConnectionId'));
  665.  
  666. $liveChat.isVideoStreamed = true;
  667. cancel.addEventListener('click', function () {
  668. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, connectionId);
  669. $('#' + myvideo.id).hide();
  670. });
  671. angular.forEach($liveChat.connectedUsers, function(item){
  672. if(item.connection == null){
  673. item.connection = $liveChat.createVideoConnection(item.userConnectionId);
  674. item.type = "video";
  675. item.connection.addStream($liveChat._myMediaStream);
  676. item.connection.createOffer(function (desc) {
  677. item.connection.setLocalDescription(desc, function () {
  678. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "video");
  679. });
  680. }, function (error) { console.log('Error creating session description: ' + error); });
  681. }
  682. else if(item.connection != null){
  683. if (item.type != "video") {
  684. item.connection = $liveChat.createVideoConnection(item.userConnectionId);
  685. item.type = "video";
  686. }
  687. item.connection.addStream($liveChat._myMediaStream);
  688. item.connection.createOffer(function (desc) {
  689. item.connection.setLocalDescription(desc, function () {
  690. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "video");
  691. });
  692. }, function (error) { console.log('Error creating session description: ' + error); });
  693. }
  694. });
  695. },
  696. function (error) {
  697. alert(JSON.stringify(error));
  698. });
  699. }
  700. $liveChat.audioCall = function($rootScope, cancel, connectionId){
  701. getUserMedia({
  702. video: false,
  703. audio: true
  704. }, function (stream) {
  705. $liveChat._myMediaStream = stream;
  706.  
  707. cancel.addEventListener('click', function () {
  708. $liveChat.stopVideoStream($rootScope, $liveChat._myMediaStream, connectionId);
  709. });
  710.  
  711. $liveChat.isAudioStreamed = true;
  712.  
  713. angular.forEach($liveChat.connectedUsers, function(item){
  714.  
  715. if(item.connection == null){
  716. item.connection = $liveChat.createAudioConnection(item.userConnectionId);
  717. item.type = "audio";
  718. item.connection.addStream($liveChat._myMediaStream);
  719. item.connection.createOffer(function (desc) {
  720. item.connection.setLocalDescription(desc, function () {
  721. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "audio");
  722. });
  723. }, function (error) { console.log('Error creating session description: ' + error); });
  724. }
  725. else if(item.connection != null){
  726. if(item.type != "audio") {
  727. item.connection = $liveChat.createAudioConnection(item.userConnectionId);
  728. item.type = "audio";
  729. }
  730. item.connection.addStream($liveChat._myMediaStream);
  731. item.connection.createOffer(function (desc) {
  732. item.connection.setLocalDescription(desc, function () {
  733. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': desc }), item.userConnectionId, "audio");
  734. });
  735. }, function (error) { console.log('Error creating session description: ' + error); });
  736. }
  737. });
  738. },
  739. function (error) {
  740. alert(JSON.stringify(error));
  741. });
  742. }
  743. $liveChat.stopVideoStream = function ($rootScope, stream, connectionId) {
  744. var videos = stream.getVideoTracks();
  745. if(videos != null && videos != undefined){
  746. angular.forEach(videos, function (track) {
  747. track.stop();
  748. });
  749. }
  750. var audios = stream.getAudioTracks();
  751. if(audios != null && audios != undefined){
  752. angular.forEach(audios, function (track) {
  753. track.stop();
  754. });
  755. }
  756. $rootScope.$broadcast('stopVideoStream');
  757. $liveChat.isAudioStreamed = false;
  758. $liveChat.isVideoStreamed = false;
  759. $liveChat.chatProxy.invoke("cancelVideo", connectionId, stream.id);
  760. }
  761. $liveChat.createVideoConnection = function(connectionId) {
  762. var connection = new RTCPeerConnection($liveChat.configuration);
  763. connection.onicecandidate = function (event) {
  764. if (event.candidate) {
  765. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'candidate': event.candidate }), connectionId, "video");
  766. }
  767. };
  768. connection.onaddstream = function (event) {
  769. var newVideoElement = document.createElement('video');
  770. newVideoElement.className = 'guest-video';
  771. newVideoElement.autoplay = 'autoplay';
  772. newVideoElement.id = event.stream.id.toString();
  773.  
  774. attachMediaStream(newVideoElement, event.stream);
  775.  
  776. document.querySelector('.chat-video').appendChild(newVideoElement);
  777. };
  778. return connection;
  779. }
  780. $liveChat.createAudioConnection = function(connectionId) {
  781. var connection = new RTCPeerConnection($liveChat.configuration);
  782. connection.onicecandidate = function (event) {
  783. if (event.candidate) {
  784. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'candidate': event.candidate }), connectionId, "audio");
  785. }
  786. };
  787. connection.onaddstream = function (event) {
  788. var newAudioElement = document.createElement('audio');
  789. newAudioElement.className = 'guest-audio';
  790. newAudioElement.autoplay = 'autoplay';
  791. newAudioElement.id = event.stream.id.toString();
  792.  
  793. attachMediaStream(newAudioElement, event.stream);
  794.  
  795. document.querySelector('body').appendChild(newAudioElement);
  796. };
  797. return connection;
  798. }
  799. $liveChat.handleStream = function (data, senderConnectionId, type) {
  800. var message = JSON.parse(data);
  801. angular.forEach($liveChat.connectedUsers, function(item){
  802. if(item.userConnectionId === senderConnectionId){
  803. if(item.connection === null || item.type != type){
  804. if (type === "video"){
  805. item.connection = $liveChat.createVideoConnection(senderConnectionId);
  806. item.type = "video";
  807. }
  808. else {
  809. item.connection = $liveChat.createAudioConnection(senderConnectionId);
  810. item.type = "audio";
  811. }
  812. }
  813. }
  814. if (message.sdp) {
  815. item.connection.setRemoteDescription(new RTCSessionDescription(message.sdp), function () {
  816. if (item.connection.remoteDescription.type == 'offer') {
  817. console.log('received offer, sending answer...');
  818. item.connection.createAnswer(function (desc) {
  819. item.connection.setLocalDescription(desc, function () {
  820. $liveChat.chatProxy.invoke('stream', JSON.stringify({ 'sdp': item.connection.localDescription }), senderConnectionId, type);
  821. });
  822. }, function (error) { console.log('Error creating session description: ' + error); });
  823. }
  824. else if (item.connection.remoteDescription.type == 'answer') {
  825. console.log('got an answer');
  826. }
  827. });
  828. }
  829. else if (message.candidate) {
  830. console.log('adding ice candidate...');
  831. item.connection.addIceCandidate(new RTCIceCandidate(message.candidate));
  832. }
  833. });
  834. }
  835. $liveChat.startUploading = function ($files, uploadedFiles, upload, MessageService, MessageModel, participantId, chatRoomConnectionId, chatId, $upload) {
  836. for (var i = 0; i < $files.length; i++) {
  837. var $file = $files[i];
  838. (function (index) {
  839. upload[index] = $upload.upload({
  840. url: "http://livechattests.azurewebsites.net/api/fileupload", // webapi url
  841. method: "POST",
  842. file: $file
  843. }).progress(function (evt) {
  844. }).success(function (data, status, headers, config) {
  845. // file is uploaded successfully
  846. var type = $liveChat.checkFileExtension(data.fileName);
  847. var newMessage = new MessageModel("http://livechattests.azurewebsites.net/api/Files/" + data.fileName, participantId, chatId, false, false, "", "");
  848. if(type === "image"){
  849. newMessage.isImage = true;
  850. }
  851. else if(type === "file"){
  852. newMessage.isFileOrDocument = true;
  853. }
  854. newMessage.fileName = data.fileName;
  855. newMessage.fileSize = $file.size;
  856. MessageService.sendMessageService(newMessage, chatRoomConnectionId);
  857. }).error(function (data, status, headers, config) {
  858. console.log(data);
  859. });
  860. })(i);
  861. }
  862. }
  863. $liveChat.checkFileExtension = function(dataFile){
  864. var lastDot = 0;
  865. var resultString = "";
  866.  
  867. for(var i = 0; i < dataFile.length; i++){
  868. if(dataFile.charAt(i) === "."){
  869. lastDot = i;
  870. }
  871. }
  872. resultString = "";
  873. lastDot++;
  874. var loop = true;
  875. while(loop){
  876. resultString = resultString + dataFile.charAt(lastDot).toString();
  877. lastDot++;
  878. if(lastDot === dataFile.length)
  879. loop = false;
  880. }
  881. if(resultString === "png" || resultString === "jpg" || resultString === "jpeg" || resultString === "gif" || resultString === "bmp" )
  882. resultString = "image";
  883. else
  884. resultString = "file";
  885. return resultString;
  886. }
  887. $liveChat.getParameterByName = function(name, url) {
  888. if (!url) {
  889. url = window.location.href;
  890. }
  891. name = name.replace(/[\[\]]/g, "\\$&");
  892. var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  893. results = regex.exec(url);
  894. if (!results) return null;
  895. if (!results[2]) return '';
  896. return decodeURIComponent(results[2].replace(/\+/g, " "));
  897. }
  898. //////events to subscribe on
  899. /*
  900. $rootScope.$on('nameReceived', function(event, name, userId) {
  901. });
  902. $rootScope.$on('mediaStatus', function(event, status) {
  903. });
  904. $rootScope.$on('stopVideoStream', function(event){
  905. });
  906. $rootScope.$on('chatRoomClosed', function(event){
  907. });
  908. $rootScope.$on('userDisconnected', function(event, userId){
  909. });
  910. $rootScope.$on('guestDisconnectedRoom', function(event){
  911. });
  912. $rootScope.$on('agentDisconnectedRoom', function(event){
  913. });
  914. $rootScope.$on('messageSent', function(event, senderName, message, fileSize, messageUrl, type, date, senderConnectionId){
  915. });
  916. $rootScope.$on('pullHistory', function(event){
  917. });
  918. $rootScope.$on("guestInfoUpdated"), function(event){
  919. });
  920. $rootScope.$on("guestListUpdated", function(event){
  921. });
  922. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement