167 lines · 8.1 KB · GoRaw
package mainimport ( "os" "os/exec" "path/filepath" "testing" "go.mau.fi/whatsmeow")// RULE (owner, FEEDBACK-3): a picture, video, voice note or document goes as WhatsApp's own kind, with its caption// and the quote of a reply; a voice note as a voice note (PTT), never a file.func TestAFileGoesAsItsOwnKind(t *testing.T) { up := whatsmeow.UploadResponse{URL: "https://mmg.example/x", DirectPath: "/v/x", MediaKey: make([]byte, 32), FileSHA256: make([]byte, 32), FileEncSHA256: make([]byte, 32), FileLength: 1234} pic, p := mediaMessage(&Request{Kind: "picture", Text: "the view", Mimetype: "image/jpeg", QuotedID: "3EB0Q", QuotedSender: "15550002222@s.whatsapp.net"}, up) im := pic.GetImageMessage() if im == nil || im.GetCaption() != "the view" || im.GetDirectPath() != "/v/x" || im.GetContextInfo().GetStanzaID() != "3EB0Q" || p.Type != "image" { t.Fatalf("picture = %v, pointer %+v", pic, p) } voice, _ := mediaMessage(&Request{Kind: "voice", Mimetype: "audio/ogg; codecs=opus", Seconds: 9}, up) if a := voice.GetAudioMessage(); a == nil || !a.GetPTT() || a.GetSeconds() != 9 { t.Fatalf("voice = %v", voice) } doc, _ := mediaMessage(&Request{Kind: "document", FileName: "plan.pdf", Mimetype: "application/pdf"}, up) if d := doc.GetDocumentMessage(); d == nil || d.GetFileName() != "plan.pdf" { t.Fatalf("document = %v", doc) }}// RULE: what the helper keeps of each send is the event a received one makes, as the owner's, under the id it went// out with: Cotton lands it once.func TestEachSendIsKeptAsTheOwnersOwn(t *testing.T) { chat := jid("15550002222@s.whatsapp.net") cases := map[string]func(*Event) bool{ "picture": func(e *Event) bool { return e.Event == "message" && e.Message.Kind == "image" && e.Message.Media.MessageID == "3EB0S" && e.Message.Media.FromMe }, "poll": func(e *Event) bool { return e.Message.Kind == "poll" && len(e.Message.Poll.Options) == 2 }, "reaction": func(e *Event) bool { return e.Message.ReactionTo == "3EB0T" && e.Message.Text == "👍" }, "edit": func(e *Event) bool { return e.Message.EditOf == "3EB0T" && e.Message.Text == "new words" }, "delete": func(e *Event) bool { return e.Event == "revoke" && e.Target == "3EB0T" }, "poll_vote": func(e *Event) bool { return e.Event == "poll_vote" && e.Target == "3EB0T" && len(e.Votes) == 2 && e.Message.FromMe }, } for kind, ok := range cases { req := &Request{Kind: kind, Target: "3EB0T", Emoji: "👍", Text: "new words", Options: []string{"Thursday", "Friday"}} ev := sentKindEvent(req, chat, "3EB0S", 1_760_000_000, &MediaPointer{Type: "image"}) if ev == nil || !ev.Message.FromMe || ev.Message.ID != "3EB0S" || !ok(ev) { t.Errorf("%s kept as %+v / %+v", kind, ev, ev.Message) } } if sentKindEvent(&Request{Kind: "nonsense"}, chat, "x", 1, nil) != nil { t.Fatal("an unknown kind kept something") }}// RULE: a send that names no message id, no chat or an unknown kind is refused before anything goes.func TestASendKindIsRefusedWithoutWhatItNeeds(t *testing.T) { h := NewHub(nil, nil, nil) for _, req := range []*Request{ {Kind: "picture", Chat: "15550002222@s.whatsapp.net"}, {Kind: "picture", MessageID: "3EB0", Chat: ""}, {Kind: "reaction", MessageID: "3EB0", Chat: "15550002222@s.whatsapp.net", Account: "nobody"}, } { if _, err := h.SendKind(t.Context(), req); err == nil { t.Errorf("%+v was not refused", req) } }}// RULE: a voice note reaches WhatsApp as Ogg Opus, so it plays as a voice note: a phone's AAC recording is turned// into one by macOS's own afconvert; one that is Ogg Opus already goes as it is.func TestAVoiceNoteBecomesOggOpus(t *testing.T) { dir := t.TempDir() wav := filepath.Join(dir, "tone.wav") m4a := filepath.Join(dir, "tone.m4a") // One second of silence as a WAV, then AAC, as a phone records it. header := []byte("RIFF\x24\x7d\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\x80\x3e\x00\x00\x00\x7d\x00\x00\x02\x00\x10\x00data\x00\x7d\x00\x00") if err := os.WriteFile(wav, append(header, make([]byte, 32000)...), 0o600); err != nil { t.Fatal(err) } if out, err := exec.Command("/usr/bin/afconvert", "-f", "m4af", "-d", "aac", wav, m4a).CombinedOutput(); err != nil { t.Fatalf("making the AAC: %v %s", err, out) } path, cleanup, err := asVoiceNote(t.Context(), m4a, "audio/mp4") if err != nil { t.Fatal(err) } head := make([]byte, 4) f, _ := os.Open(path) _, _ = f.Read(head) f.Close() if string(head) != "OggS" { t.Fatalf("the voice note is not Ogg: %q", head) } cleanup() if _, err := os.Stat(path); !os.IsNotExist(err) { t.Fatal("the converted file was left behind") } if same, _, _ := asVoiceNote(t.Context(), m4a, "audio/ogg; codecs=opus"); same != m4a { t.Fatal("an Ogg Opus note was converted again") }}// RULE (CONTRACT "Pictures, voice notes and video"): a picture or video carries its sides and the phone's small// preview; an audio file goes as a file (not PTT, no waveform); a file sent from Cotton lands as his own copy// already in Cotton (the landed media), never as a pointer to fetch back from WhatsApp.func TestAPictureCarriesItsSidesAndASentFileLandsAsHisOwnCopy(t *testing.T) { up := whatsmeow.UploadResponse{URL: "https://mmg.example/x", DirectPath: "/v/x", MediaKey: make([]byte, 32), FileSHA256: make([]byte, 32), FileEncSHA256: make([]byte, 32), FileLength: 1234} pic, _ := mediaMessage(&Request{Kind: "picture", Mimetype: "image/jpeg", Width: 1200, Height: 900, Preview: []byte{0xff, 0xd8}}, up) if im := pic.GetImageMessage(); im.GetWidth() != 1200 || im.GetHeight() != 900 || len(im.GetJPEGThumbnail()) != 2 { t.Fatalf("picture = %v", im) } bare, _ := mediaMessage(&Request{Kind: "picture", Mimetype: "image/jpeg"}, up) if bare.GetImageMessage().Width != nil { t.Fatal("a side the phone did not say was sent as 0") } audio, p := mediaMessage(&Request{Kind: "audio", Mimetype: "audio/mp4", Seconds: 3, Waveform: []byte{1, 2}}, up) if a := audio.GetAudioMessage(); a == nil || a.GetPTT() || a.Waveform != nil || p.Type != "audio" { t.Fatalf("audio file = %v", audio) } landed := []byte(`[{"key":"db/messages/t/abc.jpg","contentType":"image/jpeg"}]`) ev := sentKindEvent(&Request{Kind: "picture", Text: "the view", Landed: landed}, jid("15550002222@s.whatsapp.net"), "3EB0S", 1, &MediaPointer{Type: "image"}) if ev.Message.Media != nil || string(ev.Message.Landed) != string(landed) || ev.Message.Text != "the view" || ev.Message.Kind != "image" { t.Fatalf("sent picture kept as %+v", ev.Message) }}// RULE: a picture WhatsApp does not show (HEIC) is turned into a JPEG on the Mac, and a QuickTime video into MP4;// JPEG and MP4 go as they are.func TestAPictureOrVideoBecomesOneWhatsAppShows(t *testing.T) { if _, err := exec.LookPath("ffmpeg"); err != nil { t.Skip("ffmpeg makes the invented files") } dir := t.TempDir() png, heic, mov := filepath.Join(dir, "a.png"), filepath.Join(dir, "a.heic"), filepath.Join(dir, "a.mov") if out, err := exec.Command("ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48", "-frames:v", "1", png).CombinedOutput(); err != nil { t.Fatalf("%v %s", err, out) } if out, err := exec.Command("/usr/bin/sips", "-s", "format", "heic", png, "--out", heic).CombinedOutput(); err != nil { t.Fatalf("%v %s", err, out) } if out, err := exec.Command("ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=25", "-t", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p", mov).CombinedOutput(); err != nil { t.Fatalf("%v %s", err, out) } path, mime, cleanup, err := shown(t.Context(), "picture", heic, "image/heic") if err != nil || mime != "image/jpeg" { t.Fatalf("heic: %v %s", err, mime) } if b, _ := os.ReadFile(path); len(b) < 3 || b[0] != 0xff || b[1] != 0xd8 { t.Fatal("not a JPEG") } cleanup() if _, err := os.Stat(path); err == nil { t.Fatal("the JPEG was left behind") } path, mime, cleanup, err = shown(t.Context(), "video", mov, "video/quicktime") if err != nil || mime != "video/mp4" || filepath.Ext(path) != ".mp4" { t.Fatalf("mov: %v %s %s", err, mime, path) } cleanup() if p, m, _, _ := shown(t.Context(), "picture", png, "image/png"); p != png || m != "image/png" { t.Fatal("a PNG was turned") }}