chatServices.js 2.5 KB

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