1
0

io.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Created by Hongcai Deng on 2015/12/28.
  3. */
  4. 'use strict';
  5. let shortid = require('shortid');
  6. let mailin = require('./mailin');
  7. let onlines = new Map();
  8. module.exports = function(io) {
  9. mailin.on('message', function(connection, data) {
  10. let to = data.headers.to.toLowerCase();
  11. let exp = /[\w\._\-\+]+@[\w\._\-\+]+/i;
  12. if(exp.test(to)) {
  13. let matches = to.match(exp);
  14. let shortid = matches[0].substring(0, matches[0].indexOf('@'));
  15. if(onlines.has(shortid)) {
  16. onlines.get(shortid).emit('mail', data);
  17. }
  18. }
  19. });
  20. io.on('connection', socket => {
  21. socket.on('request shortid', function() {
  22. onlines.delete(socket.shortid);
  23. socket.shortid = shortid.generate().toLowerCase(); // generate shortid for a request
  24. onlines.set(socket.shortid, socket); // add incomming connection to online table
  25. socket.emit('shortid', socket.shortid);
  26. });
  27. socket.on('set shortid', function(id) {
  28. onlines.delete(socket.shortid);
  29. socket.shortid = id;
  30. onlines.set(socket.shortid, socket);
  31. socket.emit('shortid', socket.shortid);
  32. })
  33. });
  34. io.on('disconnect', socket => {
  35. onlines.delete(socket.shortid);
  36. });
  37. };