@mtkruto/node 0.1.139 → 0.1.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/esm/3_types.d.ts +10 -36
  2. package/esm/3_types.js +10 -36
  3. package/esm/4_constants.d.ts +1 -1
  4. package/esm/4_constants.js +1 -1
  5. package/esm/5_client.d.ts +1 -1
  6. package/esm/5_client.js +1 -1
  7. package/esm/_dnt.polyfills.d.ts +6 -0
  8. package/esm/client/0_filters.d.ts +60 -0
  9. package/esm/client/0_filters.js +27 -0
  10. package/esm/client/0_message.js +2 -2
  11. package/esm/client/{3_params.d.ts → 0_params.d.ts} +30 -33
  12. package/esm/client/0_types.d.ts +39 -0
  13. package/esm/client/0_types.js +2 -0
  14. package/esm/client/0_utilities.d.ts +1 -47
  15. package/esm/client/0_utilities.js +0 -27
  16. package/esm/client/1_composer.d.ts +1 -1
  17. package/esm/client/1_composer.js +1 -1
  18. package/esm/client/1_file_manager.d.ts +10 -0
  19. package/esm/client/1_file_manager.js +241 -0
  20. package/esm/client/1_update_manager.d.ts +18 -0
  21. package/esm/client/1_update_manager.js +553 -0
  22. package/esm/client/2_message_manager.d.ts +40 -0
  23. package/esm/client/2_message_manager.js +621 -0
  24. package/esm/client/3_chat_list_manager.d.ts +21 -0
  25. package/esm/client/3_chat_list_manager.js +353 -0
  26. package/esm/client/3_reaction_manager.d.ts +16 -0
  27. package/esm/client/3_reaction_manager.js +61 -0
  28. package/esm/client/4_client.d.ts +187 -60
  29. package/esm/client/4_client.js +492 -1698
  30. package/esm/connection/1_connection_web_socket.js +6 -6
  31. package/esm/deps/raw.githubusercontent.com/MTKruto/debug/main/deps.d.ts +1 -1
  32. package/esm/deps/raw.githubusercontent.com/MTKruto/debug/main/deps.js +1 -1
  33. package/esm/deps/raw.githubusercontent.com/MTKruto/object-inspect/main/index.d.ts +1 -0
  34. package/esm/deps/raw.githubusercontent.com/MTKruto/object-inspect/main/index.js +524 -0
  35. package/esm/mod.d.ts +1 -0
  36. package/esm/mod.js +1 -0
  37. package/esm/storage/0_storage.d.ts +5 -3
  38. package/esm/storage/0_storage.js +14 -4
  39. package/esm/tl/1_tl_object.d.ts +1 -0
  40. package/esm/tl/1_tl_object.js +24 -0
  41. package/esm/types/0_bot_command.d.ts +1 -0
  42. package/esm/types/0_chat_member_rights.d.ts +37 -0
  43. package/esm/types/0_chat_photo.d.ts +4 -4
  44. package/esm/types/0_file_source.d.ts +5 -0
  45. package/esm/types/0_giveaway_parameters.js +2 -1
  46. package/esm/types/0_id.d.ts +4 -0
  47. package/esm/types/0_message_entity.d.ts +20 -20
  48. package/esm/types/1__getters.d.ts +2 -2
  49. package/esm/types/1_animation.d.ts +1 -1
  50. package/esm/types/1_bot_command_scope.d.ts +5 -4
  51. package/esm/types/1_chat_p.d.ts +5 -6
  52. package/esm/types/1_document.d.ts +1 -0
  53. package/esm/types/1_input_message_content.d.ts +88 -0
  54. package/esm/types/1_photo.d.ts +1 -1
  55. package/esm/types/1_sticker.d.ts +1 -1
  56. package/esm/types/1_user.d.ts +1 -1
  57. package/esm/types/1_video.d.ts +1 -1
  58. package/esm/types/1_video_note.d.ts +1 -1
  59. package/esm/types/2_inline_keyboard_button.d.ts +10 -10
  60. package/esm/types/2_message_reaction_count.d.ts +3 -0
  61. package/esm/types/2_message_reaction_count.js +17 -1
  62. package/esm/types/2_message_reactions.d.ts +15 -0
  63. package/esm/types/2_message_reactions.js +37 -0
  64. package/esm/types/3_reply_markup.d.ts +42 -0
  65. package/esm/types/3_reply_markup.js +117 -0
  66. package/esm/types/4_inline_query_result.d.ts +193 -0
  67. package/esm/types/{5_inline_query_result.js → 4_inline_query_result.js} +2 -2
  68. package/esm/types/4_message.d.ts +36 -39
  69. package/esm/types/4_message.js +7 -24
  70. package/esm/types/5_callback_query.d.ts +2 -1
  71. package/esm/types/5_chat.d.ts +8 -5
  72. package/esm/types/6_update.d.ts +12 -2
  73. package/esm/utilities/0_buffer.js +9 -6
  74. package/esm/utilities/0_object.d.ts +1 -1
  75. package/esm/utilities/0_object.js +1 -6
  76. package/esm/utilities/1_misc.d.ts +2 -0
  77. package/esm/utilities/1_misc.js +6 -0
  78. package/package.json +1 -2
  79. package/script/3_types.d.ts +10 -36
  80. package/script/3_types.js +10 -36
  81. package/script/4_constants.d.ts +1 -1
  82. package/script/4_constants.js +1 -1
  83. package/script/5_client.d.ts +1 -1
  84. package/script/5_client.js +1 -1
  85. package/script/_dnt.polyfills.d.ts +6 -0
  86. package/script/client/0_filters.d.ts +60 -0
  87. package/script/client/0_filters.js +31 -0
  88. package/script/client/0_message.js +1 -1
  89. package/script/client/{3_params.d.ts → 0_params.d.ts} +30 -33
  90. package/script/client/0_types.d.ts +39 -0
  91. package/script/client/0_types.js +6 -0
  92. package/script/client/0_utilities.d.ts +1 -47
  93. package/script/client/0_utilities.js +1 -29
  94. package/script/client/1_composer.d.ts +1 -1
  95. package/script/client/1_composer.js +2 -2
  96. package/script/client/1_file_manager.d.ts +10 -0
  97. package/script/client/1_file_manager.js +245 -0
  98. package/script/client/1_update_manager.d.ts +18 -0
  99. package/script/client/1_update_manager.js +557 -0
  100. package/script/client/2_message_manager.d.ts +40 -0
  101. package/script/client/2_message_manager.js +625 -0
  102. package/script/client/3_chat_list_manager.d.ts +21 -0
  103. package/script/client/3_chat_list_manager.js +357 -0
  104. package/script/client/3_reaction_manager.d.ts +16 -0
  105. package/script/client/3_reaction_manager.js +65 -0
  106. package/script/client/4_client.d.ts +187 -60
  107. package/script/client/4_client.js +491 -1698
  108. package/script/connection/1_connection_web_socket.js +5 -5
  109. package/script/deps/raw.githubusercontent.com/MTKruto/debug/main/deps.d.ts +1 -1
  110. package/script/deps/raw.githubusercontent.com/MTKruto/debug/main/deps.js +2 -2
  111. package/script/deps/raw.githubusercontent.com/MTKruto/object-inspect/main/index.d.ts +1 -0
  112. package/script/deps/raw.githubusercontent.com/MTKruto/object-inspect/main/index.js +550 -0
  113. package/script/mod.d.ts +1 -0
  114. package/script/mod.js +1 -0
  115. package/script/storage/0_storage.d.ts +5 -3
  116. package/script/storage/0_storage.js +14 -4
  117. package/script/tl/1_tl_object.d.ts +1 -0
  118. package/script/tl/1_tl_object.js +24 -0
  119. package/script/types/0_bot_command.d.ts +1 -0
  120. package/script/types/0_chat_member_rights.d.ts +37 -0
  121. package/script/types/0_chat_photo.d.ts +4 -4
  122. package/script/types/0_file_source.d.ts +5 -0
  123. package/script/types/0_giveaway_parameters.js +2 -1
  124. package/script/types/0_id.d.ts +4 -0
  125. package/script/types/0_message_entity.d.ts +20 -20
  126. package/script/types/1__getters.d.ts +2 -2
  127. package/script/types/1_animation.d.ts +1 -1
  128. package/script/types/1_bot_command_scope.d.ts +5 -4
  129. package/script/types/1_chat_p.d.ts +5 -6
  130. package/script/types/1_document.d.ts +1 -0
  131. package/script/types/1_input_message_content.d.ts +88 -0
  132. package/script/types/1_photo.d.ts +1 -1
  133. package/script/types/1_sticker.d.ts +1 -1
  134. package/script/types/1_user.d.ts +1 -1
  135. package/script/types/1_video.d.ts +1 -1
  136. package/script/types/1_video_note.d.ts +1 -1
  137. package/script/types/2_inline_keyboard_button.d.ts +10 -10
  138. package/script/types/2_message_reaction_count.d.ts +3 -0
  139. package/script/types/2_message_reaction_count.js +19 -0
  140. package/script/types/2_message_reactions.d.ts +15 -0
  141. package/script/types/2_message_reactions.js +41 -0
  142. package/script/types/3_reply_markup.d.ts +42 -0
  143. package/script/types/3_reply_markup.js +122 -0
  144. package/script/types/4_inline_query_result.d.ts +193 -0
  145. package/script/types/{5_inline_query_result.js → 4_inline_query_result.js} +3 -3
  146. package/script/types/4_message.d.ts +36 -39
  147. package/script/types/4_message.js +6 -23
  148. package/script/types/5_callback_query.d.ts +2 -1
  149. package/script/types/5_chat.d.ts +8 -5
  150. package/script/types/6_update.d.ts +12 -2
  151. package/script/utilities/0_buffer.js +9 -6
  152. package/script/utilities/0_object.d.ts +1 -1
  153. package/script/utilities/0_object.js +1 -6
  154. package/script/utilities/1_misc.d.ts +2 -0
  155. package/script/utilities/1_misc.js +9 -1
  156. package/esm/types/0_chat_id.d.ts +0 -4
  157. package/esm/types/0_force_reply.d.ts +0 -12
  158. package/esm/types/0_force_reply.js +0 -17
  159. package/esm/types/0_input_contact_message_content.d.ts +0 -11
  160. package/esm/types/0_input_location_message_content.d.ts +0 -15
  161. package/esm/types/0_input_venue_message_content.d.ts +0 -19
  162. package/esm/types/0_reply_keyboard_remove.d.ts +0 -10
  163. package/esm/types/0_reply_keyboard_remove.js +0 -8
  164. package/esm/types/1_input_invoice_message_content.d.ts +0 -23
  165. package/esm/types/1_input_text_message_content.d.ts +0 -8
  166. package/esm/types/1_input_text_message_content.js +0 -1
  167. package/esm/types/2_input_message_content.d.ts +0 -6
  168. package/esm/types/2_input_message_content.js +0 -1
  169. package/esm/types/2_reply_keyboard_markup.d.ts +0 -12
  170. package/esm/types/2_reply_keyboard_markup.js +0 -37
  171. package/esm/types/3_inline_keyboard_markup.d.ts +0 -8
  172. package/esm/types/3_inline_keyboard_markup.js +0 -24
  173. package/esm/types/4_inline_query_result_article.d.ts +0 -15
  174. package/esm/types/4_inline_query_result_article.js +0 -1
  175. package/esm/types/4_inline_query_result_audio.d.ts +0 -17
  176. package/esm/types/4_inline_query_result_audio.js +0 -1
  177. package/esm/types/4_inline_query_result_cached_audio.d.ts +0 -14
  178. package/esm/types/4_inline_query_result_cached_audio.js +0 -1
  179. package/esm/types/4_inline_query_result_cached_document.d.ts +0 -15
  180. package/esm/types/4_inline_query_result_cached_document.js +0 -1
  181. package/esm/types/4_inline_query_result_cached_gif.d.ts +0 -15
  182. package/esm/types/4_inline_query_result_cached_gif.js +0 -1
  183. package/esm/types/4_inline_query_result_cached_mpeg4_gif.d.ts +0 -15
  184. package/esm/types/4_inline_query_result_cached_mpeg4_gif.js +0 -1
  185. package/esm/types/4_inline_query_result_cached_photo.d.ts +0 -16
  186. package/esm/types/4_inline_query_result_cached_photo.js +0 -1
  187. package/esm/types/4_inline_query_result_cached_sticker.d.ts +0 -9
  188. package/esm/types/4_inline_query_result_cached_sticker.js +0 -1
  189. package/esm/types/4_inline_query_result_cached_video.d.ts +0 -16
  190. package/esm/types/4_inline_query_result_cached_video.js +0 -1
  191. package/esm/types/4_inline_query_result_cached_voice.d.ts +0 -15
  192. package/esm/types/4_inline_query_result_cached_voice.js +0 -1
  193. package/esm/types/4_inline_query_result_contact.d.ts +0 -15
  194. package/esm/types/4_inline_query_result_contact.js +0 -1
  195. package/esm/types/4_inline_query_result_document.d.ts +0 -18
  196. package/esm/types/4_inline_query_result_document.js +0 -1
  197. package/esm/types/4_inline_query_result_game.d.ts +0 -7
  198. package/esm/types/4_inline_query_result_game.js +0 -1
  199. package/esm/types/4_inline_query_result_gif.d.ts +0 -20
  200. package/esm/types/4_inline_query_result_gif.js +0 -1
  201. package/esm/types/4_inline_query_result_location.d.ts +0 -18
  202. package/esm/types/4_inline_query_result_location.js +0 -1
  203. package/esm/types/4_inline_query_result_mpeg4_gif.d.ts +0 -20
  204. package/esm/types/4_inline_query_result_mpeg4_gif.js +0 -1
  205. package/esm/types/4_inline_query_result_photo.d.ts +0 -19
  206. package/esm/types/4_inline_query_result_photo.js +0 -1
  207. package/esm/types/4_inline_query_result_venue.d.ts +0 -19
  208. package/esm/types/4_inline_query_result_venue.js +0 -1
  209. package/esm/types/4_inline_query_result_video.d.ts +0 -21
  210. package/esm/types/4_inline_query_result_video.js +0 -1
  211. package/esm/types/4_inline_query_result_voice.d.ts +0 -16
  212. package/esm/types/4_inline_query_result_voice.js +0 -1
  213. package/esm/types/4_reply_markup.d.ts +0 -7
  214. package/esm/types/4_reply_markup.js +0 -22
  215. package/esm/types/5_inline_query_result.d.ts +0 -28
  216. package/script/types/0_chat_id.d.ts +0 -4
  217. package/script/types/0_force_reply.d.ts +0 -12
  218. package/script/types/0_force_reply.js +0 -22
  219. package/script/types/0_input_contact_message_content.d.ts +0 -11
  220. package/script/types/0_input_location_message_content.d.ts +0 -15
  221. package/script/types/0_input_venue_message_content.d.ts +0 -19
  222. package/script/types/0_reply_keyboard_remove.d.ts +0 -10
  223. package/script/types/0_reply_keyboard_remove.js +0 -13
  224. package/script/types/1_input_invoice_message_content.d.ts +0 -23
  225. package/script/types/1_input_text_message_content.d.ts +0 -8
  226. package/script/types/1_input_text_message_content.js +0 -2
  227. package/script/types/2_input_message_content.d.ts +0 -6
  228. package/script/types/2_input_message_content.js +0 -2
  229. package/script/types/2_reply_keyboard_markup.d.ts +0 -12
  230. package/script/types/2_reply_keyboard_markup.js +0 -42
  231. package/script/types/3_inline_keyboard_markup.d.ts +0 -8
  232. package/script/types/3_inline_keyboard_markup.js +0 -29
  233. package/script/types/4_inline_query_result_article.d.ts +0 -15
  234. package/script/types/4_inline_query_result_article.js +0 -2
  235. package/script/types/4_inline_query_result_audio.d.ts +0 -17
  236. package/script/types/4_inline_query_result_audio.js +0 -2
  237. package/script/types/4_inline_query_result_cached_audio.d.ts +0 -14
  238. package/script/types/4_inline_query_result_cached_audio.js +0 -2
  239. package/script/types/4_inline_query_result_cached_document.d.ts +0 -15
  240. package/script/types/4_inline_query_result_cached_document.js +0 -2
  241. package/script/types/4_inline_query_result_cached_gif.d.ts +0 -15
  242. package/script/types/4_inline_query_result_cached_gif.js +0 -2
  243. package/script/types/4_inline_query_result_cached_mpeg4_gif.d.ts +0 -15
  244. package/script/types/4_inline_query_result_cached_mpeg4_gif.js +0 -2
  245. package/script/types/4_inline_query_result_cached_photo.d.ts +0 -16
  246. package/script/types/4_inline_query_result_cached_photo.js +0 -2
  247. package/script/types/4_inline_query_result_cached_sticker.d.ts +0 -9
  248. package/script/types/4_inline_query_result_cached_sticker.js +0 -2
  249. package/script/types/4_inline_query_result_cached_video.d.ts +0 -16
  250. package/script/types/4_inline_query_result_cached_video.js +0 -2
  251. package/script/types/4_inline_query_result_cached_voice.d.ts +0 -15
  252. package/script/types/4_inline_query_result_cached_voice.js +0 -2
  253. package/script/types/4_inline_query_result_contact.d.ts +0 -15
  254. package/script/types/4_inline_query_result_contact.js +0 -2
  255. package/script/types/4_inline_query_result_document.d.ts +0 -18
  256. package/script/types/4_inline_query_result_document.js +0 -2
  257. package/script/types/4_inline_query_result_game.d.ts +0 -7
  258. package/script/types/4_inline_query_result_game.js +0 -2
  259. package/script/types/4_inline_query_result_gif.d.ts +0 -20
  260. package/script/types/4_inline_query_result_gif.js +0 -2
  261. package/script/types/4_inline_query_result_location.d.ts +0 -18
  262. package/script/types/4_inline_query_result_location.js +0 -2
  263. package/script/types/4_inline_query_result_mpeg4_gif.d.ts +0 -20
  264. package/script/types/4_inline_query_result_mpeg4_gif.js +0 -2
  265. package/script/types/4_inline_query_result_photo.d.ts +0 -19
  266. package/script/types/4_inline_query_result_photo.js +0 -2
  267. package/script/types/4_inline_query_result_venue.d.ts +0 -19
  268. package/script/types/4_inline_query_result_venue.js +0 -2
  269. package/script/types/4_inline_query_result_video.d.ts +0 -21
  270. package/script/types/4_inline_query_result_video.js +0 -2
  271. package/script/types/4_inline_query_result_voice.d.ts +0 -16
  272. package/script/types/4_inline_query_result_voice.js +0 -2
  273. package/script/types/4_reply_markup.d.ts +0 -7
  274. package/script/types/4_reply_markup.js +0 -26
  275. package/script/types/5_inline_query_result.d.ts +0 -28
  276. /package/esm/{client/3_params.js → _dnt.polyfills.js} +0 -0
  277. /package/esm/{types/0_chat_id.js → client/0_params.js} +0 -0
  278. /package/esm/types/{0_input_contact_message_content.js → 0_chat_member_rights.js} +0 -0
  279. /package/esm/types/{0_input_location_message_content.js → 0_file_source.js} +0 -0
  280. /package/esm/types/{0_input_venue_message_content.js → 0_id.js} +0 -0
  281. /package/esm/types/{1_input_invoice_message_content.js → 1_input_message_content.js} +0 -0
  282. /package/script/{client/3_params.js → _dnt.polyfills.js} +0 -0
  283. /package/script/{types/0_chat_id.js → client/0_params.js} +0 -0
  284. /package/script/types/{0_input_contact_message_content.js → 0_chat_member_rights.js} +0 -0
  285. /package/script/types/{0_input_location_message_content.js → 0_file_source.js} +0 -0
  286. /package/script/types/{0_input_venue_message_content.js → 0_id.js} +0 -0
  287. /package/script/types/{1_input_invoice_message_content.js → 1_input_message_content.js} +0 -0
