io.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Created by Hongcai Deng on 2015/12/28.
  3. */
  4. 'use strict';
  5. const shortid = require('shortid');
  6. const mailin = require('./mailin');
  7. const config = require('./config');
  8. let onlines = new Map();
  9. function checkShortIdMatchBlackList(id) {
  10. const keywordBlackList = config.keywordBlackList;
  11. if (keywordBlackList && keywordBlackList.length > 0) {
  12. for (let i = 0; i < keywordBlackList.length; i++) {
  13. const keyword = keywordBlackList[i];
  14. if (id.includes(keyword)) {
  15. return true;
  16. }
  17. }
  18. }
  19. return false;
  20. }
  21. module.exports = function(io) {
  22. mailin.on('message', function(connection, data) {
  23. let to = data.headers.to.toLowerCase();
  24. let exp = /[\w\._\-\+]+@[\w\._\-\+]+/i;
  25. if(exp.test(to)) {
  26. let matches = to.match(exp);
  27. let shortid = matches[0].substring(0, matches[0].indexOf('@'));
  28. if(onlines.has(shortid)) {
  29. onlines.get(shortid).emit('mail', data);
  30. }
  31. }
  32. });
  33. io.on('connection', socket => {
  34. socket.on('request shortid', function() {
  35. onlines.delete(socket.shortid);
  36. socket.shortid = shortid.generate().toLowerCase(); // generate shortid for a request
  37. onlines.set(socket.shortid, socket); // add incomming connection to online table
  38. socket.emit('shortid', socket.shortid);
  39. });
  40. socket.on('set shortid', function(id) {
  41. if (checkShortIdMatchBlackList(id)) {
  42. // skip set shortid if match keyword blacklist
  43. return;
  44. }
  45. onlines.delete(socket.shortid);
  46. socket.shortid = id;
  47. onlines.set(socket.shortid, socket);
  48. socket.emit('shortid', socket.shortid);
  49. })
  50. socket.on('disconnect', socket => {
  51. onlines.delete(socket.shortid);
  52. });
  53. });
  54. };