@imessaging/telegram-mtproto 0.6.7 → 0.7.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imessaging/telegram-mtproto",
3
- "version": "0.6.7",
3
+ "version": "0.7.1",
4
4
  "description": "Telegram MTProto user-account transport for imessaging",
5
5
  "keywords": [
6
6
  "messaging",
@@ -31,7 +31,7 @@
31
31
  "test": "bun test"
32
32
  },
33
33
  "dependencies": {
34
- "@imessaging/core": "0.6.0",
34
+ "@imessaging/core": "^0.7.1",
35
35
  "big-integer": "^1.6.52"
36
36
  },
37
37
  "peerDependencies": {
package/src/incoming.ts CHANGED
@@ -18,6 +18,12 @@ export type MtprotoMessageLike = {
18
18
  fromId?: MtprotoPeerLike;
19
19
  media?: MtprotoMediaLike;
20
20
  replyTo?: { replyToMsgId?: number | string };
21
+ /** Заголовок форварда. Пусто — сообщение своё, не пересланное. */
22
+ fwdFrom?: {
23
+ fromId?: MtprotoPeerLike;
24
+ fromName?: string;
25
+ channelPost?: number;
26
+ };
21
27
  /**
22
28
  * Отправитель целиком — его приносит обновление вместе с `accessHash`.
23
29
  *
@@ -31,7 +37,9 @@ export type MtprotoMessageLike = {
31
37
  * Без него ответить по одному номеру нельзя: клиент знает только тех, кого уже разрешал, а
32
38
  * `accessHash` из обновления больше нигде не хранится.
33
39
  */
34
- getInputSender?: () => Promise<{ userId?: { toString(): string }; accessHash?: { toString(): string } } | undefined>;
40
+ getInputSender?: () => Promise<
41
+ { userId?: { toString(): string }; accessHash?: { toString(): string } } | undefined
42
+ >;
35
43
  /** Отправитель целиком. Обращение к сущностям обновления, а не поход в сеть. */
36
44
  getSender?: () => Promise<{ username?: string } | undefined>;
37
45
  };
@@ -64,7 +72,8 @@ export function peerToChat(peer: MtprotoPeerLike | undefined): {
64
72
  } {
65
73
  if (peer?.channelId !== undefined)
66
74
  return { chatId: `-100${peer.channelId.toString()}`, chatType: "channel" };
67
- if (peer?.chatId !== undefined) return { chatId: `-${peer.chatId.toString()}`, chatType: "group" };
75
+ if (peer?.chatId !== undefined)
76
+ return { chatId: `-${peer.chatId.toString()}`, chatType: "group" };
68
77
  if (peer?.userId !== undefined) return { chatId: peer.userId.toString(), chatType: "user" };
69
78
  throw new Error("MTProto peer without userId, chatId or channelId");
70
79
  }
@@ -81,6 +90,25 @@ export function unmarkPeerId(chatId: string): string {
81
90
  return chatId;
82
91
  }
83
92
 
93
+ /**
94
+ * Источник форварда → общий вид.
95
+ *
96
+ * Пир источника МОЖЕТ отсутствовать: автор форварда вправе скрыть его. Тогда остаётся имя, а
97
+ * иногда и оно пустое — и это честнее выдумывания, чем подстановка чата, в котором сообщение лежит.
98
+ */
99
+ function toForwardedFrom(
100
+ fwdFrom: MtprotoMessageLike["fwdFrom"],
101
+ ): IncomingMessage["forwardedFrom"] {
102
+ if (!fwdFrom) return undefined;
103
+ const peer = fwdFrom.fromId ? peerToChat(fwdFrom.fromId) : null;
104
+ return {
105
+ chatId: peer?.chatId,
106
+ chatType: peer?.chatType,
107
+ title: fwdFrom.fromName,
108
+ messageId: fwdFrom.channelPost === undefined ? undefined : String(fwdFrom.channelPost),
109
+ };
110
+ }
111
+
84
112
  /**
85
113
  * Что приехало файлом.
86
114
  *
@@ -154,6 +182,7 @@ export function toIncomingMessage(
154
182
  message.replyTo?.replyToMsgId === undefined
155
183
  ? undefined
156
184
  : String(message.replyTo.replyToMsgId),
185
+ forwardedFrom: toForwardedFrom(message.fwdFrom),
157
186
  };
158
187
  }
159
188
 
@@ -243,7 +243,9 @@ export class TelegramMtprotoTransport
243
243
  * Повторы неизбежны и это нормально: потребитель обязан отсеивать по идентификатору сообщения,
244
244
  * а не полагаться на то, что канал не повторится. Он и так повторяется в обычной жизни.
245
245
  */
246
- async catchUp(options: { limit?: number; dialogs?: number; sinceMs?: number } = {}): Promise<number> {
246
+ async catchUp(
247
+ options: { limit?: number; dialogs?: number; sinceMs?: number } = {},
248
+ ): Promise<number> {
247
249
  const limit = options.limit ?? 20;
248
250
  // ГРАНИЦА ПО ВРЕМЕНИ ОБЯЗАТЕЛЬНА ПО СМЫСЛУ: без неё первый же опрос поднимает всю доступную
249
251
  // историю каждого диалога и отдаёт её потребителю как новьё. Замер 07.09.2026 — сотни старых
@@ -402,7 +404,7 @@ export class TelegramMtprotoTransport
402
404
  * «мы этому человеку ещё не писали и он нам тоже», а не поломку.
403
405
  */
404
406
  private async knownInputPeer(recipient: MessageRecipient): Promise<Api.TypeInputPeer | null> {
405
- if (recipient.type === "email" || recipient.type === "username") return null;
407
+ if (!isTelegramRecipient(recipient) || recipient.type === "username") return null;
406
408
  // Обычной группе ни клиент, ни хранилище не нужны: `InputPeerChat` строится из одного номера.
407
409
  if (recipient.type === "group") {
408
410
  return new Api.InputPeerChat({ chatId: bigInt(unmarkPeerId(recipient.id)) });
@@ -418,7 +420,10 @@ export class TelegramMtprotoTransport
418
420
  // Почтовый получатель сюда доходить не должен: разрешать адрес как @username бессмысленно, а
419
421
  // сообщение об отказе тогда врало бы про Telegram.
420
422
  if (!isTelegramRecipient(recipient)) {
421
- throw new Error("Telegram MTProto cannot send email");
423
+ if (recipient.type === "email") {
424
+ throw new Error("Telegram MTProto cannot send email");
425
+ }
426
+ throw new Error(`Telegram MTProto cannot address ${recipient.type}`);
422
427
  }
423
428
  if (recipient.type !== "username" && !recipient.username) {
424
429
  throw new Error(