feat(protocol): send and receive official my-device chats
Pad and phone device conversations were missing from the friend list and arrived as empty private messages. They now show up as stable contacts and support text send/receive. Fixes #452
This commit is contained in:
16 files changed
+692
-17
No files matched your search
@@ -1,4 +1,5 @@
|
|||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
|
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
import { ApproveDoubtBuddyReq } from '@snowluma/protocol/oidb-services/friend/approve-doubt-buddy-req';
|
||||||
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
import { ClearFriendRemark } from '@snowluma/protocol/oidb-services/friend/clear-friend-remark';
|
||||||
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
import { DeleteFriend } from '@snowluma/protocol/oidb-services/friend/delete-friend';
|
||||||
@@ -24,6 +25,9 @@ export class FriendApi {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async delete(userId: number, block = false): Promise<void> {
|
async delete(userId: number, block = false): Promise<void> {
|
||||||
|
if (findDatalineDeviceByUin(userId)) {
|
||||||
|
throw new Error('this contact cannot be deleted');
|
||||||
|
}
|
||||||
await DeleteFriend.invoke(this.ctx, { userId, block });
|
await DeleteFriend.invoke(this.ctx, { userId, block });
|
||||||
|
|
||||||
// The server-side delete has already completed. A refresh failure must be
|
// The server-side delete has already completed. A refresh failure must be
|
||||||
@@ -40,11 +44,15 @@ export class FriendApi {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setRemark(userId: number, remark: string): Promise<void> {
|
async setRemark(userId: number, remark: string): Promise<void> {
|
||||||
if (remark === '') {
|
if (findDatalineDeviceByUin(userId)) {
|
||||||
return ClearFriendRemark.invoke(this.ctx, { userId });
|
throw new Error('this contact does not support remarks');
|
||||||
}
|
}
|
||||||
return SetFriendRemark.invoke(this.ctx, { userId, remark });
|
if (remark === '') {
|
||||||
|
await ClearFriendRemark.invoke(this.ctx, { userId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await SetFriendRemark.invoke(this.ctx, { userId, remark });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** List doubtful friend-add requests (可能认识的人). */
|
/** List doubtful friend-add requests (可能认识的人). */
|
||||||
|
|||||||
@@ -14,6 +14,14 @@ import type {
|
|||||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||||
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
|
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
|
||||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||||
|
import {
|
||||||
|
datalineTextFromElements,
|
||||||
|
encodeDatalineText,
|
||||||
|
} from '@snowluma/protocol/dataline/codec';
|
||||||
|
import {
|
||||||
|
findDatalineDeviceByUin,
|
||||||
|
type DatalineDeviceContact,
|
||||||
|
} from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||||
import {
|
import {
|
||||||
fetchC2cMessageRange,
|
fetchC2cMessageRange,
|
||||||
@@ -417,6 +425,8 @@ export class MessageApi {
|
|||||||
* (and optionally `c2c.uid` for the media case).
|
* (and optionally `c2c.uid` for the media case).
|
||||||
*/
|
*/
|
||||||
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||||
|
const device = findDatalineDeviceByUin(userUin);
|
||||||
|
if (device) return this.sendDatalineText(device, elements);
|
||||||
if (elements.length === 0) throw new Error('message is empty');
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
assertWindowShakeSendPolicy(
|
assertWindowShakeSendPolicy(
|
||||||
elements.filter((element) => element.type === 'poke').length,
|
elements.filter((element) => element.type === 'poke').length,
|
||||||
@@ -483,6 +493,67 @@ export class MessageApi {
|
|||||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send text to an official my-device contact. These peers are not
|
||||||
|
* ordinary friends — they use the same trans0x211 send path as c2c
|
||||||
|
* files, with a device-chat body instead of FileExtra.
|
||||||
|
*/
|
||||||
|
private async sendDatalineText(
|
||||||
|
device: DatalineDeviceContact,
|
||||||
|
elements: MessageElement[],
|
||||||
|
): Promise<SendMessageReceipt> {
|
||||||
|
const text = datalineTextFromElements(elements);
|
||||||
|
const selfUin = parseInt(this.ctx.identity.uin, 10);
|
||||||
|
if (!Number.isSafeInteger(selfUin) || selfUin <= 0) {
|
||||||
|
throw new Error('self uin unavailable');
|
||||||
|
}
|
||||||
|
|
||||||
|
const random = this.ctx.nextMessageRandom();
|
||||||
|
const clientSeq = this.ctx.nextClientSequence();
|
||||||
|
const nowSec = Math.floor(Date.now() / 1000);
|
||||||
|
const request = protobuf_encode<SendMessageRequest>({
|
||||||
|
routingHead: {
|
||||||
|
trans0x211: {
|
||||||
|
toUin: BigInt(selfUin),
|
||||||
|
ccCmd: 7,
|
||||||
|
uid: device.uid,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
contentHead: {
|
||||||
|
type: 1,
|
||||||
|
subType: 0,
|
||||||
|
},
|
||||||
|
messageBody: {
|
||||||
|
msgContent: encodeDatalineText({
|
||||||
|
selfUin,
|
||||||
|
dstTerType: device.terType,
|
||||||
|
text,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
clientSequence: clientSeq,
|
||||||
|
random,
|
||||||
|
syncCookie: new Uint8Array(0),
|
||||||
|
via: 0,
|
||||||
|
dataStatist: 0,
|
||||||
|
ctrl: { msgFlag: nowSec },
|
||||||
|
multiSendSeq: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||||
|
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||||
|
throw new Error(`send device message failed: ${result.errorMessage || 'no response'}`);
|
||||||
|
}
|
||||||
|
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||||
|
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||||
|
if (response.result != null && response.result !== 0) {
|
||||||
|
throw new Error(`send device message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||||
|
}
|
||||||
|
const seq = response.privateSequence ?? 0;
|
||||||
|
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||||
|
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||||
|
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reply into an existing group temp session (临时会话). Wire primitive only —
|
* Reply into an existing group temp session (临时会话). Wire primitive only —
|
||||||
* it does NOT gate; the caller verifies the session before calling. Routes
|
* it does NOT gate; the caller verifies the session before calling. Routes
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import type {
|
|||||||
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
|
// namespaces under @snowluma/protocol/oidb-services/friend. Tests assert
|
||||||
// against the bridge mock's sendRawPacket directly — no need for
|
// against the bridge mock's sendRawPacket directly — no need for
|
||||||
// module-level bridge-oidb mocks anymore.
|
// module-level bridge-oidb mocks anymore.
|
||||||
|
import { DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import { FriendApi } from '../../src/bridge/apis/friend';
|
import { FriendApi } from '../../src/bridge/apis/friend';
|
||||||
import { mockBridge } from './_helpers';
|
import { mockBridge } from './_helpers';
|
||||||
|
|
||||||
@@ -89,6 +90,14 @@ describe('apis/friend', () => {
|
|||||||
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
|
.toHaveBeenCalledWith('resolved-uid', 10001, 'best-friend');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('refuses to delete or rename a my-device contact', async () => {
|
||||||
|
const bridge = mockBridge();
|
||||||
|
const api = new FriendApi(bridge as any);
|
||||||
|
await expect(api.delete(DATALINE_UIN_PAD)).rejects.toThrow('cannot be deleted');
|
||||||
|
await expect(api.setRemark(DATALINE_UIN_PAD, 'pad')).rejects.toThrow('does not support remarks');
|
||||||
|
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('setRemark uses the dedicated clear command for an empty remark', async () => {
|
it('setRemark uses the dedicated clear command for an empty remark', async () => {
|
||||||
const bridge = mockBridge();
|
const bridge = mockBridge();
|
||||||
await new FriendApi(bridge as any).setRemark(10001, '');
|
await new FriendApi(bridge as any).setRemark(10001, '');
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||||
|
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
|
||||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||||
import type { FileExtra } from '@snowluma/proto-defs/message';
|
import type { FileExtra } from '@snowluma/proto-defs/message';
|
||||||
|
import { DATALINE_UIN_PHONE } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||||
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
|
import type { OidbOfflineFileFinalizeResp } from '@snowluma/proto-defs/oidb-actions/media';
|
||||||
|
|
||||||
@@ -201,4 +203,62 @@ describe('Bridge private media routing', () => {
|
|||||||
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
|
expect(fileExtra?.file?.fileUuid).toBe('uuid-abc-123');
|
||||||
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
|
expect(fileExtra?.field6 ?? undefined).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sends my-device text through trans0x211 instead of ordinary c2c', async () => {
|
||||||
|
class TestBridge extends Bridge {
|
||||||
|
capturedBody: Uint8Array | null = null;
|
||||||
|
|
||||||
|
override async sendRawPacket(serviceCmd: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||||
|
expect(serviceCmd).toBe('MessageSvc.PbSendMsg');
|
||||||
|
this.capturedBody = body;
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
gotResponse: true,
|
||||||
|
errorCode: 0,
|
||||||
|
errorMessage: '',
|
||||||
|
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||||
|
result: 0,
|
||||||
|
errMsg: '',
|
||||||
|
privateSequence: 88,
|
||||||
|
timestamp1: 1710000000,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||||
|
await bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [{ type: 'text', text: 'hello phone' }]);
|
||||||
|
|
||||||
|
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody as Uint8Array);
|
||||||
|
expect(request?.routingHead?.trans0x211).toMatchObject({
|
||||||
|
ccCmd: 7,
|
||||||
|
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
|
||||||
|
toUin: 10000n,
|
||||||
|
});
|
||||||
|
expect(request?.routingHead?.c2c ?? undefined).toBeUndefined();
|
||||||
|
const body = protobuf_decode<DatalineMsgBody>(request!.messageBody!.msgContent as Uint8Array);
|
||||||
|
expect(body?.subCmd).toBe(4);
|
||||||
|
expect(body?.header).toMatchObject({
|
||||||
|
srcAppId: 1,
|
||||||
|
dstAppId: 1001,
|
||||||
|
srcTerType: 1,
|
||||||
|
dstTerType: 2,
|
||||||
|
srcUin: 10000n,
|
||||||
|
dstUin: 10000n,
|
||||||
|
});
|
||||||
|
const text = protobuf_decode<DatalineTextMsg>(body!.generic!.buf as Uint8Array);
|
||||||
|
expect(new TextDecoder().decode(text!.items![0]!.text as Uint8Array)).toBe('hello phone');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects non-text my-device sends', async () => {
|
||||||
|
class TestBridge extends Bridge {
|
||||||
|
override async sendRawPacket(): Promise<SendPacketResult> {
|
||||||
|
throw new Error('should not send');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||||
|
await expect(bridge.apis.message.sendPrivate(DATALINE_UIN_PHONE, [
|
||||||
|
{ type: 'image', url: 'file:///tmp/a.png' } as any,
|
||||||
|
])).rejects.toThrow('only accepts text');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||||
|
import { datalineFriendListEntries, findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import {
|
import {
|
||||||
formatGroupRequestFlag,
|
formatGroupRequestFlag,
|
||||||
type GroupMemberInfo,
|
type GroupMemberInfo,
|
||||||
@@ -45,21 +46,31 @@ async function fetchSingleGroupMembers(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toFriendRow(friend: { uin: number; nickname: string; remark: string }): JsonObject {
|
||||||
|
return {
|
||||||
|
user_id: friend.uin,
|
||||||
|
nickname: friend.nickname,
|
||||||
|
remark: friend.remark,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
|
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
|
||||||
|
let rows: JsonObject[];
|
||||||
try {
|
try {
|
||||||
const friends = await bridge.apis.contacts.fetchFriendList();
|
rows = (await bridge.apis.contacts.fetchFriendList()).map(toFriendRow);
|
||||||
return friends.map(f => ({
|
|
||||||
user_id: f.uin,
|
|
||||||
nickname: f.nickname,
|
|
||||||
remark: f.remark,
|
|
||||||
}));
|
|
||||||
} catch {
|
} catch {
|
||||||
return bridge.identity.friends.map(f => ({
|
rows = bridge.identity.friends.map(toFriendRow);
|
||||||
user_id: f.uin,
|
|
||||||
nickname: f.nickname,
|
|
||||||
remark: f.remark,
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
const occupied = new Set(rows.map((row) => Number(row.user_id)));
|
||||||
|
for (const extra of datalineFriendListEntries()) {
|
||||||
|
if (occupied.has(extra.user_id)) continue;
|
||||||
|
rows.push({
|
||||||
|
user_id: extra.user_id,
|
||||||
|
nickname: extra.nickname,
|
||||||
|
remark: extra.remark,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getGroupList(
|
export async function getGroupList(
|
||||||
@@ -332,6 +343,17 @@ export async function getStrangerInfo(
|
|||||||
bridge: BridgeInterface,
|
bridge: BridgeInterface,
|
||||||
userId: number,
|
userId: number,
|
||||||
): Promise<JsonObject | null> {
|
): Promise<JsonObject | null> {
|
||||||
|
const device = findDatalineDeviceByUin(userId);
|
||||||
|
if (device) {
|
||||||
|
return {
|
||||||
|
user_id: device.uin,
|
||||||
|
nickname: device.name,
|
||||||
|
remark: device.name,
|
||||||
|
sex: 'unknown',
|
||||||
|
age: 0,
|
||||||
|
long_nick: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const p = await bridge.apis.contacts.fetchUserProfile(userId);
|
const p = await bridge.apis.contacts.fetchUserProfile(userId);
|
||||||
const corp = await strangerCorpInfo(bridge, p);
|
const corp = await strangerCorpInfo(bridge, p);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||||
|
import { findDatalineDeviceByUin } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, MessageElementOf, QQEventVariant } from '@snowluma/protocol/events';
|
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, MessageElementOf, QQEventVariant } from '@snowluma/protocol/events';
|
||||||
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
|
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
|
||||||
import { guessFileNameFromUrl } from '@snowluma/protocol/highway/utils';
|
import { guessFileNameFromUrl } from '@snowluma/protocol/highway/utils';
|
||||||
@@ -870,6 +871,17 @@ export async function sendPrivateMessage(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (findDatalineDeviceByUin(userId)) {
|
||||||
|
const unsupported = elements.find((element) => element.type !== 'text');
|
||||||
|
if (unsupported) {
|
||||||
|
throw new MessageElementValidationError(
|
||||||
|
'UNSENDABLE_TYPE',
|
||||||
|
`message element "${unsupported.type}" cannot be sent to this contact`,
|
||||||
|
unsupported.type,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Temp sessions only have the message-element transport. File elements use
|
// Temp sessions only have the message-element transport. File elements use
|
||||||
// the friend c2c upload path, so reject them before sending any preceding
|
// the friend c2c upload path, so reject them before sending any preceding
|
||||||
// text/media batch; discovering this after sendText would create a partial
|
// text/media batch; discovering this after sendText would create a partial
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
|
|
||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||||
|
import { datalineFriendListEntries, DATALINE_UIN_PAD } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import type {
|
import type {
|
||||||
FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo,
|
FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo,
|
||||||
} from '@snowluma/protocol/qq-info';
|
} from '@snowluma/protocol/qq-info';
|
||||||
@@ -158,7 +159,10 @@ describe('onebot/contact-actions / getFriendList', () => {
|
|||||||
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
|
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
|
||||||
});
|
});
|
||||||
const out = await getFriendList(bridge);
|
const out = await getFriendList(bridge);
|
||||||
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
|
expect(out).toEqual([
|
||||||
|
{ user_id: 22222, nickname: 'alice', remark: 'best-friend' },
|
||||||
|
...datalineFriendListEntries(),
|
||||||
|
]);
|
||||||
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
|
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -169,7 +173,10 @@ describe('onebot/contact-actions / getFriendList', () => {
|
|||||||
identity: fakeIdentity({ friends: cached }),
|
identity: fakeIdentity({ friends: cached }),
|
||||||
});
|
});
|
||||||
const out = await getFriendList(bridge);
|
const out = await getFriendList(bridge);
|
||||||
expect(out).toEqual([{ user_id: 33333, nickname: 'bob', remark: '' }]);
|
expect(out).toEqual([
|
||||||
|
{ user_id: 33333, nickname: 'bob', remark: '' },
|
||||||
|
...datalineFriendListEntries(),
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -709,6 +716,20 @@ describe('onebot/contact-actions / getStrangerInfo', () => {
|
|||||||
});
|
});
|
||||||
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
|
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('returns the official my-device contact without a profile fetch', async () => {
|
||||||
|
const fetchUserProfile = vi.fn(async () => { throw new Error('should not fetch'); });
|
||||||
|
const bridge = fakeBridge({ fetchUserProfile });
|
||||||
|
expect(await getStrangerInfo(bridge, DATALINE_UIN_PAD)).toEqual({
|
||||||
|
user_id: DATALINE_UIN_PAD,
|
||||||
|
nickname: '我的Pad',
|
||||||
|
remark: '我的Pad',
|
||||||
|
sex: 'unknown',
|
||||||
|
age: 0,
|
||||||
|
long_nick: '',
|
||||||
|
});
|
||||||
|
expect(fetchUserProfile).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('onebot/contact-actions / getGroupSystemMessages', () => {
|
describe('onebot/contact-actions / getGroupSystemMessages', () => {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { datalineFriendListEntries } from '@snowluma/protocol/dataline/device-contacts';
|
||||||
import type { GroupMemberInfo, GroupRequestInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
import type { GroupMemberInfo, GroupRequestInfo, QQGroupInfo } from '@snowluma/protocol/qq-info';
|
||||||
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
|
||||||
import {
|
import {
|
||||||
@@ -688,6 +689,7 @@ describe('buildApiContext contact reads', () => {
|
|||||||
|
|
||||||
await expect(api.getFriendList()).resolves.toEqual([
|
await expect(api.getFriendList()).resolves.toEqual([
|
||||||
{ user_id: 22222, nickname: 'alice', remark: 'best-friend' },
|
{ user_id: 22222, nickname: 'alice', remark: 'best-friend' },
|
||||||
|
...datalineFriendListEntries(),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,10 @@
|
|||||||
"types": "./src/collection.ts",
|
"types": "./src/collection.ts",
|
||||||
"default": "./src/collection.ts"
|
"default": "./src/collection.ts"
|
||||||
},
|
},
|
||||||
|
"./dataline": {
|
||||||
|
"types": "./src/dataline.ts",
|
||||||
|
"default": "./src/dataline.ts"
|
||||||
|
},
|
||||||
"./element": {
|
"./element": {
|
||||||
"types": "./src/element.ts",
|
"types": "./src/element.ts",
|
||||||
"default": "./src/element.ts"
|
"default": "./src/element.ts"
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import type { pb, pb_repeated, uint_32, uint_64, bytes } from '@snowluma/proton';
|
||||||
|
|
||||||
|
/** Header identifying the source/destination device on a my-device chat. */
|
||||||
|
export interface DatalineMsgHeader {
|
||||||
|
srcAppId?: pb<1, uint_32>;
|
||||||
|
srcInstId?: pb<2, uint_32>;
|
||||||
|
dstAppId?: pb<3, uint_32>;
|
||||||
|
dstInstId?: pb<4, uint_32>;
|
||||||
|
dstUin?: pb<5, uint_64>;
|
||||||
|
srcUin?: pb<6, uint_64>;
|
||||||
|
srcUinType?: pb<7, uint_32>;
|
||||||
|
dstUinType?: pb<8, uint_32>;
|
||||||
|
srcTerType?: pb<9, uint_32>;
|
||||||
|
dstTerType?: pb<10, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** File notify carried on a my-device transfer. */
|
||||||
|
export interface DatalineFtnNotify {
|
||||||
|
sessionId?: pb<1, uint_64>;
|
||||||
|
fileName?: pb<2, string>;
|
||||||
|
fileIndex?: pb<3, string>;
|
||||||
|
fileMd5?: pb<4, bytes>;
|
||||||
|
fileKey?: pb<5, string>;
|
||||||
|
fileLen?: pb<6, uint_64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generic my-device command; text lives in `buf`. */
|
||||||
|
export interface DatalineGenericSubCmd {
|
||||||
|
sessionId?: pb<1, uint_64>;
|
||||||
|
size?: pb<2, uint_32>;
|
||||||
|
index?: pb<3, uint_32>;
|
||||||
|
type?: pb<4, uint_32>;
|
||||||
|
buf?: pb<5, bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatalineTextItem {
|
||||||
|
type?: pb<1, uint_32>;
|
||||||
|
text?: pb<2, bytes>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatalineTextMsg {
|
||||||
|
items?: pb_repeated<1, DatalineTextItem>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatalineMsgBody {
|
||||||
|
subCmd?: pb<1, uint_32>;
|
||||||
|
header?: pb<2, DatalineMsgHeader>;
|
||||||
|
ftn?: pb_repeated<3, DatalineFtnNotify>;
|
||||||
|
generic?: pb<6, DatalineGenericSubCmd>;
|
||||||
|
}
|
||||||
@@ -99,6 +99,10 @@
|
|||||||
"./web/*": {
|
"./web/*": {
|
||||||
"types": "./src/web/*.ts",
|
"types": "./src/web/*.ts",
|
||||||
"default": "./src/web/*.ts"
|
"default": "./src/web/*.ts"
|
||||||
|
},
|
||||||
|
"./dataline/*": {
|
||||||
|
"types": "./src/dataline/*.ts",
|
||||||
|
"default": "./src/dataline/*.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { toHex } from '@snowluma/common/hex';
|
||||||
|
import type {
|
||||||
|
DatalineMsgBody,
|
||||||
|
DatalineTextMsg,
|
||||||
|
} from '@snowluma/proto-defs/dataline';
|
||||||
|
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||||
|
import type { MessageElement } from '../events';
|
||||||
|
import { appIdForTerType, DATALINE_SELF_TER_TYPE } from './device-contacts';
|
||||||
|
|
||||||
|
const DATALINE_SUBCMD_FTN = 1;
|
||||||
|
const DATALINE_SUBCMD_GENERIC = 4;
|
||||||
|
const DATALINE_GENERIC_TEXT = 1;
|
||||||
|
const DATALINE_TEXT_ITEM = 1;
|
||||||
|
|
||||||
|
const textEncoder = new TextEncoder();
|
||||||
|
const textDecoder = new TextDecoder();
|
||||||
|
|
||||||
|
export function encodeDatalineText(params: {
|
||||||
|
selfUin: number;
|
||||||
|
srcTerType?: number;
|
||||||
|
dstTerType: number;
|
||||||
|
text: string;
|
||||||
|
}): Uint8Array {
|
||||||
|
const srcTerType = params.srcTerType ?? DATALINE_SELF_TER_TYPE;
|
||||||
|
const textBytes = textEncoder.encode(params.text);
|
||||||
|
const buf = protobuf_encode<DatalineTextMsg>({
|
||||||
|
items: [{ type: DATALINE_TEXT_ITEM, text: textBytes }],
|
||||||
|
});
|
||||||
|
const selfUin = BigInt(params.selfUin);
|
||||||
|
return protobuf_encode<DatalineMsgBody>({
|
||||||
|
subCmd: DATALINE_SUBCMD_GENERIC,
|
||||||
|
header: {
|
||||||
|
srcAppId: appIdForTerType(srcTerType),
|
||||||
|
srcInstId: 1,
|
||||||
|
dstAppId: appIdForTerType(params.dstTerType),
|
||||||
|
dstInstId: 1,
|
||||||
|
dstUin: selfUin,
|
||||||
|
srcUin: selfUin,
|
||||||
|
srcTerType,
|
||||||
|
dstTerType: params.dstTerType,
|
||||||
|
},
|
||||||
|
generic: {
|
||||||
|
sessionId: BigInt(Date.now()),
|
||||||
|
size: 1,
|
||||||
|
index: 0,
|
||||||
|
type: DATALINE_GENERIC_TEXT,
|
||||||
|
buf,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeDatalineMsgBody(bytes: Uint8Array): DatalineMsgBody | undefined {
|
||||||
|
return protobuf_decode<DatalineMsgBody>(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function elementsFromDatalineBody(body: DatalineMsgBody): MessageElement[] {
|
||||||
|
const elements: MessageElement[] = [];
|
||||||
|
if (body.subCmd === DATALINE_SUBCMD_GENERIC || body.generic) {
|
||||||
|
const genericType = body.generic?.type ?? 0;
|
||||||
|
if (genericType === 0 || genericType === DATALINE_GENERIC_TEXT) {
|
||||||
|
const text = decodeGenericText(body.generic?.buf);
|
||||||
|
if (text.length > 0) elements.push({ type: 'text', text });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (body.subCmd === DATALINE_SUBCMD_FTN || (body.ftn && body.ftn.length > 0)) {
|
||||||
|
for (const notify of body.ftn ?? []) {
|
||||||
|
const fileName = notify.fileName?.trim();
|
||||||
|
if (!fileName && notify.fileIndex == null && notify.sessionId == null) continue;
|
||||||
|
const fileSize = notify.fileLen != null ? Number(notify.fileLen) : undefined;
|
||||||
|
elements.push({
|
||||||
|
type: 'file',
|
||||||
|
fileId: notify.fileIndex || (notify.sessionId != null ? String(notify.sessionId) : undefined),
|
||||||
|
fileName: fileName || undefined,
|
||||||
|
fileSize: fileSize != null && Number.isFinite(fileSize) ? fileSize : undefined,
|
||||||
|
md5Hex: notify.fileMd5 && notify.fileMd5.length > 0 ? toHex(notify.fileMd5) : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeGenericText(buf: Uint8Array | undefined): string {
|
||||||
|
if (!buf || buf.length === 0) return '';
|
||||||
|
const parsed = protobuf_decode<DatalineTextMsg>(buf);
|
||||||
|
const parts: string[] = [];
|
||||||
|
for (const item of parsed?.items ?? []) {
|
||||||
|
if (!item.text || item.text.length === 0) continue;
|
||||||
|
parts.push(textDecoder.decode(item.text));
|
||||||
|
}
|
||||||
|
return parts.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function datalineTextFromElements(elements: readonly MessageElement[]): string {
|
||||||
|
if (elements.length === 0) throw new Error('message is empty');
|
||||||
|
const unsupported = elements.find((element) => element.type !== 'text');
|
||||||
|
if (unsupported) {
|
||||||
|
throw new Error(`this contact only accepts text messages, got ${unsupported.type}`);
|
||||||
|
}
|
||||||
|
const text = elements
|
||||||
|
.filter((element): element is Extract<MessageElement, { type: 'text' }> => element.type === 'text')
|
||||||
|
.map((element) => element.text)
|
||||||
|
.join('');
|
||||||
|
if (text.length === 0) throw new Error('message is empty');
|
||||||
|
return text;
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import type { FriendMessage } from '../events';
|
||||||
|
import type { MsgPushContext } from '../msg-push/context';
|
||||||
|
import { decodeDatalineMsgBody, elementsFromDatalineBody } from './codec';
|
||||||
|
import {
|
||||||
|
DATALINE_SELF_TER_TYPE,
|
||||||
|
findDatalineDeviceByTerType,
|
||||||
|
} from './device-contacts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Incoming my-device chats reuse the private-file push type but carry a
|
||||||
|
* different body. Rewrite the conversation peer onto the matching device
|
||||||
|
* contact — both sides of the wire use the logged-in account number.
|
||||||
|
*/
|
||||||
|
export function tryDecodeDatalineFriendMessage(ctx: MsgPushContext): FriendMessage | null {
|
||||||
|
if (ctx.head.msgType !== 529 || ctx.head.subType !== 7) return null;
|
||||||
|
const raw = ctx.body?.msgContent;
|
||||||
|
if (!raw || raw.length === 0) return null;
|
||||||
|
const body = decodeDatalineMsgBody(raw);
|
||||||
|
if (!body) return null;
|
||||||
|
if (
|
||||||
|
body.subCmd == null
|
||||||
|
&& !body.header
|
||||||
|
&& !body.generic
|
||||||
|
&& !(body.ftn && body.ftn.length > 0)
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const elements = elementsFromDatalineBody(body);
|
||||||
|
const srcTer = body.header?.srcTerType ?? 0;
|
||||||
|
const dstTer = body.header?.dstTerType ?? 0;
|
||||||
|
const sentBySelf = srcTer === DATALINE_SELF_TER_TYPE;
|
||||||
|
const peerTer = peerTerType(srcTer, dstTer);
|
||||||
|
const peer = findDatalineDeviceByTerType(peerTer);
|
||||||
|
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
|
||||||
|
|
||||||
|
return {
|
||||||
|
kind: 'friend_message',
|
||||||
|
time: ctx.head.timestamp,
|
||||||
|
selfUin: ctx.selfUin,
|
||||||
|
senderUin: sentBySelf ? ctx.selfUin : (peer?.uin ?? ctx.fromUin),
|
||||||
|
senderUid: sentBySelf ? ctx.fromUid : (peer?.uid ?? ctx.fromUid),
|
||||||
|
...(peer ? { peerUin: peer.uin } : {}),
|
||||||
|
msgSeq: ctx.head.sequence,
|
||||||
|
ntMsgSeq: ctx.head.ntMsgSeq,
|
||||||
|
clientSeq: ctx.head.sequence,
|
||||||
|
sequenceAuthoritative,
|
||||||
|
msgId: ctx.head.msgId & 0x7FFFFFFF,
|
||||||
|
elements,
|
||||||
|
senderNick: sentBySelf ? '' : (peer?.name ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function peerTerType(srcTer: number, dstTer: number): number {
|
||||||
|
if (srcTer !== DATALINE_SELF_TER_TYPE && srcTer > 0) return srcTer;
|
||||||
|
if (dstTer !== DATALINE_SELF_TER_TYPE && dstTer > 0) return dstTer;
|
||||||
|
return dstTer || srcTer || DATALINE_SELF_TER_TYPE;
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/** Official "my computer / my phone / my Pad" device contacts. */
|
||||||
|
|
||||||
|
export const DATALINE_SELF_TER_TYPE = 1;
|
||||||
|
|
||||||
|
export const DATALINE_TER_PC = 1;
|
||||||
|
export const DATALINE_TER_PHONE = 2;
|
||||||
|
export const DATALINE_TER_PAD = 3;
|
||||||
|
|
||||||
|
/** Stable OneBot user_ids reserved for the three official device peers. */
|
||||||
|
export const DATALINE_UIN_PC = 0x7E000001;
|
||||||
|
export const DATALINE_UIN_PHONE = 0x7E000002;
|
||||||
|
export const DATALINE_UIN_PAD = 0x7E000003;
|
||||||
|
|
||||||
|
export interface DatalineDeviceContact {
|
||||||
|
readonly terType: number;
|
||||||
|
readonly uid: string;
|
||||||
|
readonly name: string;
|
||||||
|
readonly uin: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DatalineFriendEntry {
|
||||||
|
user_id: number;
|
||||||
|
nickname: string;
|
||||||
|
remark: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DATALINE_DEVICES: readonly DatalineDeviceContact[] = [
|
||||||
|
{
|
||||||
|
terType: DATALINE_TER_PC,
|
||||||
|
uid: 'u_rK7NMsbv2ZjEGPdCuOiCfw',
|
||||||
|
name: '我的电脑',
|
||||||
|
uin: DATALINE_UIN_PC,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
terType: DATALINE_TER_PHONE,
|
||||||
|
uid: 'u_Wcc5rknRRqRO8y5gxMD6sA',
|
||||||
|
name: '我的手机',
|
||||||
|
uin: DATALINE_UIN_PHONE,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
terType: DATALINE_TER_PAD,
|
||||||
|
uid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
|
||||||
|
name: '我的Pad',
|
||||||
|
uin: DATALINE_UIN_PAD,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const BY_UIN = new Map(DATALINE_DEVICES.map((device) => [device.uin, device]));
|
||||||
|
const BY_TER = new Map(DATALINE_DEVICES.map((device) => [device.terType, device]));
|
||||||
|
|
||||||
|
export function findDatalineDeviceByUin(uin: number): DatalineDeviceContact | undefined {
|
||||||
|
return BY_UIN.get(uin);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findDatalineDeviceByTerType(terType: number): DatalineDeviceContact | undefined {
|
||||||
|
return BY_TER.get(terType);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDatalineDeviceUin(uin: number): boolean {
|
||||||
|
return BY_UIN.has(uin);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function datalineFriendListEntries(): DatalineFriendEntry[] {
|
||||||
|
return DATALINE_DEVICES.map((device) => ({
|
||||||
|
user_id: device.uin,
|
||||||
|
nickname: device.name,
|
||||||
|
remark: device.name,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appendDatalineFriendEntries<T extends { user_id: number }>(
|
||||||
|
friends: readonly T[],
|
||||||
|
): Array<T | DatalineFriendEntry> {
|
||||||
|
const occupied = new Set(friends.map((friend) => friend.user_id));
|
||||||
|
const extras = datalineFriendListEntries().filter((entry) => !occupied.has(entry.user_id));
|
||||||
|
return extras.length === 0 ? [...friends] : [...friends, ...extras];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function appIdForTerType(terType: number): number {
|
||||||
|
return terType === DATALINE_TER_PC ? 1 : 1001;
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tryDecodeDatalineFriendMessage } from '../../dataline/decode-push';
|
||||||
import type { FriendMessage } from '../../events';
|
import type { FriendMessage } from '../../events';
|
||||||
import type { MsgPushDecoder } from '../registry';
|
import type { MsgPushDecoder } from '../registry';
|
||||||
import { decodeRichBody } from '../rich-body-decoder';
|
import { decodeRichBody } from '../rich-body-decoder';
|
||||||
@@ -24,6 +25,9 @@ function parseGroupInviteCard(jsonText: string): { groupUin: number; sequence: n
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||||
|
const dataline = tryDecodeDatalineFriendMessage(ctx);
|
||||||
|
if (dataline) return [dataline];
|
||||||
|
|
||||||
const elements = decodeRichBody(ctx.body, false);
|
const elements = decodeRichBody(ctx.body, false);
|
||||||
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
|
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
|
||||||
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
|
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||||
|
import type { DatalineMsgBody, DatalineTextMsg } from '@snowluma/proto-defs/dataline';
|
||||||
|
import type { PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||||
|
import { protobuf_encode } from '@snowluma/proton';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { encodeDatalineText } from '../src/dataline/codec';
|
||||||
|
import {
|
||||||
|
DATALINE_UIN_PAD,
|
||||||
|
DATALINE_UIN_PHONE,
|
||||||
|
} from '../src/dataline/device-contacts';
|
||||||
|
import type { IdentityService } from '../src/identity-service';
|
||||||
|
import { parseMsgPush } from '../src/msg-push';
|
||||||
|
|
||||||
|
const identity = { findFriend: () => undefined } as unknown as IdentityService;
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
|
||||||
|
function pushPacket(message: PushMsgBody): PacketInfo {
|
||||||
|
return {
|
||||||
|
pid: 0,
|
||||||
|
uin: '2000000001',
|
||||||
|
serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush',
|
||||||
|
seqId: 0,
|
||||||
|
retCode: 0,
|
||||||
|
fromClient: false,
|
||||||
|
body: protobuf_encode<PushMsg>({ message }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function datalinePush(
|
||||||
|
body: DatalineMsgBody,
|
||||||
|
extras: Partial<PushMsgBody> = {},
|
||||||
|
): PacketInfo {
|
||||||
|
return pushPacket({
|
||||||
|
responseHead: { fromUin: 2000000001, fromUid: 'u_self' },
|
||||||
|
contentHead: {
|
||||||
|
msgType: 529,
|
||||||
|
subType: 7,
|
||||||
|
sequence: 11,
|
||||||
|
ntMsgSeq: 22,
|
||||||
|
timestamp: 1710000000,
|
||||||
|
msgId: 33,
|
||||||
|
},
|
||||||
|
body: { msgContent: protobuf_encode<DatalineMsgBody>(body) },
|
||||||
|
...extras,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function textBuf(text: string): Uint8Array {
|
||||||
|
return protobuf_encode<DatalineTextMsg>({
|
||||||
|
items: [{ type: 1, text: encoder.encode(text) }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('dataline my-device chats', () => {
|
||||||
|
it('decodes an incoming Pad text push as a named device peer', () => {
|
||||||
|
const out = parseMsgPush(datalinePush({
|
||||||
|
subCmd: 4,
|
||||||
|
header: {
|
||||||
|
srcAppId: 1001,
|
||||||
|
srcInstId: 1,
|
||||||
|
dstAppId: 1,
|
||||||
|
dstInstId: 1,
|
||||||
|
dstUin: 2000000001n,
|
||||||
|
srcUin: 2000000001n,
|
||||||
|
srcTerType: 3,
|
||||||
|
dstTerType: 1,
|
||||||
|
},
|
||||||
|
generic: {
|
||||||
|
sessionId: 1n,
|
||||||
|
size: 1,
|
||||||
|
index: 0,
|
||||||
|
type: 1,
|
||||||
|
buf: textBuf('from pad'),
|
||||||
|
},
|
||||||
|
}), identity);
|
||||||
|
|
||||||
|
expect(out).toHaveLength(1);
|
||||||
|
expect(out[0]).toMatchObject({
|
||||||
|
kind: 'friend_message',
|
||||||
|
senderUin: DATALINE_UIN_PAD,
|
||||||
|
senderUid: 'u_l7jpPIZxQo0mzJwoEt-SKw',
|
||||||
|
peerUin: DATALINE_UIN_PAD,
|
||||||
|
senderNick: '我的Pad',
|
||||||
|
elements: [{ type: 'text', text: 'from pad' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('treats a self-originated device text as a message_sent-style peer rewrite', () => {
|
||||||
|
const out = parseMsgPush(datalinePush({
|
||||||
|
subCmd: 4,
|
||||||
|
header: {
|
||||||
|
srcAppId: 1,
|
||||||
|
srcInstId: 1,
|
||||||
|
dstAppId: 1001,
|
||||||
|
dstInstId: 1,
|
||||||
|
dstUin: 2000000001n,
|
||||||
|
srcUin: 2000000001n,
|
||||||
|
srcTerType: 1,
|
||||||
|
dstTerType: 2,
|
||||||
|
},
|
||||||
|
generic: {
|
||||||
|
sessionId: 2n,
|
||||||
|
size: 1,
|
||||||
|
index: 0,
|
||||||
|
type: 1,
|
||||||
|
buf: textBuf('to phone'),
|
||||||
|
},
|
||||||
|
}), identity);
|
||||||
|
|
||||||
|
expect(out[0]).toMatchObject({
|
||||||
|
kind: 'friend_message',
|
||||||
|
senderUin: 2000000001,
|
||||||
|
senderUid: 'u_self',
|
||||||
|
peerUin: DATALINE_UIN_PHONE,
|
||||||
|
senderNick: '',
|
||||||
|
elements: [{ type: 'text', text: 'to phone' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('surfaces a device file notify as a file element', () => {
|
||||||
|
const out = parseMsgPush(datalinePush({
|
||||||
|
subCmd: 1,
|
||||||
|
header: {
|
||||||
|
srcTerType: 2,
|
||||||
|
dstTerType: 1,
|
||||||
|
srcUin: 2000000001n,
|
||||||
|
dstUin: 2000000001n,
|
||||||
|
},
|
||||||
|
ftn: [{
|
||||||
|
sessionId: 9n,
|
||||||
|
fileName: 'shot.png',
|
||||||
|
fileIndex: 'ftn-1',
|
||||||
|
fileLen: 32n,
|
||||||
|
}],
|
||||||
|
}), identity);
|
||||||
|
|
||||||
|
expect(out[0]).toMatchObject({
|
||||||
|
kind: 'friend_message',
|
||||||
|
senderUin: DATALINE_UIN_PHONE,
|
||||||
|
senderNick: '我的手机',
|
||||||
|
elements: [{ type: 'file', fileId: 'ftn-1', fileName: 'shot.png', fileSize: 32 }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('round-trips outbound device text through the same decoder', () => {
|
||||||
|
const encoded = encodeDatalineText({
|
||||||
|
selfUin: 2000000001,
|
||||||
|
dstTerType: 2,
|
||||||
|
text: 'hello phone',
|
||||||
|
});
|
||||||
|
const out = parseMsgPush(pushPacket({
|
||||||
|
responseHead: { fromUin: 2000000001, fromUid: 'u_self' },
|
||||||
|
contentHead: { msgType: 529, subType: 7, sequence: 1, timestamp: 1, msgId: 1 },
|
||||||
|
body: { msgContent: encoded },
|
||||||
|
}), identity);
|
||||||
|
|
||||||
|
expect(out[0]).toMatchObject({
|
||||||
|
kind: 'friend_message',
|
||||||
|
senderUin: 2000000001,
|
||||||
|
peerUin: DATALINE_UIN_PHONE,
|
||||||
|
elements: [{ type: 'text', text: 'hello phone' }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user