@@ -9,38 +9,38 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_guaranteeUpdateDelivery, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_prefixes, _Client_namespaceProxies, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingLoopAbortSignal, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueues, _Client_getHandleUpdateQueue, _Client_processUpdatesQueue, _Client_checkGap, _Client_checkChannelGap, _Client_channelUpdateQueues, _Client_processChannelPtsUpdateInner, _Client_queueUpdate, _Client_processChannelPtsUpdate, _Client_mainBoxId, _Client_processPtsUpdateInner, _Client_ptsUpdateQueue, _Client_processPtsUpdate, _Client_lastUpdates, _Client_processUpdates, _Client_setUpdateStateDate, _Client_setUpdatePts, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_constructReplyTo, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_lastGetMe, _Client_getMe, _Client_handleUpdatesSet, _Client_handleStoredUpdates, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_handle, _Client_setMyInfo, _Client_getMyInfo, _Client_resolveFileId, _Client_sendMedia, _Client_sendDocumentInner, _Client_sendChatUpdate, _Client_reassignChatLastMessage, _Client_chats, _Client_archivedChats, _Client_chatsLoadedFromStorage, _Client_tryGetChatId, _Client_getChatAnywhere, _Client_getChatList, _Client_loadChatsFromStorage, _Client_getLoadedChats, _Client_pinnedChats, _Client_pinnedArchiveChats, _Client_storageHadPinnedChats, _Client_pinnedChatsLoaded, _Client_loadPinnedChats, _Client_fetchPinnedChats, _Client_getPinnedChats, _Client_updateOrAddChat, _Client_removeChat, _Client_updatePinnedChats, _Client_fetchChats, _Client_sendReaction;
13
- import { contentType, debug, extension, gunzip, Mutex } from "../0_deps.js";
14
- import { bigIntFromBuffer, cleanObject, drop, getRandomBigInt, getRandomId, mod, mustPrompt, mustPromptOneOf, Queue, sha1, UNREACHABLE, ZERO_CHANNEL_ID } from "../1_utilities.js";
15
- import { as, functions, getChannelChatId, inputPeerToPeer, Message_, MessageContainer, name, peerToChatId, RPCResult, TLError, TLReader, types } from "../2_tl.js";
12
+ var _Client_instances, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_guaranteeUpdateDelivery, _Client_updateManager, _Client_fileManager, _Client_messageManager, _Client_chatListManager, _Client_reactionManager, _Client_parseMode, _Client_publicKeys, _Client_autoStart, _Client_ignoreOutgoing, _Client_prefixes, _Client_namespaceProxies, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingLoopAbortSignal, _Client_pingInterval, _Client_lastUpdates, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_getUserAccessHash, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_parseText, _Client_lastGetMe, _Client_getMe, _Client_handleCtxUpdate, _Client_queueHandleCtxUpdate, _Client_handleUpdate, _Client_usernameResolver, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
13
+ import { debug, gunzip, Mutex } from "../0_deps.js";
14
+ import { bigIntFromBuffer, cleanObject, drop, getRandomBigInt, getRandomId, mustPrompt, mustPromptOneOf, sha1, toUnixTimestamp, UNREACHABLE, ZERO_CHANNEL_ID } from "../1_utilities.js";
15
+ import { as, functions, getChannelChatId, Message_, MessageContainer, name, peerToChatId, RPCResult, TLError, TLReader, types } from "../2_tl.js";
16
16
  import { StorageMemory } from "../3_storage.js";
17
- import { assertMessageType, botCommandScopeToTlObject, constructCallbackQuery, constructChat, constructChat2, constructChat3, constructChat4, constructChatP, constructChosenInlineResult, constructDocument, constructInlineQuery, constructMessage, constructMessageReaction, constructReactionCount, constructUser, FileID, FileType, FileUniqueID, FileUniqueType, getChatOrder, inlineQueryResultToTlObject, messageEntityToTlObject, reactionEqual, reactionToTlObject, replyMarkupToTlObject, ThumbnailSource } from "../3_types.js";
18
- import { ACK_THRESHOLD, APP_VERSION, CHANNEL_DIFFERENCE_LIMIT_BOT, CHANNEL_DIFFERENCE_LIMIT_USER, DEVICE_MODEL, LANG_CODE, LANG_PACK, LAYER, MAX_CHANNEL_ID, MAX_CHAT_ID, STICKER_SET_NAME_TTL, SYSTEM_LANG_CODE, SYSTEM_VERSION, USERNAME_TTL } from "../4_constants.js";
17
+ import { botCommandScopeToTlObject, constructCallbackQuery, constructChat2, constructChat3, constructChosenInlineResult, constructInlineQuery, constructMessageReaction, constructMessageReactionCount, constructMessageReactions, constructUser, inlineQueryResultToTlObject, messageEntityToTlObject } from "../3_types.js";
18
+ import { ACK_THRESHOLD, APP_VERSION, DEVICE_MODEL, LANG_CODE, LANG_PACK, LAYER, MAX_CHANNEL_ID, MAX_CHAT_ID, SYSTEM_LANG_CODE, SYSTEM_VERSION, USERNAME_TTL } from "../4_constants.js";
19
19
  import { AuthKeyUnregistered, FloodWait, Migrate, PasswordHashInvalid, PhoneNumberInvalid, SessionPasswordNeeded, upgradeInstance } from "../4_errors.js";
20
20
  import { ClientAbstract } from "./0_client_abstract.js";
21
+ import { match } from "./0_filters.js";
21
22
  import { parseHtml } from "./0_html.js";
22
23
  import { decryptMessage, encryptMessage, getMessageId } from "./0_message.js";
23
24
  import { checkPassword } from "./0_password.js";
24
- import { getChatListId, getFileContents, getUsername, isChannelPtsUpdate, isHttpUrl, isPtsUpdate, match, resolve } from "./0_utilities.js";
25
+ import { ConnectionError } from "./0_types.js";
26
+ import { getFileContents, getUsername, resolve } from "./0_utilities.js";
25
27
  import { Composer, concat, flatten, skip } from "./1_composer.js";
28
+ import { FileManager } from "./1_file_manager.js";
29
+ import { UpdateManager } from "./1_update_manager.js";
26
30
  import { ClientPlain } from "./2_client_plain.js";
31
+ import { MessageManager } from "./2_message_manager.js";
32
+ import { ChatListManager } from "./3_chat_list_manager.js";
33
+ import { ReactionManager } from "./3_reaction_manager.js";
27
34
  const d = debug("Client");
28
- const dGap = debug("Client/recoverUpdateGap");
29
- const dGapC = debug("Client/recoverChannelUpdateGap");
30
35
  const dAuth = debug("Client/authorize");
31
36
  const dRecv = debug("Client/receiveLoop");
32
- const dUpload = debug("Client/upload");
33
37
  const getEntity = Symbol();
34
- const getStickerSetName = Symbol();
35
38
  export const handleMigrationError = Symbol();
36
- const getMessageWithReply = Symbol();
37
39
  const functionNamespaces = Object.entries(functions).filter(([, v]) => !(v instanceof Function)).map(([k]) => k);
38
40
  export function skipInvoke() {
39
41
  return (_ctx, next) => next();
40
42
  }
41
43
  export const restartAuth = Symbol();
