No passo anterior você adicionou perfis e salas. Agora um app guarda várias conversas: uma "Family" e uma "Work" na mesma janela, cada uma com os próprios membros, salas e mensagens.
O código do chat que você escreveu nos passos 2 a 5 muda pouco. Ele vira o motor de uma conversa, e um serviço novo, Conversations, roda um motor por conversa e leva cada chamada da janela para o motor certo. Cada conversa mora na própria pasta, com a própria chave, kolo-id, logs, capacidade do pin e convites.
Este passo é só backend, como o passo 5: você escreve o código Go abaixo no projeto do passo anterior. A janela deste passo, com a lista de conversas, já está pronta, e você a traz com um comando.
1Confira o que você precisa
Você precisa do mesmo que no passo 5: Go 1.26 ou mais novo, Node.js, wails3, o nó de bootstrap e um pin local. Parta do projeto que você terminou no passo 5. Este passo não adiciona nenhuma biblioteca.
2Traga a janela
A janela deste passo tem uma primeira coluna nova, da altura toda da janela, com as suas conversas, o número de mensagens novas de cada uma, "New conversation" e "Join with an invite". Cada chamada que ela faz diz de qual conversa se trata. Ela já está pronta: traga-a da tag step-6. A tag também tem a versão pronta de cada arquivo abaixo, caso você queira comparar o seu.
git fetch origin --tagsgit checkout step-6 -- frontend3Guarde cada conversa na própria pasta
Até agora uma pasta de dados era uma conversa: a chave, o kolo-id, os logs e os convites ficavam na raiz da pasta. Agora a raiz tem um layout.json, que diz como a pasta está organizada, e uma pasta conversations/ com uma pasta por conversa:
<data>/ 0700
layout.json {"layout":2}, written once in a new data folder
conversations/ 0700
<id>/ 0700; 32 hex characters from crypto/rand, not from the key
identity.key the kolo-id of this conversation
local.json the name only you see, and when it was added
conversation.json the key and the pin (not there while a join waits)
members.json, directory-log, store/, invites/, pin-token as in step 5O ID da pasta de uma conversa é aleatório, então ele não diz nada sobre a chave. O nome dela é local: fica em local.json, nunca é enviado e só você vê.
Uma pasta de dados do passo 5 não tem layout.json e guarda na raiz os arquivos da única conversa dela. O app a recusa e não muda nada nela: não há migração, e nada é movido nem apagado. A mensagem diz qual é a pasta, para você tirá-la do caminho e começar de novo. Um layout.json de outra organização, ou um danificado, é recusado do mesmo jeito, e também uma pasta de dados que outros usuários podem abrir, porque eles poderiam renomear ou trocar o que o app guarda ali. Antes deste passo, o arquivo do kolo-id na raiz fazia o kolo-id recusar essa pasta; agora o próprio app confere.
Crie conversations.go com:
package main
//lint:file-ignore ST1005 these errors are sentences the window shows as they are
// Several conversations in one app.
//
// Each conversation lives in a folder of its own, <data>/conversations/<id>, with its own engine (ChatService) and
// so its own kolo-id, swarm, logs, pin and invites. One engine per conversation follows the rules of the libraries
// as they are: a pin keeps the newest capability of each owner, and a connection to a peer key serves one protocol.
// Conversations lists the folders, starts an engine for each, and routes every call of the window by ID.
import (
"cmp"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"time"
"unicode/utf8"
)Adicione a conversations.go os limites, os nomes que uma pasta do passo 5 tem e os erros. Cada erro é uma frase que a janela mostra do jeito que está:
const (
layoutVersion = 2
layoutFile = "layout.json"
conversationDir = "conversations"
localFile = "local.json"
defaultConvName = "Conversation"
maxConvName = 32 // characters in a conversation's name, as in a room's
maxConversations = 8 // engines one app runs, each with its own socket, swarm and two stores
)
// oldLayoutNames are the files a data folder of step 5 or older held at its top, for its one conversation.
var oldLayoutNames = []string{"identity.key", "conversation.json", "members.json", "directory-log", "store", "invites", "pin-token"}
var (
// ErrOldLayout matches the *DataDirError of a data folder of step 5 or older (Layout 1).
ErrOldLayout = errors.New("data folder made by Kolo Chat step 5 or older")
ErrUnknownConversation = errors.New("That conversation is not on this computer.")
ErrTooManyConversations = errors.New("You have the most conversations this app keeps.")
ErrNoPins = errors.New("Start Kolo Chat with -pin-key to start a conversation. You can still join one with an invite.")
ErrInvalidName = errors.New("That name cannot be used")
errNotStarted = errors.New("not started")
)A recusa é um erro tipado que diz qual é a pasta, para que a janela o mostre e o código possa perguntar errors.Is(err, ErrOldLayout):
// DataDirError is returned for a data folder this version cannot use, and nothing in it is changed. Layout 1 is a
// folder of step 5 or older, which held one conversation; another Layout is one of another version (-1: its
// layout.json is damaged), and Open one that other users can open. Dir is that folder.
type DataDirError struct {
Dir string `json:"dir"`
Layout int `json:"layout,omitempty"`
Open bool `json:"open,omitempty"`
}
func (e *DataDirError) Error() string {
switch {
case e.Open:
return "The data folder " + e.Dir + " is open to other users, who could change what Kolo Chat keeps in it. " +
"Run chmod 700 on it, or start with another -data. Nothing in the folder is changed."
case e.Layout == 1:
return "The data folder " + e.Dir + " holds one conversation of Kolo Chat step 5 or older, and this version keeps " +
"each conversation in a folder of its own. Quit Kolo Chat, move or rename that folder (nothing in it is " +
"deleted), then open Kolo Chat again: start a new conversation, or paste a new invite."
}
return fmt.Sprintf("The data folder %s was made by another version of Kolo Chat (layout %d). Use that version, "+
"or start with another -data. Nothing in the folder is changed.", e.Dir, e.Layout)
}
func (e *DataDirError) Is(target error) bool { return e.Layout == 1 && target == ErrOldLayout }openLayout roda primeiro em cada início. Ele escreve layout.json só em uma pasta nova, depois de conferir que nenhum dos nomes do passo 5 está lá:
// localInfo is local.json: the name only we see, and when the conversation was added here, in Unix seconds.
type localInfo struct {
Name string `json:"name"`
Created int64 `json:"created"`
}
// openLayout checks the data folder's layout.json, or writes it in a new folder. A folder of step 5 or older, or of
// another layout, is refused and nothing in it is changed: there is no migration.
func openLayout(root string) error {
if err := os.MkdirAll(root, 0o700); err != nil {
return err
}
if err := privateDir(root); err != nil {
return err
}
data, err := os.ReadFile(filepath.Join(root, layoutFile))
switch {
case err == nil:
var l struct {
Layout int `json:"layout"`
}
if json.Unmarshal(data, &l) != nil || l.Layout < layoutVersion {
return &DataDirError{Dir: root, Layout: -1}
}
if l.Layout != layoutVersion {
return &DataDirError{Dir: root, Layout: l.Layout}
}
if err := os.MkdirAll(filepath.Join(root, conversationDir), 0o700); err != nil { // deleted by hand: start empty
return err
}
return privateDir(filepath.Join(root, conversationDir))
case !errors.Is(err, fs.ErrNotExist): // a folder or a file we cannot read: no version wrote it
return &DataDirError{Dir: root, Layout: -1}
}
for _, name := range oldLayoutNames {
if _, err := os.Lstat(filepath.Join(root, name)); !errors.Is(err, fs.ErrNotExist) {
return &DataDirError{Dir: root, Layout: 1}
}
}
if err := os.MkdirAll(filepath.Join(root, conversationDir), 0o700); err != nil {
return err
}
if err := privateDir(filepath.Join(root, conversationDir)); err != nil {
return err
}
return writeJSON(filepath.Join(root, layoutFile), map[string]int{"layout": layoutVersion})
}
// privateDir refuses a folder that other users can open, who could list, rename or replace what the app keeps
// there. Windows has no such mode bits; there the folder's place in the user's profile protects it.
func privateDir(dir string) error {
fi, err := os.Stat(dir)
if err != nil {
return err
}
if runtime.GOOS != "windows" && fi.Mode().Perm()&0o077 != 0 {
return &DataDirError{Dir: dir, Open: true}
}
return nil
}A lista de conversas é a listagem de conversations/, então não existe uma segunda lista para manter em dia. Uma pasta sem conversation.json é uma entrada que espera a resposta de um convite. Um local.json que falta ou está danificado dá o nome "Conversation", e a conversa abre mesmo assim:
// listConversations lists the conversation folders, oldest first. Of the folders without a conversation.json, the
// joins that wait, only the first is used.
func listConversations(root string) ([]*convEntry, error) {
dir := filepath.Join(root, conversationDir)
items, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
var all []*convEntry
for _, it := range items {
if !it.IsDir() || !validID(it.Name()) {
log.Printf("%s/%q: not a conversation, ignored", conversationDir, it.Name())
continue
}
e := &convEntry{id: it.Name(), dir: filepath.Join(dir, it.Name())}
e.local = loadLocal(e.dir)
_, err := os.Lstat(filepath.Join(e.dir, "conversation.json"))
e.joined = err == nil
all = append(all, e)
}
slices.SortFunc(all, compareEntries)
out, pending := all[:0], false
for _, e := range all {
if !e.joined && pending {
log.Printf("%s/%s: not a conversation, ignored", conversationDir, e.id)
continue
}
pending = pending || !e.joined
out = append(out, e)
}
return out, nil
}
func compareEntries(x, y *convEntry) int {
return cmp.Or(cmp.Compare(x.local.Created, y.local.Created), strings.Compare(x.id, y.id))
}
// loadLocal reads local.json. A damaged or missing one gives the name "Conversation", and the conversation opens.
func loadLocal(dir string) localInfo {
var l localInfo
data, err := os.ReadFile(filepath.Join(dir, localFile))
if err == nil {
err = json.Unmarshal(data, &l)
}
if err != nil {
return localInfo{Name: defaultConvName}
}
if l.Name, err = convName(l.Name, defaultConvName); err != nil {
l.Name = defaultConvName
}
return l
}
// convName checks a conversation's name: plain text of 1 to maxConvName characters. An empty one is def, or refused
// when def is empty.
func convName(name, def string) (string, error) {
if name = strings.TrimSpace(name); name == "" {
name = def
}
if name == "" || utf8.RuneCountInString(name) > maxConvName || !plainText(name) {
return "", fmt.Errorf("%w: a name has 1 to %d characters, with no control characters.", ErrInvalidName, maxConvName)
}
return name, nil
}
// validID says whether id is one the app makes: 32 lowercase hex characters.
func validID(id string) bool {
return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == ""
}
// writeJSON replaces the file at path with v in one step, mode 0600.
func writeJSON(path string, v any) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}4Dê a cada conversa o próprio kolo-id e o próprio swarm
Por que não um só kolo-id e um só swarm para todas as conversas? Duas regras das bibliotecas decidem. Um pin guarda a capacidade mais recente de cada dono, então com um só kolo-id a capacidade de uma conversa tiraria do pin os logs da outra. E uma conexão com a chave de um peer serve a um só protocolo, então alguém já conectado a você em uma conversa não conseguiria usar nessa conexão o convite de outra. Com um motor por conversa nenhuma das duas coisas acontece, e o código dos passos 2 a 5 fica como está.
A janela recebe uma lista de ConversationInfo, e cada evento de um motor chega a ela como um ConvEvent, com o ID da conversa:
// ConversationInfo is one conversation as the window lists it. Me is our kolo-id in it, Joined is false for the
// join that waits for an invite's answer, and Error says why it did not start, with the Folder it is in.
type ConversationInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Me string `json:"me"`
Joined bool `json:"joined"`
Owner bool `json:"owner"`
Error string `json:"error"`
Folder string `json:"folder"`
}
// AppInfo is what Start returns. CanCreate says the app has a pin, which a new conversation needs.
type AppInfo struct {
Conversations []ConversationInfo `json:"conversations"`
MaxConversations int `json:"maxConversations"`
CanCreate bool `json:"canCreate"`
}
// ConvEvent is the payload of every chat event: the conversation it is about, and the engine's payload.
type ConvEvent struct {
Conv string `json:"conv"`
Data any `json:"data"`
}
// convEntry is one conversation folder and its engine, nil when it did not start.
type convEntry struct {
id, dir string
local localInfo
joined bool
chat *ChatService
me string
err error
}
// Conversations is the window's service: it keeps one engine per conversation folder and routes every call by ID.
type Conversations struct {
cfg Config
emit func(name string, data any)
opMu sync.Mutex // one Start, Create, Join or ServiceShutdown at a time
set settings
root string
mu sync.Mutex // guards the fields below
started bool
convs map[string]*convEntry
}
// NewConversations returns the service that reads cfg when it starts and tells the window what happens through emit.
func NewConversations(cfg Config, emit func(name string, data any)) *Conversations {
return &Conversations{cfg: cfg, emit: emit}
}Um motor é um ChatService com a configuração do app, na pasta da conversa. A chave, o pin e o token da linha de comando vão só para a conversa que eles nomeiam. O emit do motor embrulha cada evento com o ID:
// engineConfig is the configuration of one engine: the app's, in the conversation's folder. The key, the pin and
// the token are only for the -conversation-key conversation; every other one reads its own conversation.json.
func (a *Conversations) engineConfig(dir string, configured bool) Config {
cfg := a.cfg
cfg.DataDir = dir
if !configured {
cfg.ConversationKey, cfg.PinAddr, cfg.PinKey, cfg.PinToken = "", "", "", ""
}
return cfg
}
// startEngine starts the conversation's engine, whose events go to the window tagged with the conversation's ID.
func (a *Conversations) startEngine(e *convEntry, cfg Config) {
c := NewChatService(cfg, func(name string, data any) { a.emit(name, ConvEvent{Conv: e.id, Data: data}) })
if e.me, e.err = c.Start(); e.err == nil {
e.chat, e.joined = c, c.Joined()
} else {
log.Printf("conversation %s did not start: %v", e.id, e.err)
}
}
func (a *Conversations) add(e *convEntry) {
a.mu.Lock()
defer a.mu.Unlock()
a.convs[e.id] = e
}5Crie conversas e entre nelas
Start abre a pasta de dados, lista as conversas e inicia todos os motores de uma vez. Uma conversa que não inicia mostra o motivo na sua linha da lista, com a pasta dela, e as outras funcionam. -conversation-key continua funcionando: inicia a pasta cujo conversation.json tem essa chave, ou cria uma para ela. Uma porta fixa em -listen comporta uma só conversa, porque cada motor tem o próprio socket:
// Start opens the data folder and starts every conversation in it, each on its own. It fails only for a bad
// setting (*ConfigError) or a data folder it cannot use (*DataDirError): a conversation that does not start
// shows its Error in the list, and the others run.
func (a *Conversations) Start() (AppInfo, error) {
a.opMu.Lock()
defer a.opMu.Unlock()
if a.isStarted() {
return a.info(), nil
}
set, err := a.cfg.resolve()
if err != nil {
return AppInfo{}, err
}
if err := openLayout(set.DataDir); err != nil {
return AppInfo{}, err
}
entries, err := listConversations(set.DataDir)
if err != nil {
return AppInfo{}, err
}
a.set, a.root = set, set.DataDir
configured, err := a.findConfigured(entries)
if err != nil {
return AppInfo{}, err
}
isNew := configured != nil && !slices.Contains(entries, configured)
if isNew {
entries = append(entries, configured)
}
if set.fixedPort() && len(entries) > 1 {
if isNew {
a.dropFolder(configured)
}
return AppInfo{}, &ConfigError{Setting: "listen", Err: errFixedPort}
}
a.mu.Lock()
a.started, a.convs = true, map[string]*convEntry{}
a.mu.Unlock()
var wg sync.WaitGroup
for _, e := range entries {
wg.Go(func() { a.startEngine(e, a.engineConfig(e.dir, e == configured)) })
}
wg.Wait()
for _, e := range entries {
a.add(e)
}
if isNew && configured.err != nil { // a bad setting, such as a -pin-token, as before there were several
a.dropFolder(configured)
a.shutdown()
return AppInfo{}, configured.err
}
a.emitList()
return a.info(), nil
}
// findConfigured returns the conversation that -conversation-key names: the folder whose conversation.json holds
// the key, or a new folder for it. It is nil without the setting.
func (a *Conversations) findConfigured(entries []*convEntry) (*convEntry, error) {
if !a.set.inConversation {
return nil, nil
}
for _, e := range entries {
if v, found, err := loadConversation(e.dir); err == nil && found && slices.Equal(v.Key, a.set.conversationKey[:]) {
return e, nil
}
}
return a.newFolder(defaultConvName)
}Create começa uma conversa da qual você é dono. A chave dela são 32 bytes de crypto/rand, na memória até o motor salvá-la em conversation.json, com modo 0600. Ela usa o pin de -pin e -pin-key. Um Create que falha antes de a chave ser salva apaga a pasta nova:
// Create starts a new conversation that we own, with a key from crypto/rand and the app's pin. name is only ours.
func (a *Conversations) Create(name string) (ConversationInfo, error) {
a.opMu.Lock()
defer a.opMu.Unlock()
name, err := convName(name, defaultConvName)
if err != nil {
return ConversationInfo{}, err
}
if err := a.hasRoom(); err != nil {
return ConversationInfo{}, err
}
if len(a.set.pinKey) == 0 {
return ConversationInfo{}, ErrNoPins
}
e, err := a.newFolder(name)
if err != nil {
return ConversationInfo{}, err
}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
a.dropFolder(e)
return ConversationInfo{}, err
}
cfg := a.engineConfig(e.dir, false)
cfg.ConversationKey, cfg.PinAddr, cfg.PinKey = hex.EncodeToString(key), a.cfg.PinAddr, a.cfg.PinKey
clear(key)
if a.startEngine(e, cfg); e.err != nil {
a.dropFolder(e)
return ConversationInfo{}, e.err
}
a.add(e)
a.emitList()
return a.infoOf(e), nil
}
// newFolder makes the folder of a new conversation, with a random ID that has nothing to do with its key.
func (a *Conversations) newFolder(name string) (*convEntry, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return nil, err
}
id := hex.EncodeToString(b)
e := &convEntry{id: id, dir: filepath.Join(a.root, conversationDir, id), local: localInfo{Name: name, Created: time.Now().Unix()}}
if err := os.Mkdir(e.dir, 0o700); err != nil {
return nil, err
}
if err := writeJSON(filepath.Join(e.dir, localFile), e.local); err != nil {
os.RemoveAll(e.dir)
return nil, err
}
return e, nil
}
// dropFolder removes the folder of a conversation that failed before it had a conversation.json: nothing in it is
// worth keeping.
func (a *Conversations) dropFolder(e *convEntry) {
if _, err := os.Lstat(filepath.Join(e.dir, "conversation.json")); errors.Is(err, fs.ErrNotExist) {
os.RemoveAll(e.dir)
}
}Join recebe um código de convite e um nome. Cada convite é uma conversa própria, em uma pasta nova com um kolo-id novo, então quem convidou você nunca está já conectado a esse kolo-id. Um Join que falha, ou que você cancela, mantém a pasta, e o próximo Join a usa de novo. O limite de oito conversas conta a entrada que espera:
// Join uses an invite code in the join that waits, or in a new folder: each invite is a conversation of its own,
// with a new kolo-id. A Join that fails or is cancelled keeps that folder for the next one.
func (a *Conversations) Join(code, name string) (ConversationInfo, error) {
name, err := convName(name, defaultConvName)
if err != nil {
return ConversationInfo{}, err
}
a.opMu.Lock()
e, err := a.pendingJoin()
a.opMu.Unlock()
if err != nil {
return ConversationInfo{}, err
}
if err := e.chat.Join(code); err != nil {
return ConversationInfo{}, err
}
a.opMu.Lock()
defer a.opMu.Unlock()
a.mu.Lock()
e.local.Name, e.joined = name, true
local := e.local
a.mu.Unlock()
if err := writeJSON(filepath.Join(e.dir, localFile), local); err != nil {
log.Print("conversation name: ", err) // the conversation works, and shows as "Conversation" after a restart
}
a.emitList()
return a.infoOf(e), nil
}
// pendingJoin returns the conversation that waits for a join, made and started when there is none. One that did not
// start is refused with its error: its folder has to be moved first.
func (a *Conversations) pendingJoin() (*convEntry, error) {
a.mu.Lock()
var pending *convEntry
for _, e := range a.convs {
if !e.joined {
pending = e
}
}
a.mu.Unlock()
switch {
case pending != nil && pending.chat == nil:
return nil, pending.err
case pending != nil:
return pending, nil
}
if err := a.hasRoom(); err != nil {
return nil, err
}
e, err := a.newFolder(defaultConvName)
if err != nil {
return nil, err
}
if a.startEngine(e, a.engineConfig(e.dir, false)); e.err != nil {
a.dropFolder(e)
return nil, e.err
}
a.add(e)
a.emitList() // the window shows the kolo-id the join uses, for an invite that needs approval
return e, nil
}
// CancelJoin stops the Join that waits, for the inviter or for its answer.
func (a *Conversations) CancelJoin() {
a.mu.Lock()
var c *ChatService
for _, e := range a.convs {
if !e.joined && e.chat != nil {
c = e.chat
}
}
a.mu.Unlock()
if c != nil {
c.CancelJoin()
}
}
// hasRoom says whether one more conversation may be added: the bound counts the join that waits and the ones that
// did not start, and a fixed -listen port holds one conversation only.
func (a *Conversations) hasRoom() error {
a.mu.Lock()
defer a.mu.Unlock()
switch n := len(a.convs); {
case !a.started:
return errNotStarted
case n >= maxConversations:
return ErrTooManyConversations
case n >= 1 && a.set.fixedPort():
return &ConfigError{Setting: "listen", Err: errFixedPort}
}
return nil
}6Leve as chamadas da janela para a conversa certa
Cada chamada da janela nomeia a sua conversa. engine procura o ID no mapa de motores rodando e devolve ErrUnknownConversation para qualquer outro. O mapa só tem IDs que o app listou ou criou, então nenhum caminho é montado com o que a janela envia:
// List returns the conversations in the order they were added, never nil.
func (a *Conversations) List() []ConversationInfo {
a.mu.Lock()
entries := make([]convEntry, 0, len(a.convs))
for _, e := range a.convs {
entries = append(entries, *e)
}
a.mu.Unlock()
slices.SortFunc(entries, func(x, y convEntry) int { return compareEntries(&x, &y) })
out := make([]ConversationInfo, 0, len(entries))
for _, e := range entries {
out = append(out, e.info())
}
return out
}
func (e convEntry) info() ConversationInfo {
info := ConversationInfo{ID: e.id, Name: e.local.Name, Me: e.me, Joined: e.joined}
if e.chat != nil {
info.Owner = e.chat.IsOwner()
}
if e.err != nil {
info.Error, info.Folder = e.err.Error(), e.dir
}
return info
}
func (a *Conversations) info() AppInfo {
return AppInfo{Conversations: a.List(), MaxConversations: maxConversations, CanCreate: len(a.set.pinKey) > 0}
}
func (a *Conversations) infoOf(e *convEntry) ConversationInfo {
a.mu.Lock()
snapshot := *e
a.mu.Unlock()
return snapshot.info()
}
func (a *Conversations) emitList() { a.emit("chat:conversations", a.List()) }// Send, Members and the methods down to Deny are the engine's, for the conversation conv.
func (a *Conversations) Send(conv, room, text string) error {
return call(a, conv, func(c *ChatService) error { return c.Send(room, text) })
}
func (a *Conversations) Members(conv string) ([]Member, error) {
return get(a, conv, (*ChatService).Members)
}
func (a *Conversations) Rooms(conv string) ([]string, error) {
return get(a, conv, (*ChatService).Rooms)
}
func (a *Conversations) IsOwner(conv string) (bool, error) {
return get(a, conv, (*ChatService).IsOwner)
}
func (a *Conversations) SetProfile(conv, name, avatar string) error {
return call(a, conv, func(c *ChatService) error { return c.SetProfile(name, avatar) })
}
func (a *Conversations) AddRoom(conv, name string) error {
return call(a, conv, func(c *ChatService) error { return c.AddRoom(name) })
}
func (a *Conversations) CreateInvite(conv string, opts InviteOptions) (InviteInfo, error) {
c, err := a.engine(conv)
if err != nil {
return InviteInfo{}, err
}
return c.CreateInvite(opts)
}
func (a *Conversations) Invites(conv string) ([]InviteInfo, error) {
c, err := a.engine(conv)
if err != nil {
return nil, err
}
return c.Invites()
}
func (a *Conversations) Revoke(conv, id string) error {
return call(a, conv, func(c *ChatService) error { return c.Revoke(id) })
}
func (a *Conversations) Approve(conv string, request uint64) error {
return call(a, conv, func(c *ChatService) error { return c.Approve(request) })
}
func (a *Conversations) Deny(conv string, request uint64) error {
return call(a, conv, func(c *ChatService) error { return c.Deny(request) })
}// engine returns the running engine of conv. Only IDs the app listed or made are in the map, so no path is ever
// built from what the window sends.
func (a *Conversations) engine(conv string) (*ChatService, error) {
a.mu.Lock()
defer a.mu.Unlock()
if e := a.convs[conv]; e != nil && e.chat != nil {
return e.chat, nil
}
return nil, ErrUnknownConversation
}
func call(a *Conversations, conv string, f func(*ChatService) error) error {
c, err := a.engine(conv)
if err != nil {
return err
}
return f(c)
}
func get[T any](a *Conversations, conv string, f func(*ChatService) T) (T, error) {
c, err := a.engine(conv)
if err != nil {
var zero T
return zero, err
}
return f(c), nil
}Quando o app fecha, o Wails chama ServiceShutdown, que para todos os motores:
// ServiceShutdown stops every conversation. Wails calls it when the app quits.
func (a *Conversations) ServiceShutdown() error {
a.opMu.Lock()
defer a.opMu.Unlock()
return a.shutdown()
}
func (a *Conversations) shutdown() error {
a.mu.Lock()
engines := a.running()
a.started, a.convs = false, nil
a.mu.Unlock()
errs := make([]error, len(engines))
var wg sync.WaitGroup
for i, c := range engines {
wg.Go(func() { errs[i] = c.ServiceShutdown() })
}
wg.Wait()
return errors.Join(errs...)
}
// running returns the engines that run. The caller holds mu.
func (a *Conversations) running() []*ChatService {
var out []*ChatService
for _, e := range a.convs {
if e.chat != nil {
out = append(out, e.chat)
}
}
return out
}
func (a *Conversations) isStarted() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.started
}7Deixe o pin começar conversas
No passo 5, -pin-key era recusado sem -conversation-key. Agora -pin e -pin-key nomeiam o pin das conversas que você começa na janela, então -pin-key é aceito sozinho. -pin-token continua precisando de -conversation-key: um token é emitido por um kolo-id, e só aquela conversa o tem.
Em config.go, troque as causas de um ConfigError por:
// Causes of a ConfigError, besides the errors of kolo-pin for a bad token.
var (
ErrMissing = errors.New("is required")
ErrMalformed = errors.New("is malformed")
errFixedPort = errors.New("has a fixed port, which only one conversation can use: use port 0")
)Em config.go, troque Config por:
// Config is everything the chat needs from outside. A zero field takes its default, if it has one.
// LoadConfig fills it from flags and environment variables.
type Config struct {
DataDir string // -data, KOLO_CHAT_DATA: one folder per conversation, see conversations.go. Default: <user config dir>/kolo-chat
Bootstrap string // -bootstrap, KOLO_CHAT_BOOTSTRAP: IP:PORT of a bootstrap node. Default 127.0.0.1:4000
Listen string // -listen, KOLO_CHAT_LISTEN: local IP:PORT of every conversation. Default 127.0.0.1:0; a fixed port allows one conversation
ConversationKey string // -conversation-key, KOLO_CHAT_CONVERSATION_KEY: 64 hex characters (32 bytes), the key of one conversation, kept in its folder. Empty to start conversations in the window or join with an invite
PinAddr string // -pin, KOLO_CHAT_PIN: IP:PORT of the pin. Default 127.0.0.1:7450. The pin of the conversations started here; a joiner gets the pin from the invite
PinKey string // -pin-key, KOLO_CHAT_PIN_KEY: the pin's public key in hex (`kolo-pin id`). Required with a conversation key and to start conversations in the window
PinToken string // -pin-token, KOLO_CHAT_PIN_TOKEN: a capability in hex for the -conversation-key conversation, issued by its kolo-id. Default: the app issues one
PinTTL time.Duration // -pin-ttl, KOLO_CHAT_PIN_TTL: lifetime of the capability the app issues. Default 720h
PinQuota uint64 // -pin-quota, KOLO_CHAT_PIN_QUOTA: bytes the pin may keep for you, in the capability the app issues. Default 16777216
LookupInterval time.Duration // -lookup-interval, KOLO_CHAT_LOOKUP_INTERVAL: time between topic lookups. Default 5s
}Em LoadConfig, troque as linhas de conversation-key, pin, pin-key e pin-token por:
{"conversation-key", "KOLO_CHAT_CONVERSATION_KEY", "32-byte key of one conversation, in hex (leave it out to start conversations in the window or join with an invite)", text(&c.ConversationKey)},
{"pin", "KOLO_CHAT_PIN", "IP:PORT of the pin (default " + defaultPinAddr + ")", text(&c.PinAddr)},
{"pin-key", "KOLO_CHAT_PIN_KEY", "public key of the pin, in hex: the pin of the conversations you start (required with -conversation-key)", text(&c.PinKey)},
{"pin-token", "KOLO_CHAT_PIN_TOKEN", "capability for the pin of the -conversation-key conversation, in hex (default: issued by the app)", text(&c.PinToken)},Em config.go, troque o comentário de resolve por:
// resolve applies the defaults and checks every setting, returning a *ConfigError for the first bad one.
// Without a conversation key a chat starts as a joiner: the key and the pin come from an invite (see
// useConversation). The pin is then the one of the conversations started in the window, and a token, which is
// for the key's conversation only, is refused. A token is checked later, in capability, because it needs the
// identity.
func (c Config) resolve() (settings, error) {Em resolve, troque as verificações da chave da conversa e da chave do pin, até s.inConversation = true, por:
if c.ConversationKey == "" && c.PinToken != "" {
return s, &ConfigError{Setting: "conversation-key", Err: ErrMissing}
}
if c.ConversationKey != "" || c.PinKey != "" {
s.pinKey = make(ed25519.PublicKey, ed25519.PublicKeySize)
if err := parseHex("pin-key", c.PinKey, s.pinKey); err != nil {
return s, err
}
}
if c.ConversationKey == "" {
return s, nil
}
if err := parseHex("conversation-key", c.ConversationKey, s.conversationKey[:]); err != nil {
return s, err
}
s.inConversation = trueAdicione a config.go:
// fixedPort says whether the listen address names a port, which one socket only can hold.
func (s settings) fixedPort() bool {
ap, err := netip.ParseAddrPort(s.Listen)
return err == nil && ap.Port() != 0
}Um dono do passo 5 informava a chave a cada início. Uma conversa criada com New conversation só tem a chave na própria pasta, então agora o motor guarda em conversation.json a chave que recebeu. Em invite.go, troque savedConversation por:
// savedConversation returns the conversation this chat is in at start: the one in the configuration, or the one
// the data directory keeps, from an invite or from an earlier start with a key. A joiner that has none yet returns
// false. The configured one is kept, so the app finds it again after a restart.
func (c *ChatService) savedConversation() (conversation, bool, error) {
saved, found, err := loadConversation(c.set.DataDir)
if err != nil {
return saved, false, err
}
if !c.set.inConversation {
return saved, found, nil
}
mine := conversation{Key: slices.Clone(c.set.conversationKey[:]), PinAddr: c.set.PinAddr, PinKey: slices.Clone(c.set.pinKey), Owner: slices.Clone(c.pub)}
if found && !slices.Equal(saved.Key, mine.Key) {
err := errors.New("is not the conversation this data directory joined with an invite: use another -data")
return mine, false, &ConfigError{Setting: "conversation-key", Err: err}
}
if found {
mine.Owner = saved.Owner // a member that also has the key is still a member
}
if err := saveConversation(c.set.DataDir, mine); err != nil {
return mine, false, err
}
return mine, true, nil
}O motor não é mais o serviço da janela. Em chatservice.go, adicione este comentário acima de ChatService:
// ChatService is the engine of one conversation: its own kolo-id, swarm, logs, pin and invites in its own folder.
// Conversations runs one per conversation and routes the window's calls to it.
type ChatService struct {Em chatservice.go, troque o comentário de ServiceShutdown por:
// ServiceShutdown stops the chat and closes the store. Conversations calls it when the app quits.
func (c *ChatService) ServiceShutdown() error {8Ligue tudo no main.go
Agora a janela fala com Conversations. Em main.go, troque o comentário acima de emit e o serviço por:
// Each conversation tells the window what happens by emitting events; the Wails app is only needed once one is.
emit := func(name string, data any) { application.Get().Event.Emit(name, data) }
app := application.New(application.Options{
Name: "Kolo Chat",
Description: "Peer-to-peer desktop chat built with Kolo",
Icon: appIcon,
Services: []application.Service{
application.NewService(NewConversations(cfg, emit)),9O que a janela faz com isso
A janela guarda separado o estado de cada conversa. Ela escuta cada evento do chat e o entrega à conversa que ele nomeia, e à lista:
const offs = CHAT_EVENTS.map((name) => Events.On(name, (e) => dispatch({ type: 'event', name, payload: e.data })))
offs.push(Events.On('chat:conversations', (e) => dispatch({ type: 'list', list: e.data })))Enviar nomeia a conversa selecionada:
Send(id, room, text)
.then(() => {
setError('')
dispatch({ type: 'sent', conv: id, from: row.me, room, text })
})
.catch((err) => setError(errorText(err)))New conversation chama Create com o nome que você digitou:
Create(name)
.then((info) => {
setName('')
setNaming(false)
onCreated(info)
})
.catch((err) => setError(errorText(err)))E Join with an invite chama Join com o código e o nome:
Join(code, name)
.then((info) => onJoined(info))10Rode
Inicie o nó de bootstrap e deixe-o rodando:
go run ./cmd/bootstrapEm outro terminal, inicie o pin local e deixe-o rodando:
go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin run -data .data/pin -max-bytes 100MBCompile o app:
GOWORK=off wails3 buildAs pastas de dados do passo 5 agora são recusadas. Experimente, se quiser: a janela diz qual é a pasta e que nada nela foi mudado.
./bin/kolo-chat -data .data/aliceEntão use pastas novas. A Alice só precisa da chave pública do pin, no terminal dela, para começar conversas:
export KOLO_CHAT_PIN_KEY=$(go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin id -data .data/pin)./bin/kolo-chat -data .data/alice-6Na janela da Alice clique em New conversation, digite "Family" e clique em Create. Faça de novo com "Work". Cada conversa tem o próprio kolo-id: o começo da chave ao lado de "you" muda quando você seleciona a outra.
Inicie o Bob em outro terminal, sem a variável:
./bin/kolo-chat -data .data/bob-6O Bob entra nas duas. Na janela da Alice selecione Family, clique em Invite e crie um convite. Na janela do Bob clique em Join with an invite, cole o código, digite o nome "Family" e clique em Join. Com "Require my approval", a Alice vê "wants to join" em Family e clica em Approve. Depois faça o mesmo com Work. O Bob entra na segunda conversa da Alice enquanto está na primeira: para ele, o outro kolo-id da Alice é um desconhecido.
Inicie a Carol em um terceiro terminal, e convide-a só para Work:
./bin/kolo-chat -data .data/carol-6Envie uma mensagem em Family e outra em Work. Cada uma aparece só na própria conversa. A janela da Carol tem Work e nada de Family. Quando chega uma mensagem em uma conversa que você não selecionou, a lista mostra quantas são novas.
11Rode os testes
A tag tem os testes deste passo: duas conversas que nunca veem as mensagens uma da outra, uma segunda entrada enquanto você está na primeira, as duas conversas em um mesmo pin, a recusa de uma pasta do passo 5, -conversation-key e cada chamada recusada. Traga-os:
git checkout step-6 -- '*_test.go'GOWORK=off go test ./...12O que fica separado, e os limites
Cada conversa tem a própria chave, kolo-id, perfil, salas, logs, capacidade do pin e convites. O nome de uma conversa é local. Os membros de duas conversas não conseguem ligar você pelo kolo-id, porque você tem um diferente em cada uma, mas o endereço do seu computador e o horário das suas conexões ainda conseguem.
Conheça os limites:
- Não há Leave neste passo. O exemplo pronto tem Leave, que tira uma conversa do seu computador: a pasta dela, com a chave, os logs, os convites e o kolo-id que ela usava. Os outros não são avisados e guardam o que você enviou, e as suas outras conversas continuam.
- Não dá para remover um membro. Ninguém consegue remover um membro nem trocar a chave de uma conversa, como no passo 5. Revogar um convite barra gente nova, não quem já entrou.
- No máximo oito conversas, contando a entrada que espera. Cada uma custa um socket UDP, um nó DHT, um swarm e dois armazenamentos Pebble. O exemplo pronto transforma o limite em uma configuração, 64 por padrão.
- Pastas antigas são recusadas. Uma pasta de dados do passo 5 é recusada, nunca migrada, e nada nela é mudado.
- Uma porta fixa, uma conversa. Com
-listenem uma porta diferente de 0, uma segunda conversa é recusada. - Um segundo convite para a mesma conversa cria uma segunda pasta com um segundo kolo-id: os outros veem um membro novo.
Próximos passos
- Combinem quem está em uma conversa e quais salas ela tem: Passo 7: Combine membros e salas com o kolo-braid.
- O exemplo pronto, kolo-chat-wails3-example, adiciona Leave, uma configuração para o limite, relays de conexão, o notch e a bandeja. O
docs/how-it-works.mddele, seção "Several conversations", conta como; odocs/security.mddele tem as notas de segurança. O exemplo pronto mostra uma única lista de salas, uma para cada conversa, e o pin dele é opcional: sem ele, as mensagens chegam às pessoas só enquanto elas estão online. - Leia a página do kolo-swarm: uma conexão por chave de peer, e os topics.
- Para comparar seus arquivos com os prontos, use a tag
step-6do repositório do starter.