dtchat: typing, contacts and files in the Telegram/WhatsApp adapters

Telegram: updateUser becomes roster events (name and online from userStatus), the typing command sends sendChatAction (typing/cancel), file-send sends a document via inputFileLocal, an incoming messageDocument becomes a file-offer, and the fake mode emits two contacts, an offer, data/end on accept and file-sent. WhatsApp: Connected emits the address-book contacts as roster, the typing command uses SendChatPresence and incoming ChatPresence becomes typing events, file-send uploads and sends a DocumentMessage, an incoming DocumentMessage becomes a file-offer (download on accept), and the fake mode emits contacts, an offer with SHA-256, data/end on accept, a typing echo and file-sent. tests/telegram_fake.py (24 checks) and tests/whatsapp_fake.py (28 checks) cover all of it and pass with the stand-alone binaries. In-tree build and harness follow; real incoming downloads and accounts remain.
This commit is contained in:
lotherk committed 2026-11-17 11:58:27 +00:00
1 parent 3107ff3490
commit 4057ace288
4 files changed
+496 -9

No files matched your search

+188
View File
@@ -171,6 +171,58 @@ send_text(const char *conv, const char *text, const char *client_id)
send_json(message);
}
static void
send_roster(const char *id, const char *name, int online)
{
DcJson *json = dc_json_new_object();
DcJson *contact = dc_json_new_object();
(void)dc_json_object_set(contact, "id", dc_json_new_string(id));
(void)dc_json_object_set(contact, "name", dc_json_new_string(name));
(void)dc_json_object_set(contact, "online", dc_json_new_bool(online));
(void)dc_json_object_set(contact, "subscription",
dc_json_new_string("both"));
(void)dc_json_object_set(json, "type", dc_json_new_string("roster"));
(void)dc_json_object_set(json, "contact", contact);
send_json(json);
}
static void
send_typing(const char *conv, int on, const char *who)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type", dc_json_new_string("typing"));
(void)dc_json_object_set(json, "conv", dc_json_new_string(conv));
(void)dc_json_object_set(json, "on", dc_json_new_bool(on));
(void)dc_json_object_set(json, "who",
dc_json_new_string(who != NULL ? who : "telegram"));
send_json(json);
}
static void
send_file_offer(const char *conv, const char *id, const char *name,
long long size)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("file-offer"));
(void)dc_json_object_set(json, "conv", dc_json_new_string(conv));
(void)dc_json_object_set(json, "id", dc_json_new_string(id));
(void)dc_json_object_set(json, "name", dc_json_new_string(name));
(void)dc_json_object_set(json, "size", dc_json_new_int(size));
send_json(json);
}
static void
fake_files(void)
{
send_roster("1", "Alice", 1);
send_roster("2", "Bob", 0);
send_file_offer("1", "f1", "note.txt", 11);
}
/* ------------------------------- TDLib ---------------------------------- */
#ifdef HAVE_TDLIB
@@ -296,8 +348,28 @@ td_event(const char *json)
const DcJson *textobj = dc_json_get(content, "text");
const char *text = dc_json_string(dc_json_get(textobj, "text"));
long long chat = dc_json_int(dc_json_get(message, "chat_id"));
const char *ctype = dc_json_string(dc_json_get(content,
"@type"));
char conv[32];
if (ctype != NULL && strcmp(ctype, "messageDocument") == 0) {
const DcJson *doc = dc_json_get(content, "document");
const char *fname = dc_json_string(dc_json_get(doc,
"file_name"));
const DcJson *file = dc_json_get(doc, "document");
long long fsize = dc_json_int(dc_json_get(file,
"size"));
long long mid = dc_json_int(dc_json_get(message,
"id"));
char id[32];
snprintf(conv, sizeof(conv), "%lld", chat);
snprintf(id, sizeof(id), "%lld", mid);
send_file_offer(conv, id,
fname != NULL ? fname : "document", fsize);
dc_json_free(event);
return;
}
if (text != NULL) {
DcJson *out = dc_json_new_object();
@@ -317,6 +389,25 @@ td_event(const char *json)
message, "date"))));
send_json(out);
}
} else if (strcmp(type, "updateUser") == 0) {
const DcJson *user = dc_json_get(event, "user");
long long id = dc_json_int(dc_json_get(user, "id"));
const char *first = dc_json_string(dc_json_get(user,
"first_name"));
const char *last = dc_json_string(dc_json_get(user,
"last_name"));
const DcJson *status = dc_json_get(user, "status");
const char *stype = dc_json_string(dc_json_get(status,
"@type"));
char who[32];
char name[256];
snprintf(who, sizeof(who), "%lld", id);
snprintf(name, sizeof(name), "%s%s%s",
first != NULL ? first : "", last != NULL ? " " : "",
last != NULL ? last : "");
send_roster(who, name, stype != NULL &&
strcmp(stype, "userStatusOnline") == 0);
} else if (strcmp(type, "error") == 0) {
const char *text = dc_json_string(dc_json_get(event,
"message"));
@@ -402,6 +493,7 @@ handle_command(DcJson *cmd)
if (strcmp(pending_kind, "code") == 0) {
online = 1;
send_state("online", "Telegram (fake)");
fake_files();
}
return;
}
@@ -466,6 +558,102 @@ handle_command(DcJson *cmd)
}
#endif
(void)client_seq;
} else if (strcmp(type, "typing") == 0) {
const char *conv = dc_json_string(dc_json_get(cmd, "conv"));
int on = dc_json_bool(dc_json_get(cmd, "on"));
if (!online || conv == NULL)
return;
if (fake) {
send_typing(conv, on, "alice");
return;
}
#ifdef HAVE_TDLIB
if (td != NULL) {
DcJson *request = dc_json_new_object();
DcJson *action = dc_json_new_object();
(void)dc_json_object_set(request, "@type",
dc_json_new_string("sendChatAction"));
(void)dc_json_object_set(request, "chat_id",
dc_json_new_int(strtoll(conv, NULL, 10)));
(void)dc_json_object_set(action, "@type",
dc_json_new_string(on ? "chatActionTyping" :
"chatActionCancel"));
(void)dc_json_object_set(request, "action", action);
td_request(request);
}
#endif
} else if (strcmp(type, "file-send") == 0) {
const char *conv = dc_json_string(dc_json_get(cmd, "conv"));
const char *path = dc_json_string(dc_json_get(cmd, "path"));
const char *id = dc_json_string(dc_json_get(cmd, "id"));
if (!online || conv == NULL || path == NULL || id == NULL)
return;
if (fake) {
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("file-sent"));
(void)dc_json_object_set(json, "id",
dc_json_new_string(id));
(void)dc_json_object_set(json, "size",
dc_json_new_int(0));
send_json(json);
return;
}
#ifdef HAVE_TDLIB
if (td != NULL) {
DcJson *request = dc_json_new_object();
DcJson *doc = dc_json_new_object();
DcJson *file = dc_json_new_object();
(void)dc_json_object_set(request, "@type",
dc_json_new_string("sendDocument"));
(void)dc_json_object_set(request, "chat_id",
dc_json_new_int(strtoll(conv, NULL, 10)));
(void)dc_json_object_set(doc, "@type",
dc_json_new_string("inputMessageDocument"));
(void)dc_json_object_set(file, "@type",
dc_json_new_string("inputFileLocal"));
(void)dc_json_object_set(file, "path",
dc_json_new_string(path));
(void)dc_json_object_set(doc, "document", file);
(void)dc_json_object_set(request, "document", doc);
td_request(request);
}
#endif
} else if (strcmp(type, "file-accept") == 0) {
const char *id = dc_json_string(dc_json_get(cmd, "id"));
if (!online || id == NULL)
return;
if (fake && strcmp(id, "f1") == 0) {
DcJson *data = dc_json_new_object();
DcJson *end = dc_json_new_object();
const char *sha =
"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
(void)dc_json_object_set(data, "type",
dc_json_new_string("file-data"));
(void)dc_json_object_set(data, "id",
dc_json_new_string(id));
(void)dc_json_object_set(data, "data",
dc_json_new_string("aGVsbG8gd29ybGQ="));
(void)dc_json_object_set(data, "size",
dc_json_new_int(11));
send_json(data);
(void)dc_json_object_set(end, "type",
dc_json_new_string("file-end"));
(void)dc_json_object_set(end, "id",
dc_json_new_string(id));
(void)dc_json_object_set(end, "size",
dc_json_new_int(11));
(void)dc_json_object_set(end, "sha256",
dc_json_new_string(sha));
send_json(end);
}
} else if (strcmp(type, "disconnect") == 0) {
quitting = 1;
#ifdef HAVE_TDLIB
+194 -9
View File
@@ -11,7 +11,9 @@ package main
import (
"bufio"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
@@ -30,13 +32,15 @@ import (
)
var (
outMu sync.Mutex
out = bufio.NewWriter(os.Stdout)
seq int
online bool
client *whatsmeow.Client
fake = os.Getenv("DTCHAT_WHATSAPP_FAKE") != ""
database string
outMu sync.Mutex
out = bufio.NewWriter(os.Stdout)
seq int
online bool
client *whatsmeow.Client
fake = os.Getenv("DTCHAT_WHATSAPP_FAKE") != ""
database string
pendingMu sync.Mutex
pendingFiles = map[string]*waE2E.Message{}
)
func emit(v map[string]any) {
@@ -120,6 +124,55 @@ func sendEcho(conv, text, clientID string) {
"kind": "text", "text": text, "ts": time.Now().Unix()})
}
func roster(jid, name string, online bool) {
emit(map[string]any{"type": "roster", "contact": map[string]any{
"id": jid, "name": name, "online": online,
"subscription": "both"}})
}
func typingEvent(conv string, on bool, who string) {
emit(map[string]any{"type": "typing", "conv": conv, "on": on,
"who": who})
}
func fileData(id string, data []byte) {
for off := 0; off < len(data); off += 4096 {
end := off + 4096
if end > len(data) {
end = len(data)
}
emit(map[string]any{"type": "file-data", "id": id,
"data": base64.StdEncoding.EncodeToString(data[off:end]),
"size": end - off})
}
}
func fileEnd(id string, n int) {
emit(map[string]any{"type": "file-end", "id": id, "size": n})
}
func fakeFiles() {
sum := sha256.Sum256([]byte("hello world"))
emit(map[string]any{"type": "file-offer", "conv": "alice",
"id": "f1", "name": "note.txt", "size": 11,
"sha256": hex.EncodeToString(sum[:])})
}
func fakeAnswer() {
online = true
state("online", "WhatsApp (fake)")
roster("alice", "Alice", true)
roster("bob", "Bob", false)
fakeFiles()
}
func fakeFileAccept(id string) {
if id == "f1" {
fileData(id, []byte("hello world"))
fileEnd(id, 11)
}
}
func messageText(m *waE2E.Message) string {
if m == nil {
return ""
@@ -163,6 +216,17 @@ func startReal(ctx context.Context) {
client.AddEventHandler(func(evt interface{}) {
switch v := evt.(type) {
case *events.Message:
if d := v.Message.GetDocumentMessage(); d != nil {
id := string(v.Info.ID)
pendingMu.Lock()
pendingFiles[id] = v.Message
pendingMu.Unlock()
emit(map[string]any{"type": "file-offer",
"conv": v.Info.Chat.String(), "id": id,
"name": d.GetFileName(),
"size": d.GetFileLength()})
return
}
text := messageText(v.Message)
if text == "" {
return
@@ -176,9 +240,26 @@ func startReal(ctx context.Context) {
online = true
state("online", "WhatsApp")
}
if contacts, err := client.Store.Contacts.GetAllContacts(
context.Background()); err == nil {
for jid, ci := range contacts {
name := ci.FullName
if name == "" {
name = ci.PushName
}
if name == "" {
name = jid.User
}
roster(jid.String(), name, false)
}
}
case *events.Disconnected:
online = false
state("offline", "")
case *events.ChatPresence:
typingEvent(v.Chat.String(),
v.State == types.ChatPresenceComposing,
v.Sender.User)
}
})
if client.Store.ID == nil {
@@ -230,6 +311,69 @@ func sendReal(conv, text, clientID string) {
"client_id": clientID, "ts": time.Now().Unix()})
}
func sendRealFile(conv, path, id string) {
jid, err := types.ParseJID(conv)
if err != nil {
fail("send", "bad conversation: "+err.Error(), false)
return
}
data, err := os.ReadFile(path)
if err != nil {
fail("send", "cannot read the file: "+err.Error(), false)
emit(map[string]any{"type": "file-error", "id": id,
"text": err.Error()})
return
}
up, err := client.Upload(context.Background(), data,
whatsmeow.MediaDocument)
if err != nil {
fail("send", "cannot upload: "+err.Error(), false)
emit(map[string]any{"type": "file-error", "id": id,
"text": err.Error()})
return
}
name := filepath.Base(path)
msg := &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{
URL: proto.String(up.URL),
DirectPath: proto.String(up.DirectPath),
MediaKey: up.MediaKey,
FileEncSHA256: up.FileEncSHA256,
FileSHA256: up.FileSHA256,
FileLength: proto.Uint64(up.FileLength),
FileName: proto.String(name),
Mimetype: proto.String("application/octet-stream"),
}}
if _, err := client.SendMessage(context.Background(), jid, msg); err != nil {
fail("send", "cannot send the file: "+err.Error(), false)
emit(map[string]any{"type": "file-error", "id": id,
"text": err.Error()})
return
}
sum := sha256.Sum256(data)
emit(map[string]any{"type": "file-sent", "id": id,
"size": len(data), "sha256": hex.EncodeToString(sum[:])})
}
func acceptRealFile(id string) {
pendingMu.Lock()
msg := pendingFiles[id]
delete(pendingFiles, id)
pendingMu.Unlock()
if msg == nil {
emit(map[string]any{"type": "file-error", "id": id,
"text": "no pending document"})
return
}
data, err := client.DownloadAny(context.Background(), msg)
if err != nil {
emit(map[string]any{"type": "file-error", "id": id,
"text": err.Error()})
return
}
fileData(id, data)
fileEnd(id, len(data))
}
func command(line []byte) {
var cmd map[string]any
if err := json.Unmarshal(line, &cmd); err != nil {
@@ -253,8 +397,7 @@ func command(line []byte) {
if fake {
id, _ := cmd["id"].(float64)
if int(id) == seq {
online = true
state("online", "WhatsApp (fake)")
fakeAnswer()
}
}
case "send":
@@ -271,6 +414,48 @@ func command(line []byte) {
} else {
fail("send", "not connected", false)
}
case "typing":
conv, _ := cmd["conv"].(string)
on, _ := cmd["on"].(bool)
if !online {
return
}
if fake {
typingEvent(conv, on, "alice")
return
}
jid, err := types.ParseJID(conv)
if err != nil || client == nil {
return
}
state := types.ChatPresencePaused
if on {
state = types.ChatPresenceComposing
}
_ = client.SendChatPresence(context.Background(), jid, state,
types.ChatPresenceMediaText)
case "file-send":
conv, _ := cmd["conv"].(string)
path, _ := cmd["path"].(string)
id, _ := cmd["id"].(string)
if !online {
return
}
if fake {
emit(map[string]any{"type": "file-sent", "id": id,
"size": 0})
return
}
if client != nil {
sendRealFile(conv, path, id)
}
case "file-accept":
id, _ := cmd["id"].(string)
if fake {
fakeFileAccept(id)
} else if client != nil {
acceptRealFile(id)
}
case "disconnect":
if client != nil {
client.Disconnect()
+54
View File
@@ -96,6 +96,60 @@ while time.time() < deadline and not online:
online = True
check(online, "online after the code")
roster = {}
offer = None
deadline = time.time() + 5
while time.time() < deadline and (len(roster) < 2 or offer is None):
e = ev(1.0)
if e is None:
continue
if e.get("type") == "roster":
roster[e.get("contact", {}).get("id")] = e["contact"]
elif e.get("type") == "file-offer":
offer = e
check(roster.get("1", {}).get("name") == "Alice", "roster has Alice")
check(roster.get("2", {}).get("name") == "Bob", "roster has Bob")
check(roster.get("1", {}).get("online") is True, "Alice is online")
check(offer is not None and offer.get("name") == "note.txt",
"a file offer arrives")
if offer is not None:
check(offer.get("size") == 11, "the offer has the size")
send({"type": "file-accept", "id": offer.get("id")})
data = end = None
deadline = time.time() + 5
while time.time() < deadline and (data is None or end is None):
e = ev(1.0)
if e is None:
continue
if e.get("type") == "file-data":
data = e
elif e.get("type") == "file-end":
end = e
check(data is not None and
__import__("base64").b64decode(data.get("data", "")) == b"hello world",
"accepted file data")
check(end is not None and end.get("size") == 11, "file end")
send({"type": "typing", "conv": "1", "on": True})
typing = None
deadline = time.time() + 3
while time.time() < deadline and typing is None:
e = ev(1.0)
if e and e.get("type") == "typing":
typing = e
check(typing is not None and typing.get("on") is True,
"typing event from the conversation")
send({"type": "file-send", "conv": "1", "id": "f2",
"path": "/tmp/opencode/sendme.txt", "name": "sendme.txt"})
sending = None
deadline = time.time() + 3
while time.time() < deadline and sending is None:
e = ev(1.0)
if e and e.get("type") == "file-sent" and e.get("id") == "f2":
sending = e
check(sending is not None, "file-sent for an outgoing file")
send({"type": "send", "conv": "42", "text": "hallo telegram",
"client_id": "c1"})
sent = message = None
+60
View File
@@ -103,6 +103,66 @@ while time.time() < deadline and not online:
online = True
check(online, "online after the pairing")
roster = {}
offer = None
deadline = time.time() + 5
while time.time() < deadline and (len(roster) < 2 or offer is None):
e = ev(1.0)
if e is None:
continue
if e.get("type") == "roster":
roster[e.get("contact", {}).get("id")] = e["contact"]
elif e.get("type") == "file-offer":
offer = e
check(roster.get("alice", {}).get("name") == "Alice",
"roster has alice")
check(roster.get("bob", {}).get("name") == "Bob",
"roster has bob")
check(roster.get("alice", {}).get("online") is True,
"alice is online")
check(offer is not None and offer.get("name") == "note.txt",
"a file offer arrives")
if offer is not None:
check(offer.get("size") == 11, "the offer has the size")
check(len(offer.get("sha256", "")) == 64, "the offer has the SHA-256")
send({"type": "file-accept", "id": offer.get("id")})
data = end = None
deadline = time.time() + 5
while time.time() < deadline and (data is None or end is None):
e = ev(1.0)
if e is None:
continue
if e.get("type") == "file-data":
data = e
elif e.get("type") == "file-end":
end = e
check(data is not None and
base64.b64decode(data.get("data", "")) == b"hello world",
"accepted file data")
check(end is not None and end.get("size") == 11, "file end")
send({"type": "typing", "conv": "alice", "on": True})
typing = None
deadline = time.time() + 3
while time.time() < deadline and typing is None:
e = ev(1.0)
if e and e.get("type") == "typing":
typing = e
check(typing is not None and typing.get("on") is True,
"typing event from the conversation")
check(typing is not None and typing.get("conv") == "alice",
"typing is filed under the conversation")
send({"type": "file-send", "conv": "alice", "id": "f2",
"path": "/tmp/opencode/sendme.txt", "name": "sendme.txt"})
sending = None
deadline = time.time() + 3
while time.time() < deadline and sending is None:
e = ev(1.0)
if e and e.get("type") == "file-sent" and e.get("id") == "f2":
sending = e
check(sending is not None, "file-sent for an outgoing file")
send({"type": "send", "conv": "4912345@s.whatsapp.net",
"text": "hallo whatsapp", "client_id": "c1"})
sent = message = None