42
- export class ConnectionError extends Error {
43
- }
44
44
  export class Client extends ClientAbstract {
45
45
  /**
46
46
  * Constructs the client.
@@ -69,20 +69,19 @@ export class Client extends ClientAbstract {
69
69
  _Client_state.set(this, { salt: 0n, seqNo: 0 });
70
70
  _Client_promises.set(this, new Map());
71
71
  _Client_toAcknowledge.set(this, new Set());
72
- _Client_updateState.set(this, void 0);
73
72
  _Client_guaranteeUpdateDelivery.set(this, void 0);
73
+ _Client_updateManager.set(this, void 0);
74
+ _Client_fileManager.set(this, void 0);
75
+ _Client_messageManager.set(this, void 0);
76
+ _Client_chatListManager.set(this, void 0);
77
+ _Client_reactionManager.set(this, void 0);
74
78
  Object.defineProperty(this, "storage", {
75
79
  enumerable: true,
76
80
  configurable: true,
77
81
  writable: true,
78
82
  value: void 0
79
83
  });
80
- Object.defineProperty(this, "parseMode", {
81
- enumerable: true,
82
- configurable: true,
83
- writable: true,
84
- value: void 0
85
- });
84
+ _Client_parseMode.set(this, void 0);
86
85
  Object.defineProperty(this, "appVersion", {
87
86
  enumerable: true,
88
87
  configurable: true,
@@ -184,7 +183,7 @@ export class Client extends ClientAbstract {
184
183
  const reactions = "messageInteractions" in update ? update.messageInteractions : undefined;
185
184
  const mustGetMsg = () => {
186
185
  if (msg !== undefined) {
187
- return { chatId: msg.chat.id, messageId: msg.id };
186
+ return { chatId: msg.chat.id, messageId: msg.id, senderId: (msg.from ?? msg.senderChat)?.id };
188
187
  }
189
188
  else if (reactions !== undefined) {
190
189
  return { chatId: reactions.chatId, messageId: reactions.messageId };
@@ -193,7 +192,8 @@ export class Client extends ClientAbstract {
193
192
  UNREACHABLE();
194
193
  }
195
194
  };
196
- const chat = msg?.chat;
195
+ const chat_ = "messageReactions" in update ? update.messageReactions.chat : "messageReactionCount" in update ? update.messageReactionCount.chat : undefined;
196
+ const chat = chat_ ?? msg?.chat;
197
197
  const from = "callbackQuery" in update ? update.callbackQuery.from : "inlineQuery" in update ? update.inlineQuery.from : "message" in update ? update.message.from : "editedMessage" in update ? update.editedMessage?.from : undefined;
198
198
  const senderChat = msg?.senderChat;
199
199
  const getReplyToMessageId = (quote, chatId, messageId) => {
@@ -287,6 +287,35 @@ export class Client extends ClientAbstract {
287
287
  const { chatId, messageId } = mustGetMsg();
288
288
  return this.forwardMessage(chatId, to, messageId, params);
289
289
  },
290
+ pin: (params) => {
291
+ const { chatId, messageId } = mustGetMsg();
292
+ return this.pinMessage(chatId, messageId, params);
293
+ },
294
+ unpin: () => {
295
+ const { chatId, messageId } = mustGetMsg();
296
+ return this.unpinMessage(chatId, messageId);
297
+ },
298
+ banSender: (params) => {
299
+ const { chatId, senderId } = mustGetMsg();
300
+ if (!senderId) {
301
+ UNREACHABLE();
302
+ }
303
+ return this.banChatMember(chatId, senderId, params);
304
+ },
305
+ kickSender: () => {
306
+ const { chatId, senderId } = mustGetMsg();
307
+ if (!senderId) {
308
+ UNREACHABLE();
309
+ }
310
+ return this.kickChatMember(chatId, senderId);
311
+ },
312
+ setSenderRights: (params) => {
313
+ const { chatId, senderId } = mustGetMsg();
314
+ if (!senderId) {
315
+ UNREACHABLE();
316
+ }
317
+ return this.setChatMemberRights(chatId, senderId, params);
318
+ },
290
319
  react: (reactions, params) => {
291
320
  const { chatId, messageId } = mustGetMsg();
292
321
  return this.setReactions(chatId, messageId, reactions, params);
@@ -311,6 +340,10 @@ export class Client extends ClientAbstract {
311
340
  const { chatId } = mustGetMsg();
312
341
  return this.editMessageText(chatId, messageId, text, params);
313
342
  },
343
+ editMessageReplyMarkup: (messageId, params) => {
344
+ const { chatId } = mustGetMsg();
345
+ return this.editMessageReplyMarkup(chatId, messageId, params);
346
+ },
314
347
  getMessage: (messageId) => {
315
348
  const { chatId } = mustGetMsg();
316
349
  return this.getMessage(chatId, messageId);
@@ -335,6 +368,18 @@ export class Client extends ClientAbstract {
335
368
  const { chatId } = mustGetMsg();
336
369
  return this.deleteMessages(chatId, messageIds, params);
337
370
  },
371
+ pinMessage: (messageId, params) => {
372
+ const { chatId } = mustGetMsg();
373
+ return this.pinMessage(chatId, messageId, params);
374
+ },
375
+ unpinMessage: (messageId) => {
376
+ const { chatId } = mustGetMsg();
377
+ return this.unpinMessage(chatId, messageId);
378
+ },
379
+ unpinMessages: () => {
380
+ const { chatId } = mustGetMsg();
381
+ return this.unpinMessages(chatId);
382
+ },
338
383
  setAvailableReactions: (availableReactions) => {
339
384
  const { chatId } = mustGetMsg();
340
385
  return this.setAvailableReactions(chatId, availableReactions);
@@ -351,8 +396,36 @@ export class Client extends ClientAbstract {
351
396
  const { chatId } = mustGetMsg();
352
397
  return this.setReactions(chatId, messageId, reactions, params);
353
398
  },
399
+ setChatPhoto: (photo, params) => {
400
+ const { chatId } = mustGetMsg();
401
+ return this.setChatPhoto(chatId, photo, params);
402
+ },
403
+ deleteChatPhoto: () => {
404
+ const { chatId } = mustGetMsg();
405
+ return this.deleteChatPhoto(chatId);
406
+ },
407
+ banChatMember: (memberId, params) => {
408
+ const { chatId } = mustGetMsg();
409
+ return this.banChatMember(chatId, memberId, params);
410
+ },
411
+ unbanChatMember: (memberId) => {
412
+ const { chatId } = mustGetMsg();
413
+ return this.unbanChatMember(chatId, memberId);
414
+ },
415
+ kickChatMember: (memberId) => {
416
+ const { chatId } = mustGetMsg();
417
+ return this.kickChatMember(chatId, memberId);
418
+ },
419
+ setChatMemberRights: (memberId, params) => {
420
+ const { chatId } = mustGetMsg();
421
+ return this.setChatMemberRights(chatId, memberId, params);
422
+ },
423
+ deleteChatMemberMessages: (userId) => {
424
+ const { chatId } = mustGetMsg();
425
+ return this.deleteChatMemberMessages(chatId, userId);
426
+ },
354
427
  };
355
- return cleanObject(context, false);
428
+ return cleanObject(context);
356
429
  });
357
430
  _Client_lastPropagatedConnectionState.set(this, null);
358
431
  Object.defineProperty(this, "stateChangeHandler", {
@@ -381,6 +454,7 @@ export class Client extends ClientAbstract {
381
454
  _Client_selfId.set(this, null);
382
455
  _Client_pingLoopAbortSignal.set(this, null);
383
456
  _Client_pingInterval.set(this, 60 * 1000); // 60 seconds
457
+ _Client_lastUpdates.set(this, new Date());
384
458
  _Client_pingLoopStarted.set(this, false);
385
459
  _Client_autoStarted.set(this, false);
386
460
  _Client_lastMsgId.set(this, 0n);
@@ -410,29 +484,15 @@ export class Client extends ClientAbstract {
410
484
  },
411
485
  })
412
486
  });
413
- _Client_handleUpdateQueues.set(this, new Map());
414
- _Client_processUpdatesQueue.set(this, new Queue("processUpdates"));
415
- _Client_channelUpdateQueues.set(this, new Map());
416
- _Client_mainBoxId.set(this, 0n);
417
- _Client_ptsUpdateQueue.set(this, new Queue("ptsUpdate"));
418
- _Client_lastUpdates.set(this, new Date());
419
487
  _Client_lastGetMe.set(this, null);
420
- _Client_handleUpdatesSet.set(this, new Set());
421
488
  _Client_usernameResolver.set(this, async (v) => {
422
489
  const inputPeer = await this.getInputPeer(v).then((v) => v[as](types.InputPeerUser));
423
490
  return new types.InputUser(inputPeer);
424
491
  });
425
492
  //#region Composer
426
493
  _Client_handle.set(this, skip);
427
- _Client_chats.set(this, new Map());
428
- _Client_archivedChats.set(this, new Map());
429
- _Client_chatsLoadedFromStorage.set(this, false);
430
- _Client_pinnedChats.set(this, new Array());
431
- _Client_pinnedArchiveChats.set(this, new Array());
432
- _Client_storageHadPinnedChats.set(this, false);
433
- _Client_pinnedChatsLoaded.set(this, false);
434
494
  this.storage = storage ?? new StorageMemory();
435
- this.parseMode = params?.parseMode ?? null;
495
+ __classPrivateFieldSet(this, _Client_parseMode, params?.parseMode ?? null, "f");
436
496
  this.appVersion = params?.appVersion ?? APP_VERSION;
437
497
  this.deviceModel = params?.deviceModel ?? DEVICE_MODEL;
438
498
  this.langCode = params?.langCode ?? LANG_CODE;
@@ -444,6 +504,67 @@ export class Client extends ClientAbstract {
444
504
  __classPrivateFieldSet(this, _Client_ignoreOutgoing, params?.ignoreOutgoing ?? null, "f");
445
505
  __classPrivateFieldSet(this, _Client_prefixes, params?.prefixes, "f");
446
506
  __classPrivateFieldSet(this, _Client_guaranteeUpdateDelivery, params?.guaranteeUpdateDelivery ?? false, "f");
507
+ const c = {
508
+ api: this.api,
509
+ storage: this.storage,
510
+ guaranteeUpdateDelivery: __classPrivateFieldGet(this, _Client_guaranteeUpdateDelivery, "f"),
511
+ setConnectionState: __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).bind(this),
512
+ resetConnectionState: () => this.stateChangeHandler(this.connected),
513
+ getSelfId: __classPrivateFieldGet(this, _Client_instances, "m", _Client_getSelfId).bind(this),
514
+ getInputPeer: this.getInputPeer.bind(this),
515
+ getEntity: this[getEntity].bind(this),
516
+ handleUpdate: __classPrivateFieldGet(this, _Client_instances, "m", _Client_queueHandleCtxUpdate).bind(this),
517
+ parseMode: __classPrivateFieldGet(this, _Client_parseMode, "f"),
518
+ apiFactory: (dcId) => {
519
+ const client = new Client((!dcId || dcId == this.dcId) ? this.storage : this.storage.branch(`download_client_${dcId}`), this.apiId, this.apiHash, {
520
+ transportProvider: this.transportProvider,
521
+ appVersion: this.appVersion,
522
+ deviceModel: this.deviceModel,
523
+ langCode: this.langCode,
524
+ langPack: this.langPack,
525
+ systemLangCode: this.systemLangCode,
526
+ systemVersion: this.systemVersion,
527
+ cdn: true,
528
+ });
529
+ __classPrivateFieldGet(client, _Client_state, "f").salt = __classPrivateFieldGet(this, _Client_state, "f").salt;
530
+ client.invoke.use(async (ctx, next) => {
531
+ if (ctx.error instanceof AuthKeyUnregistered && dcId) {
532
+ try {
533
+ const exportedAuth = await this.api.auth.exportAuthorization({ dc_id: dcId });
534
+ await client.authorize(exportedAuth);
535
+ return true;
536
+ }
537
+ catch (err) {
538
+ throw err;
539
+ }
540
+ }
541
+ else {
542
+ return await next();
543
+ }
544
+ });
545
+ return {
546
+ api: client.api,
547
+ connect: async () => {
548
+ await client.connect();
549
+ if (dcId != this.dcId) {
550
+ let dc = String(dcId);
551
+ if (this.dcId < 0) {
552
+ dc += "-test";
553
+ }
554
+ await client.setDc(dc);
555
+ }
556
+ await __classPrivateFieldGet(client, _Client_instances, "m", _Client_initConnection).call(client);
557
+ },
558
+ disconnect: client.disconnect.bind(client),
559
+ };
560
+ },
561
+ };
562
+ __classPrivateFieldSet(this, _Client_updateManager, new UpdateManager(c), "f");
563
+ __classPrivateFieldSet(this, _Client_fileManager, new FileManager(c), "f");
564
+ __classPrivateFieldSet(this, _Client_messageManager, new MessageManager({ ...c, fileManager: __classPrivateFieldGet(this, _Client_fileManager, "f") }), "f");
565
+ __classPrivateFieldSet(this, _Client_chatListManager, new ChatListManager({ ...c, messageManager: __classPrivateFieldGet(this, _Client_messageManager, "f") }), "f");
566
+ __classPrivateFieldSet(this, _Client_reactionManager, new ReactionManager({ ...c, messageManager: __classPrivateFieldGet(this, _Client_messageManager, "f") }), "f");
567
+ __classPrivateFieldGet(this, _Client_updateManager, "f").setUpdateHandler(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleUpdate).bind(this));
447
568
  const transportProvider = this.transportProvider;
448
569
  this.transportProvider = (params) => {
449
570
  const transport = transportProvider(params);
@@ -473,7 +594,7 @@ export class Client extends ClientAbstract {
473
594
  try {
474
595
  await this.connect();
475
596
  d("reconnected");
476
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "reconnect"));
597
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("reconnect"));
477
598
  break;
478
599
  }
479
600
  catch (err) {
@@ -576,27 +697,13 @@ export class Client extends ClientAbstract {
576
697
  release();
577
698
  }
578
699
  }
579
- async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_guaranteeUpdateDelivery = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_prefixes = new WeakMap(), _Client_namespaceProxies = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingLoopAbortSignal = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueues = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_channelUpdateQueues = new WeakMap(), _Client_mainBoxId = new WeakMap(), _Client_ptsUpdateQueue = new WeakMap(), _Client_lastUpdates = new WeakMap(), _Client_lastGetMe = new WeakMap(), _Client_handleUpdatesSet = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_chats = new WeakMap(), _Client_archivedChats = new WeakMap(), _Client_chatsLoadedFromStorage = new WeakMap(), _Client_pinnedChats = new WeakMap(), _Client_pinnedArchiveChats = new WeakMap(), _Client_storageHadPinnedChats = new WeakMap(), _Client_pinnedChatsLoaded = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
580
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getHandleUpdateQueue).call(this, __classPrivateFieldGet(this, _Client_mainBoxId, "f")).add(async () => {
581
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), resolve);
582
- });
700
+ async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_guaranteeUpdateDelivery = new WeakMap(), _Client_updateManager = new WeakMap(), _Client_fileManager = new WeakMap(), _Client_messageManager = new WeakMap(), _Client_chatListManager = new WeakMap(), _Client_reactionManager = new WeakMap(), _Client_parseMode = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_prefixes = new WeakMap(), _Client_namespaceProxies = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingLoopAbortSignal = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_lastUpdates = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_lastGetMe = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
701
+ __classPrivateFieldGet(this, _Client_instances, "m", _Client_queueHandleCtxUpdate).call(this, { connectionState });
583
702
  __classPrivateFieldSet(this, _Client_lastPropagatedConnectionState, connectionState, "f");
584
703
  }, _Client_setAuth = async function _Client_setAuth(key) {
585
704
  const hash = await sha1(key);
586
705
  const id = bigIntFromBuffer(hash.slice(-8), true, false);
587
706
  __classPrivateFieldSet(this, _Client_auth, { key, id }, "f");
588
- }, _Client_assertUser = async function _Client_assertUser(source) {
589
- if (await this.storage.getAccountType() != "user") {
590
- throw new Error(`${source}: not user a client`);
591
- }
592
- }, _Client_assertBot = async function _Client_assertBot(source) {
593
- if (await this.storage.getAccountType() != "bot") {
594
- throw new Error(`${source}: not a bot client`);
595
- }
596
- }, _Client_fetchState = async function _Client_fetchState(source) {
597
- const state = await this.api.updates.getState();
598
- __classPrivateFieldSet(this, _Client_updateState, state, "f");
599
- d("state fetched [%s]", source);
600
707
  }, handleMigrationError)](err) {
601
708
  let newDc = String(err.dc);
602
709
  if (Math.abs(this.dcId) >= 10000) {
@@ -646,9 +753,9 @@ export class Client extends ClientAbstract {
646
753
  dAuth("authorizing with %s", typeof params === "string" ? "bot token" : params instanceof types.auth.ExportedAuthorization ? "exported authorization" : "AuthorizeUserParams");
647
754
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_initConnection).call(this);
648
755
  try {
649
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "authorize");
756
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").fetchState("authorize");
650
757
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, true);
651
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "authorize"));
758
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("authorize"));
652
759
  d("already authorized");
653
760
  return;
654
761
  }
@@ -678,7 +785,7 @@ export class Client extends ClientAbstract {
678
785
  }
679
786
  dAuth("authorized as bot");
680
787
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, true);
681
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "authorize");
788
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").fetchState("authorize");
682
789
  return;
683
790
  }
684
791
  if (params instanceof types.auth.ExportedAuthorization) {
@@ -737,7 +844,7 @@ export class Client extends ClientAbstract {
737
844
  await this.storage.setAccountType("user");
738
845
  dAuth("authorized as user");
739
846
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, true);
740
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "authorize");
847
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").fetchState("authorize");
741
848
  return;
742
849
  }
743
850
  catch (err_) {
@@ -766,7 +873,7 @@ export class Client extends ClientAbstract {
766
873
  await this.storage.setAccountType("user");
767
874
  dAuth("authorized as user");
768
875
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, true);
769
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "authorize");
876
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").fetchState("authorize");
770
877
  return;
771
878
  }
772
879
  catch (err) {
@@ -796,8 +903,8 @@ export class Client extends ClientAbstract {
796
903
  await this.connect();
797
904
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_initConnection).call(this);
798
905
  if (!__classPrivateFieldGet(this, _Client_authKeyWasCreated, "f")) {
799
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "start"));
800
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "start"));
906
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").fetchState("start"));
907
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("start"));
801
908
  return;
802
909
  }
803
910
  await this.authorize(params);
@@ -808,10 +915,6 @@ export class Client extends ClientAbstract {
808
915
  send(function_) {
809
916
  return this.invoke(function_, true);
810
917
  }
811
- async getUserAccessHash(userId) {
812
- const users = await this.api.users.getUsers({ id: [new types.InputUser({ user_id: userId, access_hash: 0n })] });
813
- return users[0]?.[as](types.User).access_hash ?? 0n;
814
- }
815
918
  async getInputPeer(id) {
816
919
  const inputPeer = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getInputPeerInner).call(this, id);
817
920
  if ((inputPeer instanceof types.InputPeerUser || inputPeer instanceof types.InputPeerChannel && inputPeer.access_hash == 0n) && await this.storage.getAccountType() == "bot") {
@@ -819,7 +922,7 @@ export class Client extends ClientAbstract {
819
922
  inputPeer.access_hash = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChannelAccessHash).call(this, inputPeer.channel_id);
820
923
  }
821
924
  else {
822
- inputPeer.access_hash = await this.getUserAccessHash(inputPeer.user_id);
925
+ inputPeer.access_hash = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getUserAccessHash).call(this, inputPeer.user_id);
823
926
  await this.storage.setUserAccessHash(inputPeer.user_id, inputPeer.access_hash);
824
927
  }
825
928
  }
@@ -878,7 +981,7 @@ export class Client extends ClientAbstract {
878
981
  //
879
982
  }
880
983
  await this.connect();
881
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "decryption");
984
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("decryption");
882
985
  })());
883
986
  continue;
884
987
  }
@@ -890,7 +993,7 @@ export class Client extends ClientAbstract {
890
993
  }
891
994
  dRecv("received %s", (typeof body === "object" && name in body) ? body[name] : body.constructor.name);
892
995
  if (body instanceof types._Updates || body instanceof types._Update) {
893
- __classPrivateFieldGet(this, _Client_processUpdatesQueue, "f").add(() => __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, body, true));
996
+ __classPrivateFieldGet(this, _Client_updateManager, "f").processUpdates(body, true);
894
997
  }
895
998
  else if (body instanceof types.New_session_created) {
896
999
  __classPrivateFieldGet(this, _Client_state, "f").salt = body.server_salt;
@@ -921,13 +1024,10 @@ export class Client extends ClientAbstract {
921
1024
  }
922
1025
  };
923
1026
  if (result instanceof types._Updates || result instanceof types._Update) {
924
- __classPrivateFieldGet(this, _Client_processUpdatesQueue, "f").add(async () => {
925
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, result, true, promise?.call);
926
- resolvePromise();
927
- });
1027
+ __classPrivateFieldGet(this, _Client_updateManager, "f").processUpdates(result, true, promise?.call, resolvePromise);
928
1028
  }
929
1029
  else {
930
- await this.processResult(result);
1030
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").processResult(result);
931
1031
  resolvePromise();
932
1032
  }
933
1033
  }
@@ -957,7 +1057,7 @@ export class Client extends ClientAbstract {
957
1057
  }
958
1058
  else if (err instanceof TLError) {
959
1059
  dRecv("failed to deserialize: %o", err);
960
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "deserialize"));
1060
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("deserialize"));
961
1061
  }
962
1062
  else {
963
1063
  dRecv("uncaught error: %o", err);
@@ -984,7 +1084,7 @@ export class Client extends ClientAbstract {
984
1084
  });
985
1085
  await this.api.ping_delay_disconnect({ ping_id: getRandomId(), disconnect_delay: __classPrivateFieldGet(this, _Client_pingInterval, "f") / 1000 + 15 });
986
1086
  if (Date.now() - __classPrivateFieldGet(this, _Client_lastUpdates, "f").getTime() >= 15 * 60 * 1000) {
987
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "lastUpdates"));
1087
+ drop(__classPrivateFieldGet(this, _Client_updateManager, "f").recoverUpdateGap("lastUpdates"));
988
1088
  }
989
1089
  }
990
1090
  catch (err) {
@@ -1059,408 +1159,9 @@ export class Client extends ClientAbstract {
1059
1159
  }
1060
1160
  }
1061
1161
  }
1062
- }, _Client_processChats = async function _Client_processChats(chats) {
1063
- for (const chat of chats) {
1064
- if (chat instanceof types.Channel && chat.access_hash) {
1065
- await this.storage.setEntity(chat);
1066
- await this.storage.setChannelAccessHash(chat.id, chat.access_hash);
1067
- if (chat.username) {
1068
- await this.storage.updateUsernames("channel", chat.id, [chat.username]);
1069
- }
1070
- if (chat.usernames) {
1071
- await this.storage.updateUsernames("channel", chat.id, chat.usernames.map((v) => v.username));
1072
- }
1073
- }
1074
- else if (chat instanceof types.Chat) {
1075
- await this.storage.setEntity(chat);
1076
- }
1077
- else if (chat instanceof types.ChannelForbidden || chat instanceof types.ChatForbidden) {
1078
- await this.storage.removeEntity(chat);
1079
- }
1080
- }
1081
- }, _Client_processUsers = async function _Client_processUsers(users) {
1082
- for (const user of users) {
1083
- if (user instanceof types.User && user.access_hash) {
1084
- await this.storage.setEntity(user);
1085
- await this.storage.setUserAccessHash(user.id, user.access_hash);
1086
- if (user.username) {
1087
- await this.storage.updateUsernames("user", user.id, [user.username]);
1088
- }
1089
- if (user.usernames) {
1090
- await this.storage.updateUsernames("user", user.id, user.usernames.map((v) => v.username));
1091
- }
1092
- }
1093
- }
1094
- }, _Client_getHandleUpdateQueue = function _Client_getHandleUpdateQueue(boxId) {
1095
- let queue = __classPrivateFieldGet(this, _Client_handleUpdateQueues, "f").get(boxId);
1096
- if (queue !== undefined) {
1097
- return queue;
1098
- }
1099
- else {
1100
- queue = new Queue(`handleUpdate-${boxId}`);
1101
- return queue;
1102
- }
1103
- }, _Client_checkGap = async function _Client_checkGap(pts, ptsCount) {
1104
- const localState = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1105
- if (localState.pts + ptsCount < pts) {
1106
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "processUpdates");
1107
- }
1108
- }, _Client_checkChannelGap = async function _Client_checkChannelGap(channelId, pts, ptsCount) {
1109
- let localPts = await this.storage.getChannelPts(channelId);
1110
- if (!localPts) {
1111
- localPts = pts - ptsCount;
1112
- }
1113
- if (localPts + ptsCount < pts) {
1114
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverChannelUpdateGap).call(this, channelId, "processUpdates");
1115
- }
1116
- }, _Client_processChannelPtsUpdateInner = async function _Client_processChannelPtsUpdateInner(update, checkGap) {
1117
- const channelId = update instanceof types.UpdateNewChannelMessage || update instanceof types.UpdateEditChannelMessage ? update.message.peer_id[as](types.PeerChannel).channel_id : update.channel_id;
1118
- if (update instanceof types.UpdateChannelTooLong) {
1119
- if (update.pts != undefined) {
1120
- await this.storage.setChannelPts(channelId, update.pts);
1121
- }
1122
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverChannelUpdateGap).call(this, channelId, "updateChannelTooLong");
1123
- return;
1124
- }
1125
- if (update.pts != 0) {
1126
- const ptsCount = update.pts_count;
1127
- if (checkGap) {
1128
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_checkChannelGap).call(this, channelId, update.pts, ptsCount);
1129
- }
1130
- let currentPts = await this.storage.getChannelPts(channelId);
1131
- currentPts ??= update.pts - ptsCount;
1132
- if (currentPts + ptsCount > update.pts) {
1133
- return;
1134
- }
1135
- }
1136
- if (__classPrivateFieldGet(this, _Client_guaranteeUpdateDelivery, "f")) {
1137
- await this.storage.setUpdate(channelId, update);
1138
- }
1139
- if (update.pts != 0) {
1140
- await this.storage.setChannelPts(channelId, update.pts);
1141
- }
1142
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_queueUpdate).call(this, update, channelId, true);
1143
- }, _Client_queueUpdate = function _Client_queueUpdate(update, boxId, pts) {
1144
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getHandleUpdateQueue).call(this, boxId).add(async () => {
1145
- if (__classPrivateFieldGet(this, _Client_guaranteeUpdateDelivery, "f") && pts) {
1146
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleStoredUpdates).call(this, boxId);
1147
- }
1148
- else {
1149
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleUpdate).call(this, update);
1150
- }
1151
- });
1152
- }, _Client_processChannelPtsUpdate = function _Client_processChannelPtsUpdate(update, checkGap) {
1153
- const channelId = update instanceof types.UpdateNewChannelMessage || update instanceof types.UpdateEditChannelMessage ? update.message.peer_id[as](types.PeerChannel).channel_id : update.channel_id;
1154
- let queue = __classPrivateFieldGet(this, _Client_channelUpdateQueues, "f").get(channelId);
1155
- if (queue == undefined) {
1156
- queue = new Queue(`channelUpdates-${channelId}`);
1157
- __classPrivateFieldGet(this, _Client_channelUpdateQueues, "f").set(channelId, queue);
1158
- }
1159
- queue.add(async () => {
1160
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChannelPtsUpdateInner).call(this, update, checkGap);
1161
- });
1162
- }, _Client_processPtsUpdateInner = async function _Client_processPtsUpdateInner(update, checkGap) {
1163
- const localState = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1164
- if (update.pts != 0) {
1165
- if (checkGap) {
1166
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_checkGap).call(this, update.pts, update.pts_count);
1167
- }
1168
- if (localState.pts + update.pts_count > update.pts) {
1169
- return;
1170
- }
1171
- }
1172
- if (__classPrivateFieldGet(this, _Client_guaranteeUpdateDelivery, "f")) {
1173
- await this.storage.setUpdate(__classPrivateFieldGet(this, _Client_mainBoxId, "f"), update);
1174
- }
1175
- if (update.pts != 0) {
1176
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setUpdatePts).call(this, update.pts);
1177
- }
1178
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_queueUpdate).call(this, update, 0n, true);
1179
- }, _Client_processPtsUpdate = function _Client_processPtsUpdate(update, checkGap) {
1180
- __classPrivateFieldGet(this, _Client_ptsUpdateQueue, "f").add(async () => {
1181
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processPtsUpdateInner).call(this, update, checkGap);
1182
- });
1183
- }, _Client_processUpdates = async function _Client_processUpdates(updates_, checkGap, call = null) {
1184
- __classPrivateFieldSet(this, _Client_lastUpdates, new Date(), "f");
1185
- /// First, individual updates (Update[1]) are extracted from Updates.[2]
1186
- ///
1187
- /// If an updatesTooLong[3] was received, an update gap recovery is initiated and no further action will be taken.
1188
- ///
1189
- /// [1]: https://core.telegram.org/type/Update
1190
- /// [2]: https://core.telegram.org/type/Updates
1191
- /// [3]: https://core.telegram.org/constructor/updatesTooLong
1192
- let updates;
1193
- if (updates_ instanceof types.UpdatesCombined || updates_ instanceof types.Updates) {
1194
- updates = updates_.updates;
1195
- const seq = updates_.seq;
1196
- const seqStart = "seq_start" in updates_ ? updates_.seq_start : updates_.seq;
1197
- if (checkGap) {
1198
- if (seqStart == 0) {
1199
- checkGap = false;
1200
- d("seqStart=0");
1201
- }
1202
- else {
1203
- const localState = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1204
- const localSeq = localState.seq;
1205
- if (localSeq + 1 == seqStart) {
1206
- // The update sequence can be applied.
1207
- localState.seq = seq;
1208
- localState.date = updates_.date;
1209
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setUpdateStateDate).call(this, updates_.date);
1210
- await this.storage.setState(localState);
1211
- }
1212
- else if (localSeq + 1 > seqStart) {
1213
- // The update sequence was already applied, and must be ignored.
1214
- d("localSeq + 1 > seqStart");
1215
- return;
1216
- }
1217
- else if (localSeq + 1 < seqStart) {
1218
- // There's an updates gap that must be filled.
1219
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "localSeq + 1 < seqStart");
1220
- }
1221
- }
1222
- }
1223
- }
1224
- else if (updates_ instanceof types.UpdateShort) {
1225
- updates = [updates_.update];
1226
- }
1227
- else if (updates_ instanceof types.UpdateShortMessage) {
1228
- updates = [
1229
- new types.UpdateNewMessage({
1230
- message: new types.Message({
1231
- out: updates_.out,
1232
- mentioned: updates_.mentioned,
1233
- media_unread: updates_.media_unread,
1234
- silent: updates_.silent,
1235
- id: updates_.id,
1236
- from_id: updates_.out ? new types.PeerUser({ user_id: await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getSelfId).call(this).then(BigInt) }) : new types.PeerUser({ user_id: updates_.user_id }),
1237
- peer_id: new types.PeerUser({ user_id: updates_.user_id }),
1238
- message: updates_.message,
1239
- date: updates_.date,
1240
- fwd_from: updates_.fwd_from,
1241
- via_bot_id: updates_.via_bot_id,
1242
- reply_to: updates_.reply_to,
1243
- entities: updates_.entities,
1244
- ttl_period: updates_.ttl_period,
1245
- }),
1246
- pts: updates_.pts,
1247
- pts_count: updates_.pts_count,
1248
- }),
1249
- ];
1250
- }
1251
- else if (updates_ instanceof types.UpdateShortChatMessage) {
1252
- updates = [
1253
- new types.UpdateNewMessage({
1254
- message: new types.Message({
1255
- out: updates_.out,
1256
- mentioned: updates_.mentioned,
1257
- media_unread: updates_.media_unread,
1258
- silent: updates_.silent,
1259
- id: updates_.id,
1260
- from_id: new types.PeerUser({ user_id: updates_.from_id }),
1261
- peer_id: new types.PeerChat({ chat_id: updates_.chat_id }),
1262
- fwd_from: updates_.fwd_from,
1263
- via_bot_id: updates_.via_bot_id,
1264
- reply_to: updates_.reply_to,
1265
- date: updates_.date,
1266
- message: updates_.message,
1267
- entities: updates_.entities,
1268
- ttl_period: updates_.ttl_period,
1269
- }),
1270
- pts: updates_.pts,
1271
- pts_count: updates_.pts_count,
1272
- }),
1273
- ];
1274
- }
1275
- else if (updates_ instanceof types.UpdateShortSentMessage) {
1276
- if (!(call instanceof functions.messages.sendMessage)) {
1277
- UNREACHABLE();
1278
- }
1279
- updates = [
1280
- new types.UpdateNewMessage({
1281
- message: new types.Message({
1282
- out: updates_.out,
1283
- silent: call.silent,
1284
- id: updates_.id,
1285
- from_id: new types.PeerUser({ user_id: await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getSelfId).call(this).then(BigInt) }),
1286
- peer_id: inputPeerToPeer(call.peer),
1287
- message: call.message,
1288
- media: updates_.media,
1289
- date: updates_.date,
1290
- // reply_to: call.reply_to, // TODO?
1291
- entities: updates_.entities,
1292
- ttl_period: updates_.ttl_period,
1293
- }),
1294
- pts: updates_.pts,
1295
- pts_count: updates_.pts_count,
1296
- }),
1297
- ];
1298
- }
1299
- else if (updates_ instanceof types.UpdatesTooLong) {
1300
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_recoverUpdateGap).call(this, "updatesTooLong");
1301
- return;
1302
- }
1303
- else if (updates_ instanceof types._Update) {
1304
- updates = [updates_];
1305
- }
1306
- else {
1307
- UNREACHABLE();
1308
- }
1309
- /// We process the updates when we are sure there is no gap.
1310
- if (updates_ instanceof types.Updates || updates_ instanceof types.UpdatesCombined) {
1311
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, updates_.chats);
1312
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, updates_.users);
1313
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setUpdateStateDate).call(this, updates_.date);
1314
- }
1315
- else if (updates_ instanceof types.UpdateShort ||
1316
- updates_ instanceof types.UpdateShortMessage ||
1317
- updates_ instanceof types.UpdateShortChatMessage ||
1318
- updates_ instanceof types.UpdateShortSentMessage) {
1319
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setUpdateStateDate).call(this, updates_.date);
1320
- }
1321
- for (const update of updates) {
1322
- if (update instanceof types.UpdatePtsChanged) {
1323
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "updatePtsChanged");
1324
- if (__classPrivateFieldGet(this, _Client_updateState, "f")) {
1325
- await this.storage.setState(__classPrivateFieldGet(this, _Client_updateState, "f"));
1326
- }
1327
- else {
1328
- UNREACHABLE();
1329
- }
1330
- }
1331
- else if (isPtsUpdate(update)) {
1332
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_processPtsUpdate).call(this, update, checkGap);
1333
- }
1334
- else if (isChannelPtsUpdate(update)) {
1335
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChannelPtsUpdate).call(this, update, checkGap);
1336
- }
1337
- else {
1338
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_queueUpdate).call(this, update, 0n, false);
1339
- }
1340
- }
1341
- }, _Client_setUpdateStateDate = async function _Client_setUpdateStateDate(date) {
1342
- const localState = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1343
- localState.date = date;
1344
- await this.storage.setState(localState);
1345
- }, _Client_setUpdatePts = async function _Client_setUpdatePts(pts) {
1346
- const localState = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1347
- localState.pts = pts;
1348
- await this.storage.setState(localState);
1349
- }, _Client_getLocalState = async function _Client_getLocalState() {
1350
- let localState = await this.storage.getState();
1351
- if (!localState) {
1352
- if (__classPrivateFieldGet(this, _Client_updateState, "f")) {
1353
- localState = __classPrivateFieldGet(this, _Client_updateState, "f");
1354
- await this.storage.setState(localState);
1355
- }
1356
- else {
1357
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchState).call(this, "getLocalState");
1358
- if (__classPrivateFieldGet(this, _Client_updateState, "f")) {
1359
- localState = __classPrivateFieldGet(this, _Client_updateState, "f");
1360
- await this.storage.setState(localState);
1361
- }
1362
- else {
1363
- UNREACHABLE();
1364
- }
1365
- }
1366
- }
1367
- return localState;
1368
- }, _Client_recoverUpdateGap = async function _Client_recoverUpdateGap(source) {
1369
- dGap("recovering from update gap [%s]", source);
1370
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).call(this, "updating");
1371
- try {
1372
- let state = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
1373
- while (true) {
1374
- const difference = await this.api.updates.getDifference({ pts: state.pts, date: state.date, qts: state.qts ?? 0 });
1375
- if (difference instanceof types.updates.Difference || difference instanceof types.updates.DifferenceSlice) {
1376
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, difference.chats);
1377
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, difference.users);
1378
- for (const message of difference.new_messages) {
1379
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, new types.UpdateNewMessage({ message, pts: 0, pts_count: 0 }), false);
1380
- }
1381
- for (const update of difference.other_updates) {
1382
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, update, false);
1383
- }
1384
- if (difference instanceof types.updates.Difference) {
1385
- await this.storage.setState(difference.state);
1386
- dGap("recovered from update gap");
1387
- break;
1388
- }
1389
- else if (difference instanceof types.updates.DifferenceSlice) {
1390
- state = difference.intermediate_state;
1391
- }
1392
- else {
1393
- UNREACHABLE();
1394
- }
1395
- }
1396
- else if (difference instanceof types.updates.DifferenceTooLong) {
1397
- await this.storage.deleteMessages();
1398
- await this.storage.removeChats(0);
1399
- await this.storage.removeChats(1);
1400
- state.pts = difference.pts;
1401
- dGap("received differenceTooLong");
1402
- }
1403
- else if (difference instanceof types.updates.DifferenceEmpty) {
1404
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setUpdateStateDate).call(this, difference.date);
1405
- dGap("there was no update gap");
1406
- break;
1407
- }
1408
- else {
1409
- UNREACHABLE();
1410
- }
1411
- }
1412
- }
1413
- finally {
1414
- this.stateChangeHandler(this.connected);
1415
- __classPrivateFieldSet(this, _Client_lastUpdates, new Date(), "f");
1416
- }
1417
- }, _Client_recoverChannelUpdateGap = async function _Client_recoverChannelUpdateGap(channelId, source) {
1418
- dGapC("recovering channel update gap [%o, %s]", channelId, source);
1419
- const pts_ = await this.storage.getChannelPts(channelId);
1420
- let pts = pts_ == null ? 1 : pts_;
1421
- while (true) {
1422
- const { access_hash } = await this.getInputPeer(ZERO_CHANNEL_ID + -Number(channelId)).then((v) => v[as](types.InputPeerChannel));
1423
- const difference = await this.api.updates.getChannelDifference({
1424
- pts,
1425
- channel: new types.InputChannel({ channel_id: channelId, access_hash }),
1426
- filter: new types.ChannelMessagesFilterEmpty(),
1427
- limit: await this.storage.getAccountType() == "user" ? CHANNEL_DIFFERENCE_LIMIT_USER : CHANNEL_DIFFERENCE_LIMIT_BOT,
1428
- });
1429
- if (difference instanceof types.updates.ChannelDifference) {
1430
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, difference.chats);
1431
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, difference.users);
1432
- for (const message of difference.new_messages) {
1433
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, new types.UpdateNewChannelMessage({ message, pts: 0, pts_count: 0 }), false);
1434
- }
1435
- for (const update of difference.other_updates) {
1436
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, update, false);
1437
- }
1438
- await this.storage.setChannelPts(channelId, difference.pts);
1439
- dGapC("recovered from update gap [%o, %s]", channelId, source);
1440
- break;
1441
- }
1442
- else if (difference instanceof types.updates.ChannelDifferenceTooLong) {
1443
- // TODO: invalidate messages
1444
- dGapC("received channelDifferenceTooLong");
1445
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, difference.chats);
1446
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, difference.users);
1447
- for (const message of difference.messages) {
1448
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUpdates).call(this, new types.UpdateNewChannelMessage({ message, pts: 0, pts_count: 0 }), false);
1449
- }
1450
- const pts_ = difference.dialog[as](types.Dialog).pts;
1451
- if (pts_ != undefined) {
1452
- pts = pts_;
1453
- }
1454
- else {
1455
- UNREACHABLE();
1456
- }
1457
- dGapC("processed channelDifferenceTooLong");
1458
- }
1459
- else if (difference instanceof types.updates.ChannelDifferenceEmpty) {
1460
- dGapC("there was no update gap");
1461
- break;
1462
- }
1463
- }
1162
+ }, _Client_getUserAccessHash = async function _Client_getUserAccessHash(userId) {
1163
+ const users = await this.api.users.getUsers({ id: [new types.InputUser({ user_id: userId, access_hash: 0n })] });
1164
+ return users[0]?.[as](types.User).access_hash ?? 0n;
1464
1165
  }, _Client_getChannelAccessHash = async function _Client_getChannelAccessHash(channelId) {
1465
1166
  const channels = await this.api.channels.getChannels({ id: [new types.InputChannel({ channel_id: channelId, access_hash: 0n })] });
1466
1167
  return channels.chats[0][as](types.Channel).access_hash ?? 0n;
@@ -1481,8 +1182,8 @@ export class Client extends ClientAbstract {
1481
1182
  }
1482
1183
  else {
1483
1184
  const resolved = await this.api.contacts.resolveUsername({ username: id });
1484
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, resolved.chats);
1485
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, resolved.users);
1185
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").processChats(resolved.chats);
1186
+ await __classPrivateFieldGet(this, _Client_updateManager, "f").processUsers(resolved.users);
1486
1187
  if (resolved.peer instanceof types.PeerUser) {
1487
1188
  userId = resolved.peer.user_id;
1488
1189
  }
@@ -1526,63 +1227,6 @@ export class Client extends ClientAbstract {
1526
1227
  const id = peer instanceof types.PeerUser ? peer.user_id : peer instanceof types.PeerChat ? peer.chat_id : peer instanceof types.PeerChannel ? peer.channel_id : UNREACHABLE();
1527
1228
  return this.storage.getEntity(type, id);
1528
1229
  }
1529
- async processResult(result) {
1530
- if (result instanceof types.messages.Dialogs ||
1531
- result instanceof types.messages.DialogsSlice ||
1532
- result instanceof types.messages.Messages ||
1533
- result instanceof types.messages.MessagesSlice ||
1534
- result instanceof types.messages.ChannelMessages ||
1535
- result instanceof types.messages.ChatFull ||
1536
- result instanceof types.contacts.Found ||
1537
- result instanceof types.account.PrivacyRules ||
1538
- result instanceof types.contacts.ResolvedPeer ||
1539
- result instanceof types.channels.ChannelParticipants ||
1540
- result instanceof types.channels.ChannelParticipant ||
1541
- result instanceof types.messages.PeerDialogs ||
1542
- result instanceof types.contacts.TopPeers ||
1543
- result instanceof types.channels.AdminLogResults ||
1544
- result instanceof types.help.RecentMeUrls ||
1545
- result instanceof types.messages.InactiveChats ||
1546
- result instanceof types.help.PromoData ||
1547
- result instanceof types.messages.MessageViews ||
1548
- result instanceof types.messages.DiscussionMessage ||
1549
- result instanceof types.phone.GroupCall ||
1550
- result instanceof types.phone.GroupParticipants ||
1551
- result instanceof types.phone.JoinAsPeers ||
1552
- result instanceof types.messages.SponsoredMessages ||
1553
- result instanceof types.messages.SearchResultsCalendar ||
1554
- result instanceof types.channels.SendAsPeers ||
1555
- result instanceof types.users.UserFull ||
1556
- result instanceof types.messages.PeerSettings ||
1557
- result instanceof types.messages.MessageReactionsList ||
1558
- result instanceof types.messages.ForumTopics ||
1559
- result instanceof types.account.AutoSaveSettings ||
1560
- result instanceof types.chatlists.ExportedInvites ||
1561
- result instanceof types.chatlists.ChatlistInviteAlready ||
1562
- result instanceof types.chatlists.ChatlistInvite ||
1563
- result instanceof types.chatlists.ChatlistUpdates ||
1564
- result instanceof types.messages.Chats ||
1565
- result instanceof types.messages.ChatsSlice) {
1566
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processChats).call(this, result.chats);
1567
- if ("users" in result) {
1568
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_processUsers).call(this, result.users);
1569
- }
1570
- if ("messages" in result) {
1571
- for (const message of result.messages) {
1572
- if (message instanceof types.Message || message instanceof types.MessageService) {
1573
- await this.storage.setMessage(peerToChatId(message.peer_id), message.id, message);
1574
- }
1575
- }
1576
- }
1577
- }
1578
- if (result instanceof types.messages.Messages) {
1579
- for (const message of result.messages) {
1580
- if (message instanceof types.Message || message instanceof types.MessageService) {
1581
- await this.storage.setMessage(peerToChatId(message.peer_id), message.id, message);
1582
- }
1583
- }
1584
- }
1585
- }
1586
1230
  /**
1587
1231
  * Send a text message.
1588
1232
  *
@@ -1592,50 +1236,30 @@ export class Client extends ClientAbstract {
1592
1236
  * @returns The sent text message.
1593
1237
  */
1594
1238
  async sendMessage(chatId, text, params) {
1595
- const [message, entities] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_parseText).call(this, text, params);
1596
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
1597
- const peer = await this.getInputPeer(chatId);
1598
- const randomId = getRandomId();
1599
- const noWebpage = params?.disableWebPagePreview ? true : undefined;
1600
- const silent = params?.disableNotification ? true : undefined;
1601
- const noforwards = params?.protectContent ? true : undefined;
1602
- const sendAs = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_resolveSendAs).call(this, params);
1603
- const result = await this.api.messages.sendMessage({
1604
- peer,
1605
- random_id: randomId,
1606
- message,
1607
- no_webpage: noWebpage,
1608
- silent,
1609
- noforwards,
1610
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
1611
- send_as: sendAs,
1612
- entities,
1613
- reply_markup: replyMarkup,
1614
- });
1615
- const message_ = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
1616
- return assertMessageType(message_, "text");
1239
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendMessage(chatId, text, params);
1617
1240
  }
