telegramClient.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. const Session = require("./Session");
  2. const doAuthentication = require("../network/authenticator");
  3. const MtProtoSender = require("../network/mtprotoSender");
  4. const MTProtoRequest = require("../tl/MTProtoRequest");
  5. const TcpTransport = require("../network/tcpTransport");
  6. const {InvokeWithLayerRequest, InitConnectionRequest} = require("../gramjs/tl/functions/index");
  7. const {GetConfigRequest} = require("../gramjs/tl/functions/help");
  8. class TelegramClient {
  9. constructor(sessionUserId, layer, apiId, apiHash) {
  10. if (apiId === undefined || apiHash === undefined) {
  11. throw Error("Your API ID or Hash are invalid. Please read \"Requirements\" on README.md");
  12. }
  13. this.apiId = apiId;
  14. this.apiHash = apiHash;
  15. this.layer = layer;
  16. this.session = Session.tryLoadOrCreateNew(sessionUserId);
  17. this.transport = new TcpTransport(this.session.serverAddress, this.session.port);
  18. //These will be set later
  19. this.dcOptions = null;
  20. this.sender = null;
  21. this.phoneCodeHashes = Array();
  22. }
  23. /**
  24. * Connects to the Telegram servers, executing authentication if required.
  25. * Note that authenticating to the Telegram servers is not the same as authenticating
  26. * the app, which requires to send a code first.
  27. * @param reconnect {Boolean}
  28. * @returns {Promise<Boolean>}
  29. */
  30. async connect(reconnect = false) {
  31. await this.transport.connect();
  32. try {
  33. if (!this.session.authKey || reconnect) {
  34. let res = await doAuthentication(this.transport);
  35. console.log("authenticated");
  36. this.session.authKey = res.authKey;
  37. this.session.timeOffset = res.timeOffset;
  38. this.session.save();
  39. }
  40. this.sender = new MtProtoSender(this.transport, this.session);
  41. let r = await this.invoke(new GetConfigRequest());
  42. console.log(r);
  43. process.exit(0)
  44. // Now it's time to send an InitConnectionRequest
  45. // This must always be invoked with the layer we'll be using
  46. let query = new InitConnectionRequest({
  47. apiId: this.apiId,
  48. deviceModel: "PlaceHolder",
  49. systemVersion: "PlaceHolder",
  50. appVersion: "0.0.1",
  51. langCode: "en",
  52. query: new GetConfigRequest()
  53. });
  54. let result = await this.invoke(new InvokeWithLayerRequest({
  55. layer: this.layer,
  56. query: query
  57. }));
  58. // We're only interested in the DC options
  59. // although many other options are available!
  60. this.dcOptions = result.dcOptions;
  61. return true;
  62. } catch (error) {
  63. console.log('Could not stabilise initial connection: {}'.replace("{}", error));
  64. console.log(error.stack);
  65. return false;
  66. }
  67. }
  68. /**
  69. * Reconnects to the specified DC ID. This is automatically called after an InvalidDCError is raised
  70. * @param dc_id {number}
  71. */
  72. async reconnect_to_dc(dc_id) {
  73. if (this.dcOptions === undefined || this.dcOptions.length === 0) {
  74. throw new Error("Can't reconnect. Stabilise an initial connection first.");
  75. }
  76. let dc;
  77. for (dc of this.dcOptions) {
  78. if (dc.id === dc_id) {
  79. break;
  80. }
  81. }
  82. await this.transport.close();
  83. this.transport = new TcpTransport(dc.ipAddress, dc.port);
  84. await this.transport.connect();
  85. this.session.server_address = dc.ipAddress;
  86. this.session.port = dc.port;
  87. this.session.save();
  88. await this.connect(true);
  89. }
  90. /**
  91. * Disconnects from the Telegram server
  92. * @returns {Promise<void>}
  93. */
  94. async disconnect() {
  95. if (this.sender) {
  96. await this.sender.disconnect();
  97. }
  98. }
  99. /**
  100. * Invokes a MTProtoRequest (sends and receives it) and returns its result
  101. * @param request
  102. * @returns {Promise}
  103. */
  104. async invoke(request) {
  105. if (!(request instanceof MTProtoRequest)) {
  106. throw new Error("You can only invoke MTProtoRequests");
  107. }
  108. await this.sender.send(request);
  109. await this.sender.receive(request);
  110. return request.result;
  111. }
  112. }
  113. module.exports = TelegramClient;