Session.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const Helpers = require("../utils/Helpers");
  2. const fs = require("fs");
  3. class Session {
  4. constructor(sessionUserId) {
  5. this.sessionUserId = sessionUserId;
  6. this.serverAddress = "149.154.167.40";
  7. this.port = 80;
  8. this.authKey = undefined;
  9. this.id = Helpers.generateRandomLong(false);
  10. this.sequence = 0;
  11. this.salt = 0; // Unsigned long
  12. this.timeOffset = 0;
  13. this.lastMessageId = 0;
  14. this.user = undefined;
  15. }
  16. /**
  17. * Saves the current session object as session_user_id.session
  18. */
  19. async save() {
  20. if (this.sessionUserId) {
  21. await fs.writeFile(`${this.sessionUserId}.session`, JSON.stringify(this));
  22. }
  23. }
  24. static tryLoadOrCreateNew(sessionUserId) {
  25. if (sessionUserId === undefined) {
  26. return new Session();
  27. }
  28. let filepath = `${sessionUserId}.session`;
  29. if (fs.existsSync(filepath)) {
  30. return JSON.parse(fs.readFileSync(filepath, "utf-8"));
  31. } else {
  32. return Session(sessionUserId);
  33. }
  34. }
  35. getNewMsgId() {
  36. let msTime = new Date().getTime();
  37. let newMessageId = (BigInt(Math.floor(msTime / 1000) + this.timeOffset) << BigInt(32)) |
  38. ((msTime % 1000) << 22) |
  39. (Helpers.getRandomInt(0, 524288) << 2); // 2^19
  40. if (this.lastMessageId >= newMessageId) {
  41. newMessageId = this.lastMessageId + 4;
  42. }
  43. this.lastMessageId = newMessageId;
  44. return newMessageId;
  45. }
  46. }
  47. module.exports = Session;