1618
1241
  /**
1619
1242
  * Edit a message's text.
1620
1243
  *
1621
1244
  * @method
1622
- * @param chatId The chat where the message is.
1623
- * @param messageId The ID of the message.
1245
+ * @param chatId The identifier of the chat that contains the messages.
1246
+ * @param messageId The message's identifier.
1624
1247
  * @param text The new text of the message.
1625
1248
  * @returns The edited text message.
1626
1249
  */
1627
1250
  async editMessageText(chatId, messageId, text, params) {
1628
- const [message, entities] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_parseText).call(this, text, params);
1629
- const result = await this.api.messages.editMessage({
1630
- id: messageId,
1631
- peer: await this.getInputPeer(chatId),
1632
- entities,
1633
- message,
1634
- no_webpage: params?.disableWebPagePreview ? true : undefined,
1635
- reply_markup: await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params),
1636
- });
1637
- const message_ = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
1638
- return assertMessageType(message_, "text");
1251
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").editMessageText(chatId, messageId, text, params);
1252
+ }
1253
+ /**
1254
+ * Edit a message's reply markup.
1255
+ *
1256
+ * @method
1257
+ * @param chatId The identifier of the chat that contains the messages.
1258
+ * @param messageId The message's identifier.
1259
+ * @returns The edited message.
1260
+ */
1261
+ async editMessageReplyMarkup(chatId, messageId, params) {
1262
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").editMessageReplyMarkup(chatId, messageId, params);
1639
1263
  }
1640
1264
  /**
1641
1265
  * Retrieve multiple messages.
@@ -1649,101 +1273,7 @@ export class Client extends ClientAbstract {
1649
1273
  * @returns The retrieved messages.
1650
1274
  */
1651
1275
  async getMessages(chatId, messageIds) {
1652
- return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMessagesInner).call(this, chatId, messageIds).then((v) => v.map((v) => v.message));
1653
- }
1654
- async [(_Client_updatesToMessages = async function _Client_updatesToMessages(chatId, updates) {
1655
- const messages = new Array();
1656
- if (updates instanceof types.Updates) {
1657
- for (const update of updates.updates) {
1658
- if ("message" in update && update.message instanceof types.MessageEmpty) {
1659
- continue;
1660
- }
1661
- if (update instanceof types.UpdateNewMessage || update instanceof types.UpdateEditMessage) {
1662
- messages.push(await constructMessage(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this)));
1663
- }
1664
- else if (update instanceof types.UpdateNewChannelMessage || update instanceof types.UpdateEditChannelMessage) {
1665
- messages.push(await constructMessage(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this)));
1666
- }
1667
- }
1668
- }
1669
- else if (updates instanceof types.UpdateShortSentMessage) {
1670
- const message = await this.getMessage(chatId, updates.id);
1671
- if (message != null) {
1672
- messages.push(message);
1673
- }
1674
- }
1675
- return messages;
1676
- }, _Client_resolveSendAs = async function _Client_resolveSendAs(params) {
1677
- const sendAs = params?.sendAs;
1678
- if (sendAs !== undefined) {
1679
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertUser).call(this, "sendAs");
1680
- return sendAs ? await this.getInputPeer(sendAs) : undefined;
1681
- }
1682
- }, _Client_constructReplyTo = function _Client_constructReplyTo(params) {
1683
- const topMsgId = params?.messageThreadId;
1684
- const replyToMsgId = params?.replyToMessageId;
1685
- return replyToMsgId !== undefined ? new types.InputReplyToMessage({ reply_to_msg_id: replyToMsgId, top_msg_id: topMsgId, quote_text: params?.replyQuote?.text, quote_entities: params?.replyQuote?.entities.map(messageEntityToTlObject), quote_offset: params?.replyQuote?.offset }) : undefined;
1686
- }, _Client_parseText = function _Client_parseText(text, params) {
1687
- const entities_ = params?.entities ?? [];
1688
- const parseMode = params?.parseMode ?? this.parseMode;
1689
- switch (parseMode) {
1690
- case null:
1691
- break;
1692
- case "HTML": {
1693
- const [newText, entitiesToPush] = parseHtml(text);
1694
- text = newText;
1695
- for (const entity of entitiesToPush) {
1696
- entities_.push(entity);
1697
- }
1698
- break;
1699
- }
1700
- default:
1701
- UNREACHABLE();
1702
- }
1703
- const entities = entities_?.length > 0 ? entities_.map((v) => messageEntityToTlObject(v)) : undefined;
1704
- return [text, entities];
1705
- }, _Client_getMessagesInner = async function _Client_getMessagesInner(chatId_, messageIds) {
1706
- const peer = await this.getInputPeer(chatId_);
1707
- let messages_ = new Array();
1708
- const chatId = peerToChatId(peer);
1709
- let shouldFetch = false;
1710
- for (const messageId of messageIds) {
1711
- const message = await this.storage.getMessage(chatId, messageId);
1712
- if (message == null) {
1713
- messages_ = [];
1714
- shouldFetch = true;
1715
- break;
1716
- }
1717
- else {
1718
- messages_.push(message);
1719
- }
1720
- }
1721
- if (shouldFetch) {
1722
- if (peer instanceof types.InputPeerChannel) {
1723
- messages_ = await this.api.channels.getMessages({
1724
- channel: new types.InputChannel(peer),
1725
- id: messageIds.map((v) => new types.InputMessageID({ id: v })),
1726
- }).then((v) => v[as](types.messages.ChannelMessages).messages);
1727
- }
1728
- else {
1729
- messages_ = await this.api.messages.getMessages({
1730
- id: messageIds.map((v) => new types.InputMessageID({ id: v })),
1731
- }).then((v) => v[as](types.messages.Messages).messages);
1732
- }
1733
- }
1734
- const messages = new Array();
1735
- for (const message_ of messages_) {
1736
- if (message_ instanceof types.MessageEmpty) {
1737
- continue;
1738
- }
1739
- const message = await constructMessage(message_, this[getEntity].bind(this), null, this[getStickerSetName].bind(this));
1740
- const isReplyToMessage = message_ instanceof types.Message && message_.reply_to instanceof types.MessageReplyHeader;
1741
- messages.push({ message, isReplyToMessage });
1742
- }
1743
- return messages;
1744
- }, getMessageWithReply)](chatId, messageId) {
1745
- const messages = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMessagesInner).call(this, chatId, [messageId]);
1746
- return messages[0]?.message ?? null;
1276
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").getMessages(chatId, messageIds);
1747
1277
  }
