TelegramClient.js 4.0 KB

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