You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
3.3 KiB

  1. const net = require("net")
  2. const User = require("../src/user.js")
  3. const RPL_WELCOME = '001'
  4. const ERR_NOSUCHNICK = '401'
  5. const ERR_NOSUCHCHANNEL = '403'
  6. const ERR_CANNOTSENDTOCHAN = '404'
  7. const ERR_UNKNOWNCOMMAND = '421'
  8. const ERR_ERRONEUSNICKNAME = '432'
  9. const ERR_NONICKNAMEGIVEN = '431'
  10. const ERR_NICKNAMEINUSE = '433'
  11. const ERR_NEEDMOREPARAMS = '461'
  12. let server = {}
  13. server.create = function create() {
  14. let userlist = {}
  15. let server = net.createServer((socket) => {
  16. const user = new User(socket)
  17. socket.on('data', function (data) {
  18. let splitted = data.toString("ascii").split("\r\n")[0].split(" ")
  19. let tokenized = []
  20. let lastParam = -1
  21. for (let i = 0; i < splitted.length; i++) {
  22. if (lastParam > 0) {
  23. tokenized[lastParam] = tokenized[lastParam] + " " + splitted[i]
  24. } else if (splitted[i].charAt(0) == ":" && i > 0) {
  25. lastParam = i
  26. tokenized[lastParam] = splitted[i].slice(1)
  27. } else {
  28. tokenized[i] = splitted[i]
  29. }
  30. }
  31. let command = tokenized[0].toUpperCase()
  32. switch (command) {
  33. case "PING":
  34. if (tokenized[1] && tokenized[1] === "irc.example.com") {
  35. socket.write("PONG irc.example.com\r\n")
  36. }
  37. break;
  38. case "NICK":
  39. if (tokenized[1]) {
  40. let nickname = tokenized[1]
  41. // nick collision test
  42. if (!Object.keys(userlist).includes(nickname)) {
  43. user.setNickname(nickname)
  44. userlist[user.nickname] = user
  45. } else {
  46. socket.write(ERR_NICKNAMEINUSE, " nickname in use")
  47. }
  48. } else {
  49. socket.write(ERR_NONICKNAMEGIVEN, "ERROR: NO NICKNAME PROVIDED")
  50. }
  51. break;
  52. case "USER":
  53. // ignoring servername and hostname, not useful these days
  54. user.register(tokenized[1], tokenized[4])
  55. let address = user.getAddress()
  56. socket.write(`001 ${user.nickname} :Welcome to the example IRC Project ${user.nickname}!~${user.username}@${address}`)
  57. break;
  58. case "PRIVMSG":
  59. let target = userlist[tokenized[1]]
  60. let message = tokenized[2]
  61. target.sendMsg(user, message)
  62. break;
  63. case "QUIT":
  64. server.closeConnection(user.nickname)
  65. break;
  66. default:
  67. console.error(`Unknown command: ${command}`);
  68. }
  69. }).on('error', (err) => {
  70. console.error(err);
  71. })
  72. }).on('error', (err) => {
  73. console.error(err);
  74. throw err;
  75. });
  76. server.getUserlist = function () {
  77. return userlist
  78. }
  79. server.closeConnection = function (user_nickname) {
  80. let user = userlist[user_nickname]
  81. user.closeConnection()
  82. delete userlist[user_nickname];
  83. }
  84. return server
  85. }
  86. module.exports = server