1748
1278
  /**
1749
1279
  * Retrieve a single message.
@@ -1757,8 +1287,7 @@ export class Client extends ClientAbstract {
1757
1287
  * @returns The retrieved message.
1758
1288
  */
1759
1289
  async getMessage(chatId, messageId) {
1760
- const messages = await this.getMessages(chatId, [messageId]);
1761
- return messages[0] ?? null;
1290
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").getMessage(chatId, messageId);
1762
1291
  }
1763
1292
  /**
1764
1293
  * Download a file.
@@ -1773,139 +1302,8 @@ export class Client extends ClientAbstract {
1773
1302
  * @returns A generator yielding the contents of the file.
1774
1303
  */
1775
1304
  async *download(fileId, params) {
1776
- const fileId_ = FileID.decode(fileId);
1777
- switch (fileId_.fileType) {
1778
- case FileType.ChatPhoto: {
1779
- const big = fileId_.params.thumbnailSource == ThumbnailSource.ChatPhotoBig;
1780
- const peer = await this.getInputPeer(fileId_.params.chatId);
1781
- const location = new types.InputPeerPhotoFileLocation({ big: big ? true : undefined, peer, photo_id: fileId_.params.mediaId });
1782
- for await (const chunk of __classPrivateFieldGet(this, _Client_instances, "m", _Client_downloadInner).call(this, location, fileId_.dcId, params)) {
1783
- yield chunk;
1784
- }
1785
- break;
1786
- }
1787
- case FileType.Photo: {
1788
- if (fileId_.params.mediaId == undefined || fileId_.params.accessHash == undefined || fileId_.params.fileReference == undefined || fileId_.params.thumbnailSize == undefined) {
1789
- UNREACHABLE();
1790
- }
1791
- const location = new types.InputPhotoFileLocation({
1792
- id: fileId_.params.mediaId,
1793
- access_hash: fileId_.params.accessHash,
1794
- file_reference: fileId_.params.fileReference,
1795
- thumb_size: fileId_.params.thumbnailSize,
1796
- });
1797
- for await (const chunk of __classPrivateFieldGet(this, _Client_instances, "m", _Client_downloadInner).call(this, location, fileId_.dcId, params)) {
1798
- yield chunk;
1799
- }
1800
- break;
1801
- }
1802
- case FileType.Document:
1803
- case FileType.Sticker:
1804
- case FileType.VideoNote:
1805
- case FileType.Video:
1806
- case FileType.Audio:
1807
- case FileType.Voice:
1808
- case FileType.Animation: {
1809
- if (fileId_.params.mediaId == undefined || fileId_.params.accessHash == undefined || fileId_.params.fileReference == undefined || fileId_.params.thumbnailSize == undefined) {
1810
- UNREACHABLE();
1811
- }
1812
- const location = new types.InputDocumentFileLocation({
1813
- id: fileId_.params.mediaId,
1814
- access_hash: fileId_.params.accessHash,
1815
- file_reference: fileId_.params.fileReference,
1816
- thumb_size: fileId_.params.thumbnailSize,
1817
- });
1818
- for await (const chunk of __classPrivateFieldGet(this, _Client_instances, "m", _Client_downloadInner).call(this, location, fileId_.dcId, params)) {
1819
- yield chunk;
1820
- }
1821
- break;
1822
- }
1823
- default:
1824
- UNREACHABLE();
1825
- }
1826
- }
1827
- async [(_Client_downloadInner = async function* _Client_downloadInner(location, dcId, params) {
1828
- const id = "id" in location ? location.id : "photo_id" in location ? location.photo_id : null;
1829
- if (id != null) {
1830
- const partCount = await this.storage.getFile(id);
1831
- if (partCount != null && partCount > 0) {
1832
- for await (const part of this.storage.iterFileParts(id, partCount)) {
1833
- yield part;
1834
- }
1835
- return;
1836
- }
1837
- }
1838
- const chunkSize = params?.chunkSize ?? 1024 * 1024;
1839
- if (mod(chunkSize, 1024) != 0) {
1840
- throw new Error("chunkSize must be divisible by 1024");
1841
- }
1842
- const client = new _a(dcId == this.dcId ? this.storage : this.storage.branch(`download_client_${dcId}`), this.apiId, this.apiHash, {
1843
- transportProvider: this.transportProvider,
1844
- appVersion: this.appVersion,
1845
- deviceModel: this.deviceModel,
1846
- langCode: this.langCode,
1847
- langPack: this.langPack,
1848
- systemLangCode: this.systemLangCode,
1849
- systemVersion: this.systemVersion,
1850
- cdn: true,
1851
- });
1852
- let dc = String(dcId);
1853
- if (this.dcId < 0) {
1854
- dc += "-test";
1855
- }
1856
- await client.setDc(dc);
1857
- await client.connect();
1858
- await __classPrivateFieldGet(client, _Client_instances, "m", _Client_initConnection).call(client);
1859
- client.invoke.use(async (ctx, next) => {
1860
- if (ctx.error instanceof AuthKeyUnregistered) {
1861
- try {
1862
- const exportedAuth = await this.api.auth.exportAuthorization({ dc_id: dcId });
1863
- await client.authorize(exportedAuth);
1864
- return true;
1865
- }
1866
- catch (err) {
1867
- throw err;
1868
- }
1869
- }
1870
- else {
1871
- return await next();
1872
- }
1873
- });
1874
- const limit = chunkSize;
1875
- let offset = 0n;
1876
- let part = 0;
1877
- while (true) {
1878
- const file = await (client ?? this).invoke(new functions.upload.getFile({ location, offset, limit }));
1879
- if (file instanceof types.upload.File) {
1880
- yield file.bytes;
1881
- if (id != null) {
1882
- await this.storage.saveFilePart(id, part, file.bytes);
1883
- }
1884
- ++part;
1885
- if (file.bytes.length < limit) {
1886
- if (id != null) {
1887
- await this.storage.setFilePartCount(id, part + 1);
1888
- }
1889
- break;
1890
- }
1891
- else {
1892
- offset += BigInt(file.bytes.length);
1893
- }
1894
- }
1895
- else {
1896
- UNREACHABLE();
1897
- }
1898
- }
1899
- }, getStickerSetName)](inputStickerSet, hash = 0) {
1900
- const maybeStickerSetName = await this.storage.getStickerSetName(inputStickerSet.id, inputStickerSet.access_hash);
1901
- if (maybeStickerSetName != null && Date.now() - maybeStickerSetName[1].getTime() < STICKER_SET_NAME_TTL) {
1902
- return maybeStickerSetName[0];
1903
- }
1904
- else {
1905
- const stickerSet = await this.api.messages.getStickerSet({ stickerset: inputStickerSet, hash });
1906
- const name = stickerSet[as](types.messages.StickerSet).set.short_name;
1907
- await this.storage.updateStickerSetName(inputStickerSet.id, inputStickerSet.access_hash, name);
1908
- return name;
1305
+ for await (const chunk of __classPrivateFieldGet(this, _Client_fileManager, "f").download(fileId, params)) {
1306
+ yield chunk;
1909
1307
  }
1910
1308
  }
1911
1309
  /**
@@ -1918,19 +1316,7 @@ export class Client extends ClientAbstract {
1918
1316
  * @returns The forwarded messages.
1919
1317
  */
1920
1318
  async forwardMessages(from, to, messageIds, params) {
1921
- const result = await this.api.messages.forwardMessages({
1922
- from_peer: await this.getInputPeer(from),
1923
- to_peer: await this.getInputPeer(to),
1924
- id: messageIds,
1925
- random_id: messageIds.map(() => getRandomId()),
1926
- silent: params?.disableNotification || undefined,
1927
- top_msg_id: params?.messageThreadId,
1928
- noforwards: params?.disableNotification || undefined,
1929
- send_as: params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined,
1930
- drop_author: params?.dropSenderName || undefined,
1931
- drop_media_captions: params?.dropCaption || undefined,
1932
- });
1933
- return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, to, result);
1319
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").forwardMessages(from, to, messageIds, params);
1934
1320
  }
1935
1321
  /**
1936
1322
  * Forward a single message.
@@ -1965,7 +1351,7 @@ export class Client extends ClientAbstract {
1965
1351
  * @param id ID of the callback query to answer.
1966
1352
  */
1967
1353
  async answerCallbackQuery(id, params) {
1968
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "answerCallbackQuery");
1354
+ await this.storage.assertBot("answerCallbackQuery");
1969
1355
  await this.api.messages.setBotCallbackAnswer({
1970
1356
  query_id: BigInt(id),
1971
1357
  cache_time: params?.cacheTime ?? 0,
@@ -1983,47 +1369,7 @@ export class Client extends ClientAbstract {
1983
1369
  * @returns The sent poll.
1984
1370
  */
1985
1371
  async sendPoll(chatId, question, options, params) {
1986
- const peer = await this.getInputPeer(chatId);
1987
- const randomId = getRandomId();
1988
- const silent = params?.disableNotification ? true : undefined;
1989
- const noforwards = params?.protectContent ? true : undefined;
1990
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
1991
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
1992
- const explanation = params?.explanation;
1993
- const parseResult = explanation !== undefined ? __classPrivateFieldGet(this, _Client_instances, "m", _Client_parseText).call(this, explanation, { parseMode: params?.explanationParseMode, entities: params?.explanationEntities }) : undefined;
1994
- const solution = parseResult === undefined ? undefined : parseResult[0];
1995
- const solutionEntities = parseResult === undefined ? undefined : parseResult[1];
1996
- const answers = options.map((v, i) => new types.PollAnswer({ option: new Uint8Array([i]), text: v }));
1997
- const poll = new types.Poll({
1998
- id: getRandomId(),
1999
- answers,
2000
- question,
2001
- closed: params?.isClosed ? true : undefined,
2002
- close_date: params?.closeDate ? Math.floor(params.closeDate.getTime() / 1000) : undefined,
2003
- close_period: params?.openPeriod ? params.openPeriod : undefined,
2004
- multiple_choice: params?.allowMultipleAnswers ? true : undefined,
2005
- public_voters: params?.isAnonymous === false ? true : undefined,
2006
- quiz: params?.type == "quiz" ? true : undefined,
2007
- });
2008
- const media = new types.InputMediaPoll({
2009
- poll,
2010
- correct_answers: params?.correctOptionIndex ? [new Uint8Array([params.correctOptionIndex])] : undefined,
2011
- solution,
2012
- solution_entities: solutionEntities,
2013
- });
2014
- const result = await this.api.messages.sendMedia({
2015
- peer,
2016
- random_id: randomId,
2017
- silent,
2018
- noforwards,
2019
- reply_markup: replyMarkup,
2020
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
2021
- send_as: sendAs,
2022
- media,
2023
- message: "",
2024
- });
2025
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
2026
- return assertMessageType(message, "poll");
1372
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendPoll(chatId, question, options, params);
2027
1373
  }
2028
1374
  /**
2029
1375
  * Send a chat action.
@@ -2081,89 +1427,7 @@ export class Client extends ClientAbstract {
2081
1427
  * @param contents The contents of the file.
2082
1428
  */
2083
1429
  async upload(contents, params) {
2084
- const isBig = contents.length > 1048576; // 10 MB
2085
- const chunkSize = params?.chunkSize ?? 512 * 1024;
2086
- if (mod(chunkSize, 1024) != 0) {
2087
- throw new Error("chunkSize must be divisible by 1024");
2088
- }
2089
- const signal = params?.signal;
2090
- dUpload("uploading " + (isBig ? "big " : "") + "file of size " + contents.length + " with chunk size of " + chunkSize);
2091
- const fileId = getRandomId();
2092
- const name = params?.fileName ?? fileId.toString();
2093
- const client = new _a(this.storage, this.apiId, this.apiHash, {
2094
- transportProvider: this.transportProvider,
2095
- appVersion: this.appVersion,
2096
- deviceModel: this.deviceModel,
2097
- langCode: this.langCode,
2098
- langPack: this.langPack,
2099
- systemLangCode: this.systemLangCode,
2100
- systemVersion: this.systemVersion,
2101
- cdn: true,
2102
- initialDc: this.initialDc,
2103
- autoStart: false,
2104
- });
2105
- signal?.addEventListener("abort", () => drop(client.disconnect()));
2106
- __classPrivateFieldGet(client, _Client_state, "f").salt = __classPrivateFieldGet(this, _Client_state, "f").salt;
2107
- await client.connect();
2108
- let part = 0;
2109
- const partCount = Math.ceil(contents.length / chunkSize);
2110
- try {
2111
- main: for (; part < partCount; part++) {
2112
- chunk: while (true) {
2113
- try {
2114
- const start = part * chunkSize;
2115
- const end = start + chunkSize;
2116
- const bytes = contents.slice(start, end);
2117
- if (bytes.length == 0) {
2118
- continue main;
2119
- }
2120
- if (isBig) {
2121
- await client.invoke(new functions.upload.saveBigFilePart({ file_id: fileId, file_part: part, bytes, file_total_parts: partCount }));
2122
- }
2123
- else {
2124
- await client.invoke(new functions.upload.saveFilePart({ file_id: fileId, bytes, file_part: part }));
2125
- }
2126
- dUpload((part + 1) + " out of " + partCount + " chunks have been uploaded so far");
2127
- break chunk;
2128
- }
2129
- catch (err) {
2130
- if (signal?.aborted) {
2131
- break main;
2132
- }
2133
- if (err instanceof FloodWait) {
2134
- dUpload("got a flood wait of " + err.seconds + " seconds");
2135
- await new Promise((r) => setTimeout(r, err.seconds * 1000));
2136
- }
2137
- else if (err instanceof ConnectionError) {
2138
- while (true) {
2139
- try {
2140
- await new Promise((r) => setTimeout(r, 3000));
2141
- await client.connect();
2142
- }
2143
- catch {
2144
- if (signal?.aborted) {
2145
- break main;
2146
- }
2147
- }
2148
- }
2149
- }
2150
- else {
2151
- throw err;
2152
- }
2153
- }
2154
- }
2155
- }
2156
- }
2157
- finally {
2158
- drop(client.disconnect());
2159
- }
2160
- dUpload("uploaded all " + partCount + " chunk(s)");
2161
- if (isBig) {
2162
- return new types.InputFileBig({ id: fileId, parts: contents.length / chunkSize, name });
2163
- }
2164
- else {
2165
- return new types.InputFile({ id: fileId, name, parts: part, md5_checksum: "" });
2166
- }
1430
+ return await __classPrivateFieldGet(this, _Client_fileManager, "f").upload(contents, params);
2167
1431
  }
2168
1432
  /**
2169
1433
  * Set the bot's commands in the given scope and/or language. Bot-only.
@@ -2283,7 +1547,7 @@ export class Client extends ClientAbstract {
2283
1547
  * @method
2284
1548
  */
2285
1549
  async setMyDescription(params) {
2286
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "setMyDescription");
1550
+ await this.storage.assertBot("setMyDescription");
2287
1551
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setMyInfo).call(this, { description: params?.description, lang_code: params?.languageCode ?? "" });
2288
1552
  }
2289
1553
  /**
@@ -2292,7 +1556,7 @@ export class Client extends ClientAbstract {
2292
1556
  * @method
2293
1557
  */
2294
1558
  async setMyName(params) {
2295
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "setMyName");
1559
+ await this.storage.assertBot("setMyName");
2296
1560
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setMyInfo).call(this, { name: params?.name, lang_code: params?.languageCode ?? "" });
2297
1561
  }
2298
1562
  /**
@@ -2301,7 +1565,7 @@ export class Client extends ClientAbstract {
2301
1565
  * @method
2302
1566
  */
2303
1567
  async setMyShortDescription(params) {
2304
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "setMyShortDescription");
1568
+ await this.storage.assertBot("setMyShortDescription");
2305
1569
  await __classPrivateFieldGet(this, _Client_instances, "m", _Client_setMyInfo).call(this, { about: params?.shortDescription, lang_code: params?.languageCode ?? "" });
2306
1570
  }
2307
1571
  /**
@@ -2310,7 +1574,7 @@ export class Client extends ClientAbstract {
2310
1574
  * @method
2311
1575
  */
2312
1576
  async getMyDescription(params) {
2313
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "getMyDescription");
1577
+ await this.storage.assertBot("getMyDescription");
2314
1578
  return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMyInfo).call(this, params?.languageCode).then((v) => v.description);
2315
1579
  }
2316
1580
  /**
@@ -2319,7 +1583,7 @@ export class Client extends ClientAbstract {
2319
1583
  * @method
2320
1584
  */
2321
1585
  async getMyName(params) {
2322
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "getMyName");
1586
+ await this.storage.assertBot("getMyName");
2323
1587
  return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMyInfo).call(this, params?.languageCode).then((v) => v.description);
2324
1588
  }
2325
1589
  /**
@@ -2328,34 +1592,28 @@ export class Client extends ClientAbstract {
2328
1592
  * @method
2329
1593
  */
2330
1594
  async getMyShortDescription(params) {
2331
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "getMyShortDescription");
1595
+ await this.storage.assertBot("getMyShortDescription");
2332
1596
  return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getMyInfo).call(this, params?.languageCode).then((v) => v.about);
2333
1597
  }
2334
1598
  /**
2335
1599
  * Delete multiple messages.
2336
1600
  *
2337
1601
  * @method
2338
- * @param chatId The chat that contains the messages.
1602
+ * @param chatId The identifier of the chat that contains the messages.
2339
1603
  * @param messageIds The identifier of the messages to delete.
2340
1604
  */
2341
1605
  async deleteMessages(chatId, messageIds, params) {
2342
- const peer = await this.getInputPeer(chatId);
2343
- if (peer instanceof types.InputPeerChannel) {
2344
- await this.api.channels.deleteMessages({ channel: new types.InputChannel(peer), id: messageIds });
2345
- }
2346
- else {
2347
- await this.api.messages.deleteMessages({ id: messageIds, revoke: params?.onlyForMe ? undefined : true });
2348
- }
1606
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").deleteMessages(chatId, messageIds, params);
2349
1607
  }
2350
1608
  /**
2351
1609
  * Delete a single message.
2352
1610
  *
2353
1611
  * @method
2354
- * @param chatId The chat that contains the message.
1612
+ * @param chatId The identifier of the chat that contains the message.
2355
1613
  * @param messageId The identifier of the message to delete.
2356
1614
  */
2357
1615
  async deleteMessage(chatId, messageId, params) {
2358
- await this.deleteMessages(chatId, [messageId], params);
1616
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").deleteMessages(chatId, [messageId], params);
2359
1617
  }
2360
1618
  /**
2361
1619
  * Send a photo.
@@ -2365,29 +1623,7 @@ export class Client extends ClientAbstract {
2365
1623
  * @param photo The photo to send.
2366
1624
  */
