chatServices.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. angular.module('chatServices', [])
  2. .factory('Connection', function($rootScope, $timeout) {
  3. var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
  4. var chatSocket = null;
  5. var service = {
  6. username: '',
  7. error: null,
  8. messages: [],
  9. isConnected: function() {
  10. return this.username != '';
  11. },
  12. addListener: function(f) {
  13. messageListeners.add(f);
  14. }
  15. };
  16. function wrap(func) {
  17. return function() {
  18. var args = arguments;
  19. $timeout(function() {
  20. func.apply(null, args);
  21. });
  22. }
  23. };
  24. service.connect = function(username) {
  25. chatSocket = new WS(jsRoutes.controllers.Application.chat(username).webSocketURL());
  26. chatSocket.onmessage = wrap(function(event) {
  27. var message = JSON.parse(event.data);
  28. $rootScope.$broadcast('ws:message', message);
  29. });
  30. chatSocket.onopen = wrap(function() {
  31. $rootScope.$broadcast('ws:connected', username);
  32. service.username = username;
  33. });
  34. chatSocket.onclose = wrap(function() {
  35. $rootScope.$broadcast('ws:disconnected');
  36. service.username = '';
  37. });
  38. }
  39. service.disconnect = function() {
  40. chatSocket.close();
  41. chatSocket = null;
  42. }
  43. service.send = function(message) {
  44. chatSocket.send(JSON.stringify({text: message}));
  45. }
  46. return service;
  47. })
  48. .factory('Chat', function($rootScope, Connection) {
  49. var service = {
  50. username: '',
  51. messages: [],
  52. receive: function(message) {
  53. if(arguments.length == 3) {
  54. message = {
  55. kind: arguments[0],
  56. user: arguments[1],
  57. message: arguments[2]
  58. };
  59. }
  60. service.messages.push(message);
  61. },
  62. isConnected: Connection.isConnected,
  63. send: Connection.send
  64. };
  65. $rootScope.$on('ws:connected', function(event, username) {
  66. service.username = username;
  67. });
  68. $rootScope.$on('ws:message', function(event, message) {
  69. if(message.kind == "talk") {
  70. service.receive(message);
  71. }
  72. else if(message.kind == "join") {
  73. service.receive("join", message.user, " has joined.");
  74. }
  75. else if(message.kind == "quit") {
  76. service.receive("quit", message.user, " has left.");
  77. }
  78. });
  79. $rootScope.$on('ws:disconnected', function() {
  80. service.messages = [];
  81. service.username = '';
  82. });
  83. if(Connection.isConnected()) {
  84. service.username = Connection.username;
  85. }
  86. return service;
  87. })