Cotton code
196 lines · 11.2 KB · GoRaw
package mainimport "encoding/json"// The socket speaks JSON lines, one object per line, both ways.//// Client → helper, a request:   {"id": 7, "op": "pair", ...arguments}// Helper → client, its reply:   {"reply": 7, "ok": true, "result": {...}} or {"reply": 7, "ok": false, "error": "..."}// Helper → client, an event:    {"seq": 41, "event": "message", "account": "...", ...}//// Durable events are PULLED with {"op": "events", "after": 0, "limit": 500}, answered {"events": [...]}// oldest first — what the ingest source does on each pass. Events are also PUSHED to the one// connection that sent {"op": "subscribe"} (a later subscriber replaces it), live ones included.// An event with a seq is durable: it stays in the outbox and is sent again on every connection until// the client sends {"op": "ack", "seq": 41}. An event without a seq (state, pairing codes) is live only.//// Linking a number: {"op":"pair","phone"?:"…"} → {"pairing":"<id>"}; {"op":"pair_status","pairing":"<id>"}// answers its PairState (pairing.go). When WhatsApp asks for a passkey the status is "passkey" with// `passkey` (the WebAuthn request options); {"op":"passkey_response","pairing":"<id>","response":{…}}// hands back the assertion; status "passkey_code" with `confirm` is the code the phone shows too,// and {"op":"passkey_confirm","pairing":"<id>"} says the person saw it match.// `hello` answers `unlinked` ({account, reason, at}) while the last linked number WhatsApp removed is// not linked again.//// The one op that writes to a chat is send — text the owner typed in Cotton, optionally a reply://   {"id":7,"op":"send","account":"…","chat":"<jid>","text":"…","message_id":"3EB0…","quoted_id"?:"…","quoted_sender"?:"<jid>"}//   → {"reply":7,"ok":true,"result":{"id":"3EB0…","ts":<unix seconds>}}// Errors are ok:false with a plain reason. `id` is the request id, never the message id; message_id is// Cotton's and is passed through unchanged, so a retry with the same id is deduped by WhatsApp.//// Profile pictures, reading only (pictures.go)://   {"id":7,"op":"pictures","chats":["<jid>",…]} → the chats it may ask WhatsApp about, replacing the last list;//   `hello` answers its digest as "pictures" so an unchanged list is not sent again.//   A durable {"event":"picture","chat":"<jid>","is_group":…,"target":"<picture id>"} when one is new or changed.//   {"id":7,"op":"picture","account":"…","chat":"<jid>","dest":"<file>"} downloads it; ok:false "gone" when none is shown.//// The Rust side of this contract is crates/cotton-client/src/ingest/sources/whatsapp_link.rs (blocking// client) and crates/cotton-server/src/whatsapp_link.rs; change all of them together.type Request struct {	ID int64  `json:"id"`	Op string `json:"op"`	Seq     int64  `json:"seq,omitempty"`     // ack	After   int64  `json:"after,omitempty"`   // events	Limit   int    `json:"limit,omitempty"`   // events	Account string `json:"account,omitempty"` // history, media, logout	Phone   string `json:"phone,omitempty"`   // pair: when set, a pairing code for this number instead of a QR	Pairing string `json:"pairing,omitempty"` // pair_status, pair_cancel, passkey_response, passkey_confirm	Response json.RawMessage `json:"response,omitempty"` // passkey_response: the WebAuthn assertion, browser-shaped	Chat   string        `json:"chat,omitempty"`   // history	Before *MessageRef   `json:"before,omitempty"` // history: the oldest message Cotton holds in that chat	Count  int           `json:"count,omitempty"`  // history	Media  *MediaPointer `json:"media,omitempty"`  // media	Dest   string        `json:"dest,omitempty"`   // media, picture: the file to write	Accounts []string `json:"accounts,omitempty"` // hold: every number to keep linked but unconnected (its connection is paused)	Chats    []string `json:"chats,omitempty"`    // pictures: every chat whose profile picture Cotton would take	Text         string `json:"text,omitempty"`          // send	MessageID    string `json:"message_id,omitempty"`    // send: the WhatsApp message id, chosen by Cotton	QuotedID     string `json:"quoted_id,omitempty"`     // send: the message replied to	QuotedSender string `json:"quoted_sender,omitempty"` // send: who wrote it (his own account's jid for his own)	QuotedKind   string `json:"quoted_kind,omitempty"`   // send: what it is (text, image, video, voice, audio, document, contact)	QuotedText   string `json:"quoted_text,omitempty"`   // send: its words, caption, file name or contact name, drawn in the quote	// send, beyond a text (send_kinds.go). Kind: text (or empty), picture, video, voice, document, reaction, edit,	// delete, poll, poll_vote. Target is the message a reaction, edit, delete or vote acts on (quoted_id stays the	// reply's), TargetSender its sender in a group and TargetFromMe whether it is the owner's own.	Kind         string `json:"kind,omitempty"`	Target       string `json:"target,omitempty"`	TargetSender string `json:"target_sender,omitempty"`	TargetFromMe bool   `json:"target_from_me,omitempty"`	TargetTS     int64  `json:"target_ts,omitempty"` // delete_chat: the chat's newest message's time, unix seconds (source_acts.go)	Emoji        string `json:"emoji,omitempty"`     // reaction: empty takes it back	Path         string `json:"path,omitempty"`      // picture, video, voice, document: the plain file on this Mac	Mimetype     string `json:"mimetype,omitempty"`  // its type	FileName     string `json:"file_name,omitempty"` // document: the name the other person sees	Seconds      uint32 `json:"seconds,omitempty"`   // voice, video: its length	Waveform     []byte `json:"waveform,omitempty"`  // voice: up to 64 levels, 0..100	Width        uint32 `json:"width,omitempty"`     // picture, video	Height       uint32 `json:"height,omitempty"`    // picture, video	Preview      []byte `json:"preview,omitempty"`   // picture, video: a small JPEG, WhatsApp's jpegThumbnail	// A file: what Cotton lands the sent message with (his own copy already in Cotton), handed back unchanged on	// the sent message so the file is never fetched from WhatsApp or stored a second time.	Landed     json.RawMessage `json:"landed,omitempty"`	Options    []string        `json:"options,omitempty"`    // poll: its options; poll_vote: the options picked	Selectable int             `json:"selectable,omitempty"` // poll: how many one may pick (0: any)}type Reply struct {	Reply  int64  `json:"reply"`	OK     bool   `json:"ok"`	Error  string `json:"error,omitempty"`	Result any    `json:"result,omitempty"`}type Event struct {	Seq     int64  `json:"seq,omitempty"`	Event   string `json:"event"`	Account string `json:"account,omitempty"`	// state	State  string `json:"state,omitempty"` // connected, disconnected, logged_out, banned, outdated, replaced	Detail string `json:"detail,omitempty"`	// pair_qr, pair_code, pair_passkey, pair_passkey_code, paired, pair_failed	Pairing string          `json:"pairing,omitempty"`	Code    string          `json:"code,omitempty"`	Options json.RawMessage `json:"options,omitempty"` // pair_passkey: WhatsApp's WebAuthn request options	Skip    bool            `json:"skip,omitempty"`    // pair_passkey_code: the helper confirmed; nothing to check	// chat: a conversation's name as WhatsApp knows it	Chat    string `json:"chat,omitempty"`	Name    string `json:"name,omitempty"`	IsGroup bool   `json:"is_group,omitempty"`	// message, revoke	Message *Message `json:"message,omitempty"`	// revoke: the id of the message deleted for everyone; picture: the new picture's id; poll_vote: the poll's id	Target string `json:"target,omitempty"`	// poll_vote: the options the voter now picks, each the SHA-256 (hex) of the option's words as WhatsApp hashes	// them; none is a vote taken back. Message names the voter (sender, or from_me) and when.	Votes []string `json:"votes,omitempty"`}// Message is one WhatsApp message as Cotton stores it. `id` is WhatsApp's own message id — the same// stanza id the iPhone backup holds — so a message read here and the same message restored from a// backup are one row.type Message struct {	ID         string        `json:"id"`	Chat       string        `json:"chat"`             // phone-number JID for a person, …@g.us for a group	Sender     string        `json:"sender,omitempty"` // phone-number JID when known; empty when from_me	SenderLID  string        `json:"sender_lid,omitempty"`	FromMe     bool          `json:"from_me"`	IsGroup    bool          `json:"is_group"`	ChatName   string        `json:"chat_name,omitempty"` // the group's subject or the contact's name, when known	Timestamp  int64         `json:"ts"`                  // unix seconds	PushName   string        `json:"push_name,omitempty"`	Kind       string        `json:"kind"` // text, image, video, audio, voice, document, sticker, location, contact, reaction, poll, call, other	Text       string        `json:"text,omitempty"`	QuotedID   string        `json:"quoted_id,omitempty"`	EditOf     string        `json:"edit_of,omitempty"` // set when this is a new text for an earlier message	ReactionTo string        `json:"reaction_to,omitempty"`	Media      *MediaPointer `json:"media,omitempty"`	Poll       *Poll         `json:"poll,omitempty"` // kind poll: its options (Text is the question)	Call       *Call         `json:"call,omitempty"` // kind call: the call's facts (calls.go)	// A file the owner sent from Cotton: the media Cotton lands it with (Request.Landed), in place of a pointer.	Landed json.RawMessage `json:"landed,omitempty"`	Origin string          `json:"origin"` // live or history}// Poll is a poll's options in WhatsApp's order and how many one voter may pick (0: any number).type Poll struct {	Options    []string `json:"options"`	Selectable uint32   `json:"selectable,omitempty"`}// MediaPointer is what WhatsApp needs to fetch and decrypt an attachment. It is handed back unchanged// in a `media` request; WhatsApp's servers drop old media, so a fetch can fail with gone, and one// no request can fetch — a pointer old history carries without its path or key, or bytes that are// not the file it names — fails with "unfetchable: <why>" (hub.go, Unfetchable).type MediaPointer struct {	Type          string `json:"type"` // image, video, audio, document, sticker	Mimetype      string `json:"mimetype,omitempty"`	FileName      string `json:"file_name,omitempty"`	DirectPath    string `json:"direct_path"`	MediaKey      []byte `json:"media_key"`	FileSHA256    []byte `json:"file_sha256,omitempty"`	FileEncSHA256 []byte `json:"file_enc_sha256,omitempty"`	FileLength    uint64 `json:"file_length,omitempty"`	// The message the file came in, as WhatsApp addressed it (the chat and sender may be hidden ids): what a	// request to the owner's phone to upload the file again names, once WhatsApp's servers no longer hold it.	MessageID string `json:"message_id,omitempty"`	Chat      string `json:"chat,omitempty"`	Sender    string `json:"sender,omitempty"`	FromMe    bool   `json:"from_me,omitempty"`	IsGroup   bool   `json:"is_group,omitempty"`}type MessageRef struct {	ID        string `json:"id"`	FromMe    bool   `json:"from_me"`	Sender    string `json:"sender,omitempty"`	Timestamp int64  `json:"ts"`}func encodeLine(v any) ([]byte, error) {	b, err := json.Marshal(v)	if err != nil {		return nil, err	}	return append(b, '\n'), nil}