2367
1625
  async sendPhoto(chatId, photo, params) {
2368
- let media = null;
2369
- const spoiler = params?.hasSpoiler ? true : undefined;
2370
- if (typeof photo === "string") {
2371
- const fileId = __classPrivateFieldGet(this, _Client_instances, "m", _Client_resolveFileId).call(this, photo, FileType.Photo);
2372
- if (fileId != null) {
2373
- media = new types.InputMediaPhoto({
2374
- id: new types.InputPhoto(fileId),
2375
- spoiler,
2376
- });
2377
- }
2378
- }
2379
- if (media == null) {
2380
- if (typeof photo === "string" && isHttpUrl(photo)) {
2381
- media = new types.InputMediaPhotoExternal({ url: photo, spoiler });
2382
- }
2383
- else {
2384
- const [contents, fileName] = await getFileContents(photo);
2385
- const file = await this.upload(contents, { fileName, chunkSize: params?.chunkSize, signal: params?.signal });
2386
- media = new types.InputMediaUploadedPhoto({ file, spoiler });
2387
- }
2388
- }
2389
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendMedia).call(this, chatId, media, params);
2390
- return assertMessageType(message, "photo");
1626
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendPhoto(chatId, photo, params);
2391
1627
  }
2392
1628
  /**
2393
1629
  * Send a document.
@@ -2397,8 +1633,7 @@ export class Client extends ClientAbstract {
2397
1633
  * @param document The document to send.
2398
1634
  */
2399
1635
  async sendDocument(chatId, document, params) {
2400
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, document, params, FileType.Document, []);
2401
- return assertMessageType(message, "document");
1636
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendDocument(chatId, document, params);
2402
1637
  }
2403
1638
  /**
2404
1639
  * Send a video.
@@ -2408,15 +1643,7 @@ export class Client extends ClientAbstract {
2408
1643
  * @param video The video to send.
2409
1644
  */
2410
1645
  async sendVideo(chatId, video, params) {
2411
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, video, params, FileType.Video, [
2412
- new types.DocumentAttributeVideo({
2413
- supports_streaming: params?.supportsStreaming ? true : undefined,
2414
- w: params?.width ?? 0,
2415
- h: params?.height ?? 0,
2416
- duration: params?.duration ?? 0,
2417
- }),
2418
- ]);
2419
- return assertMessageType(message, "video");
1646
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendVideo(chatId, video, params);
2420
1647
  }
2421
1648
  /**
2422
1649
  * Send an animation.
@@ -2426,16 +1653,7 @@ export class Client extends ClientAbstract {
2426
1653
  * @param animation The animation to send.
2427
1654
  */
2428
1655
  async sendAnimation(chatId, animation, params) {
2429
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, animation, params, FileType.Animation, [
2430
- new types.DocumentAttributeAnimated(),
2431
- new types.DocumentAttributeVideo({
2432
- supports_streaming: true,
2433
- w: params?.width ?? 0,
2434
- h: params?.height ?? 0,
2435
- duration: params?.duration ?? 0,
2436
- }),
2437
- ]);
2438
- return assertMessageType(message, "animation");
1656
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendAnimation(chatId, animation, params);
2439
1657
  }
2440
1658
  /**
2441
1659
  * Send a voice message.
@@ -2445,13 +1663,7 @@ export class Client extends ClientAbstract {
2445
1663
  * @param voice The voice to send.
2446
1664
  */
2447
1665
  async sendVoice(chatId, voice, params) {
2448
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, voice, params, FileType.Voice, [
2449
- new types.DocumentAttributeAudio({
2450
- voice: true,
2451
- duration: params?.duration ?? 0,
2452
- }),
2453
- ]);
2454
- return assertMessageType(message, "voice");
1666
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendVoice(chatId, voice, params);
2455
1667
  }
2456
1668
  /**
2457
1669
  * Send an audio file.
@@ -2461,14 +1673,7 @@ export class Client extends ClientAbstract {
2461
1673
  * @param audio The audio to send.
2462
1674
  */
2463
1675
  async sendAudio(chatId, audio, params) {
2464
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, audio, params, FileType.Audio, [
2465
- new types.DocumentAttributeAudio({
2466
- duration: params?.duration ?? 0,
2467
- performer: params?.performer,
2468
- title: params?.title,
2469
- }),
2470
- ]);
2471
- return assertMessageType(message, "audio");
1676
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendAudio(chatId, audio, params);
2472
1677
  }
2473
1678
  /**
2474
1679
  * Send a video note.
@@ -2477,16 +1682,8 @@ export class Client extends ClientAbstract {
2477
1682
  * @param chatId The chat to send the video note to.
2478
1683
  * @param videoNote The video note to send.
2479
1684
  */
2480
- async sendVideoNote(chatId, audio, params) {
2481
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendDocumentInner).call(this, chatId, audio, params, FileType.VideoNote, [
2482
- new types.DocumentAttributeVideo({
2483
- round_message: true,
2484
- w: params?.length ?? 0,
2485
- h: params?.length ?? 0,
2486
- duration: params?.duration ?? 0,
2487
- }),
2488
- ], false);
2489
- return assertMessageType(message, "videoNote");
1685
+ async sendVideoNote(chatId, videoNote, params) {
1686
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendVideoNote(chatId, videoNote, params);
2490
1687
  }
2491
1688
  /**
2492
1689
  * Send a location.
@@ -2497,42 +1694,7 @@ export class Client extends ClientAbstract {
2497
1694
  * @param longitude The location's longitude.
2498
1695
  */
2499
1696
  async sendLocation(chatId, latitude, longitude, params) {
2500
- const peer = await this.getInputPeer(chatId);
2501
- const randomId = getRandomId();
2502
- const silent = params?.disableNotification ? true : undefined;
2503
- const noforwards = params?.protectContent ? true : undefined;
2504
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
2505
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
2506
- const result = await this.api.messages.sendMedia({
2507
- peer,
2508
- random_id: randomId,
2509
- silent,
2510
- noforwards,
2511
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
2512
- send_as: sendAs,
2513
- reply_markup: replyMarkup,
2514
- media: params?.livePeriod !== undefined
2515
- ? new types.InputMediaGeoLive({
2516
- geo_point: new types.InputGeoPoint({
2517
- lat: latitude,
2518
- long: longitude,
2519
- accuracy_radius: params?.horizontalAccuracy,
2520
- }),
2521
- heading: params?.heading,
2522
- period: params.livePeriod,
2523
- proximity_notification_radius: params?.proximityAlertRadius,
2524
- })
2525
- : new types.InputMediaGeoPoint({
2526
- geo_point: new types.InputGeoPoint({
2527
- lat: latitude,
2528
- long: longitude,
2529
- accuracy_radius: params?.horizontalAccuracy,
2530
- }),
2531
- }),
2532
- message: "",
2533
- });
2534
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
2535
- return assertMessageType(message, "location");
1697
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendLocation(chatId, latitude, longitude, params);
2536
1698
  }
2537
1699
  /**
2538
1700
  * Send a contact.
@@ -2543,30 +1705,7 @@ export class Client extends ClientAbstract {
2543
1705
  * @param number The contact's phone number.
2544
1706
  */
2545
1707
  async sendContact(chatId, firstName, number, params) {
2546
- const peer = await this.getInputPeer(chatId);
2547
- const randomId = getRandomId();
2548
- const silent = params?.disableNotification ? true : undefined;
2549
- const noforwards = params?.protectContent ? true : undefined;
2550
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
2551
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
2552
- const result = await this.api.messages.sendMedia({
2553
- peer,
2554
- random_id: randomId,
2555
- silent,
2556
- noforwards,
2557
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
2558
- send_as: sendAs,
2559
- reply_markup: replyMarkup,
2560
- media: new types.InputMediaContact({
2561
- phone_number: number,
2562
- first_name: firstName,
2563
- last_name: params?.lastName ?? "",
2564
- vcard: params?.vcard ?? "",
2565
- }),
2566
- message: "",
2567
- });
2568
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
2569
- return assertMessageType(message, "contact");
1708
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendContact(chatId, firstName, number, params);
2570
1709
  }
2571
1710
  /**
2572
1711
  * Send a dice.
@@ -2575,27 +1714,7 @@ export class Client extends ClientAbstract {
2575
1714
  * @param chatId The chat to send the dice to.
2576
1715
  */
2577
1716
  async sendDice(chatId, params) {
2578
- const peer = await this.getInputPeer(chatId);
2579
- const randomId = getRandomId();
2580
- const silent = params?.disableNotification ? true : undefined;
2581
- const noforwards = params?.protectContent ? true : undefined;
2582
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
2583
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
2584
- const result = await this.api.messages.sendMedia({
2585
- peer,
2586
- random_id: randomId,
2587
- silent,
2588
- noforwards,
2589
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
2590
- send_as: sendAs,
2591
- reply_markup: replyMarkup,
2592
- media: new types.InputMediaDice({
2593
- emoticon: params?.emoji ?? "🎲",
2594
- }),
2595
- message: "",
2596
- });
2597
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
2598
- return assertMessageType(message, "dice");
1717
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendDice(chatId, params);
2599
1718
  }
2600
1719
  /**
2601
1720
  * Send a venue.
@@ -2608,35 +1727,7 @@ export class Client extends ClientAbstract {
2608
1727
  * @param address The written address of the venue.
2609
1728
  */
2610
1729
  async sendVenue(chatId, latitude, longitude, title, address, params) {
2611
- const peer = await this.getInputPeer(chatId);
2612
- const randomId = getRandomId();
2613
- const silent = params?.disableNotification ? true : undefined;
2614
- const noforwards = params?.protectContent ? true : undefined;
2615
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
2616
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
2617
- const result = await this.api.messages.sendMedia({
2618
- peer,
2619
- random_id: randomId,
2620
- silent,
2621
- noforwards,
2622
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
2623
- send_as: sendAs,
2624
- reply_markup: replyMarkup,
2625
- media: new types.InputMediaVenue({
2626
- geo_point: new types.InputGeoPoint({
2627
- lat: latitude,
2628
- long: longitude,
2629
- }),
2630
- title,
2631
- address,
2632
- venue_id: params?.foursquareId ?? "",
2633
- venue_type: params?.foursquareType ?? "",
2634
- provider: "foursquare",
2635
- }),
2636
- message: "",
2637
- });
2638
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
2639
- return assertMessageType(message, "venue");
1730
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").sendVenue(chatId, latitude, longitude, title, address, params);
2640
1731
  }
2641
1732
  /**
2642
1733
  * Get network statistics. This might not always be available.
@@ -2666,32 +1757,7 @@ export class Client extends ClientAbstract {
2666
1757
  * @method
2667
1758
  */
2668
1759
  async getChats(params) {
2669
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertUser).call(this, "getChats");
2670
- if (!__classPrivateFieldGet(this, _Client_chatsLoadedFromStorage, "f")) {
2671
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_loadChatsFromStorage).call(this);
2672
- }
2673
- if (params?.after?.id && !__classPrivateFieldGet(this, _Client_chats, "f").has(params.after.id)) {
2674
- throw new Error("Invalid after");
2675
- }
2676
- let limit = params?.limit ?? 100;
2677
- if (limit <= 0 || limit > 100) {
2678
- limit = 100;
2679
- }
2680
- const listId = getChatListId(params?.from ?? "main");
2681
- let chats = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLoadedChats).call(this, listId);
2682
- if (params?.after) {
2683
- chats = chats
2684
- .filter((v) => v.order < params.after.order);
2685
- }
2686
- if (chats.length < limit) {
2687
- d("have only %d chats but %d more is needed", chats.length, limit - chats.length);
2688
- if (!await this.storage.hasAllChats(listId)) {
2689
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchChats).call(this, listId, limit, params?.after);
2690
- return await this.getChats(params);
2691
- }
2692
- }
2693
- chats = chats.slice(0, limit);
2694
- return chats;
1760
+ return await __classPrivateFieldGet(this, _Client_chatListManager, "f").getChats(params?.from, params?.after, params?.limit);
2695
1761
  }
2696
1762
  /**
2697
1763
  * Get a chat.
@@ -2705,13 +1771,13 @@ export class Client extends ClientAbstract {
2705
1771
  maybeChatId = chatId;
2706
1772
  }
2707
1773
  else if (typeof chatId === "string") {
2708
- maybeChatId = __classPrivateFieldGet(this, _Client_instances, "m", _Client_tryGetChatId).call(this, getUsername(chatId));
1774
+ maybeChatId = __classPrivateFieldGet(this, _Client_chatListManager, "f").tryGetChatId(getUsername(chatId));
2709
1775
  }
2710
1776
  else {
2711
1777
  UNREACHABLE();
2712
1778
  }
2713
1779
  if (maybeChatId != null) {
2714
- const [chat] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatAnywhere).call(this, maybeChatId);
1780
+ const [chat] = __classPrivateFieldGet(this, _Client_chatListManager, "f").getChatAnywhere(maybeChatId);
2715
1781
  if (chat !== undefined) {
2716
1782
  return chat;
2717
1783
  }
@@ -2766,159 +1832,281 @@ export class Client extends ClientAbstract {
2766
1832
  /**
2767
1833
  * Get chat history. User-only.
2768
1834
  *
2769
- * @param chatId The identifier of the chat to get its history.
2770
1835
  * @method
1836
+ * @param chatId The identifier of the chat to get its history.
2771
1837
  */
2772
1838
  async getHistory(chatId, params) {
2773
- let limit = params?.limit ?? 100;
2774
- if (limit <= 0) {
2775
- limit = 1;
2776
- }
2777
- else if (limit > 100) {
2778
- limit = 100;
2779
- }
2780
- let offsetId = params?.after?.id ?? 0;
2781
- if (offsetId < 0) {
2782
- offsetId = 0;
2783
- }
2784
- const peer = await this.getInputPeer(chatId);
2785
- const messages = new Array();
2786
- for (const message_ of await this.storage.getHistory(peerToChatId(peer), offsetId, limit)) {
2787
- const message = await constructMessage(message_, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this), false);
2788
- messages.push(message);
2789
- }
2790
- if (messages.length < limit) {
2791
- d("have only %d messages but need %d more", messages.length, limit - messages.length);
2792
- if (messages.length > 0) {
2793
- offsetId = messages[messages.length - 1].id; // TODO: track id of oldest message and don't send requests for it
2794
- }
2795
- const result = await this.api.messages.getHistory({
2796
- peer: peer,
2797
- offset_id: offsetId,
2798
- offset_date: 0,
2799
- add_offset: 0,
2800
- limit,
2801
- max_id: 0,
2802
- min_id: 0,
2803
- hash: 0n,
2804
- });
2805
- if (!("messages" in result)) {
2806
- UNREACHABLE();
2807
- }
2808
- for (const message_ of result.messages) {
2809
- const message = await constructMessage(message_, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this), false);
2810
- messages.push(message);
2811
- }
2812
- }
2813
- return messages;
1839
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").getHistory(chatId, params);
2814
1840
  }
2815
1841
  /**
2816
1842
  * Get custom emoji documents for download.
2817
1843
  *
2818
- * @param id Identifier of one or more of custom emojis.
2819
1844
  * @method
1845
+ * @param id Identifier of one or more of custom emojis.
2820
1846
  */
2821
1847
  async getCustomEmojiDocuments(id) {
2822
- id = Array.isArray(id) ? id : [id];
2823
- if (!id.length) {
2824
- throw new Error("No custom emoji ID provided");
2825
- }
2826
- const documents = new Array();
2827
- let shouldFetch = false;
2828
- for (const [i, id_] of id.entries()) {
2829
- const maybeDocument = await this.storage.getCustomEmojiDocument(BigInt(id_));
2830
- if (maybeDocument != null && Date.now() - maybeDocument[1].getTime() <= 30 * 60 * 1000) {
2831
- const document_ = maybeDocument[0];
2832
- const fileUniqueId = new FileUniqueID(FileUniqueType.Document, { mediaId: document_.id }).encode();
2833
- const fileId = new FileID(null, null, FileType.Document, document_.dc_id, {
2834
- mediaId: document_.id,
2835
- accessHash: document_.access_hash,
2836
- fileReference: document_.file_reference,
2837
- }).encode();
2838
- const document = constructDocument(document_, new types.DocumentAttributeFilename({ file_name: `${id[i] ?? "customEmoji"}.${extension(document_.mime_type)}` }), fileId, fileUniqueId);
2839
- documents.push(document);
2840
- }
2841
- else {
2842
- shouldFetch = true;
2843
- break;
2844
- }
2845
- }
2846
- if (!shouldFetch) {
2847
- return documents;
2848
- }
2849
- const documents_ = await this.api.messages.getCustomEmojiDocuments({ document_id: id.map(BigInt) }).then((v) => v.map((v) => v[as](types.Document)));
2850
- for (const [i, document_] of documents_.entries()) {
2851
- const fileUniqueId = new FileUniqueID(FileUniqueType.Document, { mediaId: document_.id }).encode();
2852
- const fileId = new FileID(null, null, FileType.Document, document_.dc_id, {
2853
- mediaId: document_.id,
2854
- accessHash: document_.access_hash,
2855
- fileReference: document_.file_reference,
2856
- }).encode();
2857
- const document = constructDocument(document_, new types.DocumentAttributeFilename({ file_name: `${id[i] ?? "customEmoji"}.${extension(document_.mime_type)}` }), fileId, fileUniqueId);
2858
- documents.push(document);
2859
- }
2860
- return documents;
1848
+ return await __classPrivateFieldGet(this, _Client_fileManager, "f").getCustomEmojiDocuments(id);
2861
1849
  }
2862
1850
  /**
2863
1851
  * Set a chat's available reactions.
2864
1852
  *
1853
+ * @method
2865
1854
  * @param chatId The identifier of the chat.
2866
1855
  * @param availableReactions The new available reactions.
2867
- * @method
2868
1856
  */
2869
1857
  async setAvailableReactions(chatId, availableReactions) {
2870
- // TODO: sync with storage
2871
- await this.api.messages.setChatAvailableReactions({
2872
- peer: await this.getInputPeer(chatId),
2873
- available_reactions: availableReactions == "none" ? new types.ChatReactionsNone() : availableReactions == "all" ? new types.ChatReactionsAll() : Array.isArray(availableReactions) ? new types.ChatReactionsSome({ reactions: availableReactions.map((v) => v.type == "emoji" ? new types.ReactionEmoji({ emoticon: v.emoji }) : new types.ReactionCustomEmoji({ document_id: BigInt(v.id) })) }) : UNREACHABLE(),
2874
- });
1858
+ await __classPrivateFieldGet(this, _Client_reactionManager, "f").setAvailableReactions(chatId, availableReactions);
2875
1859
  }
2876
1860
  /**
2877
1861
  * Change reactions made to a message.
2878
1862
  *
1863
+ * @method
2879
1864
  * @param chatId The identifier of the chat which the message belongs to.
2880
1865
  * @param messageId The identifier of the message to add the reaction to.
2881
1866
  * @param reactions The new reactions.
2882
1867
  */
2883
1868
  async setReactions(chatId, messageId, reactions, params) {
2884
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendReaction).call(this, chatId, messageId, reactions, params);
1869
+ await __classPrivateFieldGet(this, _Client_reactionManager, "f").setReactions(chatId, messageId, reactions, params);
2885
1870
  }
2886
1871
  /**
2887
1872
  * Make a reaction to a message.
2888
1873
  *
1874
+ * @method
2889
1875
  * @param chatId The identifier of the chat which the message belongs to.
2890
1876
  * @param messageId The identifier of the message to add the reaction to.
2891
1877
  * @param reaction The reaction to add.
2892
1878
  */
2893
1879
  async addReaction(chatId, messageId, reaction, params) {
2894
- const chosenReactions = await this.getMessage(chatId, messageId).then((v) => v?.reactions ?? []).then((v) => v.filter((v) => v.chosen));
2895
- for (const r of chosenReactions) {
2896
- if (reactionEqual(r.reaction, reaction)) {
2897
- return;
2898
- }
2899
- }
2900
- const reactions = [reaction, ...chosenReactions.map((v) => v.reaction)];
2901
- await this.setReactions(chatId, messageId, reactions, params);
1880
+ await __classPrivateFieldGet(this, _Client_reactionManager, "f").addReaction(chatId, messageId, reaction, params);
2902
1881
  }
