telegramClient.js 3.7 KB

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