X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/ec230eee6b06580031637bc97c99ec6db7b41926..2e2524881dfe8f6c5cabfd9d342d5d3492953bd4:/whatsapp_test.go?ds=inline diff --git a/whatsapp_test.go b/whatsapp_test.go index 2504bd9..2bdb4cc 100644 --- a/whatsapp_test.go +++ b/whatsapp_test.go @@ -1,15 +1,19 @@ package main import ( - "context" - "io" - "log" + "crypto/sha256" + "encoding/hex" + "errors" + "net/http" "os" "path/filepath" + "strings" "testing" "time" "github.com/stretchr/testify/require" + "go.mau.fi/whatsmeow" + "go.mau.fi/whatsmeow/types" "go.mau.fi/whatsmeow/types/events" ) @@ -17,31 +21,10 @@ func TestWhatsAppStatusFollowsTheConnection(t *testing.T) { dir := t.TempDir() whatsappTestSession(t, dir, true) clock := newTestClock() - fake := &WhatsAppFake{ - connected: make(chan struct{}), - } - - whatsapp, err := openWhatsApp(t.Context(), dir, clock.Now, log.New(io.Discard, "", 0), fake.newClient) - require.NoError(t, err) - - t.Cleanup(func() { - require.NoError(t, whatsapp.Close()) - }) - - ctx, cancel := context.WithCancel(t.Context()) - done := make(chan struct{}) - go func() { - defer close(done) - - whatsapp.Run(ctx) - }() + whatsapp, fake, _ := whatsappStartTest(t, dir, clock) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) - t.Cleanup(func() { - cancel() - <-done - }) - - <-fake.connected + <-fake.connects require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status()) require.True(t, fake.Emit(&events.Connected{})) @@ -57,22 +40,10 @@ func TestWhatsAppStatusFollowsTheConnection(t *testing.T) { func TestWhatsAppStatusOfAFirstConnectionThatFailed(t *testing.T) { dir := t.TempDir() whatsappTestSession(t, dir, true) - whatsapp, fake := whatsappStartTest(t, dir) - - ctx, cancel := context.WithCancel(t.Context()) - done := make(chan struct{}) - go func() { - defer close(done) - - whatsapp.Run(ctx) - }() + whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) - t.Cleanup(func() { - cancel() - <-done - }) - - <-fake.connected + <-fake.connects require.True(t, fake.Emit(&events.Disconnected{})) require.Equal(t, "WhatsApp is linked and disconnected since 2026-01-01 12:00.", whatsapp.Status()) } @@ -99,8 +70,8 @@ func TestWhatsAppIsNotLinkedWithoutALinkedDevice(t *testing.T) { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() tc.session(t, dir) - whatsapp, _ := whatsappStartTest(t, dir) - require.Equal(t, "WhatsApp is not linked.", whatsapp.Status()) + whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock()) + require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) }) } } @@ -110,7 +81,7 @@ func TestWhatsAppRefusesASessionThatOthersCanRead(t *testing.T) { whatsappTestSession(t, dir, true) require.NoError(t, os.Chmod(filepath.Join(dir, whatsappDirName, whatsappSessionFileName), 0o644)) - _, err := openWhatsApp(t.Context(), dir, time.Now, log.New(io.Discard, "", 0), whatsappNewClient) + _, err := openWhatsApp(t.Context(), dir, time.Now, whatsappDiscardLog(), whatsappNewClient) require.EqualError(t, err, "whatsapp/session.db holds the WhatsApp session, so its mode must be 0600") } @@ -128,18 +99,324 @@ func TestWhatsAppCommandsAnswerOnlyTheClientThatAsked(t *testing.T) { asking.WaitFor(t, "WhatsApp is not linked.") asking.Type(" /whatsapp unknown ") asking.WaitFor(t, whatsappUsage) + asking.Type("/whatsapp pair 0123") + asking.WaitFor(t, "PHONE must be the number of your WhatsApp account") telegram.Add(TelegramUpdate{ UpdateID: 1, Message: telegramOwnerMessage("/whatsapp status"), }) - telegramWaitForSent(t, telegram, "WhatsApp is not linked.") - require.Equal(t, []string{"WhatsApp is not linked."}, telegram.Sent()) + telegramWaitForSent(t, telegram, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.") + require.Len(t, telegram.Sent(), 1) require.Equal(t, "[connected to OneChat]\n", other.Output()) require.Zero(t, server.Calls()) } +func TestWhatsAppPairsWithACode(t *testing.T) { + dir := t.TempDir() + whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + server := newModelFake(t) + socket, memory := daemonStartTestWithWhatsApp(t, server, nil, whatsapp) + asking := terminalStartTestClient(t, socket) + other := terminalStartTestClient(t, socket) + asking.WaitFor(t, "[connected to OneChat]") + other.WaitFor(t, "[connected to OneChat]") + + asking.Type("/whatsapp pair +1 555-000-1111") + items := <-fake.pairings + items <- whatsmeow.QRChannelItem{ + Event: whatsmeow.QRChannelEventCode, + } + + asking.WaitFor(t, whatsappPairSteps+"\n"+whatsappTestCode+"\n") + require.True(t, fake.Emit(&events.PairSuccess{ + ID: types.NewADJID(whatsappTestNumber, 0, 1), + LID: types.NewADJID(whatsappTestLID, 0, 1), + })) + items <- whatsmeow.QRChannelSuccess + asking.WaitFor(t, "WhatsApp is linked to +15550001111.") + + // The library connects again after the link with the context of the + // connection, so the end of the pairing must not end it. + connections := fake.Connections() + require.Len(t, connections, 1) + require.Never(t, func() bool { + return connections[0].Err() != nil + }, 200*time.Millisecond, time.Millisecond) + + require.Equal(t, []string{whatsappTestNumber}, fake.Phones()) + require.Equal(t, "WhatsApp is linked and not connected yet.", whatsapp.Status()) + require.Equal(t, "[connected to OneChat]\n", other.Output()) + require.Zero(t, server.Calls()) + require.Equal(t, []string{"WhatsApp is linked."}, whatsappTestLogTexts(t, memory)) + + info, err := os.Stat(filepath.Join(dir, whatsappDirName)) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o700), info.Mode().Perm()) + + info, err = os.Stat(filepath.Join(dir, whatsappDirName, whatsappSessionFileName)) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + +func TestWhatsAppPairingCodeIsATelegramMessageAlone(t *testing.T) { + whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + telegram := newTelegramFake(t) + bot, _ := telegramStartTestBot(t, telegram) + daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp) + + telegram.Add(TelegramUpdate{ + UpdateID: 1, + Message: telegramOwnerMessage("/whatsapp pair 15550001111"), + }) + + items := <-fake.pairings + items <- whatsmeow.QRChannelItem{ + Event: whatsmeow.QRChannelEventCode, + } + + telegramWaitForSent(t, telegram, whatsappPairSteps, whatsappTestCode) +} + +func TestWhatsAppPairingEnds(t *testing.T) { + testCases := []struct { + name string + end func(items chan whatsmeow.QRChannelItem) + answer string + }{ + { + name: "the code expires", + end: func(items chan whatsmeow.QRChannelItem) { + items <- whatsmeow.QRChannelTimeout + }, + answer: whatsappPairExpired, + }, + { + name: "the library closes the pairing", + end: func(items chan whatsmeow.QRChannelItem) { + close(items) + }, + answer: whatsappPairExpired, + }, + { + name: "the pairing fails", + end: func(items chan whatsmeow.QRChannelItem) { + items <- whatsmeow.QRChannelItem{ + Event: whatsmeow.QRChannelEventError, + Error: errors.New("bad handshake"), + } + }, + answer: "The pairing failed: bad handshake. Run /whatsapp pair PHONE again.", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + client.Type("/whatsapp pair 15550001111") + + items := <-fake.pairings + items <- whatsmeow.QRChannelItem{ + Event: whatsmeow.QRChannelEventCode, + } + + client.WaitFor(t, whatsappTestCode) + tc.end(items) + client.WaitFor(t, tc.answer) + require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) + }) + } +} + +func TestWhatsAppNewPairingEndsTheOneBefore(t *testing.T) { + whatsapp, fake, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + + client.Type("/whatsapp pair 15550001111") + <-fake.pairings + client.Type("/whatsapp pair 15550002222") + items := <-fake.pairings + items <- whatsmeow.QRChannelItem{ + Event: whatsmeow.QRChannelEventCode, + } + + client.WaitFor(t, whatsappTestCode) + require.Equal(t, []string{"15550002222"}, fake.Phones()) + require.NotContains(t, client.Output(), "did not start the pairing") +} + +func TestWhatsAppPairWhenLinked(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock()) + socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + + client.Type("/whatsapp pair 15550001111") + client.WaitFor(t, "WhatsApp is linked already. Run /whatsapp unlink first.") +} + +func TestWhatsAppUnlink(t *testing.T) { + testCases := []struct { + name string + logoutErr error + answer string + }{ + { + name: "with a logout", + answer: "WhatsApp is unlinked.", + }, + { + name: "with no logout", + logoutErr: errors.New("not connected"), + answer: "WhatsApp is unlinked here, but the phone did not get the logout. In WhatsApp on your phone, open Linked devices and remove the device.", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + fake.logoutErr = tc.logoutErr + socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + <-fake.connects + + client.Type("/whatsapp unlink") + client.WaitFor(t, tc.answer) + require.Equal(t, 1, fake.Logouts()) + require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName)) + require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) + require.Equal(t, []string{"WhatsApp is unlinked."}, whatsappTestLogTexts(t, memory)) + + client.Type("/whatsapp unlink") + client.WaitFor(t, "WhatsApp is not linked.\n") + }) + } +} + +func TestWhatsAppLogoutFromThePhone(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + telegram := newTelegramFake(t) + bot, _ := telegramStartTestBot(t, telegram) + socket, memory := daemonStartTestWithWhatsApp(t, newModelFake(t), bot, whatsapp) + client := terminalStartTestClient(t, socket) + client.WaitFor(t, "[connected to OneChat]") + <-fake.connects + + require.True(t, fake.Emit(&events.LoggedOut{})) + notice := "WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again." + client.WaitFor(t, notice) + telegramWaitForSent(t, telegram, notice) + require.NoFileExists(t, filepath.Join(dir, whatsappDirName, whatsappSessionFileName)) + require.Equal(t, "WhatsApp is not linked. Run /whatsapp pair PHONE to link it.", whatsapp.Status()) + require.Equal(t, []string{"WhatsApp was unlinked from the phone."}, whatsappTestLogTexts(t, memory)) +} + +func TestWhatsAppLongDisconnectionGivesOneNotice(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + clock := newTestClock() + whatsapp, fake, _ := whatsappStartTest(t, dir, clock) + whatsapp.noticeDelay = 300 * time.Millisecond + socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + client.WaitFor(t, "[connected to OneChat]") + <-fake.connects + + require.True(t, fake.Emit(&events.Connected{})) + require.True(t, fake.Emit(&events.Disconnected{})) + require.True(t, fake.Emit(&events.Connected{})) + time.Sleep(400 * time.Millisecond) + require.Equal(t, "[connected to OneChat]\n", client.Output()) + + clock.now = clock.now.Add(time.Hour) + require.True(t, fake.Emit(&events.Disconnected{})) + require.True(t, fake.Emit(&events.Disconnected{})) + client.WaitFor(t, "WhatsApp is disconnected since 2026-01-01 13:00. OneChat tries again.\n") + require.True(t, fake.Emit(&events.Disconnected{})) + time.Sleep(400 * time.Millisecond) + + require.True(t, fake.Emit(&events.Connected{})) + client.WaitFor(t, "WhatsApp is connected again.\n") + require.Equal(t, 1, strings.Count(client.Output(), "WhatsApp is disconnected since")) +} + +func TestWhatsAppDisconnectionWithNoRetryGivesANoticeAtOnce(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + whatsapp, fake, _ := whatsappStartTest(t, dir, newTestClock()) + socket, _ := daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + client := terminalStartTestClient(t, socket) + client.WaitFor(t, "[connected to OneChat]") + <-fake.connects + + require.True(t, fake.Emit(&events.StreamReplaced{})) + client.WaitFor(t, "WhatsApp is disconnected and does not connect again by itself: stream replaced. Restart the daemon to try again.") +} + +func TestWhatsAppLogsNoOwnNumber(t *testing.T) { + dir := t.TempDir() + whatsappTestSession(t, dir, true) + whatsapp, fake, logs := whatsappStartTest(t, dir, newTestClock()) + fake.connectErr = errors.New("no route for " + whatsappTestNumber + "@s.whatsapp.net and " + whatsappTestLID + "@lid") + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + <-fake.connects + + require.Eventually(t, func() bool { + return logs.String() != "" + }, 10*time.Second, time.Millisecond) + require.Equal(t, "connect: no route for OWN@s.whatsapp.net and OWN@lid\n", logs.String()) +} + +func TestWhatsAppPhone(t *testing.T) { + testCases := []struct { + name string + phone string + valid bool + }{ + { + name: "a number with a plus and dashes", + phone: "+1-555-000-1111", + valid: true, + }, + { + name: "a number with no country code", + phone: "0115550001111", + valid: false, + }, + { + name: "a short number", + phone: "123456", + valid: false, + }, + { + name: "a long number", + phone: "1234567890123456", + valid: false, + }, + { + name: "a number with letters", + phone: "1555ABC1111", + valid: false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, valid := whatsappPhone(tc.phone) + require.Equal(t, tc.valid, valid) + }) + } +} + func TestWhatsAppCommandArgs(t *testing.T) { testCases := []struct { name string @@ -181,3 +458,200 @@ func TestWhatsAppCommandArgs(t *testing.T) { }) } } + +func TestSubagentHasNoWhatsAppTools(t *testing.T) { + box := &Toolbox{} + require.Equal(t, `error: unknown tool "whatsapp_find"`, box.run(t.Context(), "whatsapp_find", `{"name":"ana"}`)) + require.Equal(t, `error: unknown tool "whatsapp_send"`, box.run(t.Context(), "whatsapp_send", `{"id":"a","chat":"15550002222@s.whatsapp.net","text":"hi"}`)) +} + +func TestWhatsAppSendSendsOnceForEachID(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + whatsappTestContacts(t, whatsapp) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.") + require.NoError(t, err) + require.Equal(t, "Sent to Ana Souza at 12:05.", answer) + + answer, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "The keys are under the mat.") + require.NoError(t, err) + require.Equal(t, "Sent to Ana Souza at 12:05. This is the answer of the first call with this id: nothing was sent again.", answer) + + _, err = whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "Another text.") + require.EqualError(t, err, "the id keys belongs to another message: give a new id for each message") + + require.Equal(t, []WhatsAppFakeSend{ + { + to: whatsappTestAna.String(), + text: "The keys are under the mat.", + id: "MSG1", + }, + }, fake.Sent()) + + again, err := openWhatsAppState(filepath.Join(whatsapp.dir, whatsappStateFileName), whatsappBatchQuiet, whatsappBatchWindow) + require.NoError(t, err) + + record, found := again.Send("keys") + require.True(t, found) + require.Equal(t, whatsappSent, record.State) + require.Equal(t, "MSG1", record.MessageID) +} + +func TestWhatsAppSendToAGroup(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + fake.groups = []*types.GroupInfo{ + { + JID: whatsappTestFamily, + GroupName: types.GroupName{ + Name: "Family", + }, + }, + } + + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + answer, err := whatsapp.Send(t.Context(), "cake", whatsappTestFamily.String(), "I bring the cake.") + require.NoError(t, err) + require.Equal(t, "Sent to Family at 12:05.", answer) +} + +func TestWhatsAppSendThatFails(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + fake.sendErr = errors.New("server error for " + whatsappTestNumber) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + for range 2 { + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.True(t, strings.HasPrefix(answer, "The send failed: server error for OWN."), answer) + } + + require.Len(t, fake.Sent(), 1) +} + +func TestWhatsAppSendCutByAStop(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + digest := sha256.Sum256([]byte("hi")) + require.NoError(t, whatsapp.state.PutSend(WhatsAppSend{ + ID: "keys", + Chat: whatsappTestAna.String(), + Digest: hex.EncodeToString(digest[:]), + State: whatsappSending, + })) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Contains(t, answer, "its result is unknown") + require.Empty(t, fake.Sent()) +} + +func TestWhatsAppSendRefuses(t *testing.T) { + testCases := []struct { + name string + id string + chat string + text string + err string + }{ + { + name: "no id", + id: " ", + chat: whatsappTestAna.String(), + text: "hi", + err: "the id must have 1 to 100 bytes", + }, + { + name: "no text", + id: "a", + chat: whatsappTestAna.String(), + text: "", + err: "the text must have 1 to 65536 bytes", + }, + { + name: "a name for a chat", + id: "a", + chat: "Ana Souza", + text: "hi", + err: `"Ana Souza" is not the ID of a WhatsApp chat: find the ID with whatsapp_find`, + }, + { + name: "a status broadcast", + id: "a", + chat: types.StatusBroadcastJID.String(), + text: "hi", + err: `"status@broadcast" is not a private chat or a group`, + }, + { + name: "the chat of the user", + id: "a", + chat: whatsappTestOwn.String(), + text: "hi", + err: "this is the chat of the user with itself: send to another chat", + }, + } + + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + _, err := whatsapp.Send(t.Context(), tc.id, tc.chat, tc.text) + require.EqualError(t, err, tc.err) + }) + } + + require.Empty(t, fake.Sent()) +} + +func TestWhatsAppSendWhileDisconnected(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + daemonStartTestWithWhatsApp(t, newModelFake(t), nil, whatsapp) + whatsappTestConnect(t, fake) + require.True(t, fake.Emit(&events.Disconnected{})) + + _, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.EqualError(t, err, "WhatsApp is disconnected, so nothing was sent: try again later") + + require.True(t, fake.Emit(&events.Connected{})) + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Equal(t, "Sent to +15550002222 at 12:05.", answer) +} + +func TestWhatsAppSendWithoutALink(t *testing.T) { + whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), newTestClock()) + + answer, err := whatsapp.Send(t.Context(), "keys", whatsappTestAna.String(), "hi") + require.NoError(t, err) + require.Equal(t, whatsappNotLinked, answer) +} + +func TestAgentSendsAWhatsAppMessage(t *testing.T) { + whatsapp, fake := whatsappStartTestLinked(t) + whatsappTestContacts(t, whatsapp) + server := newModelFake(t) + server.reply = func(w http.ResponseWriter, call ModelFakeCall) { + if call.number == 0 { + modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "whatsapp_send", `{"id":"keys","chat":"15550002222@s.whatsapp.net","text":"The keys are under the mat."}`)}, 100, 0, 5)) + return + } + + modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Sent.")}, 100, 0, 5)) + } + + socket, _ := daemonStartTestWithWhatsApp(t, server, nil, whatsapp) + client := terminalStartTestClient(t, socket) + whatsappTestConnect(t, fake) + + client.Type("Tell Ana that the keys are under the mat.") + client.WaitFor(t, "[result] Sent to Ana Souza at 12:05.\nSent.\n[done]") + require.Len(t, fake.Sent(), 1) +}