X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/ec230eee6b06580031637bc97c99ec6db7b41926..0018014ab36f3de61a4b8a5515009dab803d6c38:/whatsapp.go?ds=inline diff --git a/whatsapp.go b/whatsapp.go index 05db5e4..3c519e8 100644 --- a/whatsapp.go +++ b/whatsapp.go @@ -37,10 +37,33 @@ const ( whatsappCommand = "/whatsapp" // whatsappUsage is the answer to a WhatsApp command that does not exist. - whatsappUsage = "Use /whatsapp status." + whatsappUsage = "Use /whatsapp pair PHONE, /whatsapp status, or /whatsapp unlink. PHONE is the number of your WhatsApp account with its country code, such as +15550001111." + + // whatsappPairSteps tells the user what to do with the pairing code, + // which comes in the next message. + whatsappPairSteps = "In WhatsApp on your phone, open Linked devices, tap Link a device, then tap Link with phone number instead, and enter the code of the next message. The code expires in about 2 minutes." + + // whatsappPairExpired is the answer when the pairing code expires. + whatsappPairExpired = "The pairing code expired. Run /whatsapp pair PHONE again for a new code." // whatsappTimeLayout is the layout of the times in the answers. whatsappTimeLayout = "2006-01-02 15:04" + + // whatsappPairTime is the longest time of a pairing. The library closes + // the pairing connection after about 160 seconds. + whatsappPairTime = 3 * time.Minute + + // whatsappLogoutTime is the longest time of the logout call of an + // unlink. + whatsappLogoutTime = 30 * time.Second + + // whatsappNoticeDelay is how long a disconnection lasts before the user + // gets a notice. + whatsappNoticeDelay = 10 * time.Minute + + // whatsappRequests is the number of pair and unlink commands that can + // wait for Run. + whatsappRequests = 8 ) // WhatsAppClient is the part of the WhatsApp client that the daemon uses. The @@ -49,23 +72,28 @@ const ( type WhatsAppClient interface { ConnectContext(ctx context.Context) error Disconnect() + GetQRChannel(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error) + PairPhone(ctx context.Context, phone string, showPushNotification bool, clientType whatsmeow.PairClientType, clientDisplayName string) (string, error) + Logout(ctx context.Context) error } // openWhatsApp opens the WhatsApp session in the data directory dir. Without // the session file, WhatsApp is not linked. The session gives full access to // the account, so a file that another user can read is an error. The clock // gives the times of the status, logger gets the failures, and newClient makes -// the client of a linked device with its event handler. +// the client of a device with its event handler. func openWhatsApp(ctx context.Context, dir string, clock func() time.Time, logger *log.Logger, newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient) (*WhatsApp, error) { w := &WhatsApp{ - dir: filepath.Join(dir, whatsappDirName), - clock: clock, - logger: logger, - newClient: newClient, + dir: filepath.Join(dir, whatsappDirName), + clock: clock, + logger: logger, + newClient: newClient, + noticeDelay: whatsappNoticeDelay, + requests: make(chan WhatsAppRequest, whatsappRequests), + logouts: make(chan struct{}, 1), } - path := filepath.Join(w.dir, whatsappSessionFileName) - info, err := os.Stat(path) + info, err := os.Stat(w.sessionPath()) if errors.Is(err, os.ErrNotExist) { return w, nil } @@ -78,19 +106,14 @@ func openWhatsApp(ctx context.Context, dir string, clock func() time.Time, logge return nil, fmt.Errorf("%s holds the WhatsApp session, so its mode must be 0600", filepath.Join(whatsappDirName, whatsappSessionFileName)) } - address, err := whatsappSessionAddress(path) + err = w.openSession(ctx) if err != nil { return nil, err } - w.container, err = sqlstore.New(ctx, "sqlite", address, waLog.Noop) - if err != nil { - return nil, fmt.Errorf("open WhatsApp session: %w", err) - } - - w.device, err = w.container.GetFirstDevice(ctx) - if err != nil { - return nil, errors.Join(fmt.Errorf("read WhatsApp device: %w", err), w.container.Close()) + if w.device.ID != nil { + w.linked = true + w.own = whatsappOwnIDs(w.device.ID.User, w.device.LID.User) } return w, nil @@ -98,56 +121,129 @@ func openWhatsApp(ctx context.Context, dir string, clock func() time.Time, logge // WhatsApp is the link of the daemon to the WhatsApp account of the user, as // a linked device. The session database of the library in dir holds the keys -// of the device. A device with an ID is linked, and Run keeps it connected. -// The library connects again by itself after a network failure. The mutex -// protects the state of the connection, which the event handler of the library -// changes from its own goroutines. +// of the device. Run keeps a linked device connected, and the library connects +// again by itself after a network failure. +// +// The commands pair and unlink go to Run as requests, and Run runs one at a +// time. A pairing runs in its own goroutine until its code expires, and a new +// pairing ends the one before. Its phone number and code go only to the answer +// of the client that asked. A logout from the phone comes as an event of the +// library, and Run deletes the session. The mutex protects the session, the +// client, and the state of the connection, which the event handler of the +// library changes from its own goroutines. // // The library logs nothing, because its log lines hold the ID of the own -// account, which is the phone number of the user. +// account, which is the phone number of the user. The own number and the own +// LID never go to the log of the agent or to the log of the daemon: redact +// removes them from the errors. type WhatsApp struct { - dir string - clock func() time.Time - logger *log.Logger - newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient - container *sqlstore.Container - device *store.Device - client WhatsAppClient + dir string + clock func() time.Time + logger *log.Logger + newClient func(device *store.Device, handle func(event any) bool) WhatsAppClient + noticeDelay time.Duration + requests chan WhatsAppRequest + logouts chan struct{} mutex sync.Mutex + container *sqlstore.Container + device *store.Device + client WhatsAppClient + linked bool + own []string + notify func(Event) connected bool connectedAt time.Time disconnectedAt time.Time + disconnections int + noticed bool + timer *time.Timer + closed bool } -// Run connects a linked device and keeps the connection until ctx ends. A -// failed first connection is logged, and the library tries again when the -// failure is one of the network. -func (w *WhatsApp) Run(ctx context.Context) { - if !w.linked() { - <-ctx.Done() - return - } +// Run connects a linked device, runs the pair and unlink commands, and handles +// a logout from the phone, until ctx ends. Its notes go to the log of l, and +// notify gets the notices for all clients. A failed first connection is +// logged, and the library tries again when the failure is one of the network. +func (w *WhatsApp) Run(ctx context.Context, l *TurnLoop, notify func(Event)) { + w.mutex.Lock() + w.notify = notify + linked := w.linked + w.mutex.Unlock() - w.client = w.newClient(w.device, w.handle) - err := w.client.ConnectContext(ctx) - if err != nil { - w.logger.Printf("connect: %v", err) + if linked { + w.connect(ctx) } - <-ctx.Done() - w.client.Disconnect() + var pairing sync.WaitGroup + cancel := func() {} + defer func() { + cancel() + pairing.Wait() + w.close() + }() + + for { + select { + case <-ctx.Done(): + return + case <-w.logouts: + w.loggedOut(l) + case request := <-w.requests: + cancel() + pairing.Wait() + cancel = func() {} + + switch { + case request.unlink: + w.unlink(ctx, l, request.answer) + case w.isLinked(): + request.answer("WhatsApp is linked already. Run /whatsapp unlink first.") + default: + pairCtx, cancelPair := context.WithTimeout(ctx, whatsappPairTime) + cancel = cancelPair + pairing.Go(func() { + defer cancelPair() + + w.pair(pairCtx, l, request.phone, request.answer) + }) + } + } + } } // Command runs the WhatsApp command args, the text after /whatsapp, and gives // each answer to answer. The answers go only to the client that sent the // command. func (w *WhatsApp) Command(args string, answer func(text string)) { - switch strings.TrimSpace(args) { - case "status": + fields := strings.Fields(args) + request := WhatsAppRequest{ + answer: answer, + } + + switch { + case len(fields) == 1 && fields[0] == "status": answer(w.Status()) + return + case len(fields) == 1 && fields[0] == "unlink": + request.unlink = true + case len(fields) >= 2 && fields[0] == "pair": + phone, valid := whatsappPhone(strings.Join(fields[1:], "")) + if !valid { + answer("PHONE must be the number of your WhatsApp account with its country code: 7 to 15 digits, such as +15550001111.") + return + } + + request.phone = phone default: answer(whatsappUsage) + return + } + + select { + case w.requests <- request: + default: + answer("Too many WhatsApp commands wait. Try again in a minute.") } } @@ -159,8 +255,8 @@ func (w *WhatsApp) Status() string { defer w.mutex.Unlock() switch { - case !w.linked(): - return "WhatsApp is not linked." + case !w.linked: + return "WhatsApp is not linked. Run /whatsapp pair PHONE to link it." case w.connected: return "WhatsApp is linked and connected since " + w.connectedAt.Format(whatsappTimeLayout) + "." case w.disconnectedAt.IsZero(): @@ -174,44 +270,431 @@ func (w *WhatsApp) Status() string { // Close closes the session database. func (w *WhatsApp) Close() error { + w.mutex.Lock() + defer w.mutex.Unlock() + if w.container == nil { return nil } - return w.container.Close() + err := w.container.Close() + w.container = nil + + return err +} + +func (w *WhatsApp) sessionPath() string { + return filepath.Join(w.dir, whatsappSessionFileName) +} + +// openSession opens the session database and its first device. The caller +// holds the mutex, or no other goroutine uses w yet. +func (w *WhatsApp) openSession(ctx context.Context) error { + address, err := whatsappSessionAddress(w.sessionPath()) + if err != nil { + return err + } + + container, err := sqlstore.New(ctx, "sqlite", address, waLog.Noop) + if err != nil { + return fmt.Errorf("open WhatsApp session: %w", err) + } + + device, err := container.GetFirstDevice(ctx) + if err != nil { + return errors.Join(fmt.Errorf("read WhatsApp device: %w", err), container.Close()) + } + + w.container = container + w.device = device + + return nil +} + +func (w *WhatsApp) isLinked() bool { + w.mutex.Lock() + defer w.mutex.Unlock() + + return w.linked +} + +// connect makes the client of the linked device and connects it. +func (w *WhatsApp) connect(ctx context.Context) { + w.mutex.Lock() + w.client = w.newClient(w.device, w.handle) + client := w.client + w.mutex.Unlock() + + err := client.ConnectContext(ctx) + if err != nil { + w.logger.Printf("connect: %s", w.redact(err.Error())) + } +} + +// close ends the connection and the timer of the notice, and stops all +// notices. +func (w *WhatsApp) close() { + w.mutex.Lock() + w.closed = true + if w.timer != nil { + w.timer.Stop() + } + + client := w.client + w.client = nil + w.mutex.Unlock() + + if client != nil { + client.Disconnect() + } +} + +// loggedOut deletes the session after a logout from the phone, notes it in the +// log of l, and tells all clients one time. +func (w *WhatsApp) loggedOut(l *TurnLoop) { + if !w.isLinked() { + return + } + + err := w.removeSession() + if err != nil { + w.logger.Printf("delete the session after the logout: %v", err) + } + + err = l.note("WhatsApp was unlinked from the phone.") + if err != nil { + w.logger.Printf("note the logout: %v", err) + } + + w.broadcast("WhatsApp was unlinked from the phone. Run /whatsapp pair PHONE to link it again.") } -// linked tells if the session holds a linked device. -func (w *WhatsApp) linked() bool { - return w.device != nil && w.device.ID != nil +// unlink logs out the linked device and deletes the session. When the logout +// call fails, as it does while WhatsApp is disconnected, the session is +// deleted all the same, and answer tells the user to remove the device in the +// phone. +func (w *WhatsApp) unlink(ctx context.Context, l *TurnLoop, answer func(text string)) { + w.mutex.Lock() + linked := w.linked + client := w.client + w.mutex.Unlock() + + if !linked { + answer("WhatsApp is not linked.") + return + } + + var logoutErr error + if client != nil { + ctx, cancel := context.WithTimeout(ctx, whatsappLogoutTime) + defer cancel() + + logoutErr = client.Logout(ctx) + } + + err := w.removeSession() + if err != nil { + answer("The unlink failed: " + w.redact(err.Error())) + return + } + + err = l.note("WhatsApp is unlinked.") + if err != nil { + w.logger.Printf("note the unlink: %v", err) + } + + if client == nil || logoutErr != nil { + 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.") + return + } + + answer("WhatsApp is unlinked.") +} + +// removeSession ends the connection, closes the session database, and deletes +// its files. +func (w *WhatsApp) removeSession() error { + w.mutex.Lock() + client := w.client + w.client = nil + w.linked = false + w.own = nil + w.connected = false + if w.timer != nil { + w.timer.Stop() + } + + w.noticed = false + container := w.container + w.container = nil + w.device = nil + w.mutex.Unlock() + + if client != nil { + client.Disconnect() + } + + var err error + if container != nil { + err = container.Close() + } + + for _, suffix := range []string{"", "-wal", "-shm"} { + removeErr := os.Remove(w.sessionPath() + suffix) + if !errors.Is(removeErr, os.ErrNotExist) { + err = errors.Join(err, removeErr) + } + } + + return err +} + +// pair links a new device to the account of phone with a pairing code. It +// gives the steps and the code to answer, and then the end of the pairing: +// the linked number, an expired code, or a failure. A pairing that a new one +// ends gives no answer. A link notes "WhatsApp is linked." in the log of l, +// with no number. The client of a pairing that does not link is disconnected. +func (w *WhatsApp) pair(ctx context.Context, l *TurnLoop, phone string, answer func(text string)) { + device, err := w.newDevice(ctx) + if err != nil { + answer("The pairing failed: " + err.Error()) + return + } + + client := w.newClient(device, w.handle) + linked := false + defer func() { + if !linked { + client.Disconnect() + } + }() + + qr, err := client.GetQRChannel(ctx) + if err == nil { + err = client.ConnectContext(ctx) + } + + if err != nil { + answer("The connection to WhatsApp failed: " + err.Error()) + return + } + + select { + case item, open := <-qr: + if !open || item.Event != whatsmeow.QRChannelEventCode { + answer("WhatsApp did not start the pairing. Try again later.") + return + } + case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + answer("The connection to WhatsApp did not start the pairing in time. Try again later.") + } + + return + } + + code, err := client.PairPhone(ctx, phone, true, whatsmeow.PairClientChrome, "Chrome (Linux)") + if err != nil { + answer("WhatsApp refused the pairing: " + err.Error() + ". Check the phone number and run /whatsapp pair PHONE again.") + return + } + + answer(whatsappPairSteps) + answer(code) + + for { + var item whatsmeow.QRChannelItem + open := true + select { + case item, open = <-qr: + case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + answer(whatsappPairExpired) + } + + return + } + + switch { + case !open || item.Event == whatsmeow.QRChannelTimeout.Event: + answer(whatsappPairExpired) + return + case item.Event == whatsmeow.QRChannelEventCode: + continue + case item.Event == whatsmeow.QRChannelSuccess.Event: + linked = true + w.linkedBy(client) + + err = l.note("WhatsApp is linked.") + if err != nil { + w.logger.Printf("note the link: %v", err) + } + + answer("WhatsApp is linked to +" + phone + ".") + + return + default: + answer("The pairing failed: " + whatsappItemError(item) + ". Run /whatsapp pair PHONE again.") + return + } + } +} + +// newDevice returns a new device in the session database. It makes the +// directory and the file of the session first, with their modes, when they do +// not exist. +func (w *WhatsApp) newDevice(ctx context.Context) (*store.Device, error) { + w.mutex.Lock() + defer w.mutex.Unlock() + + if w.container == nil { + err := os.MkdirAll(w.dir, 0o700) + if err != nil { + return nil, fmt.Errorf("create WhatsApp directory: %w", err) + } + + file, err := os.OpenFile(w.sessionPath(), os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, fmt.Errorf("create WhatsApp session: %w", err) + } + + err = file.Close() + if err != nil { + return nil, fmt.Errorf("create WhatsApp session: %w", err) + } + + err = w.openSession(ctx) + if err != nil { + return nil, err + } + } + + w.device = w.container.NewDevice() + + return w.device, nil +} + +// linkedBy makes client the client of the linked device. +func (w *WhatsApp) linkedBy(client WhatsAppClient) { + w.mutex.Lock() + defer w.mutex.Unlock() + + w.client = client + w.linked = true } // handle takes one event of the library and tells if it was handled. A // disconnection keeps the time of its start while the library tries again. +// After noticeDelay of a disconnection, all clients get one notice, and they +// get one more when the connection comes back. A disconnection that the +// library does not try again gives a notice at once. func (w *WhatsApp) handle(event any) bool { + var notice string w.mutex.Lock() - defer w.mutex.Unlock() - - switch event.(type) { + switch event := event.(type) { + case *events.PairSuccess: + w.own = whatsappOwnIDs(event.ID.User, event.LID.User) case *events.Connected: w.connected = true w.connectedAt = w.clock() + if w.timer != nil { + w.timer.Stop() + } + + if w.noticed { + w.noticed = false + notice = "WhatsApp is connected again." + } case *events.Disconnected: - if w.connected || w.disconnectedAt.IsZero() { + if w.linked && (w.connected || w.disconnectedAt.IsZero()) { w.disconnectedAt = w.clock() + w.disconnections++ + disconnections := w.disconnections + w.timer = time.AfterFunc(w.noticeDelay, func() { + w.disconnectedLong(disconnections) + }) } w.connected = false + case *events.LoggedOut: + select { + case w.logouts <- struct{}{}: + default: + } + case events.PermanentDisconnect: + if w.linked { + w.connected = false + w.noticed = true + notice = "WhatsApp is disconnected and does not connect again by itself: " + event.PermanentDisconnectDescription() + ". Restart the daemon to try again." + } + } + w.mutex.Unlock() + + if notice != "" { + w.broadcast(notice) } return true } +// disconnectedLong gives the notice of a long disconnection, unless the +// disconnection with the number disconnections ended. +func (w *WhatsApp) disconnectedLong(disconnections int) { + w.mutex.Lock() + long := !w.closed && w.linked && !w.connected && !w.noticed && w.disconnections == disconnections + if long { + w.noticed = true + } + + since := w.disconnectedAt + w.mutex.Unlock() + + if long { + w.broadcast("WhatsApp is disconnected since " + since.Format(whatsappTimeLayout) + ". OneChat tries again.") + } +} + +// broadcast gives text as a notice to all clients. +func (w *WhatsApp) broadcast(text string) { + w.mutex.Lock() + notify := w.notify + closed := w.closed + w.mutex.Unlock() + + if notify != nil && !closed { + notify(Event{ + Kind: "notice", + Text: text, + }) + } +} + +// redact replaces the own number and the own LID in text with OWN. +func (w *WhatsApp) redact(text string) string { + w.mutex.Lock() + defer w.mutex.Unlock() + + for _, id := range w.own { + text = strings.ReplaceAll(text, id, "OWN") + } + + return text +} + +// WhatsAppRequest is a pair or unlink command for Run, with the function that +// gives its answers to the client that asked. A pairing has the phone number. +type WhatsAppRequest struct { + phone string + unlink bool + answer func(text string) +} + // whatsappNewClient returns the client of the library for device, with handle // as its event handler. The client tries again after a failed first // connection, acknowledges a message only after handle returns true, and -// downloads no old history. +// downloads no old history. The phone shows the device with the name OneChat. func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsAppClient { + store.SetOSInfo("OneChat", [3]uint32{0, 1, 0}) client := whatsmeow.NewClient(device, waLog.Noop) client.InitialAutoReconnect = true client.SynchronousAck = true @@ -221,6 +704,18 @@ func whatsappNewClient(device *store.Device, handle func(event any) bool) WhatsA return client } +// whatsappOwnIDs returns the own number and the own LID that are not empty. +func whatsappOwnIDs(ids ...string) []string { + var own []string + for _, id := range ids { + if id != "" { + own = append(own, id) + } + } + + return own +} + // whatsappSessionAddress returns the SQLite address of the session database at // path, with foreign keys on, as the library needs, and a wait for a busy // database. @@ -254,3 +749,23 @@ func whatsappCommandArgs(line string) (string, bool) { return strings.TrimSpace(args), true } + +// whatsappPhone returns the digits of phone, a number with its country code +// and an optional + and dashes, and tells if it has the form of a number: 7 to +// 15 digits, with no 0 first. +func whatsappPhone(phone string) (string, bool) { + phone = strings.ReplaceAll(strings.TrimPrefix(phone, "+"), "-", "") + valid := len(phone) >= 7 && len(phone) <= 15 && phone[0] != '0' && strings.Trim(phone, "0123456789") == "" + + return phone, valid +} + +// whatsappItemError returns the error of a pairing item that is not a code, a +// success, or a timeout. +func whatsappItemError(item whatsmeow.QRChannelItem) string { + if item.Error != nil { + return item.Error.Error() + } + + return item.Event +}