2903
1882
  /**
2904
1883
  * Undo a reaction made to a message.
2905
1884
  *
1885
+ * @method
2906
1886
  * @param chatId The identifier of the chat which the message belongs to.
2907
1887
  * @param messageId The identifier of the message which the reaction was made to.
2908
1888
  * @param reaction The reaction to remove.
2909
1889
  */
2910
1890
  async removeReaction(chatId, messageId, reaction) {
2911
- const chosenReactions = await this.getMessage(chatId, messageId).then((v) => v?.reactions ?? []).then((v) => v.filter((v) => v.chosen));
2912
- for (const r of chosenReactions) {
2913
- if (reactionEqual(r.reaction, reaction)) {
2914
- const reactions = chosenReactions.filter((v) => v != r).map((v) => v.reaction);
2915
- await this.setReactions(chatId, messageId, reactions);
2916
- break;
1891
+ await __classPrivateFieldGet(this, _Client_reactionManager, "f").removeReaction(chatId, messageId, reaction);
1892
+ }
1893
+ /**
1894
+ * Set a chat's photo.
1895
+ *
1896
+ * @method
1897
+ * @param chatId The identifier of the chat.
1898
+ * @param photo A photo to set as the chat's photo.
1899
+ */
1900
+ async setChatPhoto(chatId, photo, params) {
1901
+ const peer = await this.getInputPeer(chatId);
1902
+ if (!(peer instanceof types.InputPeerChannel) && !(peer instanceof types.InputPeerChat)) {
1903
+ UNREACHABLE();
1904
+ }
1905
+ const [contents, fileName] = await getFileContents(photo);
1906
+ const file = await this.upload(contents, { fileName: params?.fileName ?? fileName, chunkSize: params?.chunkSize, signal: params?.signal });
1907
+ const photo_ = new types.InputChatUploadedPhoto({ file });
1908
+ if (peer instanceof types.InputPeerChannel) {
1909
+ await this.api.channels.editPhoto({ channel: new types.InputChannel(peer), photo: photo_ });
1910
+ }
1911
+ else if (peer instanceof types.InputPeerChat) {
1912
+ await this.api.messages.editChatPhoto({ chat_id: peer.chat_id, photo: photo_ });
1913
+ }
1914
+ }
1915
+ /**
1916
+ * Delete a chat's photo.
1917
+ *
1918
+ * @method
1919
+ * @param chatId The identifier of the chat.
1920
+ */
1921
+ async deleteChatPhoto(chatId) {
1922
+ const peer = await this.getInputPeer(chatId);
1923
+ if (!(peer instanceof types.InputPeerChannel) && !(peer instanceof types.InputPeerChat)) {
1924
+ UNREACHABLE();
1925
+ }
1926
+ if (peer instanceof types.InputPeerChannel) {
1927
+ await this.api.channels.editPhoto({ channel: new types.InputChannel(peer), photo: new types.InputChatPhotoEmpty() });
1928
+ }
1929
+ else if (peer instanceof types.InputPeerChat) {
1930
+ await this.api.messages.editChatPhoto({ chat_id: peer.chat_id, photo: new types.InputChatPhotoEmpty() });
1931
+ }
1932
+ }
1933
+ /**
1934
+ * Delete all messages sent by a specific member of a chat.
1935
+ *
1936
+ * @method
1937
+ * @param chatId The identifier of the chat. Must be a supergroup.
1938
+ * @param memberId The identifier of the member.
1939
+ */
1940
+ async deleteChatMemberMessages(chatId, memberId) {
1941
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").deleteChatMemberMessages(chatId, memberId);
1942
+ }
1943
+ /**
1944
+ * Pin a message in a chat.
1945
+ *
1946
+ * @method
1947
+ * @param chatId The identifier of the chat that contains the message.
1948
+ * @param messageId The message's identifier.
1949
+ */
1950
+ async pinMessage(chatId, messageId, params) {
1951
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").pinMessage(chatId, messageId, params);
1952
+ }
1953
+ /**
1954
+ * Unpin a pinned message.
1955
+ *
1956
+ * @method
1957
+ * @param chatId The identifier of the chat that contains the message.
1958
+ * @param messageId The message's identifier.
1959
+ */
1960
+ async unpinMessage(chatId, messageId) {
1961
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").unpinMessage(chatId, messageId);
1962
+ }
1963
+ /**
1964
+ * Unpin all pinned messages.
1965
+ *
1966
+ * @method
1967
+ * @param chatId The identifier of the chat.
1968
+ */
1969
+ async unpinMessages(chatId) {
1970
+ return await __classPrivateFieldGet(this, _Client_messageManager, "f").unpinMessages(chatId);
1971
+ }
1972
+ /**
1973
+ * Ban a member from a chat.
1974
+ *
1975
+ * @method
1976
+ * @param chatId The identifier of the chat.
1977
+ * @param memberId The identifier of the member.
1978
+ */
1979
+ async banChatMember(chatId, memberId, params) {
1980
+ const chat = await this.getInputPeer(chatId);
1981
+ if (!(chat instanceof types.InputPeerChannel) && !(chat instanceof types.InputPeerChat)) {
1982
+ throw new Error("Invalid chat ID");
1983
+ }
1984
+ const member = await this.getInputPeer(memberId);
1985
+ if (chat instanceof types.InputPeerChannel) {
1986
+ if (params?.deleteMessages) {
1987
+ try {
1988
+ await this.deleteChatMemberMessages(chatId, memberId);
1989
+ }
1990
+ catch {
1991
+ //
1992
+ }
1993
+ }
1994
+ await this.api.channels.editBanned({
1995
+ channel: new types.InputChannel(chat),
1996
+ participant: member,
1997
+ banned_rights: new types.ChatBannedRights({
1998
+ until_date: params?.untilDate ? toUnixTimestamp(params.untilDate) : 0,
1999
+ view_messages: true,
2000
+ send_messages: true,
2001
+ send_media: true,
2002
+ send_stickers: true,
2003
+ send_gifs: true,
2004
+ send_games: true,
2005
+ send_inline: true,
2006
+ embed_links: true,
2007
+ }),
2008
+ });
2009
+ }
2010
+ else if (chat instanceof types.InputPeerChat) {
2011
+ if (!(member instanceof types.InputPeerUser)) {
2012
+ throw new Error("Invalid user ID");
2917
2013
  }
2014
+ await this.api.messages.deleteChatUser({
2015
+ chat_id: chat.chat_id,
2016
+ user_id: new types.InputUser(member),
2017
+ revoke_history: params?.deleteMessages ? true : undefined,
2018
+ });
2918
2019
  }
2919
2020
  }
2021
+ /**
2022
+ * Unban a member from a chat.
2023
+ *
2024
+ * @method
2025
+ * @param chatId The identifier of the chat. Must be a supergroup.
2026
+ * @param memberId The identifier of the member.
2027
+ */
2028
+ async unbanChatMember(chatId, memberId) {
2029
+ const chat = await this.getInputPeer(chatId);
2030
+ if (!(chat instanceof types.InputPeerChannel)) {
2031
+ throw new Error("Invalid chat ID");
2032
+ }
2033
+ const member = await this.getInputPeer(memberId);
2034
+ await this.api.channels.editBanned({
2035
+ channel: new types.InputChannel(chat),
2036
+ participant: member,
2037
+ banned_rights: new types.ChatBannedRights({ until_date: 0 }),
2038
+ });
2039
+ }
2040
+ /**
2041
+ * Kick a member from a chat. Same as a banChatMember call followed by unbanChatMember.
2042
+ *
2043
+ * @method
2044
+ * @param chatId The identifier of the chat. Must be a supergroup.
2045
+ * @param memberId The identifier of the member.
2046
+ */
2047
+ async kickChatMember(chatId, memberId) {
2048
+ await this.banChatMember(chatId, memberId);
2049
+ await this.unbanChatMember(chatId, memberId);
2050
+ }
2051
+ /**
2052
+ * Set the rights of a chat member.
2053
+ *
2054
+ * @method
2055
+ * @param chatId The identifier of the chat. Must be a supergroup.
2056
+ * @param memberId The identifier of a member.
2057
+ */
2058
+ async setChatMemberRights(chatId, memberId, params) {
2059
+ const chat = await this.getInputPeer(chatId);
2060
+ if (!(chat instanceof types.InputPeerChannel)) {
2061
+ throw new Error("Invalid chat ID");
2062
+ }
2063
+ const member = await this.getInputPeer(memberId);
2064
+ await this.api.channels.editBanned({
2065
+ channel: new types.InputChannel(chat),
2066
+ participant: member,
2067
+ banned_rights: new types.ChatBannedRights({
2068
+ until_date: params?.untilDate ? toUnixTimestamp(params.untilDate) : 0,
2069
+ send_messages: params?.rights?.canSendMessages ? true : undefined,
2070
+ send_audios: params?.rights?.canSendAudio ? true : undefined,
2071
+ send_docs: params?.rights?.canSendDocuments ? true : undefined,
2072
+ send_photos: params?.rights?.canSendPhotos ? true : undefined,
2073
+ send_videos: params?.rights?.canSendVideos ? true : undefined,
2074
+ send_roundvideos: params?.rights?.canSendVideoNotes ? true : undefined,
2075
+ send_voices: params?.rights?.canSendVoice ? true : undefined,
2076
+ send_polls: params?.rights?.canSendPolls ? true : undefined,
2077
+ send_stickers: params?.rights?.canSendStickers ? true : undefined,
2078
+ send_gifs: params?.rights?.canSendAnimations ? true : undefined,
2079
+ send_games: params?.rights?.canSendGames ? true : undefined,
2080
+ send_inline: params?.rights?.canSendInlineBotResults ? true : undefined,
2081
+ embed_links: params?.rights?.canAddWebPagePreviews ? true : undefined,
2082
+ change_info: params?.rights?.canChangeInfo ? true : undefined,
2083
+ invite_users: params?.rights?.canInviteUsers ? true : undefined,
2084
+ pin_messages: params?.rights?.canPinMessages ? true : undefined,
2085
+ manage_topics: params?.rights?.canManageTopics ? true : undefined,
2086
+ }),
2087
+ });
2088
+ }
2920
2089
  }
2921
- _a = Client, _Client_getMe = async function _Client_getMe() {
2090
+ _Client_parseText = function _Client_parseText(text, params) {
2091
+ const entities_ = params?.entities ?? [];
2092
+ const parseMode = params?.parseMode ?? __classPrivateFieldGet(this, _Client_parseMode, "f");
2093
+ switch (parseMode) {
2094
+ case null:
2095
+ break;
2096
+ case "HTML": {
2097
+ const [newText, entitiesToPush] = parseHtml(text);
2098
+ text = newText;
2099
+ for (const entity of entitiesToPush) {
2100
+ entities_.push(entity);
2101
+ }
2102
+ break;
2103
+ }
2104
+ default:
2105
+ UNREACHABLE();
2106
+ }
2107
+ const entities = entities_?.length > 0 ? entities_.map((v) => messageEntityToTlObject(v)) : undefined;
2108
+ return [text, entities];
2109
+ }, _Client_getMe = async function _Client_getMe() {
2922
2110
  if (__classPrivateFieldGet(this, _Client_lastGetMe, "f") != null) {
2923
2111
  return __classPrivateFieldGet(this, _Client_lastGetMe, "f");
2924
2112
  }
@@ -2927,38 +2115,12 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
2927
2115
  __classPrivateFieldSet(this, _Client_lastGetMe, user, "f");
2928
2116
  return user;
2929
2117
  }
2930
- }, _Client_handleStoredUpdates = async function _Client_handleStoredUpdates(boxId) {
2931
- if (__classPrivateFieldGet(this, _Client_handleUpdatesSet, "f").has(boxId)) {
2932
- return;
2933
- }
2934
- __classPrivateFieldGet(this, _Client_handleUpdatesSet, "f").add(boxId);
2935
- do {
2936
- const maybeUpdate = await this.storage.getFirstUpdate(boxId);
2937
- if (maybeUpdate == null) {
2938
- break;
2939
- }
2940
- const [key, update] = maybeUpdate;
2941
- for (let i = 0; i < 100; ++i) {
2942
- try {
2943
- const handle = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleUpdate).call(this, update);
2944
- handle: for (let i = 0; i < 2; ++i) {
2945
- try {
2946
- await handle();
2947
- break handle;
2948
- }
2949
- catch {
2950
- continue handle;
2951
- }
2952
- }
2953
- break;
2954
- }
2955
- catch (err) {
2956
- d("#handleUpdate error: %o", err);
2957
- }
2958
- }
2959
- await this.storage.set(key, null);
2960
- } while (true);
2961
- __classPrivateFieldGet(this, _Client_handleUpdatesSet, "f").delete(boxId);
2118
+ }, _Client_handleCtxUpdate = async function _Client_handleCtxUpdate(update) {
2119
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, update), resolve);
2120
+ }, _Client_queueHandleCtxUpdate = function _Client_queueHandleCtxUpdate(update) {
2121
+ __classPrivateFieldGet(this, _Client_updateManager, "f").getHandleUpdateQueue(UpdateManager.MAIN_BOX_ID).add(async () => {
2122
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, update);
2123
+ });
2962
2124
  }, _Client_handleUpdate = async function _Client_handleUpdate(update) {
2963
2125
  const promises = new Array();
2964
2126
  if (update instanceof types.UpdateUserName) {
@@ -2976,7 +2138,7 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
2976
2138
  if (update.message instanceof types.Message || update.message instanceof types.MessageService) {
2977
2139
  const chatId = peerToChatId(update.message.peer_id);
2978
2140
  await this.storage.setMessage(chatId, update.message.id, update.message);
2979
- promises.push((await __classPrivateFieldGet(this, _Client_instances, "m", _Client_reassignChatLastMessage).call(this, chatId))());
2141
+ promises.push(__classPrivateFieldGet(this, _Client_chatListManager, "f").reassignChatLastMessage(chatId));
2980
2142
  }
2981
2143
  }
2982
2144
  if (update instanceof types.UpdateMessageReactions) {
@@ -2989,7 +2151,7 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
2989
2151
  const forwards = message.forwards ?? 0;
2990
2152
  const recentReactions = update.reactions.recent_reactions ?? [];
2991
2153
  const reactions = update.reactions.results.map((v) => constructMessageReaction(v, recentReactions));
2992
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { messageInteractions: { chatId, messageId: update.msg_id, reactions, views, forwards } }), resolve))());
2154
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { messageInteractions: { chatId, messageId: update.msg_id, reactions, views, forwards } }));
2993
2155
  }
2994
2156
  }
2995
2157
  else if (update instanceof types.UpdateChannelMessageViews || update instanceof types.UpdateChannelMessageForwards) {
@@ -3006,7 +2168,7 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
3006
2168
  const forwards = message.forwards ?? 0;
3007
2169
  const recentReactions = message.reactions?.recent_reactions ?? [];
3008
2170
  const reactions = message.reactions?.results.map((v) => constructMessageReaction(v, recentReactions)) ?? [];
3009
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { messageInteractions: { chatId, messageId: update.id, reactions, views, forwards } }), resolve))());
2171
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { messageInteractions: { chatId, messageId: update.id, reactions, views, forwards } }));
3010
2172
  }
3011
2173
  }
3012
2174
  if (update instanceof types.UpdateNewMessage ||
@@ -3020,16 +2182,14 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
3020
2182
  shouldIgnore = __classPrivateFieldGet(this, _Client_ignoreOutgoing, "f");
3021
2183
  }
3022
2184
  if (!shouldIgnore) {
3023
- const message = await constructMessage(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
2185
+ const message = await __classPrivateFieldGet(this, _Client_messageManager, "f").constructMessage(update.message);
3024
2186
  promises.push((async () => {
3025
- let context;
3026
2187
  if (update instanceof types.UpdateNewMessage || update instanceof types.UpdateNewChannelMessage) {
3027
- context = await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { message });
2188
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { message });
3028
2189
  }
3029
2190
  else {
3030
- context = await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { editedMessage: message });
2191
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { editedMessage: message });
3031
2192
  }
3032
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, context, resolve);
3033
2193
  })());
3034
2194
  }
3035
2195
  }
@@ -3045,12 +2205,12 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
3045
2205
  if (deletedMessages.length > 0) {
3046
2206
  promises.push((async () => {
3047
2207
  try {
3048
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages }), resolve);
2208
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { deletedMessages });
3049
2209
  }
3050
2210
  finally {
3051
2211
  for (const { chatId, messageId } of deletedMessages) {
3052
2212
  await this.storage.setMessage(chatId, messageId, null);
3053
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_reassignChatLastMessage).call(this, chatId);
2213
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").reassignChatLastMessage(chatId);
3054
2214
  }
3055
2215
  }
3056
2216
  })());
@@ -3068,424 +2228,58 @@ _a = Client, _Client_getMe = async function _Client_getMe() {
3068
2228
  if (deletedMessages.length > 0) {
3069
2229
  promises.push((async () => {
3070
2230
  try {
3071
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages }), resolve);
2231
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { deletedMessages });
3072
2232
  }
3073
2233
  finally {
3074
2234
  for (const { chatId, messageId } of deletedMessages) {
3075
2235
  await this.storage.setMessage(chatId, messageId, null);
3076
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_reassignChatLastMessage).call(this, chatId);
2236
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").reassignChatLastMessage(chatId);
3077
2237
  }
3078
2238
  }
3079
2239
  })());
3080
2240
  }
3081
2241
  }
3082
2242
  if (update instanceof types.UpdateBotCallbackQuery || update instanceof types.UpdateInlineBotCallbackQuery) {
3083
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), resolve))());
2243
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), __classPrivateFieldGet(this, _Client_messageManager, "f").getMessageWithReply.bind(this)) }));
3084
2244
  }
3085
2245
  else if (update instanceof types.UpdateBotInlineQuery) {
3086
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }), resolve))());
2246
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }));
3087
2247
  }
3088
2248
  else if (update instanceof types.UpdateBotInlineSend) {
3089
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { chosenInlineResult: await constructChosenInlineResult(update, this[getEntity].bind(this)) }), resolve))());
2249
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { chosenInlineResult: await constructChosenInlineResult(update, this[getEntity].bind(this)) }));
3090
2250
  }
3091
2251
  else if (update instanceof types.UpdateBotMessageReactions) {
3092
- const date = new Date(update.date * 1000);
3093
- const reactions = update.reactions.map((v) => constructReactionCount(v));
3094
- const entity = await this[getEntity](update.peer);
3095
- if (entity) {
3096
- const chat = constructChatP(entity);
3097
- const messageId = update.msg_id;
3098
- const messageReactionCount = { chat, messageId, date, reactions };
3099
- promises.push((async () => __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { messageReactionCount }), resolve))());
2252
+ const messageReactionCount = await constructMessageReactionCount(update, this[getEntity].bind(this));
2253
+ if (messageReactionCount) {
2254
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { messageReactionCount }));
2255
+ }
2256
+ }
2257
+ else if (update instanceof types.UpdateBotMessageReaction) {
2258
+ const messageReactions = await constructMessageReactions(update, this[getEntity].bind(this));
2259
+ if (messageReactions) {
2260
+ promises.push(__classPrivateFieldGet(this, _Client_instances, "m", _Client_handleCtxUpdate).call(this, { messageReactions }));
3100
2261
  }
3101
2262
  }
3102
2263
  if (update instanceof types.UpdatePinnedDialogs) {
3103
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatePinnedChats).call(this, update);
2264
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").handleUpdatePinnedDialogs(update);
2265
+ }
2266
+ else if (update instanceof types.UpdateFolderPeers) {
2267
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").handelUpdateFolderPeers(update);
3104
2268
  }
3105
2269
  if (update instanceof types.UpdateChannel) {
3106
- const peer = new types.PeerChannel(update);
3107
- const channel = await this[getEntity](peer);
3108
- if (channel != null && "left" in channel && channel.left) {
3109
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_removeChat).call(this, peerToChatId(peer));
3110
- }
3111
- else if (channel instanceof types.ChannelForbidden) {
3112
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_removeChat).call(this, peerToChatId(peer));
3113
- }
3114
- else if (channel instanceof types.Channel) {
3115
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updateOrAddChat).call(this, peerToChatId(peer));
3116
- }
2270
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").handleUpdateChannel(update);
3117
2271
  }
