From 7df4d43f7f92d5b94291fedbf0c9e96bf0f4055b Mon Sep 17 00:00:00 2001 From: rodrigopavezi Date: Tue, 17 Nov 2026 04:55:08 -0300 Subject: [PATCH] feat: polls, events and votes as a page Acting as a page, a post could not carry a poll or an event, and the page could not vote or answer an event. A page now does what a person does. - account service: a page root post takes poll or event, built by the same postRecord as a person's; options, event title and place go through the blocklist; new page action choice {to, pick} writes the person's choiceRecord, pick null withdraws; status gains picked, the picks since the last withdrawal per target, newest first, so the app folds them as readers do; close tombstones every choice - app: Publicar posts a poll or event as a page; PollCard and EventCard read and set the page's vote when acting as a page, drop answers that land after an identity switch, and resend only on an explicit tap - legal: Termos and Politica describe page polls, events and votes - docs: protocol, rpc 5.84, app.md, changelog, verification --- CHANGELOG.md | 1 + apps/app/src/legal.js | 10 +- apps/app/src/pageChoice.js | 102 ++++++ apps/app/src/pagePost.js | 15 +- apps/app/src/pages.js | 14 +- apps/app/src/screens/ARua.js | 10 +- apps/app/src/screens/Conversa.js | 86 ++++- apps/app/src/screens/Publicar.js | 38 ++- apps/app/src/ui/EventCard.js | 56 +++- apps/app/src/ui/PollCard.js | 60 +++- apps/app/test/legal.test.js | 23 +- apps/app/test/musicDraft.test.js | 4 +- apps/app/test/pageChoice.test.js | 163 ++++++++++ apps/app/test/pagePost.test.js | 13 + apps/app/test/pages.test.js | 15 + apps/app/test/pollDraftGuard.test.js | 2 +- apps/app/test/postShareRow.test.js | 5 +- apps/cli/lib/account/pages-routes.js | 88 ++++- apps/cli/lib/account/pages-writer.js | 2 +- apps/cli/test/pages-choice.test.js | 336 ++++++++++++++++++++ apps/site/public/privacidade/index.html | 8 +- apps/site/public/termos/index.html | 10 +- apps/site/test/legal.test.js | 2 +- docs/app.md | 6 +- docs/changelog/feat-page-polls-events.md | 3 + docs/protocol.md | 4 +- docs/rpc.md | 4 +- docs/verification/feat-page-polls-events.md | 44 +++ packages/core/lib/page-proof.js | 3 +- packages/core/lib/terms.js | 2 +- packages/core/test/page-proof.test.js | 2 +- packages/core/test/terms.test.js | 2 +- packages/rpc/lib/methods.js | 2 +- packages/rpc/test/methods.test.js | 5 + 34 files changed, 1038 insertions(+), 102 deletions(-) create mode 100644 apps/app/src/pageChoice.js create mode 100644 apps/app/test/pageChoice.test.js create mode 100644 apps/cli/test/pages-choice.test.js create mode 100644 docs/changelog/feat-page-polls-events.md create mode 100644 docs/verification/feat-page-polls-events.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 74767f248..81a675bd2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Cada PR descreve a própria mudança num arquivo de [docs/changelog/](docs/chang ## [Não lançado] +- Enquetes, eventos e votos da Página (PR `feat/page-polls-events`): agindo como uma Página, publicar aceita uma enquete ou um evento, como a publicação de uma pessoa, e a Página vota na enquete e confirma presença no evento com a nova ação `choice`. As opções da enquete e o título e o local do evento passam pela lista de termos. O estado da Página traz `picked`, os votos dela desde a última retirada, contados como quem lê conta. Encerrar a Página apaga os votos. Termos e Política versão 79, com novo aceite. Verificação em `docs/verification/feat-page-polls-events.md`. - Publicações da Página com vídeo e prévia de link (PR `feat/page-post-media`): agindo como uma Página, publicar, responder e citar aceitam o que a publicação de uma pessoa aceita: fotos, ou um vídeo curto com a capa (MP4 de até 30 segundos), ou uma prévia de link (inclusive o cartão de música), nunca mídia e prévia juntas. O envio da Página de `video/mp4` leva `ms`; o serviço recusa um vídeo fora dos limites estritos ou que ainda tenha metadados, e o item guardado conserva `ms`. Apagar a publicação cobre a imagem da prévia, e um reinício do serviço não pausa a página por causa desse item. Termos e Política versão 78, com novo aceite. Verificação em `docs/verification/feat-page-post-media.md`. - Conversas da Página com fotos, voz e cartões (PR `feat/page-dm-media`): agindo como uma Página, a conversa envia fotos, GIFs, mensagem de voz, cartão de link (música e proposta da Feira com o cartão incluídas) e encaminha mensagens com a mídia, como a pessoa faz. Antes, a Página só mandava texto, e a proposta da Feira saía como o link puro. O aparelho de quem administra sela as mídias e as põe no canal anônimo com os próprios selos; o serviço continua assinando só o digest. Um envio incerto não se repete sozinho: tocar em tentar de novo reenvia o mesmo rascunho assinado e, se ele já expirou, o app avisa que a mensagem pode ter sido enviada. Verificação em `docs/verification/feat-page-dm-media.md`. - Resposta rápida como página (PR `feat/page-quick-reply`): agindo como uma Página, a barra de resposta da Conversa mostra a foto e o nome da Página ("Responda como Nome") e envia a resposta curta na hora, assinada como a Página, em vez de abrir a Publicar. Link ou texto longo (mais de 1000 caracteres) ainda abrem a Publicar; a recusa da fila, que abre a Publicar, vale só para a pessoa (a Página não passa pela fila). Um envio incerto guarda a resposta assinada: tocar de novo em enviar com o mesmo texto reenvia os mesmos bytes, sem duplicar. Sem internet a barra não aparece, como antes. Verificação em `docs/verification/feat-page-quick-reply.md`. diff --git a/apps/app/src/legal.js b/apps/app/src/legal.js index cea71894a..8ba80c2cf 100644 --- a/apps/app/src/legal.js +++ b/apps/app/src/legal.js @@ -3,9 +3,9 @@ // Sources: docs/design.md (LGPD, moderation, identity), docs/app.md and // SECURITY.md. Planned flows must not read as features already available. -export const LEGAL_VERSION = 78 +export const LEGAL_VERSION = 79 export const LEGAL_DATE = '17/11/2026' -export const REVIEW_NOTE = 'Versão 78, sujeita a revisão jurídica. Não é parecer jurídico.' +export const REVIEW_NOTE = 'Versão 79, sujeita a revisão jurídica. Não é parecer jurídico.' export const TERMS = { title: 'Termos de Uso', @@ -74,7 +74,7 @@ export const TERMS = { { heading: 'Convivência e denúncias', paragraphs: [ - 'O Varanda não tolera conteúdo censurável nem abuso contra outras pessoas. É proibido publicar ou enviar: conteúdo ilegal; exploração ou sexualização de crianças e adolescentes; imagens íntimas de alguém sem o consentimento dessa pessoa; pornografia; ameaças, assédio ou intimidação; discurso de ódio; incentivo à violência ou à automutilação; e spam. Quem descumprir essa regra pode ter a conta bloqueada pela moderação, como descrito em Como funciona a moderação. O app e a versão web recusam, no próprio aparelho e antes de publicar ou enviar, publicações, momentos, mensagens de grupo público, nomes, bios e @nomes de pessoas e de páginas, anúncios e avaliações da Feira, cartões de convite, nomes de grupo público ou de comunidade e depoimentos (também ao mostrar no perfil um depoimento recebido) que contêm termos de uma lista curta e pública; nada dessa conferência sai do aparelho nem fica registrado, e mensagens diretas e grupos privados não passam por ela. O serviço de conta aplica a mesma lista a um @nome novo, de pessoa ou de página, e ao que uma página publica por ele (publicações, respostas, citações, perfil, anúncios e mensagens em grupo público): recusa o pedido e não guarda o @nome nem o texto recusado. Um @nome que você já tem não é conferido de novo.', + 'O Varanda não tolera conteúdo censurável nem abuso contra outras pessoas. É proibido publicar ou enviar: conteúdo ilegal; exploração ou sexualização de crianças e adolescentes; imagens íntimas de alguém sem o consentimento dessa pessoa; pornografia; ameaças, assédio ou intimidação; discurso de ódio; incentivo à violência ou à automutilação; e spam. Quem descumprir essa regra pode ter a conta bloqueada pela moderação, como descrito em Como funciona a moderação. O app e a versão web recusam, no próprio aparelho e antes de publicar ou enviar, publicações, momentos, mensagens de grupo público, nomes, bios e @nomes de pessoas e de páginas, anúncios e avaliações da Feira, cartões de convite, nomes de grupo público ou de comunidade e depoimentos (também ao mostrar no perfil um depoimento recebido) que contêm termos de uma lista curta e pública; nada dessa conferência sai do aparelho nem fica registrado, e mensagens diretas e grupos privados não passam por ela. O serviço de conta aplica a mesma lista a um @nome novo, de pessoa ou de página, e ao que uma página publica por ele (publicações, com as opções de uma enquete e o título e o lugar de um evento, respostas, citações, perfil, anúncios e mensagens em grupo público): recusa o pedido e não guarda o @nome nem o texto recusado. Um @nome que você já tem não é conferido de novo.', 'Você pode denunciar uma publicação, uma mensagem, um anúncio ou uma conta por um destes motivos: spam, assédio, conteúdo ilegal ou outro. O motivo outro serve para o que esta regra proíbe e não se encaixa nos demais.', 'As denúncias funcionam na versão web hospedada e no app ligado à instalação da associação, com a passkey desbloqueada e a conta vinculada. A denúncia é assinada com a chave pública de quem denuncia. Você pode incluir uma observação. A denúncia também leva um trecho da publicação, do jeito que você o enviou. A moderação não confere esse trecho.', 'A pessoa denunciada não tem tela nem rota para ver a denúncia contra ela.', @@ -127,7 +127,7 @@ export const TERMS = { 'Uma página é o diário de um negócio ou projeto, com @nome próprio. Quem a cria é o dono. O serviço de conta da associação escreve no diário da página em nome do dono e dos administradores, com uma chave de assinatura da página que fica com o serviço, não no seu aparelho. Esse desenho ainda depende de parecer jurídico.', 'O dono e os administradores que aceitaram o convite formam uma lista pública de @nomes na página. Qualquer pessoa que tenha o diário da página vê essa lista. O @nome de uma página vem do mesmo conjunto dos @nomes de pessoas, e um nome já usado nunca é dado a outra conta ou página. Uma página renomeada pode retomar o próprio nome anterior depois do período de espera, e o nome de uma página encerrada fica queimado para sempre.', 'Só o dono convida e remove administradores. Passar a página para outra pessoa só vale se ela aceitar. O dono anterior continua administrador até ser removido.', - 'Tudo o que a página publica, como publicações, fotos, vídeos, prévias de links e quem ela segue, é público como a página, e os limites da exclusão abaixo valem do mesmo jeito.', + 'Tudo o que a página publica, como publicações, fotos, vídeos, prévias de links, enquetes, eventos, os votos e as respostas de presença dela e quem ela segue, é público como a página, e os limites da exclusão abaixo valem do mesmo jeito. Como os de uma pessoa, um voto ou uma resposta de presença da página é um registro no diário dela, e retirá-lo grava um novo registro que deixa os anteriores públicos.', 'Uma página também pode ter Conversas. Depois que o dono ativa as Conversas privadas da página, as mensagens são cifradas de ponta a ponta entre o aparelho de quem conversa com a página e os aparelhos do dono e dos administradores. O serviço de conta da associação guarda só envelopes de chave selados, que ele não consegue abrir, assina as mensagens da página sem vê-las e fica sabendo qual administrador pediu a assinatura de cada mensagem e quando, e quais membros guardam as chaves de mensagens da página. As mensagens escritas antes da ativação podiam ser lidas pelo serviço: na ativação, elas são copiadas para o aparelho do dono e depois apagadas no serviço. Nos dias seguintes à ativação, até o app de quem conversa com a página ver a chave nova, as mensagens que essa pessoa ainda enviar para a chave antiga da página também podem ser lidas pela associação. Um administrador removido continua com o que já leu, mas não recebe a chave nova. Por até 15 dias depois da remoção, ele ainda pode enviar, em nome da página, mensagens que já tinha preparado antes de ser removido. O serviço ainda guarda a chave de assinatura da página, então a associação poderia trocar a chave de mensagens publicada da página por uma chave dela. Nesse caso, os aparelhos do dono e dos administradores se recusam a enviar em nome da página e mostram um aviso quando alguém tenta enviar, e, até que alguém aja sobre o aviso, as mensagens enviadas para a chave trocada poderiam ser lidas pela associação. Uma mensagem para a página que nenhum aparelho de quem a administra receba em 14 dias se perde. As Conversas de uma página não acompanham uma troca de chave da página: a nova chave começa uma caixa nova.', 'Uma página pode entrar em comunidades e grupos. O que ela segue, as fotos que publica e o que escreve em comunidades e grupos públicos continua público como a página. Nos grupos privados, a chave da página fica só nos aparelhos do dono e dos administradores. O serviço de conta da associação guarda só as chaves de escrita da página e acrescenta nos grupos privados, como escritor da página, publicações já cifradas, que ele não consegue ler. Ele vê em quais grupos a página está e quando ela publica, mas não o que ela escreve. Ele também fica sabendo qual administrador enviou cada publicação da página em grupos privados e quem pediu cada renovação da chave dos grupos. As publicações da página em grupos privados escritas antes desta mudança podiam ser lidas pelo serviço. Se a página já tinha as Conversas ativas antes desta mudança, o dono precisa renovar a chave dos grupos nos ajustes da página; até lá, a página não publica nos grupos privados. Quando o dono remove um administrador, a página troca de chave de escrita em cada grupo privado, e os administradores do grupo precisam aprovar a página de novo; até lá, ela não publica naquele grupo. Até essa troca terminar e os administradores do grupo aprovarem a nova chave de escrita, o administrador removido ainda pode ler as publicações novas daquele grupo. Se um grupo não tiver vaga para a nova chave de escrita, a página sai dele.', 'O serviço de conta também lê os avisos enviados para a página, em nome de quem a administra, para mostrá-los a eles.', @@ -238,7 +238,7 @@ export const PRIVACY = { { heading: 'Páginas', paragraphs: [ - 'O diário de uma página (publicações, perfil, foto do perfil, fotos e vídeos das publicações, imagens das prévias de links e a lista de quem a página segue) é público, como o de uma pessoa, e fica nos mesmos lugares: aparelhos de quem segue a página e semeadores no Brasil. O serviço de conta da associação também guarda uma cópia completa do diário da página (publicações, perfil, fotos, vídeos, imagens das prévias de links e quem ela segue) no próprio armazenamento, porque escreve e replica a página para o semeador. Como o de qualquer diário, ele pode ficar na memória do navegador de quem espia pela Espiadinha. A lista de administradores, com o @nome do dono e dos administradores que aceitaram, também é pública.', + 'O diário de uma página (publicações, perfil, foto do perfil, fotos e vídeos das publicações, imagens das prévias de links, enquetes, eventos, os votos e as respostas de presença da página e a lista de quem a página segue) é público, como o de uma pessoa, e fica nos mesmos lugares: aparelhos de quem segue a página e semeadores no Brasil. O serviço de conta da associação também guarda uma cópia completa do diário da página (publicações, perfil, fotos, vídeos, imagens das prévias de links, votos, respostas de presença e quem ela segue) no próprio armazenamento, porque escreve e replica a página para o semeador. Como o de qualquer diário, ele pode ficar na memória do navegador de quem espia pela Espiadinha. A lista de administradores, com o @nome do dono e dos administradores que aceitaram, também é pública.', 'A chave que assina o diário da página fica no serviço de conta, no Brasil, e não no aparelho de quem a administra. A proposta é execução de contrato, Art. 7º, V, ainda sem parecer jurídico.', 'Antes de escrever no diário da página, o serviço de conta confere o texto (publicação, resposta, citação, perfil, anúncio e mensagem em grupo público) e o @nome novo de uma página com a mesma lista curta de termos que o app usa, e recusa o pedido que tem um deles. O texto recusado não é guardado, e o registro da recusa tem só o tipo do pedido e o motivo, sem a página, o texto ou o termo.', 'Depois que o dono ativa as Conversas privadas da página, as mensagens enviadas para a página e as enviadas por ela são cifradas de ponta a ponta entre o aparelho de quem conversa com a página e os aparelhos do dono e dos administradores. O serviço de conta guarda só envelopes de chave selados, que não consegue abrir, assina as mensagens da página sem vê-las e fica sabendo qual administrador pediu a assinatura de cada mensagem e quando, e quais membros guardam as chaves de mensagens da página. As mensagens escritas antes da ativação podiam ser lidas pelo serviço: elas são copiadas para o aparelho do dono e depois apagadas no serviço. Nos dias seguintes à ativação, até o app de quem conversa com a página ver a chave nova, as mensagens que essa pessoa ainda enviar para a chave antiga da página também podem ser lidas pela associação. Um administrador removido continua com o que já leu. Por até 15 dias depois da remoção, ele ainda pode enviar, em nome da página, mensagens que já tinha preparado antes de ser removido. Como o serviço ainda guarda a chave de assinatura da página, a associação poderia trocar a chave de mensagens publicada da página por uma chave dela: os aparelhos do dono e dos administradores se recusam a enviar em nome da página e mostram um aviso quando alguém tenta enviar, e, até que alguém aja sobre o aviso, as mensagens enviadas para a chave trocada poderiam ser lidas pela associação. Uma mensagem para a página que nenhum aparelho de quem a administra receba em 14 dias se perde. Esse desenho ainda depende de parecer jurídico.', diff --git a/apps/app/src/pageChoice.js b/apps/app/src/pageChoice.js new file mode 100644 index 000000000..fd2c80ace --- /dev/null +++ b/apps/app/src/pageChoice.js @@ -0,0 +1,102 @@ +// A page's votes on polls and its RSVPs to events: the pure part. The page's +// choices come from its signed 'status' answer (`picked`, keyed +// 'author:seq'); a vote or an RSVP is the page action 'choice'. No I/O here. + +const HEX64 = /^[0-9a-f]{64}$/ +const PICK_MAX = 3 + +// 'author:seq' of a post, or null for a key or seq that is not one. +export function pickRef (author, seq) { + const key = typeof author === 'string' ? author.toLowerCase() : '' + if (!HEX64.test(key) || !Number.isSafeInteger(seq) || seq < 1) return null + return key + ':' + seq +} + +// The page key when the app acts as a page, else null (the member votes). +export function choicePage (acting) { + return acting && acting.kind === 'page' && HEX64.test(String(acting.key)) ? acting.key : null +} + +// The Map 'author:seq' -> picks of a 'status' answer: each target's distinct +// picks since its last withdrawal, newest first. Keys or picks that are not +// well formed are dropped, and a repeated pick keeps its newest place. +export function pickedFromStatus (data) { + const out = new Map() + const raw = data && typeof data === 'object' && !Array.isArray(data) ? data.picked : null + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out + for (const ref of Object.keys(raw)) { + const i = ref.indexOf(':') + const seq = Number(ref.slice(i + 1)) + if (i !== 64 || pickRef(ref.slice(0, i), seq) !== ref) continue + const list = raw[ref] + if (!Array.isArray(list)) continue + const picks = [] + for (const pick of list) { + if (Number.isSafeInteger(pick) && pick >= 0 && pick <= PICK_MAX && !picks.includes(pick)) picks.push(pick) + } + if (picks.length > 0) out.set(ref, picks) + } + return out +} + +// The page's pick on `ref` for a poll or event of `count` options: the +// newest pick below `count`, or null for no vote. Readers (polls.js +// livePick) skip a pick the post does not have and keep the one before it, +// and the service cannot know a foreign post's count, so the app folds the +// same way. +export function pickedOf (picked, ref, count) { + if (!(picked instanceof Map) || ref === null || !Number.isSafeInteger(count) || count < 1) return null + const list = picked.get(ref) + if (!Array.isArray(list)) return null + for (const pick of list) if (pick < count) return pick + return null +} + +// A copy of `picked` with `pick` settled on `ref`: a pick goes first, as the +// service records it, and null withdraws (no history left). +export function withPick (picked, ref, pick) { + const next = new Map(picked instanceof Map ? picked : []) + const prior = Array.isArray(next.get(ref)) ? next.get(ref) : [] + if (pick === null) next.delete(ref) + else next.set(ref, [pick, ...prior.filter((p) => p !== pick)]) + return next +} + +// What a tap does after an unknown outcome: the same pick again resends the +// signed bytes of the attempt that was kept; any other tap drops it and +// starts anew. -> 'resend' | 'fresh' +export function tapAfterUncertain (pending, { page, ref, pick }) { + return pending && pending.page === page && pending.ref === ref && pending.pick === pick && + typeof pending.retry === 'function' + ? 'resend' + : 'fresh' +} + +export const PAGE_VOTE_UNCERTAIN = 'Não deu para confirmar o voto da Página. Toque de novo na mesma opção para reenviar.' +export const PAGE_RSVP_UNCERTAIN = 'Não deu para confirmar a resposta da Página. Toque de novo na mesma opção para reenviar.' + +export const PAGE_VOTE_NOTICE = 'O voto da Página fica público no diário dela: quem vê o diário da Página pode ver em quem ela votou.' +export const PAGE_RSVP_NOTICE = 'A resposta da Página fica pública no diário dela: quem vê o diário da Página pode ver se ela vai.' +export const PAGE_PICK_UNREAD = 'Não deu para ler o voto da Página agora. Tente de novo mais tarde.' + +// The notice a card shows: the person's text, or the Page's while acting as +// a Page. null stays null (no notice once a pick exists). +export function choiceNotice (page, notice, pageText) { + if (notice === null) return null + return page !== null ? pageText : notice +} + +// The spoken mark of the own pick on an option or answer. +export function ownMark (page, person) { + return page !== null ? ', voto da Página' : person +} + +// The page refusals a definite (not uncertain) failure names to the person. +const KNOWN_REFUSALS = ['termos-pendentes', 'encerrada', 'pausada', 'sem-permissao', 'limite', 'movida'] + +// The pt-BR text of a definite page refusal (pageError carries it), else the +// card's generic text. An uncertain failure never gets here. +export function refusalText (err, fallback) { + if (err && err.uncertain !== true && KNOWN_REFUSALS.includes(err.code) && typeof err.message === 'string' && err.message !== '') return err.message + return fallback +} diff --git a/apps/app/src/pagePost.js b/apps/app/src/pagePost.js index 3166c3761..ab01c6b99 100644 --- a/apps/app/src/pagePost.js +++ b/apps/app/src/pagePost.js @@ -1,19 +1,26 @@ // A page post, reply or quote: the same media and link preview a person's -// post carries. A video and a preview cannot travel together. No I/O of its -// own; the screen injects the upload. +// post carries, or (a root post only) a poll or an event. A video and a +// preview cannot travel together. No I/O of its own; the screen injects the +// upload. import { readyVideo } from './videoCompose.js' import { pageError } from './pages.js' import { validDescriptor, validVideoDescriptor } from './media/fetch.js' // { text } always. media when it is a non-empty array. preview when it is -// not null. Media with a preview is pedido-invalido: no record carries both. -export function pagePostOp ({ text, media = null, preview = null }) { +// not null. poll (the bare options array) or event (the event object) when +// not null. Media with a preview, and a poll or an event with media, a +// preview or each other, are pedido-invalido: no record carries both. +export function pagePostOp ({ text, media = null, preview = null, poll = null, event = null }) { const hasMedia = Array.isArray(media) && media.length > 0 if (hasMedia && preview !== null) throw pageError('pedido-invalido') + if (poll !== null && event !== null) throw pageError('pedido-invalido') + if ((poll !== null || event !== null) && (hasMedia || preview !== null)) throw pageError('pedido-invalido') const op = { text } if (hasMedia) op.media = media if (preview !== null) op.preview = preview + if (poll !== null) op.poll = poll + if (event !== null) op.event = event return op } diff --git a/apps/app/src/pages.js b/apps/app/src/pages.js index 66adc5a3e..15877f6bf 100644 --- a/apps/app/src/pages.js +++ b/apps/app/src/pages.js @@ -282,7 +282,7 @@ const GROUP_ACTIONS = ['community-join', 'community-leave', 'group-join', 'group const DM_ACTIONS = ['dm-sign', 'dm-box', 'dm-box-share', 'dm-box-read', 'dm-legacy-read', 'dm-legacy-done'] const LISTING_ACTIONS = ['listing', 'listing-edit', 'listing-status', 'listing-consent'] const STATEMENT_ACTIONS = ['list', 'status', 'post', 'reply', 'quote', 'delete', 'like', 'repost', 'profile', 'rename', - 'follow', 'follows', 'notices', 'terms', ...GROUP_ACTIONS, ...DM_ACTIONS, ...LISTING_ACTIONS] + 'follow', 'follows', 'notices', 'terms', 'choice', ...GROUP_ACTIONS, ...DM_ACTIONS, ...LISTING_ACTIONS] const ACTIONS = [...STATEMENT_ACTIONS, ...RECORD_ACTIONS, 'create', 'invite', 'move'] const signer = (node) => { @@ -399,6 +399,18 @@ export function pagesFollow (node, { member, page, key, on }) { return actAs(node, { member, action: 'follow', page, op: { key, on: on === true } }) } +// The page's vote on a poll or RSVP to an event ('choice', docs/rpc.md 5.84): +// `to` an 'author:seq' ref, `pick` an option index or null to withdraw (an +// absent pick is null). Anything else is sent as given for the service to +// refuse, never turned into a withdrawal. +export function pageChoiceOp (to, pick) { + return { to, pick: pick === undefined ? null : pick } +} + +export function pagesChoice (node, { member, page, to, pick }) { + return actAs(node, { member, action: 'choice', page, op: pageChoiceOp(to, pick) }) +} + export async function pagesFollows (node, { member, page }) { const data = await actAs(node, { member, action: 'follows', page }) return Array.isArray(data.follows) ? data.follows : [] diff --git a/apps/app/src/screens/ARua.js b/apps/app/src/screens/ARua.js index 7624aba42..4ef284a1e 100644 --- a/apps/app/src/screens/ARua.js +++ b/apps/app/src/screens/ARua.js @@ -1416,6 +1416,8 @@ export function socialRowProps ({ post, ref, repostedBy = null, social, profileO // moments never come through here and are not kind 'post'; a page's diary // is told apart by its profile. const diaryPost = post.kind === 'post' && !(prof && prof.page === true) + // A poll or an event shows for a page's post too; only the web link is off. + const pollable = post.kind === 'post' const postRef = diaryPost ? refOf(post) : null const origin = installationOrigin() || globalThis.location?.origin || null const link = postRef !== null ? postLink(origin, postRef) : null @@ -1496,8 +1498,8 @@ export function socialRowProps ({ post, ref, repostedBy = null, social, profileO text: post.text, media: post.media || null, preview: post.preview || null, - ...(diaryPost && Array.isArray(post.poll) ? { poll: post.poll } : {}), - ...(diaryPost && post.event && typeof post.event === 'object' ? { event: post.event } : {}), + ...(pollable && Array.isArray(post.poll) ? { poll: post.poll } : {}), + ...(pollable && post.event && typeof post.event === 'object' ? { event: post.event } : {}), replyToName, level: post.replyTo ? 'comment' : 'post', // Feed posts pass persist: true (own or followed by construction). @@ -1567,8 +1569,8 @@ export function socialRowProps ({ post, ref, repostedBy = null, social, profileO commenter, focusRef, focusTop, - poll: diaryPost && Array.isArray(post.poll) ? post.poll : null, - event: diaryPost && post.event && typeof post.event === 'object' ? post.event : null, + poll: pollable && Array.isArray(post.poll) ? post.poll : null, + event: pollable && post.event && typeof post.event === 'object' ? post.event : null, // By value: a refetch answers with new objects for the same numbers. counts: counts !== null && typeof counts === 'object', replies: counts ? counts.replies : null, diff --git a/apps/app/src/screens/Conversa.js b/apps/app/src/screens/Conversa.js index ad4cc56a6..9f21a4d7c 100644 --- a/apps/app/src/screens/Conversa.js +++ b/apps/app/src/screens/Conversa.js @@ -41,7 +41,8 @@ import { canDeletePost } from '../postActions' import { installationOrigin } from '../installation' import { postLink } from '../postLink' import * as actingStore from '../actingAs' -import { actAs } from '../pages' +import { actAs, pagesChoice } from '../pages' +import { pickedFromStatus, pickedOf, withPick } from '../pageChoice' import { pagesCore } from '../pageGate' import { coreActor } from '../pageCore' import { Btn, ErrorText, Row, Soft, UNCERTAIN, errorText, useAction, useBottomPad, useVisibleNow } from '../ui' @@ -136,20 +137,32 @@ const pageStatus = new Map() const pageGen = new Map() const genOf = (page) => pageGen.get(page) || 0 -export async function pageEngagement (source, page, { fresh = false } = {}) { - if (!fresh && pageStatus.has(page)) return pageStatus.get(page) +// One read per page at a time: a plain read joins the one in flight, and a +// failed read is not kept, so the next call reads again. +const pageReads = new Map() + +export function pageEngagement (source, page, { fresh = false } = {}) { + if (!fresh && pageStatus.has(page)) return Promise.resolve(pageStatus.get(page)) + if (!fresh && pageReads.has(page)) return pageReads.get(page) const started = genOf(page) - const node = nodeOf(source) - const member = await memberKeyOf(node.request, node) - const data = await actAs(node, { member, action: 'status', page }) - const eng = data && typeof data.engagement === 'object' && data.engagement !== null ? data.engagement : {} - const entry = { - liked: new Set(Array.isArray(eng.liked) ? eng.liked : []), - reposted: new Set(Array.isArray(eng.reposted) ? eng.reposted : []) - } - if (genOf(page) !== started) return pageStatus.get(page) || entry - pageStatus.set(page, entry) - return entry + const read = (async () => { + const node = nodeOf(source) + const member = await memberKeyOf(node.request, node) + const data = await actAs(node, { member, action: 'status', page }) + const eng = data && typeof data.engagement === 'object' && data.engagement !== null ? data.engagement : {} + const entry = { + liked: new Set(Array.isArray(eng.liked) ? eng.liked : []), + reposted: new Set(Array.isArray(eng.reposted) ? eng.reposted : []), + picked: pickedFromStatus(data) + } + if (genOf(page) !== started) return pageStatus.get(page) || entry + pageStatus.set(page, entry) + return entry + })() + pageReads.set(page, read) + const done = () => { if (pageReads.get(page) === read) pageReads.delete(page) } + read.then(done, done) + return read } // engagement.read of `refs`, as the member or as the page acted as. @@ -190,6 +203,42 @@ export async function setEngagement (source, kind, ref, on, page = actingPageKey return run(() => actAs(node, { member, action: kind, page, op: { to: ref, on } })) } +// The page's own pick on the poll or event `ref` ('author:seq') of `count` +// options: an option index, or null for none. Reads the page's 'status' once +// per page. +export async function readPagePick (source, page, ref, count) { + const entry = await pageEngagement(source, page) + return pickedOf(entry.picked, ref, count) +} + +// The page's vote or RSVP ('choice'; pick null withdraws). A failure after +// the signature is 'uncertain' and never signs again: its err.retry resends +// the same bytes and settles the cache like a first answer. +export async function setPagePick (source, page, ref, pick) { + const node = nodeOf(source) + const member = await memberKeyOf(node.request, node) + const settle = () => { + pageGen.set(page, genOf(page) + 1) + const entry = pageStatus.get(page) + if (entry) entry.picked = withPick(entry.picked, ref, pick) + return { pick } + } + // After an unknown outcome the cached pick may be the old one: the entry + // is dropped, so the next read asks the service again. + const run = (send) => send().then(settle, (err) => { + if (err && err.uncertain === true) { + pageGen.set(page, genOf(page) + 1) + pageStatus.delete(page) + } + if (err && typeof err.retry === 'function') { + const again = err.retry + err.retry = () => run(again) + } + throw err + }) + return run(() => pagesChoice(node, { member, page, to: ref, pick })) +} + function chunks (list, size) { const out = [] for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)) @@ -646,6 +695,9 @@ export function rowProps ({ item, names, peeked, now, ownKey, follows, eng, hand // moments never come through here and are not kind 'post'; a page's diary // is told apart by its profile. const diaryPost = item.kind === 'post' && hasSeq && !(authorProfile && authorProfile.page === true) + // A poll or an event shows for a page's post too: a page votes and + // answers like a person. Only the public web link stays off for a page. + const pollable = item.kind === 'post' && hasSeq const authorKey = String(item.author).toLowerCase() const postRef = diaryPost ? authorKey + ':' + item.seq : null const link = postRef !== null ? postLink(installationOrigin() || globalThis.location?.origin || null, postRef) : null @@ -664,9 +716,9 @@ export function rowProps ({ item, names, peeked, now, ownKey, follows, eng, hand replyToName: parentRef ? replyNameOf(parentProfile) : null, media: item.media || null, preview: item.preview || null, - // A diary post only: the poll card asks the seeder and the own diary. - ...(diaryPost && Array.isArray(item.poll) ? { poll: item.poll } : {}), - ...(diaryPost && item.event && typeof item.event === 'object' ? { event: item.event } : {}), + // A post only: the poll card asks the seeder and the own diary (a page's, its status). + ...(pollable && Array.isArray(item.poll) ? { poll: item.poll } : {}), + ...(pollable && item.event && typeof item.event === 'object' ? { event: item.event } : {}), persistMedia: item.author === ownKey || (follows !== null && follows.has(item.author)), now, quote, diff --git a/apps/app/src/screens/Publicar.js b/apps/app/src/screens/Publicar.js index 4ae7fc1b2..60202022e 100644 --- a/apps/app/src/screens/Publicar.js +++ b/apps/app/src/screens/Publicar.js @@ -977,9 +977,9 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment } const [musicPickerOpen, setMusicPickerOpen] = useState(false) // Enquete: the editor state while the poll is being written (hosted node - // only, a plain post without media, music, reply, quote or page). + // only, a plain post without media, music, reply or quote; as a page too). const [pollDraft, setPollDraft] = useState(null) - const pollOk = node.hosted === true && node.online !== false && asPage === null && !reply && !quote && !hasMedia && musicDraft === null && !momentMode + const pollOk = node.hosted === true && node.online !== false && !reply && !quote && !hasMedia && musicDraft === null && !momentMode const pollActive = pollDraft !== null && pollOk // While a poll draft exists the post is never a plain post or an outbox // entry: send refuses with a message and keeps the draft. @@ -1544,9 +1544,11 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment const sentReply = reply const sentQuote = quote if (sentQuote && countChars(sent) < 1) return + const structured = pageStructured() + if (structured.error !== undefined) { setCheckError(structured.error); return } setPageSending(true) try { - await sendNewAsPage(page, sent, sentReply, sentQuote, musicDraft) + await sendNewAsPage(page, sent, sentReply, sentQuote, musicDraft, structured) } finally { setPageSending(false) } @@ -1598,7 +1600,27 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment return null } - const sendNewAsPage = async (page, sent, sentReply, sentQuote, sentMusic) => { + // The poll or the event of the draft as a page post's extra: {} for a plain + // post, { poll } or { event } (what a person's post.create carries), or + // { error } with the text to show. + const pageStructured = () => { + if (pollDraft !== null) { + const built = editorPoll(pollDraft) + if (!built.ok) return { error: built.error } + if (countChars(text) < 1) return { error: POLL_NEEDS_TEXT } + return { poll: built.poll.options } + } + if (eventDraft !== null) { + const built = eventEditorEvent(eventDraft) + if (!built.ok) return { error: built.error } + if (countChars(text) < 1) return { error: EVENT_NEEDS_TEXT } + return { event: built.event } + } + return {} + } + + const sendNewAsPage = async (page, sent, sentReply, sentQuote, sentMusic, structured = {}) => { + const plain = structured.poll === undefined && structured.event === undefined const videoFile = hasVideo ? video.draft.state.file : null const sentIds = hasVideo ? [videoFile] : items.map((item) => item.id) let sentMedia = null @@ -1625,7 +1647,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment // The same link or music card a person's post carries; its thumbnail is // uploaded as one of the page's items. let card = null - const snapshot = sentMedia === null ? (musicSnapshot(sentMusic) ?? linkDraft.take(sent)) : null + const snapshot = sentMedia === null && plain ? (musicSnapshot(sentMusic) ?? linkDraft.take(sent)) : null // A music title comes from the provider: refused before any signature. const musicRefused = sentMusic !== null && snapshot !== null ? findPreviewTerm(snapshot) : null if (musicRefused !== null) { @@ -1658,7 +1680,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment try { built = withCardFallback((c) => { const checked = c ? withPreview(pageMethod, to !== null ? { to, text: sent } : { text: sent }, c) : null - return pagePostOp({ text: sent, media: sentMedia, preview: checked !== null ? checked.preview : null }) + return pagePostOp({ text: sent, media: sentMedia, preview: checked !== null ? checked.preview : null, ...(plain ? {} : structured) }) }, card) } catch (err) { setCheckError(errorText(err)) @@ -1728,11 +1750,11 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment } if (pollDraft !== null && pageRetryRef.current === null) { if (!pollOk) { setCheckError(node.online === false ? POLL_NEEDS_ONLINE : POLL_ALONE); return } - return sendPoll() + return asPage !== null ? sendAsPage() : sendPoll() } if (eventDraft !== null && pageRetryRef.current === null) { if (!pollOk) { setCheckError(node.online === false ? EVENT_NEEDS_ONLINE : EVENT_ALONE); return } - return sendEvent() + return asPage !== null ? sendAsPage() : sendEvent() } const sentMusic = musicDraft if (sentMusic !== null) { diff --git a/apps/app/src/ui/EventCard.js b/apps/app/src/ui/EventCard.js index e522da8c0..a7291715d 100644 --- a/apps/app/src/ui/EventCard.js +++ b/apps/app/src/ui/EventCard.js @@ -11,6 +11,11 @@ // (it sits in the diary), so the notice shows before the first one. An answer // is never resent: a failure tells the person and they decide. Title, place // and names are peer text and go through displayText. No motion. +// +// Acting as a Page (diary events only), the answer is the page's: its own +// answer comes from the page's status read and it answers with the page +// action 'choice'; after an unknown outcome the same answer tapped again +// resends the signed one. import { useCallback, useEffect, useRef, useState } from 'react' import { Pressable, StyleSheet, Text, View } from 'react-native' @@ -26,7 +31,8 @@ import { calendarExportAvailable, exportCalendar } from '../calendarExport' import { hasReminder, removeReminder, setReminder } from '../eventRemindersStore' import { whoOf } from '../who' import { confirmedVoters, voterSeqs } from './pollVoters' -import { learnPeeked, peekAll } from '../screens/Conversa' +import { learnPeeked, peekAll, readPagePick, setPagePick, useActing } from '../screens/Conversa' +import { PAGE_PICK_UNREAD, PAGE_RSVP_NOTICE, PAGE_RSVP_UNCERTAIN, choiceNotice, choicePage, pickRef, refusalText, tapAfterUncertain } from '../pageChoice' import { Icon } from './Icon' import { tap } from './haptics' import { layout, type } from './theme' @@ -81,6 +87,8 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to const grouped = group !== null && HEX64.test(String(group)) && HEX64.test(String(writer)) const valid = HEX64.test(key) && Number.isSafeInteger(seq) && seq > 0 const hosted = node.hosted === true && valid + const page = choicePage(useActing()) + const ref = pickRef(key, seq) const online = node.online !== false const { request } = node const card = eventCard(event) @@ -88,6 +96,7 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to const [claim, setClaim] = useState(null) const [busy, setBusy] = useState(false) const [error, setError] = useState('') + const [unread, setUnread] = useState(false) const [open, setOpen] = useState(null) const [voters, setVoters] = useState({ phase: 'idle', rows: [] }) const [reminder, setReminderOn] = useState(false) @@ -96,8 +105,16 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to // banner resolves reminders with diary.peek, so group events keep none. const remindable = scope !== null && valid && !grouped const gen = useRef(0) + const retryRef = useRef(null) const alive = useRef(true) useEffect(() => () => { alive.current = false }, []) + const nodeRef = useRef(node) + nodeRef.current = node + const pageRef = useRef(page) + pageRef.current = page + + // Another identity's answer is never shown: unread until this one's is. + useEffect(() => { setOwn(undefined); setError(''); setUnread(false); retryRef.current = null }, [page]) const readClaim = useCallback(async () => { if (grouped || !hosted || !online) return @@ -108,12 +125,19 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to useEffect(() => { if (grouped || !hosted || !online) return undefined let live = true - request('choice.mine', { to: { author: key, seq } }).then((r) => { - if (live && alive.current && isObject(r)) setOwn(Number.isSafeInteger(r.pick) ? r.pick : null) - }, () => {}) + if (page !== null) { + // Two picks: 0 'vou', 1 'talvez'. + readPagePick(nodeRef.current, page, ref, 2).then((pick) => { + if (live && alive.current) { setUnread(false); setOwn(pick) } + }, () => { if (live && alive.current) setUnread(true) }) + } else { + request('choice.mine', { to: { author: key, seq } }).then((r) => { + if (live && alive.current && isObject(r)) setOwn(Number.isSafeInteger(r.pick) ? r.pick : null) + }, () => {}) + } readClaim() return () => { live = false } - }, [grouped, hosted, online, request, key, seq, readClaim]) + }, [grouped, hosted, online, request, key, seq, readClaim, page, ref]) useEffect(() => { if (!remindable) return undefined @@ -139,14 +163,25 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to setBusy(true) setError('') tap('light') + const pending = retryRef.current + retryRef.current = null + const asPage = !grouped && page !== null try { if (grouped) await request('group.choose', { group, target: { writer, seq }, pick: next }) + else if (asPage) await (tapAfterUncertain(pending, { page, ref, pick: next }) === 'resend' ? pending.retry() : setPagePick(nodeRef.current, page, ref, next)) else await request('choice.set', { to: { author: key, seq }, pick: next }) - if (!alive.current) return + // The identity changed while it was in flight: the answer is not this one's. + if (!alive.current || (!grouped && pageRef.current !== page)) return if (!grouped) { setOwn(next); readClaim() } if (typeof onChanged === 'function') onChanged() - } catch { - if (alive.current) setError(FAILED) + } catch (err) { + if (!alive.current || (!grouped && pageRef.current !== page)) return + if (asPage && err && err.uncertain === true) { + if (typeof err.retry === 'function') retryRef.current = { page, ref, pick: next, retry: err.retry } + setError(PAGE_RSVP_UNCERTAIN) + } else { + setError(asPage ? refusalText(err, FAILED) : FAILED) + } } finally { if (alive.current) setBusy(false) } @@ -206,7 +241,7 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to const chip = (index, label) => ( answer(index)} @@ -242,7 +277,8 @@ export function EventCard ({ author, seq, event, group = null, writer = null, to ) : null} {!hosted ? {NOT_HOSTED} : null} - {hosted && online && !past && pick === null && known ? {NOTICE} : null} + {hosted && online && !past && pick === null && known ? {!grouped && page !== null ? choiceNotice(page, NOTICE, PAGE_RSVP_NOTICE) : NOTICE} : null} + {!grouped && page !== null && unread && hosted && online ? {PAGE_PICK_UNREAD} : null} {hosted && online && total ? {total + (grouped ? '' : '. ' + CLAIM)} : null} {hosted && online && shownTotals !== null ? ( diff --git a/apps/app/src/ui/PollCard.js b/apps/app/src/ui/PollCard.js index ee9c0723f..bd472d2d6 100644 --- a/apps/app/src/ui/PollCard.js +++ b/apps/app/src/ui/PollCard.js @@ -6,7 +6,10 @@ // the seeder only points, and each voter is shown only when their own diary // returned a signed choice for this poll and option (a seeder can omit a // voter, never add one). Voting needs the hosted node (decided by capability, -// not by platform); without it the card is read-only. A vote is never resent. +// not by platform); without it the card is read-only. A vote is never resent +// by itself. Acting as a Page, the vote is the page's: its pick comes from the +// page's own status read and it votes with the page action 'choice'; after an +// unknown outcome the same option tapped again resends the signed vote. import { useCallback, useEffect, useRef, useState } from 'react' import { Pressable, StyleSheet, Text, View } from 'react-native' @@ -17,7 +20,8 @@ import { fetchPoll, fetchPollVoters } from '../indexClient' import { nextPick, pollCard } from '../polls' import { whoOf } from '../who' import { confirmedVoters, voterSeqs } from './pollVoters' -import { learnPeeked, peekAll } from '../screens/Conversa' +import { learnPeeked, peekAll, readPagePick, setPagePick, useActing } from '../screens/Conversa' +import { PAGE_PICK_UNREAD, PAGE_VOTE_NOTICE, PAGE_VOTE_UNCERTAIN, choiceNotice, choicePage, ownMark, pickRef, refusalText, tapAfterUncertain } from '../pageChoice' import { tap } from './haptics' import { layout, type } from './theme' import { useStyles } from './ThemeProvider' @@ -38,6 +42,8 @@ export function PollCard ({ author, seq, poll }) { const key = typeof author === 'string' ? author.toLowerCase() : '' const valid = HEX64.test(key) && Number.isSafeInteger(seq) && seq > 0 const hosted = node.hosted === true && valid + const page = choicePage(useActing()) + const ref = pickRef(key, seq) const { request } = node const online = node.online !== false const count = Array.isArray(poll) ? poll.length : 0 @@ -45,11 +51,20 @@ export function PollCard ({ author, seq, poll }) { const [totals, setTotals] = useState(null) const [busy, setBusy] = useState(false) const [error, setError] = useState('') + const [unread, setUnread] = useState(false) const [open, setOpen] = useState(null) const [voters, setVoters] = useState({ pick: null, phase: 'idle', rows: [] }) const gen = useRef(0) + const retryRef = useRef(null) const alive = useRef(true) useEffect(() => () => { alive.current = false }, []) + const nodeRef = useRef(node) + nodeRef.current = node + const pageRef = useRef(page) + pageRef.current = page + + // Another identity's pick is never shown: unread until this one's is. + useEffect(() => { setOwn(undefined); setError(''); setUnread(false); retryRef.current = null }, [page]) const readTotals = useCallback(async () => { if (!hosted || !online) return @@ -60,12 +75,18 @@ export function PollCard ({ author, seq, poll }) { useEffect(() => { if (!hosted || !online) return undefined let live = true - request('choice.mine', { to: { author: key, seq } }).then((r) => { - if (live && alive.current && isObject(r)) setOwn(Number.isSafeInteger(r.pick) ? r.pick : null) - }, () => {}) + if (page !== null) { + readPagePick(nodeRef.current, page, ref, count).then((pick) => { + if (live && alive.current) { setUnread(false); setOwn(pick) } + }, () => { if (live && alive.current) setUnread(true) }) + } else { + request('choice.mine', { to: { author: key, seq } }).then((r) => { + if (live && alive.current && isObject(r)) setOwn(Number.isSafeInteger(r.pick) ? r.pick : null) + }, () => {}) + } readTotals() return () => { live = false } - }, [hosted, online, request, key, seq, readTotals]) + }, [hosted, online, request, key, seq, count, readTotals, page, ref]) const card = pollCard({ poll, totals, own }) const vote = async (index) => { @@ -75,13 +96,27 @@ export function PollCard ({ author, seq, poll }) { setBusy(true) setError('') tap('light') + const pending = retryRef.current + retryRef.current = null try { - await request('choice.set', { to: { author: key, seq }, pick: plan.pick }) - if (!alive.current) return + if (page !== null) { + const again = tapAfterUncertain(pending, { page, ref, pick: plan.pick }) === 'resend' + await (again ? pending.retry() : setPagePick(nodeRef.current, page, ref, plan.pick)) + } else { + await request('choice.set', { to: { author: key, seq }, pick: plan.pick }) + } + // The identity changed while it was in flight: the answer is not this one's. + if (!alive.current || pageRef.current !== page) return setOwn(plan.pick) readTotals() - } catch { - if (alive.current) setError(VOTE_FAILED) + } catch (err) { + if (!alive.current || pageRef.current !== page) return + if (page !== null && err && err.uncertain === true) { + if (typeof err.retry === 'function') retryRef.current = { page, ref, pick: plan.pick, retry: err.retry } + setError(PAGE_VOTE_UNCERTAIN) + } else { + setError(page !== null ? refusalText(err, VOTE_FAILED) : VOTE_FAILED) + } } finally { if (alive.current) setBusy(false) } @@ -109,7 +144,7 @@ export function PollCard ({ author, seq, poll }) { if (card === null) return null const canVote = hosted && online && card.ownKnown && !busy - const spoken = (row) => displayText(row.label) + (row.countLabel ? ', ' + row.countLabel : '') + (row.own ? ', seu voto' : '') + const spoken = (row) => displayText(row.label) + (row.countLabel ? ', ' + row.countLabel : '') + (row.own ? ownMark(page, ', seu voto') : '') return ( {card.options.map((row) => ( @@ -142,7 +177,8 @@ export function PollCard ({ author, seq, poll }) { {open === row.index ? : null} ))} - {card.notice !== null && hosted ? {card.notice} : null} + {card.notice !== null && hosted ? {choiceNotice(page, card.notice, PAGE_VOTE_NOTICE)} : null} + {page !== null && unread && hosted && online ? {PAGE_PICK_UNREAD} : null} {!hosted ? {NOT_HOSTED} : null} {hosted && online ? {(card.totalLabel ? card.totalLabel + '. ' : '') + card.totalsNote + (card.claimed && card.incomplete ? ' ' + 'A contagem pode estar incompleta.' : '')} diff --git a/apps/app/test/legal.test.js b/apps/app/test/legal.test.js index 30d3c31dd..372086e4f 100644 --- a/apps/app/test/legal.test.js +++ b/apps/app/test/legal.test.js @@ -7,9 +7,9 @@ const load = () => import('../src/legal.js') test('legal: version, date and review note', async (t) => { const { LEGAL_VERSION, LEGAL_DATE, REVIEW_NOTE } = await load() - t.is(LEGAL_VERSION, 78) + t.is(LEGAL_VERSION, 79) t.is(LEGAL_DATE, '17/11/2026') - t.is(REVIEW_NOTE, 'Versão 78, sujeita a revisão jurídica. Não é parecer jurídico.') + t.is(REVIEW_NOTE, 'Versão 79, sujeita a revisão jurídica. Não é parecer jurídico.') }) test('legal: this version describes music covers as never stored', async (t) => { @@ -363,7 +363,7 @@ test('legal: privacy identifies unresolved retention and contact', async (t) => test('legal: published text is pinned to its acceptance version', async (t) => { const { LEGAL_VERSION, TERMS, PRIVACY } = await load() const digest = createHash('sha256').update(JSON.stringify({ LEGAL_VERSION, TERMS, PRIVACY })).digest('hex') - t.is(digest, 'ecfb348bd8e63bcd7922076dc99fe8c1ffb74935d2b63c5c598c7882f4ca4477', 'o texto mudou: suba LEGAL_VERSION (e TERMS_VERSION em @varanda/core lib/terms.js) e atualize este digest') + t.is(digest, 'f00a774fa0ef2599c92e795bcd15714486d7b716afd504ee4fdd759d571133ff', 'o texto mudou: suba LEGAL_VERSION (e TERMS_VERSION em @varanda/core lib/terms.js) e atualize este digest') }) test('legal: version 41 describes group and conversation reactions and chat formatting', async (t) => { @@ -910,7 +910,18 @@ test('legal: version 78 describes video and link previews in page posts', async const { TERMS, PRIVACY } = await load() const text = (doc) => doc.sections.flatMap(({ paragraphs }) => paragraphs).join(' ') t.ok(text(TERMS).includes('As publicações de uma página também aceitam um vídeo curto, como as de uma pessoa.')) - t.ok(text(TERMS).includes('Tudo o que a página publica, como publicações, fotos, vídeos, prévias de links e quem ela segue')) - t.ok(text(PRIVACY).includes('fotos e vídeos das publicações, imagens das prévias de links e a lista de quem a página segue')) - t.ok(text(PRIVACY).includes('cópia completa do diário da página (publicações, perfil, fotos, vídeos, imagens das prévias de links e quem ela segue)')) + t.ok(text(TERMS).includes('Tudo o que a página publica, como publicações, fotos, vídeos, prévias de links')) + t.ok(text(PRIVACY).includes('fotos e vídeos das publicações, imagens das prévias de links')) + t.ok(text(PRIVACY).includes('cópia completa do diário da página (publicações, perfil, fotos, vídeos, imagens das prévias de links')) +}) + +test('legal: version 79 describes polls, events, votes and RSVPs of a page', async (t) => { + const { TERMS, PRIVACY } = await load() + const text = (doc) => doc.sections.flatMap(({ paragraphs }) => paragraphs).join(' ') + t.ok(text(TERMS).includes('Tudo o que a página publica, como publicações, fotos, vídeos, prévias de links, enquetes, eventos, os votos e as respostas de presença dela e quem ela segue, é público como a página')) + t.ok(text(TERMS).includes('Como os de uma pessoa, um voto ou uma resposta de presença da página é um registro no diário dela, e retirá-lo grava um novo registro que deixa os anteriores públicos.')) + t.ok(text(TERMS).includes('ao que uma página publica por ele (publicações, com as opções de uma enquete e o título e o lugar de um evento, respostas,')) + t.ok(text(PRIVACY).includes('imagens das prévias de links, enquetes, eventos, os votos e as respostas de presença da página e a lista de quem a página segue')) + t.ok(text(PRIVACY).includes('cópia completa do diário da página (publicações, perfil, fotos, vídeos, imagens das prévias de links, votos, respostas de presença e quem ela segue)')) + for (const doc of [TERMS, PRIVACY]) t.absent(text(doc).includes(String.fromCharCode(0x2014)), 'no em dash') }) diff --git a/apps/app/test/musicDraft.test.js b/apps/app/test/musicDraft.test.js index ac0525bce..45434c101 100644 --- a/apps/app/test/musicDraft.test.js +++ b/apps/app/test/musicDraft.test.js @@ -1009,9 +1009,9 @@ test('a page music title with a listed term is refused before any upload or sign t.ok(r.state.errors.at(-1).includes('título ou no artista da música')) }) -test('a page never queues, polls or builds events', (t) => { +test('a page never queues, but polls and builds events like a person', (t) => { t.ok(/const offlineQueue = [^\n]*asPage === null/.test(source)) - t.ok(/const pollOk = [^\n]*asPage === null/.test(source)) + t.absent(/const pollOk = [^\n]*asPage/.test(source), 'the poll and event gate does not exclude a page') const link = source.slice(source.indexOf('const linkDraft = useLinkDraft({'), source.indexOf('\n', source.indexOf('const linkDraft = useLinkDraft({'))) t.absent(link.includes('asPage'), 'the link card is not gated on the page') }) diff --git a/apps/app/test/pageChoice.test.js b/apps/app/test/pageChoice.test.js new file mode 100644 index 000000000..ef88d3bf7 --- /dev/null +++ b/apps/app/test/pageChoice.test.js @@ -0,0 +1,163 @@ +// A page's votes and RSVPs, the pure part (src/pageChoice.js): the pick key, +// the 'status' picked map, who votes, and what a tap does after an unknown +// outcome. No network. +'use strict' + +const test = require('brittle') + +const load = () => import('../src/pageChoice.js') + +const A = 'ab'.repeat(32) +const P = 'cd'.repeat(32) + +test('pickRef builds author:seq, lowercase, and refuses a bad key or seq', async (t) => { + const { pickRef } = await load() + t.is(pickRef(A.toUpperCase(), 5), A + ':5') + t.is(pickRef(A, 0), null) + t.is(pickRef(A, 1.5), null) + t.is(pickRef('nope', 1), null) + t.is(pickRef(undefined, 1), null) +}) + +test('choicePage is the page key only when acting as a page', async (t) => { + const { choicePage } = await load() + t.is(choicePage({ kind: 'page', key: P }), P) + t.is(choicePage({ kind: 'me' }), null) + t.is(choicePage({ kind: 'page', key: 'x' }), null) + t.is(choicePage(null), null) +}) + +test('pickedFromStatus keeps well formed entries and drops the rest', async (t) => { + const { pickedFromStatus, pickedOf } = await load() + const m = pickedFromStatus({ + picked: { + [A + ':3']: [1], + [A + ':4']: [0], + [A + ':5']: [4], + [A + ':0']: [1], + 'zz:1': [1], + [A + ':6']: ['x'], + [A + ':7']: 1, + [A + ':8']: [2, 4, 2, 1.5, -1, 0], + [A + ':10']: [] + } + }) + t.alike([...m.entries()], [[A + ':3', [1]], [A + ':4', [0]], [A + ':8', [2, 0]]], 'bad picks dropped, a repeat keeps its newest place') + t.is(pickedOf(m, A + ':3', 2), 1) + t.is(pickedOf(m, A + ':4', 2), 0, 'option 0 is a vote') + t.is(pickedOf(m, A + ':9', 2), null, 'absent is no vote') + t.is(pickedFromStatus({}).size, 0) + t.is(pickedFromStatus(null).size, 0) + t.is(pickedFromStatus({ picked: [1] }).size, 0) + t.is(pickedOf(m, null, 2), null) + t.is(pickedOf(m, A + ':3'), null, 'no option count, no pick') + t.is(pickedOf(m, A + ':3', 0), null) +}) + +test('pickedOf folds like polls.js livePick: the newest pick the post has', async (t) => { + const { pickedFromStatus, pickedOf } = await load() + const { livePick } = require('@varanda/core/lib/polls') + // A page voted 0, then 3 on a foreign 2-option poll: the service answers + // [3, 0] and readers count 0. + const m = pickedFromStatus({ picked: { [A + ':3']: [3, 0] } }) + t.is(pickedOf(m, A + ':3', 2), 0, 'the out-of-range 3 falls back to 0') + t.is(pickedOf(m, A + ':3', 4), 3, 'a poll with 4 options counts the 3') + t.is(pickedOf(pickedFromStatus({ picked: { [A + ':3']: [3, 2] } }), A + ':3', 2), null, 'no pick in range is no vote') + const at = '2026-01-01T00:00:00.000Z' + const choice = (seq, pick) => ({ seq, record: { type: 'choice', to: { author: A, seq: 3 }, pick, at } }) + const entries = [choice(1, 0), choice(2, 3)] + t.is(livePick({ entries, poll: { author: A, seq: 3 }, count: 2, now: Date.parse(at) + 1 }).pick, 0, 'the reader agrees') +}) + +test('withPick settles on a copy: a pick goes first, null withdraws', async (t) => { + const { withPick, pickedOf } = await load() + const base = new Map([[A + ':3', [1]]]) + const next = withPick(base, A + ':3', 0) + t.alike(next.get(A + ':3'), [0, 1], 'the new pick first, the old one kept') + t.is(pickedOf(next, A + ':3', 2), 0) + t.alike(base.get(A + ':3'), [1], 'the original is untouched') + t.alike(withPick(next, A + ':3', 1).get(A + ':3'), [1, 0], 'a repeated pick moves to the front') + t.is(withPick(next, A + ':3', null).has(A + ':3'), false, 'a withdrawal clears the history') + t.is(pickedOf(withPick(next, A + ':3', null), A + ':3', 2), null) + t.alike(withPick(undefined, A + ':7', 2).get(A + ':7'), [2]) +}) + +test('tapAfterUncertain resends only the same pick on the same page and post', async (t) => { + const { tapAfterUncertain } = await load() + const retry = () => {} + const pending = { page: P, ref: A + ':3', pick: 1, retry } + t.is(tapAfterUncertain(pending, { page: P, ref: A + ':3', pick: 1 }), 'resend') + t.is(tapAfterUncertain(pending, { page: P, ref: A + ':3', pick: 0 }), 'fresh') + t.is(tapAfterUncertain(pending, { page: P, ref: A + ':3', pick: null }), 'fresh') + t.is(tapAfterUncertain(pending, { page: 'ee'.repeat(32), ref: A + ':3', pick: 1 }), 'fresh') + t.is(tapAfterUncertain(pending, { page: P, ref: A + ':4', pick: 1 }), 'fresh') + t.is(tapAfterUncertain(null, { page: P, ref: A + ':3', pick: 1 }), 'fresh') + t.is(tapAfterUncertain({ ...pending, retry: undefined }, { page: P, ref: A + ':3', pick: 1 }), 'fresh') +}) + +test('the cards and rows wire the page identity (source pins)', (t) => { + const { readFileSync } = require('node:fs') + const { join } = require('node:path') + const read = (f) => readFileSync(join(__dirname, '../src', f), 'utf8') + for (const f of ['ui/PollCard.js', 'ui/EventCard.js']) { + const src = read(f) + t.ok(src.includes('choicePage(useActing())'), f + ' knows who acts') + t.ok(src.includes('readPagePick(nodeRef.current, page, ref, ' + (f === 'ui/PollCard.js' ? 'count' : '2') + ')'), f + ' reads the page pick from status, folded for its option count') + t.ok(src.includes('setPagePick(nodeRef.current, page, ref,'), f + ' votes with the page action') + t.ok(src.includes('tapAfterUncertain('), f + ' resends only on an explicit tap') + t.ok(src.includes("request('choice.set'"), f + ' keeps the person path') + } + for (const f of ['screens/ARua.js', 'screens/Conversa.js']) { + const src = read(f) + t.ok(/pollable && Array\.isArray\(/.test(src), f + ' shows a page post poll') + t.absent(/diaryPost && Array\.isArray\([a-z]+\.poll/.test(src), f + ' no longer hides it for a page') + t.ok(/const postRef = diaryPost/.test(src), f + ' keeps the web link off for a page') + } + const post = read('screens/Publicar.js') + t.ok(post.includes('structured.error'), 'Publicar refuses a bad page poll before signing') + t.ok(post.includes('...(plain ? {} : structured)'), 'Publicar sends the poll or event in the page post op') +}) + +test('refusalText names a definite known page refusal, never an uncertain one', async (t) => { + const { refusalText } = await load() + const err = (code, extra = {}) => Object.assign(new Error('texto ' + code), { code, ...extra }) + for (const code of ['termos-pendentes', 'encerrada', 'pausada', 'sem-permissao', 'limite']) { + t.is(refusalText(err(code), 'geral'), 'texto ' + code, code) + } + t.is(refusalText(err('pausada', { uncertain: true }), 'geral'), 'geral', 'uncertain keeps the generic text') + t.is(refusalText(err('indisponivel'), 'geral'), 'geral', 'an unknown token') + t.is(refusalText(new Error('x'), 'geral'), 'geral') + t.is(refusalText(null, 'geral'), 'geral') +}) + +test('the Page variants of the notice and the spoken mark', async (t) => { + const { choiceNotice, ownMark, PAGE_VOTE_NOTICE, PAGE_RSVP_NOTICE, PAGE_PICK_UNREAD } = await load() + t.is(choiceNotice(null, 'pessoa', PAGE_VOTE_NOTICE), 'pessoa') + t.is(choiceNotice(P, 'pessoa', PAGE_VOTE_NOTICE), PAGE_VOTE_NOTICE) + t.is(choiceNotice(P, null, PAGE_VOTE_NOTICE), null, 'no notice once picked') + t.is(ownMark(null, ', seu voto'), ', seu voto') + t.is(ownMark(P, ', seu voto'), ', voto da Página') + for (const text of [PAGE_VOTE_NOTICE, PAGE_RSVP_NOTICE, PAGE_PICK_UNREAD]) { + t.ok(text.includes('Página'), 'pt-BR text for the Page') + t.absent(text.includes('—'), 'no em dash') + } +}) + +test('Conversa shares one status read per page and drops the pick after an unknown outcome (source pins)', (t) => { + const { readFileSync } = require('node:fs') + const { join } = require('node:path') + const src = readFileSync(join(__dirname, '../src/screens/Conversa.js'), 'utf8') + t.ok(src.includes('const pageReads = new Map()'), 'pending reads are kept per page') + t.ok(src.includes('if (!fresh && pageReads.has(page)) return pageReads.get(page)'), 'a plain read joins the one in flight') + t.ok(src.includes('if (pageReads.get(page) === read) pageReads.delete(page)'), 'a failed read is not kept') + const set = src.slice(src.indexOf('export async function setPagePick')) + t.ok(set.includes('pageStatus.delete(page)'), 'an uncertain failure drops the cached entry') + const card = (f) => readFileSync(join(__dirname, '../src/ui', f), 'utf8') + for (const f of ['PollCard.js', 'EventCard.js']) { + const src2 = card(f) + t.ok(src2.includes("setError(''); setUnread(false); retryRef.current = null }, [page])"), f + ' resets the error with the identity') + t.ok(src2.includes('refusalText(err,'), f + ' names a definite page refusal') + t.ok(src2.includes('PAGE_PICK_UNREAD'), f + ' says when the page pick could not be read') + } + t.ok(card('EventCard.js').includes('(!grouped && pageRef.current !== page)'), 'a person answer is dropped after a switch to a Page too') +}) diff --git a/apps/app/test/pagePost.test.js b/apps/app/test/pagePost.test.js index c6616b672..e31242e3a 100644 --- a/apps/app/test/pagePost.test.js +++ b/apps/app/test/pagePost.test.js @@ -189,3 +189,16 @@ test('a malformed descriptor is uncertain', async (t) => { t.is(notVideo.uncertain, true) t.is(notVideo.message, 'Resposta inválida ao enviar o vídeo.') }) + +test('pagePostOp carries a poll or an event, never with media, a preview or each other', async (t) => { + const { pagePostOp } = await load() + t.alike(pagePostOp({ text: 'Qual?', poll: ['a', 'b'] }), { text: 'Qual?', poll: ['a', 'b'] }) + const event = { title: 'Festa', start: 1900000000000 } + t.alike(pagePostOp({ text: 'Vem', event }), { text: 'Vem', event }) + t.alike(pagePostOp({ text: 'oi', poll: null, event: null }), { text: 'oi' }) + const refused = (args) => { try { pagePostOp(args) } catch (err) { return err.code } return null } + t.is(refused({ text: 'x', poll: ['a', 'b'], event }), 'pedido-invalido') + t.is(refused({ text: 'x', poll: ['a', 'b'], media: [photoD()] }), 'pedido-invalido') + t.is(refused({ text: 'x', event, preview: { url: 'https://exemplo.org' } }), 'pedido-invalido') + t.is(refused({ text: 'x', poll: ['a', 'b'], media: [] }), null, 'an empty media list is no media') +}) diff --git a/apps/app/test/pages.test.js b/apps/app/test/pages.test.js index 020b112d5..f74b3f2e0 100644 --- a/apps/app/test/pages.test.js +++ b/apps/app/test/pages.test.js @@ -361,6 +361,21 @@ test('op shapes of like, delete, profile, rename, follow and the reads are sent } }) +test('choice: pageChoiceOp builds { to, pick } and pagesChoice posts it to the choice route', async (t) => { + const { pageChoiceOp, pagesChoice } = await load() + t.alike(pageChoiceOp(M + ':4', 2), { to: M + ':4', pick: 2 }) + t.alike(pageChoiceOp(M + ':4', null), { to: M + ':4', pick: null }) + t.alike(pageChoiceOp(M + ':4'), { to: M + ':4', pick: null }, 'an absent pick withdraws') + t.alike(pageChoiceOp(M + ':4', -1), { to: M + ':4', pick: -1 }, 'a bad pick is not turned into a withdrawal') + const calls = stub(t, flow(() => json(200, { seq: 9 }))) + const node = fakeNode() + const data = await pagesChoice(node, { member: M, page: P, to: M + ':4', pick: 1 }) + t.is(data.seq, 9) + t.ok(calls[1].url.endsWith('/account/pages/choice')) + t.alike(body(calls[1]).op, { to: M + ':4', pick: 1 }) + t.is(node.signs[0].params.action, 'choice') +}) + test('offer-cancel is no action: the cancel is the signed offer record', async (t) => { const { actAs } = await load() const calls = stub(t, flow(() => json(200, {}))) diff --git a/apps/app/test/pollDraftGuard.test.js b/apps/app/test/pollDraftGuard.test.js index 6ca67e325..807dc6d53 100644 --- a/apps/app/test/pollDraftGuard.test.js +++ b/apps/app/test/pollDraftGuard.test.js @@ -15,7 +15,7 @@ test('a poll draft never falls through to a plain post or the outbox', (t) => { t.ok(guard < body.indexOf("const method = sentQuote ? 'post.quote'"), 'before a plain post') const branch = body.slice(guard, guard + 260) t.ok(branch.includes('if (!pollOk) { setCheckError(node.online === false ? POLL_NEEDS_ONLINE : POLL_ALONE); return }'), 'refuses with a message and keeps the draft') - t.ok(branch.includes('return sendPoll()'), 'sends the poll when allowed') + t.ok(branch.includes('return asPage !== null ? sendAsPage() : sendPoll()'), 'sends the poll when allowed: as the page when acting as one') t.ok(!branch.includes('setPollDraft(null)'), 'the draft is kept') t.ok(src.includes("const POLL_NEEDS_ONLINE = 'Enquete só pode ser publicada com conexão.'"), 'offline message in pt-BR') }) diff --git a/apps/app/test/postShareRow.test.js b/apps/app/test/postShareRow.test.js index 3a70b3673..77393fe71 100644 --- a/apps/app/test/postShareRow.test.js +++ b/apps/app/test/postShareRow.test.js @@ -127,13 +127,14 @@ test('socialRowProps: repost, page diary, other kinds and a missing origin', asy t.is(ruaRow(socialRowProps, post(ME, 7)).link, null, 'postLink refuses an origin with a path') }) -test('a poll post hands its options to the row, only on a diary post', async (t) => { +test('a poll post hands its options to the row, a page post too but never a chat item', async (t) => { reset() const { socialRowProps, rowProps } = await builders() const poll = ['Sim', 'Não'] t.alike(ruaRow(socialRowProps, post(THEM, 4, { poll })).poll, poll, 'A Rua row') t.absent(Object.hasOwn(ruaRow(socialRowProps, post(THEM, 4)), 'poll'), 'a plain post has no poll prop') - t.absent(Object.hasOwn(ruaRow(socialRowProps, post(PAGE, 2, { poll }), { ownKey: PAGE }), 'poll'), 'a page\'s diary is no diary post') + t.alike(ruaRow(socialRowProps, post(PAGE, 2, { poll }), { ownKey: PAGE }).poll, poll, 'a page\'s post shows its poll like a person\'s') + t.is(ruaRow(socialRowProps, post(PAGE, 2, { poll }), { ownKey: PAGE }).link, null, 'but the web link stays off for a page') t.absent(Object.hasOwn(ruaRow(socialRowProps, post(THEM, 4, { poll, kind: 'dm' })), 'poll'), 'a chat item is never a diary post') t.absent(Object.hasOwn(ruaRow(socialRowProps, post(THEM, 4, { poll: 'Sim' })), 'poll'), 'not an array') t.alike(conversaRow(rowProps, post(THEM, 4, { poll })).poll, poll, 'thread and profile rows') diff --git a/apps/cli/lib/account/pages-routes.js b/apps/cli/lib/account/pages-routes.js index c56278b98..4cfda9773 100644 --- a/apps/cli/lib/account/pages-routes.js +++ b/apps/cli/lib/account/pages-routes.js @@ -38,6 +38,9 @@ // short video/mp4 already free of metadata, for a post's [poster, video] // pair; a post, reply or quote carries photos, that pair or a link card // (its thumbnail one of the page's items), as a person's post does. +// - a root post may carry a poll or an event, and 'choice' writes the +// page's vote or RSVP, the same records a person writes (records.js +// postRecord, choiceRecord); 'status' answers the page's live choices. // - close and move are the owner's record actions (docs/protocol.md §12, // "Encerrar" and "Mudar de chave"): the owner-signed page-close, or the // page-moved, page-origin and K2 genesis roster, countersigned here. At @@ -88,13 +91,14 @@ const { applyDeletes, shownMedia } = require('@varanda/core/lib/deletion') const groupLib = require('@varanda/core/lib/group') const { foldListings, countLive, liveEditOf, editPlan, deletePlan } = require('@varanda/core/lib/listing') const { feira, cardUrlHost } = require('@varanda/rpc') +const { pickCount } = require('@varanda/core/lib/polls') const { findTerm } = require('./word-check') const { MAX_PAGES_PER_OWNER, MAX_PAGE_MOVES } = require('./pages-store') const { parseBox, parseInviteShare } = require('./pages-dm') const { - postRecord, likeRecord, repostRecord, deleteRecords, profileRecords, followRecord, listingRecord, listingStatusRecord, + postRecord, likeRecord, repostRecord, choiceRecord, deleteRecords, profileRecords, followRecord, listingRecord, listingStatusRecord, parseRef, validDescriptor, validPostMedia, validPreview, validPreviewImage, isCanonicalIso, PAGE_KEYS, MEDIA_BLOCK_BYTES, MAX_MEDIA_ITEM_BLOCKS, - MEDIA_MIMES, VIDEO_MIME, MAX_VIDEO_MS, DESCRIPTOR_KEYS, VIDEO_DESCRIPTOR_KEYS, MAX_AVATAR_BYTES, AVATAR_MIMES, MAX_MEDIA_PER_POST + MEDIA_MIMES, VIDEO_MIME, MAX_VIDEO_MS, DESCRIPTOR_KEYS, VIDEO_DESCRIPTOR_KEYS, MAX_AVATAR_BYTES, AVATAR_MIMES, MAX_MEDIA_PER_POST, POLL_MAX } = require('@varanda/core/lib/records') const PREFIX = '/account/pages/' @@ -115,8 +119,9 @@ const HEX32_RE = /^[0-9a-f]{32}$/ const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/ const SUCCESSOR = PREFIX + 'successor/' // What a close tombstones: everything the page still shows, never a page-* -// record (pages-writer.js DELETABLE). -const CLOSE_DELETES = ['post', 'like', 'repost', 'profile', 'listing', 'listing-edit'] +// record (pages-writer.js DELETABLE). Every choice goes, a withdrawal too, so +// no earlier vote comes back. +const CLOSE_DELETES = ['post', 'like', 'repost', 'choice', 'profile', 'listing', 'listing-edit'] const HOUR = 3600 * 1000 const DAY = 24 * HOUR // The rebox retry (reboxSweep): every minute, a failing page backed off up @@ -141,6 +146,11 @@ function placeTexts (place) { return isPlainObject(place) ? [place.city, place.bairro] : [] } +// The texts an event post shows besides its text: the title and the place. +function eventTexts (event) { + return isPlainObject(event) ? [event.title, event.place] : [] +} + // Conversas as the page (./pages-dm.js, docs/rpc.md 5.84). const DM_ACTIONS = ['dm-list', 'dm-thread', 'dm-sign', 'dm-box', 'dm-box-share', 'dm-box-read', 'dm-legacy-read', 'dm-legacy-done'] const DM_READS = ['dm-list', 'dm-thread', 'dm-box-read', 'dm-sign', 'dm-legacy-read'] @@ -151,18 +161,21 @@ const GROUP_READ_LIMIT = 32 const LISTING_ACTIONS = ['listing', 'listing-edit', 'listing-status'] const STATEMENTS = ['create', 'list', 'status', 'post', 'reply', 'quote', 'delete', 'like', 'repost', 'profile', 'avatar', 'rename', 'invite', 'follow', 'follows', 'media', 'notices', 'terms', ...DM_ACTIONS, ...GROUP_ACTIONS, - 'listing', 'listing-edit', 'listing-status', 'listing-consent'] + 'listing', 'listing-edit', 'listing-status', 'listing-consent', 'choice'] const RECORDS = ['accept', 'remove', 'offer', 'transfer-accept', 'close', 'move'] const START_ACTIONS = [...STATEMENTS, ...RECORDS] const READS = ['list', 'status', 'follows'] // The newest refs 'status' answers per engagement list, so the answer stays // inside the app's 1 MiB read cap (about 80 bytes a ref). const MAX_STATUS_REFS = 4096 +// The newest polls and events 'status' answers the page's live choice on +// (about 75 bytes each), so the whole answer still fits that cap. +const MAX_STATUS_PICKS = 1024 const MAX_SUCCESSORS = 1000 // Actions whose whole effect is the writer's append: its nonce record is the // answer. For the others the ACL step after the append is the effect, so a // record without a spent nonce is only known to be partial. -const WRITER_ANSWERS = ['create', 'post', 'reply', 'quote', 'delete', 'like', 'repost', 'profile', 'rename', 'follow', 'media', 'avatar', +const WRITER_ANSWERS = ['create', 'post', 'reply', 'quote', 'delete', 'like', 'repost', 'choice', 'profile', 'rename', 'follow', 'media', 'avatar', ...LISTING_ACTIONS] const WRITER_TOKENS = Object.freeze({ @@ -189,6 +202,29 @@ const TOKENS = new Set(['nao-vinculado', 'sem-permissao', 'limite', 'nome-em-uso function noop () {} +// The page's choices per poll or event, from its own diary, in the form +// readers fold them: a null pick (a withdrawal) clears the target's history +// and a deleted choice never counted. The service cannot know a foreign +// poll's option count, so it hands back every distinct pick since the last +// withdrawal, newest first; the first one below the poll's count is the live +// pick, as polls.js livePick (which skips a pick out of range). -> +// { 'author:seq': [pick, ...] } for the MAX_STATUS_PICKS targets whose last +// pick is newest. +function pickedOf (entries) { + const live = new Map() + for (const e of applyDeletes(entries)) { + if (!e || e.deleted || !isPlainObject(e.record) || e.record.type !== 'choice') continue + const { to, pick } = e.record + if (!isPlainObject(to) || !HEX64_RE.test(to.author) || !Number.isSafeInteger(to.seq)) continue + if (pick !== null && !(Number.isSafeInteger(pick) && pick >= 0 && pick < POLL_MAX)) continue + const ref = to.author + ':' + to.seq + const prior = live.get(ref) || [] + live.delete(ref) + if (pick !== null) live.set(ref, [pick, ...prior.filter((p) => p !== pick)]) + } + return Object.fromEntries([...live].slice(-MAX_STATUS_PICKS)) +} + function has (obj, k) { return Object.prototype.hasOwnProperty.call(obj, k) } @@ -1025,7 +1061,21 @@ function createPagesRoutes ({ async function recordsFor (action, page, op) { try { if (action === 'post') { - if (!exactKeys(op, ['text'], ['media', 'preview'])) throw refuse('pedido-invalido') + if (!exactKeys(op, ['text'], ['media', 'preview', 'poll', 'event'])) throw refuse('pedido-invalido') + // A root post with a poll or an event, as a person's post.create + // (methods.js postPollCross): never beside media, a link card or + // each other, and never null. + if (has(op, 'poll') || has(op, 'event')) { + if (has(op, 'media') || has(op, 'preview') || (has(op, 'poll') && has(op, 'event'))) throw refuse('pedido-invalido') + if (has(op, 'event')) { + if (!isPlainObject(op.event)) throw refuse('pedido-invalido') + termFree(op.text, ...eventTexts(op.event)) + return [postRecord({ text: op.text, event: op.event })] + } + if (!Array.isArray(op.poll)) throw refuse('pedido-invalido') + termFree(op.text, ...op.poll) + return [postRecord({ text: op.text, poll: op.poll })] + } termFree(op.text) return [postRecord({ text: op.text, ...postParts(page, op) })] } @@ -1044,6 +1094,26 @@ function createPagesRoutes ({ const build = action === 'like' ? likeRecord : repostRecord return [build({ to: target(op.to), on: op.on })] } + if (action === 'choice') { + if (!exactKeys(op, ['to', 'pick'])) throw refuse('pedido-invalido') + const t = target(op.to) + if (t.seq < 1) throw refuse('pedido-invalido') + const record = choiceRecord({ to: t, pick: op.pick }) + // A withdrawal needs no read, as a person's choice.set. A pick on a + // blocked author is refused, as a follow is. Only the page's own + // diary is readable here: on it the target must be a live poll with + // that option or an event; elsewhere a pick no poll has counts for + // no reader (polls.js). + if (op.pick !== null) { + if (blocked(t.author)) throw refuse('sem-permissao') + if (t.author === page) { + const live = applyDeletes(await writer.readEntries(page)).find((e) => e && e.seq === t.seq && !e.deleted) + const count = live === undefined ? null : pickCount(live.record, t.seq) + if (count === null || !(op.pick < count)) throw refuse('pedido-invalido') + } + } + return [record] + } if (action === 'delete') { if (!exactKeys(op, ['to'])) throw refuse('pedido-invalido') const t = target(op.to) @@ -1259,6 +1329,7 @@ function createPagesRoutes ({ need(row, member, 'admin') if (action === 'follows') return { follows: writer.follows(page) } const eng = await writer.engagement(page) + const picked = pickedOf(await writer.readEntries(page)) const liked = [...eng.liked] const reposted = [...eng.reposted.keys()] const t = now() @@ -1274,6 +1345,7 @@ function createPagesRoutes ({ reposted: reposted.slice(-MAX_STATUS_REFS), truncated: liked.length > MAX_STATUS_REFS || reposted.length > MAX_STATUS_REFS }, + picked, follows: row.follows, closed: row.closed !== null, movedTo: row.movedTo, @@ -2542,7 +2614,7 @@ function createPagesRoutes ({ const body = await readJsonBody(req, MAX_BODY) if (action === 'start') return start(body) if (action === 'create') return create(body) - if (['post', 'reply', 'quote', 'delete', 'like', 'repost', 'profile', ...LISTING_ACTIONS].includes(action)) return write(action, body) + if (['post', 'reply', 'quote', 'delete', 'like', 'repost', 'choice', 'profile', ...LISTING_ACTIONS].includes(action)) return write(action, body) if (action === 'listing-consent') return consent(body) if (READS.includes(action)) return read(action, body) if (DM_ACTIONS.includes(action)) return dm(action, body) diff --git a/apps/cli/lib/account/pages-writer.js b/apps/cli/lib/account/pages-writer.js index a6c8e8fb0..14c98fa59 100644 --- a/apps/cli/lib/account/pages-writer.js +++ b/apps/cli/lib/account/pages-writer.js @@ -176,7 +176,7 @@ function copyJson (value) { } } -const DELETABLE = ['post', 'like', 'repost', 'profile', 'listing', 'listing-edit'] +const DELETABLE = ['post', 'like', 'repost', 'choice', 'profile', 'listing', 'listing-edit'] // The close list in order, in batches of at most 8, never splitting the // tombstones of one target: a reader marks a target deleted from its first diff --git a/apps/cli/test/pages-choice.test.js b/apps/cli/test/pages-choice.test.js new file mode 100644 index 000000000..0648e53c6 --- /dev/null +++ b/apps/cli/test/pages-choice.test.js @@ -0,0 +1,336 @@ +'use strict' + +// A hosted page's poll and event posts and its votes and RSVPs ('choice'), +// the same records a person writes (apps/cli/lib/account/pages-routes.js +// post, choice, status and close; pages-writer.js DELETABLE), end to end +// over loopback with the same account service and real pages writer as +// pages-media.test.js. + +const fs = require('node:fs') +const path = require('node:path') +const test = require('brittle') +const b4a = require('b4a') +const crypto = require('hypercore-crypto') +const { testnet, tmpDir, until, localSwarmOptions } = require('./helpers/net') +const { Seeder } = require('@varanda/core/lib/seeder') +const { createSeederCert, createIssuerCert, generateAssociationKeyPair } = require('@varanda/core/lib/cert') +const { signRoster, signClose } = require('@varanda/core/lib/page') +const { signPage, opHash } = require('@varanda/core/lib/page-proof') +const { postRecord, choiceRecord, validateRecord } = require('@varanda/core/lib/records') +const { livePick } = require('@varanda/core/lib/polls') +const { TERMS_VERSION } = require('@varanda/core/lib/terms') +const { BLOCKED_TERMS } = require('@varanda/rpc') +const { startSeedWs } = require('../lib/seed-ws') +const { openAccountStore } = require('../lib/account/store') +const { openTermsStore } = require('../lib/account/terms-store') +const { openPageKeys } = require('../lib/account/page-keys') +const { openPagesStore } = require('../lib/account/pages-store') +const { createPagesWriter } = require('../lib/account/pages-writer') +const { createAccountServer } = require('../lib/account/server') + +const ORIGIN = 'https://varanda.test' +const PAGE_KEYS = 'cd'.repeat(32) + +function hex (buf) { + return b4a.toString(buf, 'hex') +} + +function member () { + const kp = crypto.keyPair() + return { kp, hex: hex(kp.publicKey) } +} + +function googleStub () { + return { authorizeUrl: () => 'http://127.0.0.1:1/auth', exchange: async () => { throw new Error('unused') } } +} + +let subSeq = 300 +async function linkDirect (store, ctx, m, username) { + const row = store.start({ member: m.hex, username }) + store.reserve(row.id) + store.putGoogle(row.id, { sub: '40000000000000000' + String(subSeq++).padStart(5, '0'), email: 'p@example.test' }) + await store.finish(row.id, { signature: 'a'.repeat(128) }, ctx.issuerKp, ctx.issuerCert, ctx.association) +} + +function prepareSeederDir (t, assocKp) { + const dataDir = tmpDir(t, 'varanda-seed-') + const association = hex(assocKp.publicKey) + Seeder.ensureConfig(dataDir, association) + const { publicKey } = Seeder.createKey(dataDir) + const certFile = path.join(tmpDir(t, 'varanda-sc-'), 'seeder-cert.json') + fs.writeFileSync(certFile, JSON.stringify(createSeederCert({ seeder: publicKey }, assocKp))) + Seeder.addCert(dataDir, certFile, association) + return dataDir +} + +async function setup (t) { + const { bootstrap } = await testnet(t) + const assocKp = generateAssociationKeyPair() + const association = hex(assocKp.publicKey) + const issuerKp = crypto.keyPair() + const issuerCert = createIssuerCert({ issuer: hex(issuerKp.publicKey) }, assocKp) + const ctx = { assocKp, association, issuerKp, issuerCert, bootstrap } + + const dir = tmpDir(t, 'varanda-account-') + const store = openAccountStore(dir) + const terms = openTermsStore(dir) + const opts = { + association, + origin: ORIGIN, + google: googleStub(), + store, + issuer: { keyPair: issuerKp, cert: issuerCert }, + terms, + log: () => {}, + // About 80 requests: past the default global bucket of 100 with starts. + ratePerSecond: 1000, + burst: 1000 + } + const seederDir = prepareSeederDir(t, assocKp) + const seeder = new Seeder({ dataDir: seederDir, ...localSwarmOptions(bootstrap), associationKey: association, log: () => {} }) + t.teardown(() => seeder.close(), { force: true }) + await seeder.start() + const ws = await startSeedWs({ port: 0, seeder }) + t.teardown(() => ws.close(), { force: true }) + const keys = openPageKeys({ dir, env: { VARANDA_PAGE_KEYS: PAGE_KEYS } }) + + let listener = null + let base = null + async function boot () { + const writer = createPagesWriter({ dir, keys, association, seederWs: 'http://127.0.0.1:' + ws.port, log: () => {} }) + t.teardown(() => writer.close(), { force: true }) + await writer.ready() + await until(() => writer.connected(), { name: 'link up', timeoutMs: 20000 }) + ctx.writer = writer + ctx.pagesStore = openPagesStore(dir) + opts.pages = { keys, writer, pagesStore: ctx.pagesStore, dir, blocklist: { has: () => false } } + const server = createAccountServer(opts) + listener = await server.listen({ host: '127.0.0.1', port: 0 }) + t.teardown(() => listener.close(), { force: true }) + base = 'http://127.0.0.1:' + listener.port + } + await boot() + + async function api (method, pathname, body, headers = {}) { + const init = { method, headers: { ...headers } } + if (body !== undefined) { + init.headers.origin = ORIGIN + if (b4a.isBuffer(body)) { + init.headers['content-type'] = 'application/octet-stream' + init.body = body + } else { + init.headers['content-type'] = 'application/json' + init.body = JSON.stringify(body) + } + } + const res = await fetch(base + pathname, init) + const text = await res.text() + return { status: res.status, body: text ? JSON.parse(text) : null } + } + + let termsCount = 0 + async function newMember (username) { + const m = member() + await linkDirect(store, ctx, m, username) + termsCount++ + await terms.accept({ member: m.hex, version: TERMS_VERSION, nonce: (String(termsCount) + 'T'.repeat(43)).slice(0, 43), signature: 'a'.repeat(128) }) + return m + } + + async function start (m, action) { + const r = await api('POST', '/account/pages/start', { member: m.hex, action }) + if (r.status !== 200) throw new Error('start ' + action + ' ' + r.status + ' ' + JSON.stringify(r.body)) + return r.body + } + + function sign (m, action, nonce, page, op) { + return signPage({ action, nonce, member: m.hex, page, association, opHash: opHash(op) }, m.kp) + } + + async function act (m, action, page, op) { + const { nonce } = await start(m, action) + const body = { member: m.hex, nonce, page, op, signature: sign(m, action, nonce, page, op) } + return api('POST', '/account/pages/' + action, body) + } + + async function create (m, username) { + const { nonce, page } = await start(m, 'create') + const f = { page, gen: 1, owner: m.hex, admins: [], prev: null, at: new Date().toISOString(), nonce, association } + const record = { type: 'page-roster', ...f, signature: signRoster(f, m.kp) } + const op = { username, name: 'Página ' + username, bio: '', roster: { gen: 1, admins: [], prev: null, at: record.at, nonce } } + const r = await api('POST', '/account/pages/create', { member: m.hex, nonce, page, op, signature: sign(m, 'create', nonce, page, op), record }) + return { ...r, page } + } + + async function close (m, page) { + const { nonce } = await start(m, 'close') + const f = { page, gen: ctx.pagesStore.get(page).gen + 1, at: new Date().toISOString(), nonce, actor: m.hex, association } + return api('POST', '/account/pages/close', { member: m.hex, nonce, page, record: { type: 'page-close', ...f, signature: signClose(f, m.kp) } }) + } + + return { ctx, api, newMember, act, create, close } +} + +async function recordAt (ctx, page, seq) { + const e = (await ctx.writer.readEntries(page)).find((x) => x.seq === seq) + return e ? e.record : null +} + +async function deletedSeqs (ctx, page) { + return (await ctx.writer.readEntries(page)).filter((e) => e.record && e.record.type === 'delete').map((e) => e.record.seq) +} + +async function status (s, m, page) { + const r = await s.act(m, 'status', page, {}) + if (r.status !== 200) throw new Error('status ' + r.status + ' ' + JSON.stringify(r.body)) + return r.body +} + +const EVENT = { title: 'Feira de trocas', start: '2026-12-05T13:00:00.000Z', end: '2026-12-05T17:00:00.000Z', place: 'Praça da Matriz' } + +test('page polls and events: posts, refusals, votes, status and close, the records a person writes', async (t) => { + t.timeout(300000) + const s = await setup(t) + const { ctx } = s + const ana = await s.newMember('ana') + const caio = await s.newMember('caio') + const made = await s.create(ana, 'padaria') + t.is(made.status, 200, JSON.stringify(made.body)) + const K = made.page + const other = await s.create(caio, 'outra') + t.is(other.status, 200, JSON.stringify(other.body)) + + // A poll post and an event post: the same record a person's post.create + // writes for the same input. + const poll = await s.act(ana, 'post', K, { text: 'Qual pão amanhã?', poll: ['Francês', 'Integral', 'Broa'] }) + t.is(poll.status, 200, JSON.stringify(poll.body)) + let rec = await recordAt(ctx, K, poll.body.seq) + t.alike(rec, postRecord({ text: 'Qual pão amanhã?', poll: ['Francês', 'Integral', 'Broa'], at: rec.at })) + t.is(validateRecord(rec, poll.body.seq), null) + const event = await s.act(ana, 'post', K, { text: 'Venham!', event: EVENT }) + t.is(event.status, 200, JSON.stringify(event.body)) + rec = await recordAt(ctx, K, event.body.seq) + t.alike(rec, postRecord({ text: 'Venham!', event: EVENT, at: rec.at })) + t.is(validateRecord(rec, event.body.seq), null) + const noEnd = await s.act(ana, 'post', K, { text: 'Sem hora para acabar', event: { ...EVENT, end: null, place: '' } }) + t.is(noEnd.status, 200, JSON.stringify(noEnd.body)) + const plain = await s.act(ana, 'post', K, { text: 'Bom dia' }) + t.is(plain.status, 200, JSON.stringify(plain.body)) + + // Refusals append nothing. + const term = BLOCKED_TERMS[0] + const media = [{ core: 'ab'.repeat(32), start: 0, blocks: 1, sha256: 'cd'.repeat(32), mime: 'image/jpeg', width: 10, height: 10, bytes: 100 }] + let length = ctx.writer.info(K).length + const refusals = [ + [{ text: 'x', poll: ['Sim', term] }, 'termo-recusado', 'a blocked term in an option'], + [{ text: term, poll: ['Sim', 'Não'] }, 'termo-recusado', 'a blocked term in the poll text'], + [{ text: 'x', event: { ...EVENT, title: term } }, 'termo-recusado', 'a blocked term in the event title'], + [{ text: 'x', event: { ...EVENT, place: 'Rua ' + term } }, 'termo-recusado', 'a blocked term in the event place'], + [{ text: term, event: EVENT }, 'termo-recusado', 'a blocked term in the event text'], + [{ text: 'x', poll: ['Sim', 'Não'], media }, 'pedido-invalido', 'a poll and media'], + [{ text: 'x', poll: ['Sim', 'Não'], preview: { url: 'https://example.com/' } }, 'pedido-invalido', 'a poll and a card'], + [{ text: 'x', event: EVENT, media }, 'pedido-invalido', 'an event and media'], + [{ text: 'x', event: EVENT, preview: { url: 'https://example.com/' } }, 'pedido-invalido', 'an event and a card'], + [{ text: 'x', poll: ['Sim', 'Não'], event: EVENT }, 'pedido-invalido', 'a poll and an event'], + [{ text: 'x', poll: null }, 'pedido-invalido', 'a null poll'], + [{ text: 'x', event: null }, 'pedido-invalido', 'a null event'], + [{ text: 'x', poll: ['Sim'] }, 'pedido-invalido', 'one option'], + [{ text: 'x', poll: ['A', 'B', 'C', 'D', 'E'] }, 'pedido-invalido', 'five options'], + [{ text: 'x', poll: ['Sim', ' Sim'] }, 'pedido-invalido', 'the same option twice'], + [{ text: 'x', poll: ['Sim', 'a'.repeat(81)] }, 'pedido-invalido', 'an option past the cap'], + [{ text: 'x', poll: 'Sim,Não' }, 'pedido-invalido', 'a poll that is not a list'], + [{ text: '', poll: ['Sim', 'Não'] }, 'pedido-invalido', 'a poll without text'], + [{ text: 'x', event: { ...EVENT, end: EVENT.start } }, 'pedido-invalido', 'an end not after the start'], + [{ text: 'x', event: { ...EVENT, extra: 1 } }, 'pedido-invalido', 'an unknown event key'], + [{ text: 'x', event: 'amanhã' }, 'pedido-invalido', 'an event that is not an object'] + ] + for (const [op, error, name] of refusals) { + const r = await s.act(ana, 'post', K, op) + t.is(r.body.error, error, name) + } + const replyPoll = await s.act(ana, 'reply', K, { to: K + ':' + plain.body.seq, text: 'x', poll: ['Sim', 'Não'] }) + t.is(replyPoll.body.error, 'pedido-invalido', 'a reply never carries a poll') + const quoteEvent = await s.act(ana, 'quote', K, { to: K + ':' + plain.body.seq, text: 'x', event: EVENT }) + t.is(quoteEvent.body.error, 'pedido-invalido', 'a quote never carries an event') + t.is(ctx.writer.info(K).length, length, 'no refusal appends') + + // A vote, a changed vote and a withdrawal: each the record a person's + // choice.set writes. + const pollRef = { author: K, seq: poll.body.seq } + const pollTo = K + ':' + poll.body.seq + const v1 = await s.act(ana, 'choice', K, { to: pollTo, pick: 0 }) + t.is(v1.status, 200, JSON.stringify(v1.body)) + rec = await recordAt(ctx, K, v1.body.seq) + t.alike(rec, choiceRecord({ to: pollRef, pick: 0, at: rec.at }), 'the person\'s choice record') + t.is(validateRecord(rec, v1.body.seq), null) + t.alike((await status(s, ana, K)).picked, { [pollTo]: [0] }, 'status shows the pick') + const v2 = await s.act(ana, 'choice', K, { to: pollTo, pick: 2 }) + t.is(v2.status, 200, JSON.stringify(v2.body)) + t.alike((await status(s, ana, K)).picked, { [pollTo]: [2, 0] }, 'the last pick first, the earlier one kept') + const eventTo = K + ':' + event.body.seq + const rsvp = await s.act(ana, 'choice', K, { to: eventTo, pick: 1 }) + t.is(rsvp.status, 200, JSON.stringify(rsvp.body)) + rec = await recordAt(ctx, K, rsvp.body.seq) + t.alike(rec, choiceRecord({ to: { author: K, seq: event.body.seq }, pick: 1, at: rec.at }), 'an RSVP is a choice') + t.alike((await status(s, ana, K)).picked, { [pollTo]: [2, 0], [eventTo]: [1] }) + const cleared = await s.act(ana, 'choice', K, { to: pollTo, pick: null }) + t.is(cleared.status, 200, JSON.stringify(cleared.body)) + rec = await recordAt(ctx, K, cleared.body.seq) + t.alike(rec, choiceRecord({ to: pollRef, pick: null, at: rec.at })) + t.alike((await status(s, ana, K)).picked, { [eventTo]: [1] }, 'a withdrawal clears the history') + t.is(livePick({ entries: await ctx.writer.readEntries(K), poll: pollRef, count: 3 }), null, 'a reader sees no vote') + const again = await s.act(ana, 'choice', K, { to: pollTo, pick: 1 }) + t.is(again.status, 200, JSON.stringify(again.body)) + t.is(livePick({ entries: await ctx.writer.readEntries(K), poll: pollRef, count: 3 }).pick, 1, 'a reader folds the page vote') + + // A vote on another diary's post: only its shape is checked here (the + // service cannot read that diary). + const foreignTo = other.page + ':3' + const foreign = await s.act(ana, 'choice', K, { to: foreignTo, pick: 0 }) + t.is(foreign.status, 200, JSON.stringify(foreign.body)) + // Then a pick that post may not have: on a 2-option poll readers skip the + // 3 and keep the 0, so status hands back both and the app folds the same. + const past = await s.act(ana, 'choice', K, { to: foreignTo, pick: 3 }) + t.is(past.status, 200, JSON.stringify(past.body)) + const foreignPoll = { author: other.page, seq: 3 } + t.is(livePick({ entries: await ctx.writer.readEntries(K), poll: foreignPoll, count: 2 }).pick, 0, 'a reader of a 2-option poll counts 0') + const st = await status(s, ana, K) + t.alike(st.picked[foreignTo], [3, 0], 'status lists both, newest first') + + // Choice refusals append nothing. + length = ctx.writer.info(K).length + const choiceRefusals = [ + [{ to: pollTo, pick: 3 }, 'an option the poll does not have'], + [{ to: eventTo, pick: 2 }, 'an RSVP past talvez'], + [{ to: K + ':' + plain.body.seq, pick: 0 }, 'a post that is no poll'], + [{ to: K + ':' + (length + 5), pick: 0 }, 'a block the page does not have'], + [{ to: foreignTo, pick: 4 }, 'a pick past POLL_MAX'], + [{ to: foreignTo, pick: -1 }, 'a negative pick'], + [{ to: foreignTo, pick: '1' }, 'a pick that is not a number'], + [{ to: foreignTo }, 'no pick'], + [{ to: other.page + ':0', pick: 0 }, 'block 0'], + [{ to: 'nada', pick: 0 }, 'a bad ref'], + [{ to: pollTo, pick: 0, on: true }, 'an unknown key'] + ] + for (const [op, name] of choiceRefusals) { + const r = await s.act(ana, 'choice', K, op) + t.is(r.body.error, 'pedido-invalido', name) + } + const stranger = await s.act(caio, 'choice', K, { to: pollTo, pick: 0 }) + t.is(stranger.body.error, 'sem-permissao', 'a member who is not an admin') + const strangerStatus = await s.act(caio, 'status', K, {}) + t.is(strangerStatus.body.error, 'sem-permissao', 'nor reads its picks') + const delChoice = await s.act(ana, 'delete', K, { to: K + ':' + again.body.seq }) + t.is(delChoice.body.error, 'pedido-invalido', 'a choice is withdrawn, never deleted, as a person\'s') + t.is(ctx.writer.info(K).length, length, 'no refusal appends') + + // Closing tombstones every choice, the withdrawal included, so no earlier + // vote comes back. + const closed = await s.close(ana, K) + t.is(closed.status, 200, JSON.stringify(closed.body)) + const dels = await deletedSeqs(ctx, K) + for (const seq of [v1.body.seq, v2.body.seq, rsvp.body.seq, cleared.body.seq, again.body.seq, foreign.body.seq, past.body.seq]) { + t.ok(dels.includes(seq), 'close tombstones choice ' + seq) + } + t.is(livePick({ entries: await ctx.writer.readEntries(K), poll: pollRef, count: 3 }), null, 'no vote survives the close') +}) diff --git a/apps/site/public/privacidade/index.html b/apps/site/public/privacidade/index.html index 4c990a36a..fe336c7c5 100644 --- a/apps/site/public/privacidade/index.html +++ b/apps/site/public/privacidade/index.html @@ -7,7 +7,7 @@ Varanda: Política de Privacidade - + @@ -27,8 +27,8 @@

Política de Privacidade

- - + +