3118
- else if (update instanceof types.UpdateChat) { // TODO: handle deactivated (migration)
3119
- const peer = new types.PeerChat(update);
3120
- const chat = await this[getEntity](peer);
3121
- if (chat != null && "left" in chat && chat.left) {
3122
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_removeChat).call(this, peerToChatId(peer));
3123
- }
3124
- else if (chat instanceof types.ChatForbidden) {
3125
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_removeChat).call(this, peerToChatId(peer));
3126
- }
3127
- else if (chat instanceof types.Chat) {
3128
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updateOrAddChat).call(this, peerToChatId(peer));
3129
- }
2272
+ else if (update instanceof types.UpdateChat) {
2273
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").handleUpdateChat(update);
3130
2274
  }
3131
2275
  else if (update instanceof types.UpdateUser || update instanceof types.UpdateUserName) {
3132
- const peer = new types.PeerUser(update);
3133
- const chat = await this[getEntity](peer);
3134
- if (chat != null) {
3135
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updateOrAddChat).call(this, peerToChatId(peer));
3136
- }
2276
+ await __classPrivateFieldGet(this, _Client_chatListManager, "f").handleUpdateUser(update);
3137
2277
  }
3138
2278
  return () => Promise.all(promises);
3139
- }, _Client_constructReplyMarkup = async function _Client_constructReplyMarkup(params) {
3140
- if (params?.replyMarkup) {
3141
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertBot).call(this, "replyMarkup");
3142
- return replyMarkupToTlObject(params.replyMarkup, __classPrivateFieldGet(this, _Client_usernameResolver, "f").bind(this));
3143
- }
3144
2279
  }, _Client_setMyInfo =
3145
2280
  //#endregion
3146
2281
  async function _Client_setMyInfo(info) {
3147
2282
  await this.api.bots.setBotInfo({ bot: new types.InputUserSelf(), ...info });
3148
2283
  }, _Client_getMyInfo = function _Client_getMyInfo(languageCode) {
3149
2284
  return this.api.bots.getBotInfo({ bot: new types.InputUserSelf(), lang_code: languageCode ?? "" });
3150
- }, _Client_resolveFileId = function _Client_resolveFileId(maybeFileId, expectedFileType) {
3151
- let fileId = null;
3152
- try {
3153
- fileId = FileID.decode(maybeFileId);
3154
- }
3155
- catch (err) {
3156
- d("fileId: %o", err);
3157
- }
3158
- if (fileId != null) {
3159
- if (fileId.fileType != expectedFileType) {
3160
- UNREACHABLE();
3161
- }
3162
- if (fileId.params.mediaId == undefined || fileId.params.accessHash == undefined || fileId.params.fileReference == undefined) {
3163
- UNREACHABLE();
3164
- }
3165
- return {
3166
- id: fileId.params.mediaId,
3167
- access_hash: fileId.params.accessHash,
3168
- file_reference: fileId.params.fileReference,
3169
- };
3170
- }
3171
- return null;
3172
- }, _Client_sendMedia = async function _Client_sendMedia(chatId, media, params) {
3173
- const peer = await this.getInputPeer(chatId);
3174
- const randomId = getRandomId();
3175
- const silent = params?.disableNotification ? true : undefined;
3176
- const noforwards = params?.protectContent ? true : undefined;
3177
- const sendAs = params?.sendAs ? await this.getInputPeer(params.sendAs) : undefined; // TODO: check default sendAs
3178
- const replyMarkup = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyMarkup).call(this, params);
3179
- const caption_ = params?.caption;
3180
- const parseResult = caption_ !== undefined ? __classPrivateFieldGet(this, _Client_instances, "m", _Client_parseText).call(this, caption_, { parseMode: params?.parseMode, entities: params?.captionEntities }) : undefined;
3181
- const caption = parseResult === undefined ? undefined : parseResult[0];
3182
- const captionEntities = parseResult === undefined ? undefined : parseResult[1];
3183
- const result = await this.api.messages.sendMedia({
3184
- peer,
3185
- random_id: randomId,
3186
- silent,
3187
- noforwards,
3188
- reply_markup: replyMarkup,
3189
- reply_to: __classPrivateFieldGet(this, _Client_instances, "m", _Client_constructReplyTo).call(this, params),
3190
- send_as: sendAs,
3191
- media,
3192
- message: caption ?? "",
3193
- entities: captionEntities,
3194
- });
3195
- return await __classPrivateFieldGet(this, _Client_instances, "m", _Client_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
3196
- }, _Client_sendDocumentInner = async function _Client_sendDocumentInner(chatId, document, params, fileType, otherAttribs, urlSupported = false) {
3197
- let media = null;
3198
- const spoiler = params?.hasSpoiler ? true : undefined;
3199
- if (typeof document === "string") {
3200
- const fileId = __classPrivateFieldGet(this, _Client_instances, "m", _Client_resolveFileId).call(this, document, fileType);
3201
- if (fileId != null) {
3202
- media = new types.InputMediaDocument({
3203
- id: new types.InputDocument(fileId),
3204
- spoiler,
3205
- });
3206
- }
3207
- }
3208
- if (media == null) {
3209
- if (typeof document === "string" && isHttpUrl(document)) {
3210
- if (!urlSupported) {
3211
- throw new Error("URL not supported");
3212
- }
3213
- media = new types.InputMediaDocumentExternal({ url: document, spoiler });
3214
- }
3215
- else {
3216
- const [contents, fileName_] = await getFileContents(document);
3217
- const fileName = params?.fileName ?? fileName_;
3218
- const mimeType = params?.mimeType ?? contentType(fileName.split(".").slice(-1)[0]) ?? "application/octet-stream";
3219
- const file = await this.upload(contents, { fileName, chunkSize: params?.chunkSize, signal: params?.signal });
3220
- let thumb = undefined;
3221
- if (params?.thumbnail) {
3222
- const [thumbContents, fileName__] = await getFileContents(params.thumbnail);
3223
- thumb = await this.upload(thumbContents, { fileName: fileName__, chunkSize: params?.chunkSize, signal: params?.signal });
3224
- }
3225
- media = new types.InputMediaUploadedDocument({
3226
- file,
3227
- thumb,
3228
- spoiler,
3229
- attributes: [new types.DocumentAttributeFilename({ file_name: fileName }), ...otherAttribs],
3230
- mime_type: mimeType,
3231
- });
3232
- }
3233
- }
3234
- const message = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendMedia).call(this, chatId, media, params);
3235
- return message;
3236
- }, _Client_sendChatUpdate = async function _Client_sendChatUpdate(chatId, added) {
3237
- try {
3238
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertUser).call(this, "");
3239
- }
3240
- catch {
3241
- return;
3242
- }
3243
- const [chat] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatAnywhere).call(this, chatId);
3244
- const update = chat === undefined ? { deletedChat: { chatId } } : added ? { newChat: chat } : { editedChat: chat };
3245
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getHandleUpdateQueue).call(this, __classPrivateFieldGet(this, _Client_mainBoxId, "f")).add(async () => {
3246
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, await __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, update), resolve);
3247
- });
3248
- }, _Client_reassignChatLastMessage = async function _Client_reassignChatLastMessage(chatId, add = false, sendUpdate = true) {
3249
- try {
3250
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_assertUser).call(this, "");
3251
- }
3252
- catch {
3253
- return () => Promise.resolve();
3254
- }
3255
- const [chat, listId] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatAnywhere).call(this, chatId);
3256
- if (!chat && !add) {
3257
- return () => Promise.resolve();
3258
- }
3259
- const message_ = await this.storage.getLastMessage(chatId);
3260
- if (message_ != null) {
3261
- const message = await constructMessage(message_, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
3262
- if (chat) {
3263
- chat.order = getChatOrder(message, chat.pinned);
3264
- chat.lastMessage = message;
3265
- await this.storage.setChat(listId, chatId, chat.pinned, message.id, message.date);
3266
- }
3267
- else {
3268
- const pinnedChats = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getPinnedChats).call(this, listId);
3269
- const chat = await constructChat3(chatId, pinnedChats.indexOf(chatId), message, this[getEntity].bind(this));
3270
- if (chat == null) {
3271
- UNREACHABLE();
3272
- }
3273
- __classPrivateFieldGet(this, _Client_chats, "f").set(chatId, chat);
3274
- await this.storage.setChat(listId, chatId, chat.pinned, chat.lastMessage?.id ?? 0, chat.lastMessage?.date ?? new Date(0));
3275
- }
3276
- if (sendUpdate) {
3277
- return () => __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, !chat);
3278
- }
3279
- return () => Promise.resolve();
3280
- }
3281
- const message = await this.getHistory(chatId, { limit: 1 }).then((v) => v[0]);
3282
- if (message !== undefined) {
3283
- if (chat) {
3284
- chat.order = getChatOrder(message, chat.pinned);
3285
- chat.lastMessage = message;
3286
- await this.storage.setChat(listId, chatId, chat.pinned, message.id, message.date);
3287
- }
3288
- else {
3289
- const pinnedChats = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getPinnedChats).call(this, listId);
3290
- const chat = await constructChat3(chatId, pinnedChats.indexOf(chatId), message, this[getEntity].bind(this));
3291
- if (chat == null) {
3292
- UNREACHABLE();
3293
- }
3294
- __classPrivateFieldGet(this, _Client_chats, "f").set(chatId, chat);
3295
- }
3296
- if (sendUpdate) {
3297
- return () => __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, !chat);
3298
- }
3299
- return () => Promise.resolve();
3300
- }
3301
- if (chat) {
3302
- chat.order = getChatOrder(undefined, chat.pinned);
3303
- chat.lastMessage = undefined;
3304
- if (sendUpdate) {
3305
- return () => __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, false);
3306
- }
3307
- }
3308
- return () => Promise.resolve();
3309
- }, _Client_tryGetChatId = function _Client_tryGetChatId(username) {
3310
- username = username.toLowerCase();
3311
- for (const chat of __classPrivateFieldGet(this, _Client_chats, "f").values()) {
3312
- if ("username" in chat) {
3313
- if (chat.username === username || chat.also?.some((v) => v.toLowerCase() === username)) {
3314
- return chat.id;
3315
- }
3316
- }
3317
- }
3318
- for (const chat of __classPrivateFieldGet(this, _Client_archivedChats, "f").values()) {
3319
- if ("username" in chat) {
3320
- if (chat.username === username || chat.also?.some((v) => v.toLowerCase() === username)) {
3321
- return chat.id;
3322
- }
3323
- }
3324
- }
3325
- return null;
3326
- }, _Client_getChatAnywhere = function _Client_getChatAnywhere(chatId) {
3327
- let chat = __classPrivateFieldGet(this, _Client_chats, "f").get(chatId);
3328
- if (chat) {
3329
- return [chat, 0];
3330
- }
3331
- chat = __classPrivateFieldGet(this, _Client_archivedChats, "f").get(chatId);
3332
- if (chat) {
3333
- return [chat, 1];
3334
- }
3335
- return [undefined, -1];
3336
- }, _Client_getChatList = function _Client_getChatList(listId) {
3337
- switch (listId) {
3338
- case 0:
3339
- return __classPrivateFieldGet(this, _Client_chats, "f");
3340
- case 1:
3341
- return __classPrivateFieldGet(this, _Client_archivedChats, "f");
3342
- default:
3343
- throw new Error("Invalid chat list: " + listId);
3344
- }
3345
- }, _Client_loadChatsFromStorage = async function _Client_loadChatsFromStorage() {
3346
- const chats = await this.storage.getChats(0);
3347
- const archivedChats = await this.storage.getChats(1);
3348
- for (const { chatId, pinned, topMessageId } of chats) {
3349
- const chat = await constructChat4(chatId, pinned, topMessageId, this[getEntity].bind(this), this.getMessage.bind(this));
3350
- if (chat == null) {
3351
- continue;
3352
- }
3353
- __classPrivateFieldGet(this, _Client_chats, "f").set(chat.id, chat);
3354
- }
3355
- for (const { chatId, pinned, topMessageId } of archivedChats) {
3356
- const chat = await constructChat4(chatId, pinned, topMessageId, this[getEntity].bind(this), this.getMessage.bind(this));
3357
- if (chat == null) {
3358
- continue;
3359
- }
3360
- __classPrivateFieldGet(this, _Client_archivedChats, "f").set(chat.id, chat);
3361
- }
3362
- __classPrivateFieldSet(this, _Client_chatsLoadedFromStorage, true, "f");
3363
- }, _Client_getLoadedChats = function _Client_getLoadedChats(listId) {
3364
- const chats_ = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, listId);
3365
- const chats = new Array();
3366
- for (const chat of chats_.values()) {
3367
- chats.push(chat);
3368
- }
3369
- return chats
3370
- .sort((a, b) => b.id - a.id)
3371
- .sort((a, b) => b.order.localeCompare(a.order));
3372
- }, _Client_loadPinnedChats = async function _Client_loadPinnedChats() {
3373
- const [pinnedChats, pinnedArchiveChats] = await Promise.all([this.storage.getPinnedChats(0), this.storage.getPinnedChats(1)]);
3374
- if (pinnedChats != null && pinnedArchiveChats != null) {
3375
- __classPrivateFieldSet(this, _Client_pinnedChats, pinnedChats, "f");
3376
- __classPrivateFieldSet(this, _Client_pinnedArchiveChats, pinnedArchiveChats, "f");
3377
- __classPrivateFieldSet(this, _Client_storageHadPinnedChats, true, "f");
3378
- }
3379
- __classPrivateFieldSet(this, _Client_pinnedChatsLoaded, true, "f");
3380
- }, _Client_fetchPinnedChats = async function _Client_fetchPinnedChats(listId = null) {
3381
- if (listId == null || listId == 0) {
3382
- const dialogs = await this.api.messages.getPinnedDialogs({ folder_id: 0 });
3383
- const pinnedChats = new Array();
3384
- for (const dialog of dialogs.dialogs) {
3385
- pinnedChats.push(peerToChatId(dialog.peer));
3386
- }
3387
- __classPrivateFieldSet(this, _Client_pinnedChats, pinnedChats, "f");
3388
- await this.storage.setPinnedChats(0, __classPrivateFieldGet(this, _Client_pinnedChats, "f"));
3389
- }
3390
- if (listId == null || listId == 1) {
3391
- const dialogs = await this.api.messages.getPinnedDialogs({ folder_id: 1 });
3392
- const pinnedArchiveChats = new Array();
3393
- for (const dialog of dialogs.dialogs) {
3394
- pinnedArchiveChats.push(peerToChatId(dialog.peer));
3395
- }
3396
- __classPrivateFieldSet(this, _Client_pinnedArchiveChats, pinnedArchiveChats, "f");
3397
- await this.storage.setPinnedChats(1, __classPrivateFieldGet(this, _Client_pinnedArchiveChats, "f"));
3398
- }
3399
- if (listId != null && listId != 0 && listId != 1) {
3400
- UNREACHABLE();
3401
- }
3402
- }, _Client_getPinnedChats = async function _Client_getPinnedChats(listId) {
3403
- if (!__classPrivateFieldGet(this, _Client_pinnedChatsLoaded, "f")) {
3404
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_loadPinnedChats).call(this);
3405
- }
3406
- if (!__classPrivateFieldGet(this, _Client_storageHadPinnedChats, "f")) {
3407
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchPinnedChats).call(this);
3408
- }
3409
- switch (listId) {
3410
- case 0:
3411
- return __classPrivateFieldGet(this, _Client_pinnedChats, "f");
3412
- case 1:
3413
- return __classPrivateFieldGet(this, _Client_pinnedArchiveChats, "f");
3414
- default:
3415
- UNREACHABLE();
3416
- }
3417
- }, _Client_updateOrAddChat = async function _Client_updateOrAddChat(chatId) {
3418
- const [chat, listId] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatAnywhere).call(this, chatId);
3419
- if (chat !== undefined) {
3420
- const newChat = await constructChat3(chatId, chat.pinned, chat.lastMessage, this[getEntity].bind(this));
3421
- if (newChat != null) {
3422
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, listId).set(chatId, newChat);
3423
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, false);
3424
- }
3425
- }
3426
- else {
3427
- const chat = await constructChat4(chatId, -1, -1, this[getEntity].bind(this), this.getMessage.bind(this));
3428
- if (chat != null) {
3429
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, 0).set(chatId, chat);
3430
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_reassignChatLastMessage).call(this, chatId, false, false);
3431
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, true);
3432
- }
3433
- }
3434
- }, _Client_removeChat = async function _Client_removeChat(chatId) {
3435
- const [chat, listId] = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatAnywhere).call(this, chatId);
3436
- if (chat !== undefined) {
3437
- __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, listId).delete(chatId);
3438
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, false);
3439
- }
3440
- }, _Client_updatePinnedChats = async function _Client_updatePinnedChats(update) {
3441
- const listId = update.folder_id ?? 0;
3442
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_fetchPinnedChats).call(this, update.folder_id);
3443
- const chats = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, listId);
3444
- const pinnedChats = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getPinnedChats).call(this, listId);
3445
- for (const [i, chatId] of pinnedChats.entries()) {
3446
- const chat = chats.get(chatId);
3447
- if (chat !== undefined) {
3448
- chat.order = getChatOrder(chat.lastMessage, i);
3449
- chat.pinned = i;
3450
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chatId, false);
3451
- }
3452
- }
3453
- for (const chat of chats.values()) {
3454
- if (chat.pinned != -1 && pinnedChats.indexOf(chat.id) == -1) {
3455
- chat.order = getChatOrder(chat.lastMessage, -1);
3456
- chat.pinned = -1;
3457
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_sendChatUpdate).call(this, chat.id, false);
3458
- }
3459
- }
3460
- await this.storage.setPinnedChats(listId, await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getPinnedChats).call(this, listId));
3461
- }, _Client_fetchChats = async function _Client_fetchChats(listId, limit, after) {
3462
- const dialogs = await this.api.messages.getDialogs({
3463
- limit,
3464
- offset_id: after?.lastMessage?.id ?? 0,
3465
- offset_date: after?.lastMessage?.date ? Math.ceil(after.lastMessage.date.getTime() / 1000) : 0,
3466
- offset_peer: after ? await this.getInputPeer(after.id) : new types.InputPeerEmpty(),
3467
- hash: 0n,
3468
- folder_id: listId,
3469
- });
3470
- const pinnedChats = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getPinnedChats).call(this, listId);
3471
- if (!(dialogs instanceof types.messages.Dialogs) && !(dialogs instanceof types.messages.DialogsSlice)) {
3472
- UNREACHABLE();
3473
- }
3474
- if (dialogs.dialogs.length < limit) {
3475
- await this.storage.setHasAllChats(listId, true);
3476
- }
3477
- const chats = __classPrivateFieldGet(this, _Client_instances, "m", _Client_getChatList).call(this, listId);
3478
- for (const dialog of dialogs.dialogs) {
3479
- const chat = await constructChat(dialog, dialogs, pinnedChats, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
3480
- chats.set(chat.id, chat);
3481
- await this.storage.setChat(listId, chat.id, chat.pinned, chat.lastMessage?.id ?? 0, chat.lastMessage?.date ?? new Date(0));
3482
- }
3483
- }, _Client_sendReaction = async function _Client_sendReaction(chatId, messageId, reactions, params) {
3484
- await this.api.messages.sendReaction({
3485
- peer: await this.getInputPeer(chatId),
3486
- msg_id: messageId,
3487
- reaction: reactions.map((v) => reactionToTlObject(v)),
3488
- big: params?.big ? true : undefined,
3489
- add_to_recent: params?.addToRecents ? true : undefined,
3490
- });
3491
2285
  };