From 8cd4ac111adadf92c52d814f0fd04432789e49cb Mon Sep 17 00:00:00 2001 From: rodrigopavezi Date: Tue, 17 Nov 2026 04:04:47 -0300 Subject: [PATCH 1/2] feat: video, link previews and music in a page's posts Acting as a page, a post, reply or quote carried only text and photos. A page now posts what a person posts. - account service: the page media upload takes video/mp4 with ms, held to strict videoBounds and refused unless its metadata is already stripped; post, reply and quote take media (photos or a poster and video pair) or a link preview whose image is one of the page's own items, never both; url, title and desc go through the blocklist - writer: the stored video item keeps ms and the loader accepts it, so a restart does not pause the page; delete and close cover the preview image - app: Publicar attaches video, a link card and music as a page; the upload is resent only on an explicit tap; a music title with a blocked term is caught before sending - legal: Termos and Politica version 77 - docs: protocol, rpc 5.84, design, verification, changelog --- CHANGELOG.md | 1 + apps/app/src/legal.js | 10 +- apps/app/src/musicDraft.js | 3 +- apps/app/src/pagePost.js | 63 ++++ apps/app/src/pages.js | 53 ++- apps/app/src/screens/Publicar.js | 179 +++++++-- apps/app/src/videoCompose.js | 4 +- apps/app/test/legal.test.js | 17 +- apps/app/test/linkCardBuild.test.js | 4 +- apps/app/test/musicDraft.test.js | 221 ++++++++++- apps/app/test/pagePost.test.js | 191 ++++++++++ apps/app/test/pages.test.js | 108 +++++- apps/app/test/pollDraftGuard.test.js | 2 +- apps/app/test/shareShell.test.js | 2 +- apps/app/test/videoCompose.test.js | 5 +- apps/cli/lib/account/pages-routes.js | 101 +++-- apps/cli/lib/account/pages-writer.js | 56 ++- apps/cli/test/account-pages.test.js | 16 +- apps/cli/test/pages-media.test.js | 434 ++++++++++++++++++++++ apps/cli/test/pages-writer.test.js | 12 +- apps/site/public/privacidade/index.html | 8 +- apps/site/public/termos/index.html | 10 +- apps/site/test/legal.test.js | 2 +- docs/changelog/feat-page-post-media.md | 3 + docs/design.md | 2 +- docs/protocol.md | 8 +- docs/rpc.md | 2 + docs/verification.md | 8 +- docs/verification/feat-page-post-media.md | 42 +++ packages/core/lib/terms.js | 2 +- packages/core/test/terms.test.js | 2 +- 31 files changed, 1441 insertions(+), 130 deletions(-) create mode 100644 apps/app/src/pagePost.js create mode 100644 apps/app/test/pagePost.test.js create mode 100644 apps/cli/test/pages-media.test.js create mode 100644 docs/changelog/feat-page-post-media.md create mode 100644 docs/verification/feat-page-post-media.md diff --git a/CHANGELOG.md b/CHANGELOG.md index f24382233..22ff7c78c 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] +- 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 77, 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`. - Nada toca sozinho no feed, o silêncio do som fica guardado e o player fecha ao sair da tela (PR `feat/feed-playback-rules`): a música do Audius numa publicação toca só pelo cartão por toque, e um cartão tocado pausa (faixa, playlist) ou para (trecho) quando fica fora da tela, sem voltar sozinho. O silêncio dos vídeos do feed e dos momentos agora é lembrado neste aparelho ao reabrir o app. Um player de YouTube, SoundCloud, Spotify ou Apple Music em que a pessoa tocou fecha quando o cartão sai da tela, e volta a capa. Os momentos continuam tocando vídeo e música sozinhos. Removida a chave **Tocar música sozinha** de Ajustes e o adesivo de música da leitura. Termos e Política de Privacidade na versão 53, com novo aceite. Verificação em `docs/verification.md` §246. diff --git a/apps/app/src/legal.js b/apps/app/src/legal.js index 5b00af958..1a7ad05e2 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 = 76 +export const LEGAL_VERSION = 77 export const LEGAL_DATE = '16/11/2026' -export const REVIEW_NOTE = 'Versão 76, sujeita a revisão jurídica. Não é parecer jurídico.' +export const REVIEW_NOTE = 'Versão 77, sujeita a revisão jurídica. Não é parecer jurídico.' export const TERMS = { title: 'Termos de Uso', @@ -95,7 +95,7 @@ export const TERMS = { { heading: 'Fotos, vídeos e recursos planejados', paragraphs: [ - 'São aceitos fotos e GIFs nas publicações e a foto do perfil, pela web hospedada e pelo app ligado à instalação da associação, e fotos, GIFs e mensagens de voz nas mensagens diretas e nos grupos, como descrito abaixo. A foto do perfil é sempre uma imagem parada e quadrada; um GIF escolhido para ela vira imagem parada. Vídeos curtos são aceitos nas publicações (até 30 segundos) e nos momentos (até 15 segundos), um por publicação ou momento. Conversas, grupos, Feira, Páginas e a foto do perfil não aceitam vídeo. A comparação de imagens e vídeos com listas de hashes de mídia ilegal é planejada e ainda não existe. Hoje, denúncias e bloqueio da conta são os meios de moderação dessas imagens e vídeos. Uma foto de perfil imprópria se denuncia pela conta toda, e essa denúncia sempre é decidida por uma pessoa.', + 'São aceitos fotos e GIFs nas publicações e a foto do perfil, pela web hospedada e pelo app ligado à instalação da associação, e fotos, GIFs e mensagens de voz nas mensagens diretas e nos grupos, como descrito abaixo. A foto do perfil é sempre uma imagem parada e quadrada; um GIF escolhido para ela vira imagem parada. Vídeos curtos são aceitos nas publicações (até 30 segundos) e nos momentos (até 15 segundos), um por publicação ou momento. As publicações de uma página também aceitam um vídeo curto, como as de uma pessoa. Conversas, grupos, Feira e a foto do perfil, de uma pessoa ou de uma página, não aceitam vídeo. A comparação de imagens e vídeos com listas de hashes de mídia ilegal é planejada e ainda não existe. Hoje, denúncias e bloqueio da conta são os meios de moderação dessas imagens e vídeos. Uma foto de perfil imprópria se denuncia pela conta toda, e essa denúncia sempre é decidida por uma pessoa.', 'Na versão web hospedada, você pode ligar em Ajustes os avisos no aparelho (notificações push) de novo seguidor, resposta, curtida e republicação e o aviso de que chegou um convite para você chamar alguém para a Varanda. São opcionais e vêm desligados por padrão. Cada aviso leva o nome de quem agiu e a ação, nunca o texto da publicação, exceto o aviso de convite, que mostra sempre a mesma frase, sem nome de ninguém e sem texto de publicação. Aceitar estes documentos não liga os avisos: isso depende de uma escolha separada.', 'Na versão web hospedada e no app instalado, você pode trocar mensagens diretas com outros membros. Elas levam texto e, se você quiser, fotos e GIFs, e são cifradas de ponta a ponta entre os aparelhos de quem conversa. Os semeadores da associação guardam apenas envelopes lacrados de tamanho fixo, por até 14 dias, num conjunto comum que, em semeadores grandes, se divide em grupos de cerca de 500 pessoas; eles não conseguem ler os envelopes nem saber, pelo que guardam, quem escreveu para quem, mas podem saber de qual grupo uma pessoa é, como descrito na Política de Privacidade. Um semeador alterado ainda poderia tentar cruzar horários e endereços de rede; por isso o aparelho pega selos de envio com antecedência, o que dificulta esse cruzamento sem eliminá-lo. O serviço nunca sabe se uma mensagem foi lida. Mensagens de quem você não segue esperam em Pedidos de mensagem até você aceitar. Bloquear e apagar acontecem nos seus aparelhos. Ao denunciar, vão para os moderadores a mensagem que você escolheu, a conta de quem a enviou, o motivo e o comentário que você escrever, junto com a sua conta, como em qualquer denúncia; o resto da conversa nunca sai do aparelho. Na versão web hospedada, se você ligar os avisos no aparelho (push), o aviso de mensagem diz apenas que pode haver uma mensagem nova, sem nome nem texto. O app instalado ainda não tem avisos push.', 'Nas mensagens diretas e nos grupos, você pode enviar fotos e GIFs escolhidos da galeria do aparelho, até 4 por mensagem, com legenda opcional. A foto de uma mensagem direta é cifrada no seu aparelho antes de sair dele e fica no semeador da associação sob um identificador aleatório, por até 14 dias; o semeador não consegue ver a imagem nem saber para quem ela é. Ela também fica guardada, cifrada, nos aparelhos que a abriram, mesmo quando o app bloqueia, até você tocar em Sair ou em Recomeçar, ou apagar os dados do app. A foto de um grupo público é pública como o texto do grupo. A foto de um grupo privado é cifrada no aparelho de quem envia: o semeador guarda só a versão cifrada, e a chave vai dentro da publicação lacrada do grupo, então só os aparelhos dos membros conseguem abri-la. Ao denunciar uma mensagem direta ou uma mensagem de grupo privado com foto, a primeira imagem vai junto, aberta, numa cópia reduzida que aparece na tela da denúncia antes de você enviar; se você não enviar, nada sai do aparelho. Os moderadores a recebem marcada como não conferida, e uma denúncia com imagem sempre é decidida por uma pessoa.', @@ -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 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 e quem ela segue, é público como a página, e os limites da exclusão abaixo valem do mesmo jeito.', '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 das publicações 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 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 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.', '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/musicDraft.js b/apps/app/src/musicDraft.js index d9100753d..5c5e6085d 100644 --- a/apps/app/src/musicDraft.js +++ b/apps/app/src/musicDraft.js @@ -12,10 +12,9 @@ export function musicSnapshot (draft) { return fields === null ? null : Object.freeze({ ...fields, thumb: null }) } -export function musicBlocks ({ hasMedia, hasVideo = false, asPage, online, textLength }) { +export function musicBlocks ({ hasMedia, hasVideo = false, online, textLength }) { if (hasVideo) return MUSIC_VIDEO_TEXT if (hasMedia) return MUSIC_PHOTOS_TEXT - if (asPage !== null) return 'A música não vai em publicações de página' if (textLength < 1) return MUSIC_NEEDS_TEXT if (online === false) return 'Sem conexão: a música precisa de conexão' return '' diff --git a/apps/app/src/pagePost.js b/apps/app/src/pagePost.js new file mode 100644 index 000000000..3166c3761 --- /dev/null +++ b/apps/app/src/pagePost.js @@ -0,0 +1,63 @@ +// 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. + +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 }) { + const hasMedia = Array.isArray(media) && media.length > 0 + if (hasMedia && preview !== null) throw pageError('pedido-invalido') + const op = { text } + if (hasMedia) op.media = media + if (preview !== null) op.preview = preview + return op +} + +function descriptorOf (answer, valid, message) { + const d = answer && typeof answer === 'object' && !Array.isArray(answer) ? answer.descriptor : undefined + if (!valid(d)) { + const err = new Error(message) + err.uncertain = true + throw err + } + return d +} + +const validPoster = (d) => validDescriptor(d) && d.mime === 'image/jpeg' + +// Uploads the JPEG poster, then the video with its duration, each once. +// upload is the screen's pagesMedia wrapper. file is a readyVideo() file. +// poster is an already uploaded poster descriptor from an earlier attempt: +// its upload is skipped. When the video upload throws, the poster descriptor +// is on err.poster so the caller can resume; this never retries. +// -> [posterDescriptor, videoDescriptor] from each answer's descriptor. +export async function prepPageVideo ({ upload, file, poster = null }) { + if (!readyVideo(file) || typeof upload !== 'function') throw pageError('pedido-invalido') + let posterDescriptor = poster + if (!validPoster(posterDescriptor)) { + const answer = await upload({ + bytes: file.poster.bytes, + mime: file.poster.mime, + width: file.poster.width, + height: file.poster.height + }) + posterDescriptor = descriptorOf(answer, validPoster, 'Resposta inválida ao enviar a capa do vídeo.') + } + try { + const videoAnswer = await upload({ + bytes: file.bytes, + mime: file.mime, + width: file.width, + height: file.height, + ms: file.ms + }) + return [posterDescriptor, descriptorOf(videoAnswer, validVideoDescriptor, 'Resposta inválida ao enviar o vídeo.')] + } catch (err) { + if (err && typeof err === 'object') err.poster = posterDescriptor + throw err + } +} diff --git a/apps/app/src/pages.js b/apps/app/src/pages.js index 45faca2d5..66adc5a3e 100644 --- a/apps/app/src/pages.js +++ b/apps/app/src/pages.js @@ -18,6 +18,8 @@ import rpc from '@varanda/rpc' import { buildRequest, readJson, formatNextChange } from './account.js' +import { validDescriptor, validVideoDescriptor } from './media/fetch.js' +import { VIDEO_MIME } from './media/plan.js' import { accountOriginOf, pagesCore } from './pageGate.js' import { isLegacyPage, legacyBundleOf, nextGen, pagesNoLongerRun, planShares, secretsParams } from './pageSecrets.js' @@ -33,6 +35,8 @@ export { MAX_AVATAR_BYTES } const KEY_RE = /^[0-9a-f]{64}$/ const TIMEOUT_MS = 8000 const UPLOAD_TIMEOUT_MS = 30000 +// A video is up to MAX_MEDIA_BYTES on a slow uplink. +const VIDEO_UPLOAD_TIMEOUT_MS = 120000 const MAX_BODY = 65536 // The signed reads: 'follows' answers up to 4095 keys, 'status' up to 4096 // liked and 4096 reposted refs, 'list' every invite and offer. @@ -62,7 +66,7 @@ export const TEXTS = Object.freeze({ pausada: 'Página pausada; fale com a associação', encerrada: 'Esta página foi encerrada', movida: 'Esta página mudou para uma nova chave', - 'midia-invalida': 'Foto não aceita', + 'midia-invalida': 'Foto ou vídeo não aceito', indisponivel: 'Serviço indisponível', 'termos-pendentes': 'Aceite os Termos para continuar', 'troca-bloqueada': 'Você ainda não pode trocar o @nome', @@ -94,6 +98,11 @@ export function pageError (code, nextChangeAt) { const isKey = (v) => typeof v === 'string' && KEY_RE.test(v) const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v) +const plainObject = (v) => { + if (!isObject(v)) return false + const proto = Object.getPrototypeOf(v) + return proto === Object.prototype || proto === null +} // A header value is latin-1 on the wire: JSON with every non-ASCII character // escaped parses to the same op, and the service canonicalizes it anyway. @@ -249,12 +258,15 @@ function upload (action, { member, nonce, page, op, signature, bytes, origin }, 'x-varanda-page-signature': signature, 'x-varanda-page-op': headerJson(op) }, - timeoutMs: UPLOAD_TIMEOUT_MS, + timeoutMs: op && op.mime === VIDEO_MIME ? VIDEO_UPLOAD_TIMEOUT_MS : UPLOAD_TIMEOUT_MS, signed: true, origin }) } +// A video's duration `ms` travels inside the signed op; upload() sends the +// op whole. video/mp4 shares the still-image byte cap (MAX_VIDEO_BYTES equals +// MAX_MEDIA_BYTES). export const pagesMedia = (args) => upload('media', args, MAX_MEDIA_BYTES) export const pagesAvatar = (args) => upload('avatar', args, MAX_AVATAR_BYTES) @@ -279,10 +291,45 @@ const signer = (node) => { return null } +const MEDIA_ACTIONS = ['post', 'reply', 'quote', 'listing', 'listing-edit'] +const POST_ACTIONS = ['post', 'reply', 'quote'] + +// A diary video is exactly [JPEG poster, video], the same pair postRecord +// accepts. Anything else that carries a video is not that pair. +function isVideoPair (media) { + if (!Array.isArray(media) || media.length !== 2) return false + const poster = media[0] + const video = media[1] + return validDescriptor(poster) && poster.mime === 'image/jpeg' && validVideoDescriptor(video) +} + +function hasVideo (media) { + if (!Array.isArray(media)) return false + for (let i = 0; i < media.length; i++) { + const item = media[i] + if (validVideoDescriptor(item)) return true + if (item && typeof item === 'object' && item.mime === VIDEO_MIME) return true + } + return false +} + +// preview, when present on a post, reply or quote: a plain object with a +// url string. The service checks the card; this is only the shape. +function checkPreview (action, op) { + if (!POST_ACTIONS.includes(action) || op.preview === undefined) return true + return plainObject(op.preview) && typeof op.preview.url === 'string' +} + function checkMedia (action, op) { - if (!['post', 'reply', 'quote', 'listing', 'listing-edit'].includes(action) || !isObject(op) || op.media === undefined) return true + if (!MEDIA_ACTIONS.includes(action) || !isObject(op)) return true + if (!checkPreview(action, op)) return false + // A preview never travels with media (records.js POST_PREVIEW_KEYS). + if (op.preview !== undefined && op.media !== undefined && op.media !== null && !(Array.isArray(op.media) && op.media.length === 0)) return false + if (op.media === undefined) return true // listing.edit takes media null to drop every photo (docs/rpc.md 5.107). if (action === 'listing-edit' && op.media === null) return true + if (POST_ACTIONS.includes(action) && isVideoPair(op.media)) return true + if (POST_ACTIONS.includes(action) && hasVideo(op.media)) return false // A listing is not a diary post: Feira stays at its own cap. const cap = action === 'listing' || action === 'listing-edit' ? rpc.feira.MAX_LISTING_MEDIA : MAX_MEDIA_PER_POST return Array.isArray(op.media) && op.media.length >= 1 && op.media.length <= cap diff --git a/apps/app/src/screens/Publicar.js b/apps/app/src/screens/Publicar.js index 94aa44a29..4ae7fc1b2 100644 --- a/apps/app/src/screens/Publicar.js +++ b/apps/app/src/screens/Publicar.js @@ -69,6 +69,7 @@ import { useNode } from '../node' import { useNames } from '../names' import * as actingStore from '../actingAs' import { actAs, pagesList, pagesMedia, pagesOrigin, pagesStart } from '../pages' +import { pagePostOp, prepPageVideo } from '../pagePost' import { memberKeyOf, useActing } from './Conversa' import { useOutbox } from '../outboxProvider' import { GATE_MESSAGE, LOCKED_MESSAGE } from '../outbox' @@ -79,7 +80,7 @@ import { ringState } from '../composeRing' import { composeStatus } from '../composeStatus' import { countAfterInsert, insertAt } from '../emoji' import { MAX_MEDIA_PER_POST, durationLabel } from '../media/plan' -import { validDescriptor } from '../media/fetch' +import { validDescriptor, validVideoDescriptor } from '../media/fetch' import { pickImages, pickVideo } from '../media/attach' import { prepareVideo } from '../media/videoPrep' import { canComposeVideo, createVideoDraft, videoMomentValid, videoPostValid, VIDEO_OR_PHOTOS, MOMENT_ONE_MEDIA, mediaComposeError } from '../videoCompose' @@ -107,7 +108,7 @@ import { MusicPicker } from '../ui/MusicPicker' import { useMusicAvailable } from '../ui/MusicPlayerCard' import { MusicSticker } from '../ui/MusicSticker' import { withPreview } from '../attach-plan' -import { previewRefusal, refusalOf } from '../wordCheck' +import { findTerm, previewRefusal, refusalOf } from '../wordCheck' import { editorInit, editorPoll } from '../polls' import { PollEditor } from '../ui/PollEditor' import { EventEditor, eventEditorEvent, eventEditorInit, eventEditorTexts } from '../ui/EventEditor' @@ -805,8 +806,8 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment const [mode, setMode] = useState('post') const momentMode = momentOn && mode === 'moment' const moment = useMomentDraft({ node, member: me?.publicKey, open, active: open === true && momentMode }) - const video = useVideoDraft({ active: open === true && !momentMode && asPage === null }) - const canVideo = canComposeVideo({ node, asPage, pickVideo, prepareVideo }) + const video = useVideoDraft({ active: open === true && !momentMode }) + const canVideo = canComposeVideo({ node, pickVideo, prepareVideo }) // Only an increase is a request: the shell resets the counter to 0 when a // post is published, and that must not reopen the composer in Momento. const lastMomentRequest = useRef(momentRequest) @@ -865,6 +866,14 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (!open) closesRef.current++ }, [open]) const asPageRef = useRef(asPage) + // What a page already uploaded for its video draft: { page, file, poster, + // video, retry }. poster always; video once the pair is up; retry for a + // video upload whose outcome was unknown. Reused only on an explicit tap, + // for the same page and file. + const pagePosterRef = useRef(null) + // The page card built for { page, url, thumb }: a new tap reuses it, so its + // thumbnail is never uploaded twice. + const pageCardRef = useRef(null) asPageRef.current = asPage const canAttach = typeof pickImages === 'function' && (media !== null || asPage !== null) const { request: nodeRequest, hosted: nodeHosted } = node @@ -908,11 +917,11 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment // being sent or waiting for its retry keeps its photos: they are in the // signed bytes. useEffect(() => { - if (asPage !== null) setMusicDraft(null) if (pageRetryRef.current !== null || pageSendingRef.current) return genRef.current++ removeItems(Array.from(liveRef.current)) video.draft.clear() + pagePosterRef.current = null }, [asPage, video.draft]) // Drops the post waiting for its retry and unlocks the draft. Its photos // stay only for the page they were uploaded for. @@ -924,6 +933,8 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (pending.page !== asPage) { genRef.current++ removeItems(Array.from(liveRef.current)) + video.draft.clear() + pagePosterRef.current = null } } @@ -945,7 +956,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment // Quotes are never queued: offline they wait for the network. const offlineQueue = canQueue && asPage === null && node.online === false && !quote const quoteOffline = !!quote && node.online === false - // The draft link card (not as a page: its posts are signed statements). + // The draft link card (a page's card is uploaded as one of its items). // cardRef keeps the card a Publicar already built from a snapshot, so a // new press after a failure never uploads its thumbnail again. // linkHold: the text a share left in the field while its link waits for @@ -989,9 +1000,9 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment const musicResolveOn = musicAvailable === true && node.online !== false && previewsEnabled(previewPrefStore()) const musicResolveTarget = resolveTarget(text, musicTried.current) // Wait for the music policy before allowing an Audius page fetch on the device. - const linkDraft = useLinkDraft({ text, enabled: open === true && asPage === null && !shareLinkHeld && pollDraft === null && eventDraft === null && !musicDraft && !(musicAvailable !== false && isAudiusLink(previewTarget(text))), photos: hasMedia, member: self.publicKey, fallback: fallbackCard }) + const linkDraft = useLinkDraft({ text, enabled: open === true && !shareLinkHeld && pollDraft === null && eventDraft === null && !musicDraft && !(musicAvailable !== false && isAudiusLink(previewTarget(text))), photos: hasMedia, member: self.publicKey, fallback: fallbackCard }) useEffect(() => { - if (!open || momentMode || asPage !== null || hasMedia || musicDraft || busy || frozen || musicPickerOpen || shareLinkHeld || !musicResolveOn) return undefined + if (!open || momentMode || hasMedia || musicDraft || busy || frozen || musicPickerOpen || shareLinkHeld || !musicResolveOn) return undefined const url = musicResolveTarget if (url === null) return undefined const controller = new AbortController() @@ -1013,12 +1024,12 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment clearTimeout(timer) controller.abort() } - }, [musicResolveTarget, open, momentMode, asPage, hasMedia, musicDraft, busy, frozen, musicPickerOpen, shareLinkHeld, musicResolveOn, member, musicOrigin, nodeRequest]) + }, [musicResolveTarget, open, momentMode, hasMedia, musicDraft, busy, frozen, musicPickerOpen, shareLinkHeld, musicResolveOn, member, musicOrigin, nodeRequest]) useEffect(() => { - if (!open || momentMode || asPage !== null) setMusicPickerOpen(false) - }, [open, momentMode, asPage]) + if (!open || momentMode) setMusicPickerOpen(false) + }, [open, momentMode]) const pickMusic = (draft) => { - if (busy || frozen || asPage !== null) return + if (busy || frozen) return if (liveRef.current.size > 0) { setNote(MUSIC_PHOTOS_TEXT); return } if (video.draft.state.phase !== 'empty') { setNote(MUSIC_VIDEO_TEXT); return } if (musicSnapshot(draft) === null) return @@ -1093,14 +1104,19 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment // bytes to the service. -> the descriptor. const uploadForPage = async (page, item) => { if (typeof item.retry === 'function') return (await item.retry()).descriptor - const { encoded } = item + return (await uploadBytesForPage(page, item.encoded)).descriptor + } + + // One signed page media upload: a still image, or a video with its `ms`. + // -> the service's answer ({ descriptor }). Never retried here. + const uploadBytesForPage = async (page, encoded) => { const member = await memberKeyOf(nodeRequest, nodeRef.current) const origin = pagesOrigin(nodeRef.current) const { nonce } = await pagesStart({ member, action: 'media', page, origin }) const op = { sha256: hexOf(sha256(encoded.bytes)), mime: encoded.mime, width: encoded.width, height: encoded.height, bytes: encoded.bytes.byteLength } + if (encoded.ms !== undefined) op.ms = encoded.ms const signed = await nodeRequest('page.sign', { action: 'media', nonce, page, op }) - const res = await pagesMedia({ member, nonce, page, op, signature: signed.signature, bytes: encoded.bytes, origin }) - return res.descriptor + return pagesMedia({ member, nonce, page, op, signature: signed.signature, bytes: encoded.bytes, origin }) } // Uploads, on Publicar only, the items that have no descriptor yet, one at @@ -1502,6 +1518,8 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (openRef.current && asPageRef.current === page) return genRef.current++ removeItems(Array.from(liveRef.current)) + video.draft.clear() + pagePosterRef.current = null } const sendAsPage = async () => { @@ -1512,6 +1530,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (pageRetryRef.current !== pending) return if (r.ok) { setPageRetry(null) + pagePosterRef.current = null published(pending.sent, pending.reply, pending.ids, pending.quote) } else if (!r.uncertain) { // Refused for sure: nothing was published, the draft is free again. @@ -1527,22 +1546,73 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (sentQuote && countChars(sent) < 1) return setPageSending(true) try { - await sendNewAsPage(page, sent, sentReply, sentQuote) + await sendNewAsPage(page, sent, sentReply, sentQuote, musicDraft) } finally { setPageSending(false) } settledAsPage(page) } - const sendNewAsPage = async (page, sent, sentReply, sentQuote) => { - const sentIds = items.map((item) => item.id) + // The [poster, video] pair for a page post. What an earlier tap already + // uploaded for this same page and file is reused: the pair, the poster, or + // the signed video upload whose outcome was unknown (resent only now, on + // this explicit tap). -> the pair, or null when it stopped (error shown). + const pageVideoMedia = async (page, videoFile) => { + const gen = genRef.current + const stale = () => gen !== genRef.current || video.draft.state.file !== videoFile + const kept0 = pagePosterRef.current + const kept = kept0 !== null && kept0.page === page && kept0.file === videoFile ? kept0 : null + if (kept !== null && kept.video) return [kept.poster, kept.video] + try { + let pair + if (kept !== null && typeof kept.retry === 'function') { + const answer = await kept.retry() + const d = answer && typeof answer === 'object' ? answer.descriptor : undefined + if (!validVideoDescriptor(d)) throw Object.assign(new Error('Resposta inválida ao enviar o vídeo.'), { uncertain: true, poster: kept.poster }) + pair = [kept.poster, d] + } else { + pair = await prepPageVideo({ upload: (f) => uploadBytesForPage(page, f), file: videoFile, poster: kept !== null ? kept.poster : null }) + } + if (stale()) return null + pagePosterRef.current = { page, file: videoFile, poster: pair[0], video: pair[1] } + return pair + } catch (err) { + if (stale()) return null + const poster = err && err.poster ? err.poster : kept !== null ? kept.poster : null + // A kept retry that failed again is dropped: the next tap uploads the + // video anew (with the kept poster), never a loop of resends. + const resent = kept !== null && typeof kept.retry === 'function' + const retry = !resent && err && err.uncertain === true && typeof err.retry === 'function' ? err.retry : null + pagePosterRef.current = poster !== null ? { page, file: videoFile, poster, video: null, retry } : null + setCheckError(mediaComposeError(err) || errorText(err)) + return null + } + } + + // The first listed term in a card's title or description, or null. + const findPreviewTerm = (view) => { + for (const t of [view.title, view.desc]) { + const term = typeof t === 'string' ? findTerm(t) : null + if (term !== null) return term + } + return null + } + + const sendNewAsPage = async (page, sent, sentReply, sentQuote, sentMusic) => { + const videoFile = hasVideo ? video.draft.state.file : null + const sentIds = hasVideo ? [videoFile] : items.map((item) => item.id) let sentMedia = null if (hasMedia) { - if (!mediaReady || !mediaOnline) return + if (!mediaReady || !mediaOnline || (hasVideo && (!canVideo || video.draft.state.phase !== 'ready'))) return uploadingRef.current = true setUploading(true) try { - sentMedia = await uploadAll(items, page) + if (hasVideo) { + sentMedia = await pageVideoMedia(page, videoFile) + if (sentMedia === null) return + } else { + sentMedia = await uploadAll(items, page) + } } finally { uploadingRef.current = false setUploading(false) @@ -1550,10 +1620,55 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment if (sentMedia === null) return } const kind = sentQuote ? 'quote' : sentReply ? 'reply' : 'post' - const op = { text: sent } - if (sentQuote) op.to = sentQuote.ref - else if (sentReply) op.to = sentReply.ref - if (sentMedia !== null) op.media = sentMedia + const pageMethod = sentQuote ? 'post.quote' : sentReply ? 'post.reply' : 'post.create' + const to = sentQuote ? sentQuote.ref : sentReply ? sentReply.ref : null + // 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 + // A music title comes from the provider: refused before any signature. + const musicRefused = sentMusic !== null && snapshot !== null ? findPreviewTerm(snapshot) : null + if (musicRefused !== null) { + setCheckError('Não dá para publicar como Página: "' + musicRefused + '" aparece no título ou no artista da música, e o Varanda não permite esse termo em conteúdo público. Escolha outra música e tente de novo.') + return + } + const thumbKey = snapshot && snapshot.thumb ? snapshot.thumb.bytes : null + const cached = pageCardRef.current + if (snapshot !== null && cached !== null && cached.page === page && cached.url === snapshot.url && cached.thumb === thumbKey) { + card = cached.card + } else if (snapshot !== null) { + const gen = genRef.current + const upload = async (t) => { + const d = (await uploadBytesForPage(page, { bytes: t.bytes, mime: t.mime, width: t.width, height: t.height })).descriptor + if (!validDescriptor(d) || d.mime !== t.mime) throw new Error('resposta inválida') + return d + } + uploadingRef.current = true + setUploading(true) + try { + card = await cardForSend(snapshot, { upload }) + } finally { + uploadingRef.current = false + setUploading(false) + } + if (gen !== genRef.current) return + pageCardRef.current = { page, url: snapshot.url, thumb: thumbKey, card } + } + let built + 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 }) + }, card) + } catch (err) { + setCheckError(errorText(err)) + return + } + if (sentMusic !== null && built.card === null) { + setCheckError('A música não coube: encurte o texto') + return + } + const op = to !== null ? { ...built.op, to } : built.op let raw = null const r = await action.run(async () => { try { @@ -1563,7 +1678,10 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment throw err } }) - if (r.ok) return published(sent, sentReply, sentIds, sentQuote) + if (r.ok) { + pagePosterRef.current = null + return published(sent, sentReply, sentIds, sentQuote) + } if (r.uncertain && raw && typeof raw.retry === 'function') { setPageRetry({ retry: raw.retry, page, sent, reply: sentReply, quote: sentQuote, ids: sentIds }) } @@ -1618,7 +1736,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment } const sentMusic = musicDraft if (sentMusic !== null) { - const blocked = musicBlocks({ hasMedia, hasVideo, asPage, online: node.online, textLength: len }) + const blocked = musicBlocks({ hasMedia, hasVideo, online: node.online, textLength: len }) if (blocked !== '') { setCheckError(blocked); return } } // Never a new signature while a signed post waits for its retry. @@ -1814,6 +1932,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment genRef.current++ removeItems(Array.from(liveRef.current)) video.draft.clear() + pagePosterRef.current = null setMusicDraft(null) musicTried.current.clear() setText('') @@ -2178,7 +2297,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment /> - { video.draft.clear(); setNote('') }} /> + { video.draft.clear(); pagePosterRef.current = null; setNote('') }} /> {hasMedia && items.length > 0 ? ( @@ -2200,7 +2319,7 @@ export default function Publicar ({ open, reply: replyProp, quote = null, moment ) : hasMedia || musicDraft !== null ? null - : shareLinkHeld && open === true && asPage === null && previewsEnabled(previewPrefStore()) + : shareLinkHeld && open === true && previewsEnabled(previewPrefStore()) ? ( ) : null} - {musicAvailable === true && asPage === null && pollDraft === null && eventDraft === null + {musicAvailable === true && pollDraft === null && eventDraft === null ? ( setMusicPickerOpen(false)} onPick={pickMusic} initial={musicDraft} diff --git a/apps/app/src/videoCompose.js b/apps/app/src/videoCompose.js index 717642099..2cc27f7e4 100644 --- a/apps/app/src/videoCompose.js +++ b/apps/app/src/videoCompose.js @@ -12,8 +12,8 @@ export function mediaComposeError (err) { return err && err.uncertain !== true && err.message === 'espaço de fotos deste aparelho esgotado' ? MEDIA_FULL : '' } -export function canComposeVideo ({ node, asPage = null, pickVideo, prepareVideo }) { - return !!node && node.online !== false && node.media?.video === true && asPage === null && +export function canComposeVideo ({ node, pickVideo, prepareVideo }) { + return !!node && node.online !== false && node.media?.video === true && typeof pickVideo === 'function' && typeof prepareVideo === 'function' } diff --git a/apps/app/test/legal.test.js b/apps/app/test/legal.test.js index c3d281d4f..18c451fce 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, 76) + t.is(LEGAL_VERSION, 77) t.is(LEGAL_DATE, '16/11/2026') - t.is(REVIEW_NOTE, 'Versão 76, sujeita a revisão jurídica. Não é parecer jurídico.') + t.is(REVIEW_NOTE, 'Versão 77, 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, 'ff8c9d0e4077049a6f46fe9873ae5d8661226ed9918ad5b7c5b3822f1194097b', 'o texto mudou: suba LEGAL_VERSION (e TERMS_VERSION em @varanda/core lib/terms.js) e atualize este digest') + t.is(digest, '74821cf815cf27d5f935b2ff24e9e680518dac83fd4ea3368e5e7bdcc32ff0f7', '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) => { @@ -507,7 +507,7 @@ test('legal: version 18 describes voice notes in chats and the report audio', as t.ok(text(TERMS).includes('só pede acesso ao microfone quando você começa a gravar')) t.ok(text(TERMS).includes('o botão de gravar não aparece')) t.ok(text(TERMS).includes('só os aparelhos dos membros conseguem ouvi-la')) - t.ok(text(TERMS).includes('Conversas, grupos, Feira, Páginas e a foto do perfil não aceitam vídeo')) + t.ok(text(TERMS).includes('Conversas, grupos, Feira e a foto do perfil, de uma pessoa ou de uma página, não aceitam vídeo')) t.ok(text(PRIVACY).includes('As conversas não aceitam vídeo')) t.ok(text(PRIVACY).includes('o áudio vai junto com a denúncia, aberto')) t.ok(text(PRIVACY).includes('se tiver até 700 KB')) @@ -905,3 +905,12 @@ test('legal: version 73 keeps the one-time notes from repeating on another devic t.ok(all.indexOf(closing) > momentos && all.indexOf(closing) > all.indexOf(marks), 'the closing sentence follows the momentos list, not the marks') for (const doc of [TERMS, PRIVACY]) t.absent(text(doc).includes(String.fromCharCode(0x2014)), 'no em dash') }) + +test('legal: version 77 describes video and link previews in page posts', async (t) => { + 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)')) +}) diff --git a/apps/app/test/linkCardBuild.test.js b/apps/app/test/linkCardBuild.test.js index 6e8fd3a40..26176843c 100644 --- a/apps/app/test/linkCardBuild.test.js +++ b/apps/app/test/linkCardBuild.test.js @@ -633,8 +633,8 @@ test('Publicar holds the ordinary Audius build while availability is unknown or const src = fs.readFileSync(path.join(SRC, 'screens/Publicar.js'), 'utf8') t.ok(src.includes('useMusicAvailable(node, member, open)'), 'opening the composer refreshes music availability') t.ok(src.includes('musicAvailable === true && node.online !== false && previewsEnabled(previewPrefStore())'), 'resolution requires confirmed music and online previews') - t.ok(src.includes('{musicAvailable === true && asPage === null'), 'the music button requires confirmed availability') - t.ok(src.includes('asPage === null && musicAvailable === true && musicPickerOpen'), 'the picker requires confirmed availability') + t.ok(src.includes('{musicAvailable === true && pollDraft === null'), 'the music button requires confirmed availability') + t.ok(src.includes('!momentMode && musicAvailable === true && musicPickerOpen'), 'the picker requires confirmed availability') const slots = [] const effects = [] diff --git a/apps/app/test/musicDraft.test.js b/apps/app/test/musicDraft.test.js index 8df8dea12..ac0525bce 100644 --- a/apps/app/test/musicDraft.test.js +++ b/apps/app/test/musicDraft.test.js @@ -144,14 +144,13 @@ test('music snapshots are frozen, sanitized and have no thumbnail', async (t) => t.is(playlist.thumb, null) }) -test('music blocks photos, a video, pages, empty text and offline sends', async (t) => { +test('music blocks photos, a video, empty text and offline sends, never a page', async (t) => { const { musicBlocks, MUSIC_PHOTOS_TEXT, MUSIC_VIDEO_TEXT } = await rules() const { MUSIC_NEEDS_TEXT } = await import('../src/music.js') - const valid = { hasMedia: false, asPage: null, online: true, textLength: 1 } + const valid = { hasMedia: false, online: true, textLength: 1 } t.is(musicBlocks(valid), '') t.is(musicBlocks({ ...valid, hasMedia: true }), MUSIC_PHOTOS_TEXT) t.is(musicBlocks({ ...valid, hasMedia: true, hasVideo: true }), MUSIC_VIDEO_TEXT) - t.is(musicBlocks({ ...valid, asPage: 'page' }), 'A música não vai em publicações de página') t.is(musicBlocks({ ...valid, textLength: 0 }), MUSIC_NEEDS_TEXT) t.is(musicBlocks({ ...valid, online: false }), 'Sem conexão: a música precisa de conexão') }) @@ -264,7 +263,6 @@ test('compose-time resolution honors the preview preference and online gate', as { musicAvailable: null }, { open: false }, { momentMode: true }, - { asPage: 'page' }, { hasMedia: true }, { musicDraft: draft }, { busy: true }, @@ -502,14 +500,16 @@ function composerFunction (start, end, name, ctx) { return new Function(...Object.keys(ctx), code + '\nreturn ' + name)(...Object.values(ctx)) } -test('switching to a page clears music even while closed or waiting for a page retry', (t) => { +test('switching identity drops page uploads and the kept video pair, never the music draft', (t) => { const end = source.indexOf(' }, [asPage, video.draft])') + ' }, [asPage, video.draft])'.length const start = source.lastIndexOf(' useEffect(() => {', end) const effect = source.slice(start, end) for (const open of [true, false]) { for (const pending of ['none', 'retry', 'sending']) { let music = draft + const kept = { page: 'page', file: {}, poster: {}, video: {} } const ctx = { + pagePosterRef: { current: kept }, open, asPage: null, pageRetryRef: { current: pending === 'retry' ? { page: 'page' } : null }, @@ -523,14 +523,10 @@ test('switching to a page clears music even while closed or waiting for a page r } // eslint-disable-next-line no-new-func const run = () => new Function(...Object.keys(ctx), effect)(...Object.values(ctx)) - run() - t.is(music, draft, 'the person keeps the draft') ctx.asPage = 'page' run() - t.is(music, null, 'the page drops music: open=' + open + ', pending=' + pending) - ctx.asPage = null - run() - t.is(music, null, 'switching back does not restore the music') + t.is(music, draft, 'the music draft is kept: open=' + open + ', pending=' + pending) + t.is(ctx.pagePosterRef.current, pending === 'none' ? null : kept, 'the video pair goes unless a send holds it') } } }) @@ -856,3 +852,206 @@ test('a share call that throws still publishes the post once and never resends', t.alike(r.state.published[0][4], { ref: null, result: null }) t.is(r.state.queued.length, 0) }) + +const photoD = (over = {}) => ({ blocks: 1, bytes: 10, core: 'ab'.repeat(32), height: 1, mime: 'image/jpeg', sha256: 'cd'.repeat(32), start: 1, width: 1, ...over }) +const videoD = (over = {}) => ({ blocks: 1, bytes: 10, core: 'ef'.repeat(32), height: 360, mime: 'video/mp4', ms: 1000, sha256: '12'.repeat(32), start: 2, width: 640, ...over }) + +// send, then sendAsPage and its helpers, as a page with the service stubbed. +async function pageSender (overrides = {}) { + const base = await sender() + const state = { ...base.state, acts: [], uploads: [], preps: [] } + const { pagePostOp } = await import('../src/pagePost.js') + const { findTerm } = await import('../src/wordCheck.js') + const { validDescriptor, validVideoDescriptor } = await import('../src/media/fetch.js') + const videoFile = { name: 'video' } + const ctx = { + ...base.ctx, + asPage: 'page', + musicDraft: null, + text: 'Olá', + len: 3, + findTerm, + validDescriptor, + validVideoDescriptor, + pagePostOp, + prepPageVideo: async ({ poster }) => { state.preps.push(poster); return [poster || photoD(), videoD()] }, + uploadBytesForPage: async (page, f) => { state.uploads.push({ page, mime: f.mime }); return { descriptor: photoD() } }, + uploadAll: async () => [photoD()], + pagePosterRef: { current: null }, + pageCardRef: { current: null }, + pageSendingRef: { current: false }, + setPageSending: () => {}, + setPageRetry: (v) => { state.retry = v }, + openRef: { current: true }, + asPageRef: { current: 'page' }, + genRef: { current: 0 }, + liveRef: { current: new Set() }, + removeItems: () => {}, + mediaReady: true, + mediaOnline: true, + canVideo: true, + mediaComposeError: () => '', + nodeRef: { current: {} }, + nodeRequest: async () => ({}), + memberKeyOf: async () => 'm', + actAs: async (node, args) => { state.acts.push(args); return { ok: true } }, + published: (...args) => { state.published.push(args) }, + videoFile, + ...overrides + } + if (ctx.hasVideo && !overrides.video) ctx.video = { draft: { state: { phase: 'ready', file: videoFile }, clear: () => {} } } + const a = source.indexOf(' const settledAsPage = (page) => {') + const b = source.indexOf(' // A poll post:', a) + const start = source.lastIndexOf(' const send = async () => {') + const end = source.indexOf('\n const replyName', start) + const code = source.slice(a, b) + source.slice(start, end) + '\nreturn send' + // eslint-disable-next-line no-new-func + const send = new Function(...Object.keys(ctx), code)(...Object.values(ctx)) + return { state, send, ctx } +} + +test('a page video sends { text, media: [poster, video] } with no preview', async (t) => { + const r = await pageSender({ hasMedia: true, hasVideo: true, linkDraft: { take: () => ({ url: 'https://exemplo.com/a', title: 'T', desc: 'D', thumb: null }) } }) + await r.send() + t.is(r.state.acts.length, 1) + t.alike(r.state.acts[0].op, { text: 'Olá', media: [photoD(), videoD()] }) + t.is(r.state.acts[0].action, 'post') + t.is(r.state.published.length, 1) + t.is(r.ctx.pagePosterRef.current, null, 'cleared on success') +}) + +test('a page reply or quote carries to', async (t) => { + for (const [extra, action] of [[{ reply: target }, 'reply'], [{ quote: target }, 'quote']]) { + const r = await pageSender(extra) + await r.send() + t.is(r.state.acts[0].action, action) + t.is(r.state.acts[0].op.to, target.ref) + } +}) + +test('a page link card thumbnail goes up as a page item, or the card goes without it', async (t) => { + const thumb = { bytes: new Uint8Array([1]), mime: 'image/jpeg', width: 320, height: 320 } + const take = () => ({ url: 'https://exemplo.com/a', host: 'exemplo.com', title: 'Titulo', desc: 'Linha', thumb }) + const ok = await pageSender({ linkDraft: { take } }) + await ok.send() + t.alike(ok.state.uploads, [{ page: 'page', mime: 'image/jpeg' }]) + t.alike(ok.state.acts[0].op.preview.image, photoD()) + t.absent(ok.state.acts[0].op.media) + const failed = await pageSender({ linkDraft: { take }, uploadBytesForPage: async () => { throw new Error('falhou') } }) + await failed.send() + t.is(failed.state.acts[0].op.preview.image, null) +}) + +test('a refused page post keeps the card and the video pair for the next tap', async (t) => { + const thumb = { bytes: new Uint8Array([1]), mime: 'image/jpeg', width: 320, height: 320 } + const take = () => ({ url: 'https://exemplo.com/a', host: 'exemplo.com', title: 'Titulo', desc: 'Linha', thumb }) + const refuse = async () => { throw new Error('recusado') } + const card = await pageSender({ linkDraft: { take }, actAs: refuse }) + await card.send() + await card.send() + t.is(card.state.uploads.length, 1, 'the thumbnail is uploaded once') + const vid = await pageSender({ hasMedia: true, hasVideo: true, actAs: refuse }) + await vid.send() + await vid.send() + t.is(vid.state.preps.length, 1, 'the video is uploaded once') + t.alike(vid.ctx.pagePosterRef.current.video, videoD()) +}) + +test('a failed page video upload resumes its poster only for the same page and file', async (t) => { + const poster = photoD({ start: 3 }) + const fail = async () => { throw Object.assign(new Error('falhou'), { poster }) } + const r = await pageSender({ hasMedia: true, hasVideo: true, prepPageVideo: fail }) + await r.send() + t.is(r.state.acts.length, 0) + t.is(r.ctx.pagePosterRef.current.poster, poster) + const same = await pageSender({ hasMedia: true, hasVideo: true, pagePosterRef: { current: r.ctx.pagePosterRef.current } }) + same.ctx.pagePosterRef.current.file = same.ctx.videoFile + await same.send() + t.alike(same.state.preps, [poster], 'the poster is reused') + t.is(same.ctx.pagePosterRef.current, null) + const other = await pageSender({ hasMedia: true, hasVideo: true, asPage: 'outra', pagePosterRef: { current: { page: 'page', file: null, poster, video: null } } }) + other.ctx.pagePosterRef.current.file = other.ctx.videoFile + await other.send() + t.alike(other.state.preps, [null], 'another page uploads its own poster') +}) + +test('an uncertain page video upload is resent only by its retry on the next tap', async (t) => { + const poster = photoD() + let retried = 0 + const retry = async () => { retried++; return { descriptor: videoD() } } + const fail = async () => { throw Object.assign(new Error('incerto'), { poster, uncertain: true, retry }) } + const r = await pageSender({ hasMedia: true, hasVideo: true, prepPageVideo: fail }) + await r.send() + t.is(retried, 0, 'never automatically') + const again = await pageSender({ hasMedia: true, hasVideo: true, pagePosterRef: { current: { ...r.ctx.pagePosterRef.current } } }) + again.ctx.pagePosterRef.current.file = again.ctx.videoFile + await again.send() + t.is(retried, 1) + t.alike(again.state.acts[0].op.media, [poster, videoD()]) +}) + +test('page music sends the #varanda-musica card; one that does not fit sends nothing', async (t) => { + const r = await pageSender({ musicDraft: draft, text: 'Ouça esta música', len: 16 }) + await r.send() + t.is(r.state.acts[0].op.preview.url, track.url + '#varanda-musica=t:abc') + const big = await pageSender({ musicDraft: draft, text: 'Ouça', len: 4, withPreview: () => { throw new Error('too long') } }) + await big.send() + t.is(big.state.errors.at(-1), 'A música não coube: encurte o texto') + t.is(big.state.acts.length, 0) +}) + +test('a page music title with a listed term is refused before any upload or signature', async (t) => { + const term = require('@varanda/rpc').BLOCKED_TERMS[0] + const r = await pageSender({ musicDraft: { ...draft, item: { ...track, title: term } }, text: 'Ouça', len: 4 }) + await r.send() + t.is(r.state.acts.length, 0) + t.is(r.state.uploads.length, 0) + 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) => { + t.ok(/const offlineQueue = [^\n]*asPage === null/.test(source)) + t.ok(/const pollOk = [^\n]*asPage === null/.test(source)) + 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') +}) + +test('a page video upload that goes stale sends nothing and shows no error', async (t) => { + for (const kind of ['gen', 'file']) { + let r = null + const prep = async ({ poster }) => { + if (kind === 'gen') r.ctx.genRef.current++ + else r.ctx.video.draft.state.file = { name: 'outro' } + return [photoD(), videoD()] + } + r = await pageSender({ hasMedia: true, hasVideo: true, prepPageVideo: prep }) + await r.send() + t.is(r.state.acts.length, 0, kind) + t.is(r.state.errors.filter(Boolean).length, 0, kind) + } +}) + +test('a kept video retry is never called for another page or another file', async (t) => { + for (const [asPage, sameFile] of [['outra', true], ['page', false]]) { + let retried = 0 + const r = await pageSender({ hasMedia: true, hasVideo: true, asPage }) + r.ctx.pagePosterRef.current = { page: 'page', file: sameFile ? r.ctx.videoFile : {}, poster: photoD({ start: 3 }), video: null, retry: async () => { retried++; return { descriptor: videoD() } } } + await r.send() + t.is(retried, 0) + t.alike(r.state.preps, [null], 'a fresh upload') + } +}) + +test('a resend that fails again keeps the poster; the next tap uploads only the video', async (t) => { + const poster = photoD({ start: 3 }) + let retried = 0 + const r = await pageSender({ hasMedia: true, hasVideo: true, actAs: async () => { throw new Error('recusado') } }) + r.ctx.pagePosterRef.current = { page: 'page', file: r.ctx.videoFile, poster, video: null, retry: async () => { retried++; throw Object.assign(new Error('incerto'), { uncertain: true, retry: async () => {} }) } } + await r.send() + t.is(retried, 1) + t.is(r.ctx.pagePosterRef.current.poster, poster) + t.is(r.ctx.pagePosterRef.current.retry, null, 'the retry is dropped') + await r.send() + t.is(retried, 1, 'not resent again') + t.alike(r.state.preps, [poster], 'only the video is uploaded, with the kept poster') +}) diff --git a/apps/app/test/pagePost.test.js b/apps/app/test/pagePost.test.js new file mode 100644 index 000000000..c6616b672 --- /dev/null +++ b/apps/app/test/pagePost.test.js @@ -0,0 +1,191 @@ +// A page post op and its video upload (src/pagePost.js). The upload is +// injected; nothing here touches the network. +'use strict' + +const test = require('brittle') + +const load = () => import('../src/pagePost.js') + +function clip (overrides = {}) { + return { + bytes: new Uint8Array(24), + mime: 'video/mp4', + width: 640, + height: 360, + ms: 3000, + poster: { bytes: new Uint8Array([255, 216, 255, 217]), mime: 'image/jpeg', width: 640, height: 360 }, + ...overrides + } +} + +const photoD = (over = {}) => ({ blocks: 1, bytes: 10, core: 'ab'.repeat(32), height: 1, mime: 'image/jpeg', sha256: 'cd'.repeat(32), start: 1, width: 1, ...over }) +const videoD = (over = {}) => ({ blocks: 1, bytes: 10, core: 'ef'.repeat(32), height: 360, mime: 'video/mp4', ms: 1000, sha256: '12'.repeat(32), start: 2, width: 640, ...over }) + +async function rejected (run) { + try { + await run() + } catch (err) { + return err + } + return null +} + +test('pagePostOp keeps text and only the keys that are present', async (t) => { + const { pagePostOp } = await load() + t.alike(pagePostOp({ text: 'oi' }), { text: 'oi' }) + t.alike(pagePostOp({ text: 'oi', media: null, preview: null }), { text: 'oi' }) + t.alike(pagePostOp({ text: '', media: [] }), { text: '' }) + const photos = [{ mime: 'image/jpeg' }, { mime: 'image/png' }] + t.alike(pagePostOp({ text: 'oi', media: photos }), { text: 'oi', media: photos }) + const preview = { url: 'https://exemplo.com/a', title: 'Titulo', desc: 'Uma linha', image: null } + t.alike(pagePostOp({ text: 'oi', preview }), { text: 'oi', preview }) + t.alike(pagePostOp({ text: 'oi', media: [], preview }), { text: 'oi', preview }) +}) + +test('pagePostOp refuses any media together with a preview', async (t) => { + const { pagePostOp } = await load() + const preview = { url: 'https://exemplo.com/a', title: 'T', desc: 'D', image: null } + const pair = [photoD(), videoD()] + const photos = [{ mime: 'image/jpeg' }, { mime: 'image/png' }] + for (const media of [pair, photos, [photos[0]]]) { + const err = await rejected(() => pagePostOp({ text: 'oi', media, preview })) + t.ok(err instanceof Error) + t.is(err.code, 'pedido-invalido') + t.is(err.message, 'Pedido inválido') + t.absent(err.uncertain) + } + t.alike(pagePostOp({ text: 'oi', media: pair }), { text: 'oi', media: pair }) +}) + +test('prepPageVideo uploads the poster, then the video with ms, once each', async (t) => { + const { prepPageVideo } = await load() + const { readyVideo } = await import('../src/videoCompose.js') + const file = clip() + t.ok(readyVideo(file)) + const calls = [] + const posterDescriptor = photoD() + const videoDescriptor = videoD({ ms: file.ms }) + const pair = await prepPageVideo({ + upload: async (arg) => { + calls.push(arg) + const descriptor = arg.mime === 'video/mp4' ? videoDescriptor : posterDescriptor + return { seq: calls.length, length: calls.length + 1, pushed: true, descriptor } + }, + file + }) + t.is(calls.length, 2) + t.is(calls[0].bytes, file.poster.bytes) + t.is(calls[0].mime, 'image/jpeg') + t.is(calls[0].width, 640) + t.is(calls[0].height, 360) + t.absent(calls[0].ms) + t.is(Object.keys(calls[0]).length, 4) + t.is(calls[1].bytes, file.bytes) + t.is(calls[1].mime, 'video/mp4') + t.is(calls[1].width, 640) + t.is(calls[1].height, 360) + t.is(calls[1].ms, 3000) + t.is(Object.keys(calls[1]).length, 5) + t.is(pair[0], posterDescriptor) + t.is(pair[1], videoDescriptor) +}) + +test('prepPageVideo uploads nothing when the file is not a ready video', async (t) => { + const { prepPageVideo } = await load() + let calls = 0 + const upload = () => { calls++; return { descriptor: {} } } + const badPoster = { mime: 'image/png', bytes: new Uint8Array([1]), width: 1, height: 1 } + for (const file of [null, clip({ mime: 'image/jpeg' }), clip({ ms: 0 }), clip({ poster: badPoster })]) { + const err = await rejected(() => prepPageVideo({ upload, file })) + t.is(err.code, 'pedido-invalido') + t.absent(err.uncertain) + } + const err = await rejected(() => prepPageVideo({ upload: null, file: clip() })) + t.is(err.code, 'pedido-invalido') + t.is(calls, 0) +}) + +test('a missing descriptor is uncertain and stops the upload, with no retry', async (t) => { + const { prepPageVideo } = await load() + const file = clip() + let calls = 0 + let retried = false + const fail = Object.assign(new Error('sem resposta'), { uncertain: true, retry () { retried = true } }) + const posterOnly = await rejected(() => prepPageVideo({ + upload: async () => { + calls++ + return { seq: 1, length: 2, pushed: true } + }, + file + })) + t.is(calls, 1, 'the video is not uploaded without a poster descriptor') + t.is(posterOnly.uncertain, true) + t.is(posterOnly.message, 'Resposta inválida ao enviar a capa do vídeo.') + + calls = 0 + const videoMissing = await rejected(() => prepPageVideo({ + upload: async (arg) => { + calls++ + if (arg.mime === 'video/mp4') return { seq: 2, length: 3, pushed: true, descriptor: null } + return { seq: 1, length: 2, pushed: true, descriptor: photoD() } + }, + file + })) + t.is(calls, 2) + t.is(videoMissing.uncertain, true) + t.is(videoMissing.message, 'Resposta inválida ao enviar o vídeo.') + + calls = 0 + const thrown = await rejected(() => prepPageVideo({ + upload: async (arg) => { + calls++ + if (arg.mime === 'video/mp4') throw fail + return { descriptor: photoD() } + }, + file + })) + t.is(thrown, fail) + t.is(calls, 2) + t.is(retried, false, 'prepPageVideo does not retry') +}) + +test('a failed video upload carries the poster descriptor and a retry skips the poster', async (t) => { + const { prepPageVideo } = await load() + const file = clip() + const poster = photoD() + const video = videoD({ ms: file.ms }) + let calls = [] + const fail = Object.assign(new Error('sem resposta'), { uncertain: true }) + const err = await rejected(() => prepPageVideo({ + upload: async (arg) => { + calls.push(arg.mime) + if (arg.mime === 'video/mp4') throw fail + return { descriptor: poster } + }, + file + })) + t.is(err, fail) + t.alike(err.poster, poster) + t.alike(calls, ['image/jpeg', 'video/mp4']) + calls = [] + const pair = await prepPageVideo({ + upload: async (arg) => { calls.push(arg.mime); return { descriptor: video } }, + file, + poster: err.poster + }) + t.alike(calls, ['video/mp4'], 'the poster is not uploaded again') + t.alike(pair, [poster, video]) +}) + +test('a malformed descriptor is uncertain', async (t) => { + const { prepPageVideo } = await load() + const file = clip() + const png = await rejected(() => prepPageVideo({ upload: async () => ({ descriptor: photoD({ mime: 'image/png' }) }), file })) + t.is(png.uncertain, true) + const notVideo = await rejected(() => prepPageVideo({ + upload: async () => ({ descriptor: photoD() }), + file + })) + t.is(notVideo.uncertain, true) + t.is(notVideo.message, 'Resposta inválida ao enviar o vídeo.') +}) diff --git a/apps/app/test/pages.test.js b/apps/app/test/pages.test.js index e33a198a5..020b112d5 100644 --- a/apps/app/test/pages.test.js +++ b/apps/app/test/pages.test.js @@ -107,7 +107,7 @@ test('pageError maps tokens to pt-BR and everything else to unavailable', async t.is(pageError('expirado').message, 'Convite ou oferta expirada') t.is(pageError('pausada').message, 'Página pausada; fale com a associação') t.is(pageError('encerrada').message, 'Esta página foi encerrada') - t.is(pageError('midia-invalida').message, 'Foto não aceita') + t.is(pageError('midia-invalida').message, 'Foto ou vídeo não aceito') t.is(pageError('limite').message, 'Limite atingido') t.is(pageError('termos-pendentes').message, 'Aceite os Termos para continuar') t.is(pageError('termo-recusado').code, 'termo-recusado', 'the service word check') @@ -180,6 +180,110 @@ test('post, reply and quote carry 1..10 media descriptors, never more', async (t } }) +function photoDescriptor (over = {}) { + return { + blocks: 1, + bytes: 10, + core: 'ab'.repeat(32), + height: 1, + mime: 'image/jpeg', + sha256: 'cd'.repeat(32), + start: 1, + width: 1, + ...over + } +} + +function videoDescriptor (over = {}) { + return { + blocks: 1, + bytes: 10, + core: 'ef'.repeat(32), + height: 360, + mime: 'video/mp4', + ms: 1000, + sha256: '12'.repeat(32), + start: 2, + width: 640, + ...over + } +} + +test('post, reply and quote accept a poster and video pair, and a link preview', async (t) => { + const { actAs } = await load() + const { validDescriptor, validVideoDescriptor } = await import('../src/media/fetch.js') + const poster = photoDescriptor() + const video = videoDescriptor() + t.ok(validDescriptor(poster)) + t.ok(validVideoDescriptor(video)) + const calls = stub(t, (n, url) => url.endsWith('/start') ? json(200, { nonce: NONCE }) : json(200, { seq: 1, length: 2, pushed: true })) + const preview = { url: 'https://exemplo.com/a', title: 'Padaria', desc: 'Abre cedo', image: poster } + for (const action of ['post', 'reply', 'quote']) { + const before = calls.length + await actAs(fakeNode(), { member: M, action, page: P, op: { text: 'x', media: [poster, video] } }) + t.alike(body(calls[before + 1]).op.media, [poster, video], action + ' sends the pair') + const at = calls.length + await actAs(fakeNode(), { member: M, action, page: P, op: { text: 'x', preview } }) + t.alike(body(calls[at + 1]).op.preview, preview, action + ' sends the preview') + } + const loose = { sha256: 'a'.repeat(64), mime: 'image/png', width: 1, height: 1, bytes: 10 } + const bp = { url: 'https://exemplo.com/b', extra: 1 } + for (const media of [[loose, loose], [poster, video]]) { + const before = calls.length + const err = await caught(t, actAs(fakeNode(), { member: M, action: 'post', page: P, op: { text: 'x', media, preview: bp } })) + t.is(err.code, 'pedido-invalido', 'media with a preview is refused') + t.is(calls.length, before, 'nothing is sent') + } + await actAs(fakeNode(), { member: M, action: 'post', page: P, op: { text: 'x', preview: bp } }) + t.is(body(calls[calls.length - 1]).op.preview.url, 'https://exemplo.com/b') +}) + +test('a video list that is not the poster-then-video pair is refused before send', async (t) => { + const { actAs } = await load() + const poster = photoDescriptor() + const video = videoDescriptor() + const calls = stub(t, (n, url) => url.endsWith('/start') ? json(200, { nonce: NONCE }) : json(200, { seq: 1 })) + const bad = [ + [video, poster], + [poster, video, poster], + [video, video, video], + [photoDescriptor({ mime: 'image/png' }), video], + [{ mime: 'video/mp4' }, { mime: 'video/mp4' }, { mime: 'video/mp4' }] + ] + for (const media of bad) { + const before = calls.length + const err = await caught(t, actAs(fakeNode(), { member: M, action: 'post', page: P, op: { text: 'x', media } })) + t.is(err.code, 'pedido-invalido') + t.is(calls.length, before, 'nothing is sent') + } + for (const preview of [null, 'https://exemplo.com', { title: 'sem url' }, { url: 1 }, []]) { + const before = calls.length + const err = await caught(t, actAs(fakeNode(), { member: M, action: 'reply', page: P, op: { text: 'x', preview } })) + t.is(err.code, 'pedido-invalido') + t.is(calls.length, before, 'a bad preview sends nothing') + } +}) + +test('a video/mp4 upload sends the signed op whole', async (t) => { + const { pagesMedia, MAX_MEDIA_BYTES: cap } = await load() + const calls = stub(t, json(200, { descriptor: { mime: 'video/mp4' } })) + const bytes = new Uint8Array([1, 2, 3, 4]) + const op = { sha256: 'ab'.repeat(32), mime: 'video/mp4', width: 640, height: 360, bytes: 4, ms: 1500 } + await pagesMedia({ member: M, nonce: NONCE, page: P, op, signature: SIG, bytes }) + t.alike(JSON.parse(calls[0].init.headers['x-varanda-page-op']), op, 'ms is inside the op') + await pagesMedia({ member: M, nonce: NONCE, page: P, op: { ...op, ms: undefined }, signature: SIG, bytes, ms: 99 }) + t.absent(JSON.parse(calls[1].init.headers['x-varanda-page-op']).ms, 'a top-level ms is not copied into the op') + const image = { sha256: 'cd'.repeat(32), mime: 'image/jpeg', width: 1, height: 1, bytes: 4 } + await pagesMedia({ member: M, nonce: NONCE, page: P, op: image, signature: SIG, bytes }) + const exact = new Uint8Array(cap) + await pagesMedia({ member: M, nonce: NONCE, page: P, op: { ...op, bytes: exact.byteLength }, signature: SIG, bytes: exact }) + t.is(calls.length, 4) + const over = new Uint8Array(cap + 1) + const err = await caught(t, pagesMedia({ member: M, nonce: NONCE, page: P, op: { ...op, bytes: over.byteLength }, signature: SIG, bytes: over })) + t.is(err.code, 'midia-invalida') + t.is(calls.length, 4, 'over the cap sends nothing') +}) + test('listing actions reach the signer and post to their own route', async (t) => { const { actAs } = await load() const place = { uf: 'SP', city: 'Campinas', bairro: null } @@ -479,7 +583,7 @@ test('a refusal token maps to its pt-BR text and is never uncertain', async (t) [409, 'nome-em-uso', 'Esse @nome já está em uso'], [403, 'pausada', 'Página pausada; fale com a associação'], [403, 'encerrada', 'Esta página foi encerrada'], - [400, 'midia-invalida', 'Foto não aceita'], + [400, 'midia-invalida', 'Foto ou vídeo não aceito'], [403, 'termos-pendentes', 'Aceite os Termos para continuar'], [503, 'indisponivel', 'Serviço indisponível'] ]) { diff --git a/apps/app/test/pollDraftGuard.test.js b/apps/app/test/pollDraftGuard.test.js index 394de19e5..6ca67e325 100644 --- a/apps/app/test/pollDraftGuard.test.js +++ b/apps/app/test/pollDraftGuard.test.js @@ -22,7 +22,7 @@ test('a poll draft never falls through to a plain post or the outbox', (t) => { test('a poll draft turns off the link card and the music button', (t) => { t.ok(/useLinkDraft\(\{ text, enabled: [^\n]*pollDraft === null/.test(src), 'no link card draft while polling') - t.ok(src.includes('musicAvailable === true && asPage === null && pollDraft === null'), 'music button hidden while polling') + t.ok(src.includes('musicAvailable === true && pollDraft === null'), 'music button hidden while polling') t.ok(src.includes('refusalOf(text, ...(pollDraft !== null ? pollDraft.options : []), ...(eventDraft !== null ? eventEditorTexts(eventDraft) : []))'), 'options are word-checked whenever a draft exists') }) diff --git a/apps/app/test/shareShell.test.js b/apps/app/test/shareShell.test.js index a2422ffc3..977c3d32f 100644 --- a/apps/app/test/shareShell.test.js +++ b/apps/app/test/shareShell.test.js @@ -33,7 +33,7 @@ test('Publicar claims a share before reading its files and lets go only while mo test('Publicar builds no preview for a shared link until the person asks or edits', (t) => { const src = read('src/screens/Publicar.js') t.ok(src.includes('const shareLinkHeld = linkHeld(linkHold, text)'), 'the hold is read from the pure helper') - t.ok(/useLinkDraft\(\{ text, enabled: open === true && asPage === null && !shareLinkHeld[ ,]/.test(src), 'a held link never builds') + t.ok(/useLinkDraft\(\{ text, enabled: open === true && !shareLinkHeld[ ,]/.test(src), 'a held link never builds') t.ok(src.includes('setLinkHold((hold) => sharedLinkHold(current, merged.text, hold))'), 'applying a share sets the hold, keeping one still in place') t.ok(/if \(linkHold !== null && linkHold !== text\) setLinkHold\(null\)/.test(src), 'an edit releases it') t.ok(/onPress=\{\(\) => setLinkHold\(null\)\}[\s\S]{0,200}Mostrar prévia do link/.test(src), 'the tap releases it') diff --git a/apps/app/test/videoCompose.test.js b/apps/app/test/videoCompose.test.js index 33924399e..84160f4fa 100644 --- a/apps/app/test/videoCompose.test.js +++ b/apps/app/test/videoCompose.test.js @@ -252,11 +252,12 @@ async function postHarness ({ request = async () => ({ seq: 1 }), upload, photo } } -test('video capability is explicit, online, personal, and needs both functions', async (t) => { +test('video capability is explicit, online, and needs both functions', async (t) => { const { canComposeVideo } = await load() const args = { node: { online: true, media: { video: true } }, pickVideo () {}, prepareVideo () {} } t.ok(canComposeVideo(args)) - t.absent(canComposeVideo({ ...args, asPage: 'page' })) + t.ok(canComposeVideo({ ...args, asPage: 'page' }), 'a page can compose video') + t.ok(canComposeVideo({ ...args, asPage: null })) t.absent(canComposeVideo({ ...args, node: { ...args.node, online: false } })) t.absent(canComposeVideo({ ...args, node: { media: {} } })) t.absent(canComposeVideo({ ...args, pickVideo: null })) diff --git a/apps/cli/lib/account/pages-routes.js b/apps/cli/lib/account/pages-routes.js index a454ca3bc..c56278b98 100644 --- a/apps/cli/lib/account/pages-routes.js +++ b/apps/cli/lib/account/pages-routes.js @@ -33,8 +33,11 @@ // bundle of a legacy page's old Conversas and drop it once imported. // dm-list and dm-thread serve the old rows only while the service still // holds them. -// - media and avatar take the raw image as the body and the statement in -// x-varanda-page-* headers. +// - media and avatar take the raw bytes as the body and the statement in +// x-varanda-page-* headers. media is a still image or, with its `ms`, a +// 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. // - 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 @@ -81,16 +84,17 @@ const { isUsername } = require('@varanda/core/lib/account-link') const { writeJsonAtomic } = require('@varanda/core/lib/store') const { refuseSymlinkDir } = require('@varanda/core/lib/cert') const { issuerSignLink, verifyClose, verifyMoved, pageLifecycle } = require('@varanda/core/lib/page-lifecycle') -const { applyDeletes } = require('@varanda/core/lib/deletion') +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 } = require('@varanda/rpc') +const { feira, cardUrlHost } = require('@varanda/rpc') 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, - parseRef, validDescriptor, isCanonicalIso, PAGE_KEYS, MEDIA_BLOCK_BYTES, MAX_MEDIA_ITEM_BLOCKS, MEDIA_MIMES, MAX_AVATAR_BYTES, AVATAR_MIMES, MAX_MEDIA_PER_POST + 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 } = require('@varanda/core/lib/records') const PREFIX = '/account/pages/' @@ -943,24 +947,69 @@ function createPagesRoutes ({ // ---- posts and engagement ------------------------------------------------ - function mediaOf (page, media, max = MAX_MEDIA_PER_POST) { + // The page's own stored items for these descriptors, or 'midia-invalida'. + // Photos, or, for a post (`video`), exactly the pair [JPEG poster, video] + // as a person's post carries it (records.js validPostMedia). Every key + // must equal the stored row's, a video's `ms` included, and a row only + // answers a descriptor of its own kind (a still row has no `ms`). + function mediaOf (page, media, max = MAX_MEDIA_PER_POST, { video = false } = {}) { if (media === undefined) return undefined if (!Array.isArray(media) || media.length < 1 || media.length > max) throw refuse('midia-invalida') + const withVideo = video && media.some((d) => isPlainObject(d) && d.mime === VIDEO_MIME) + if (withVideo ? !validPostMedia(media) : !media.every((d) => isPlainObject(d) && validDescriptor(d))) throw refuse('midia-invalida') let table try { table = writer.items(page) } catch (err) { throw tokenOf(err) } - const same = (a, b) => ['core', 'start', 'blocks', 'sha256', 'mime', 'bytes', 'width', 'height'].every((k) => a[k] === b[k]) return media.map((d) => { - if (!isPlainObject(d) || !validDescriptor(d)) throw refuse('midia-invalida') + const keys = d.mime === VIDEO_MIME ? VIDEO_DESCRIPTOR_KEYS : DESCRIPTOR_KEYS const row = table.find((it) => it.core === d.core && it.start === d.start && it.blocks === d.blocks && it.sha256 === d.sha256) - if (row === undefined || !same(row, d)) throw refuse('midia-invalida') + if (row === undefined || Object.keys(row).length !== keys.length || !keys.every((k) => row[k] === d[k])) throw refuse('midia-invalida') return row }) } + // A post's link card (docs/protocol.md, "Link cards"), the music card + // included (a link card whose URL ends in #varanda-musica). The app sends + // { url, title?, desc?, image? }; a `host` given must be the URL's. The + // thumbnail must be one of the page's own items and pass the check a + // person's post preview passes (a JPEG of at most MAX_CARD_IMAGE_BYTES). + // The URL and texts go through the blocklist like the post text. -> the card, or + // undefined for none. + function previewOf (page, preview) { + if (preview === undefined || preview === null) return undefined + if (!exactKeys(preview, ['url'], ['host', 'title', 'desc', 'image'])) throw refuse('pedido-invalido') + const host = cardUrlHost(preview.url) + if (host === null || (preview.host !== undefined && preview.host !== host)) throw refuse('pedido-invalido') + const text = (v) => v === undefined || v === null ? '' : v + let image = null + if (preview.image !== undefined && preview.image !== null) { + if (!validPreviewImage(preview.image)) throw refuse('midia-invalida') + image = mediaOf(page, [preview.image], 1)[0] + } + const card = { url: preview.url, host, title: text(preview.title), desc: text(preview.desc), image } + if (!validPreview(card)) throw refuse('pedido-invalido') + termFree(card.url, card.title, card.desc) + return card + } + + // A post, reply or quote op's media and preview: never both, as a + // person's post (records.js postRecord matches no key set with the two). + function postParts (page, op) { + const hasPreview = op.preview !== undefined && op.preview !== null + if (op.media !== undefined && hasPreview) throw refuse('pedido-invalido') + return { media: mediaOf(page, op.media, MAX_MEDIA_PER_POST, { video: true }), preview: previewOf(page, op.preview) } + } + + // The media ranges a tombstone of this record frees: everything it shows + // (deletion.js shownMedia), a post's link card thumbnail included. + function rangesOf (record) { + const items = shownMedia(record).filter(isPlainObject) + return items.length > 0 ? items.map((d) => ({ core: d.core, start: d.start, blocks: d.blocks })) : undefined + } + function target (ref) { const t = parseRef(ref) if (t === null) throw refuse('pedido-invalido') @@ -976,19 +1025,19 @@ function createPagesRoutes ({ async function recordsFor (action, page, op) { try { if (action === 'post') { - if (!exactKeys(op, ['text'], ['media'])) throw refuse('pedido-invalido') + if (!exactKeys(op, ['text'], ['media', 'preview'])) throw refuse('pedido-invalido') termFree(op.text) - return [postRecord({ text: op.text, media: mediaOf(page, op.media) })] + return [postRecord({ text: op.text, ...postParts(page, op) })] } if (action === 'reply') { - if (!exactKeys(op, ['to', 'text'], ['media'])) throw refuse('pedido-invalido') + if (!exactKeys(op, ['to', 'text'], ['media', 'preview'])) throw refuse('pedido-invalido') termFree(op.text) - return [postRecord({ text: op.text, replyTo: target(op.to), media: mediaOf(page, op.media) })] + return [postRecord({ text: op.text, replyTo: target(op.to), ...postParts(page, op) })] } if (action === 'quote') { - if (!exactKeys(op, ['to', 'text'], ['media'])) throw refuse('pedido-invalido') + if (!exactKeys(op, ['to', 'text'], ['media', 'preview'])) throw refuse('pedido-invalido') termFree(op.text) - return [postRecord({ text: op.text, quote: target(op.to), media: mediaOf(page, op.media) })] + return [postRecord({ text: op.text, quote: target(op.to), ...postParts(page, op) })] } if (action === 'like' || action === 'repost') { if (!exactKeys(op, ['to', 'on']) || typeof op.on !== 'boolean') throw refuse('pedido-invalido') @@ -1009,8 +1058,7 @@ function createPagesRoutes ({ // Never a tombstone over a page record: a delete must not undo a // roster, an accept or an offer. if (!e || !isPlainObject(e.record) || !['post', 'like', 'repost'].includes(e.record.type)) throw refuse('pedido-invalido') - const media = Array.isArray(e.record.media) ? e.record.media.map((d) => ({ core: d.core, start: d.start, blocks: d.blocks })) : undefined - return deleteRecords({ seq: t.seq, media }) + return deleteRecords({ seq: t.seq, media: rangesOf(e.record) }) } if (action === 'listing') { if (!exactKeys(op, ['kind', 'title', 'text', 'price', 'unit', 'cat', 'place'], ['media'])) throw refuse('pedido-invalido') @@ -1662,9 +1710,7 @@ function createPagesRoutes ({ if (!e || e.deleted || !Number.isSafeInteger(e.seq) || e.seq < 1) continue const r = e.record if (!isPlainObject(r) || !CLOSE_DELETES.includes(r.type)) continue - const items = Array.isArray(r.media) ? r.media : isPlainObject(r.avatar) ? [r.avatar] : [] - const media = items.length > 0 ? items.map((d) => ({ core: d.core, start: d.start, blocks: d.blocks })) : undefined - out.push(...deleteRecords({ seq: e.seq, media })) + out.push(...deleteRecords({ seq: e.seq, media: rangesOf(r) })) } return out } @@ -2036,13 +2082,20 @@ function createPagesRoutes ({ const body = { member: header(req, 'member'), nonce: header(req, 'nonce'), page: header(req, 'page'), signature: header(req, 'signature'), op } const proof = await statement(body, action, false) const keysOk = action === 'media' - ? exactKeys(proof.op, ['sha256', 'mime', 'width', 'height', 'bytes']) + ? exactKeys(proof.op, ['sha256', 'mime', 'width', 'height', 'bytes'], ['ms']) : exactKeys(proof.op, ['sha256', 'mime', 'bytes', 'name', 'bio']) if (!keysOk) throw refuse('pedido-invalido') - const mimes = action === 'media' ? MEDIA_MIMES : AVATAR_MIMES + const mimes = action === 'media' ? [...MEDIA_MIMES, VIDEO_MIME] : AVATAR_MIMES const max = action === 'media' ? MAX_MEDIA_BODY : MAX_AVATAR_BYTES const { sha256, mime, bytes } = proof.op if (!mimes.includes(mime) || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > max) throw refuse('midia-invalida') + // A short video (the second item of a post's [poster, video] pair) and + // only a video carries its duration; the writer checks the container. + if (action === 'media') { + const ms = proof.op.ms + const video = mime === VIDEO_MIME + if (video ? !(Number.isSafeInteger(ms) && ms >= 1 && ms <= MAX_VIDEO_MS) : ms !== undefined) throw refuse('midia-invalida') + } const row = writableRow(proof.page) need(row, proof.member, 'admin') const raw = await readRaw(req, max) @@ -2060,7 +2113,9 @@ function createPagesRoutes ({ if (!caps.media(page)) throw refuse('limite') let descriptor try { - descriptor = await writer.mediaItem(page, { bytes: raw, mime: op.mime, width: op.width, height: op.height, sha256: op.sha256 }, { member, nonce }) + const item = { bytes: raw, mime: op.mime, width: op.width, height: op.height, sha256: op.sha256 } + if (op.ms !== undefined) item.ms = op.ms + descriptor = await writer.mediaItem(page, item, { member, nonce }) } catch (err) { if (err && typeof err.code === 'string' && has(WRITER_TOKENS, err.code)) throw tokenOf(err) throw new Uncertain() diff --git a/apps/cli/lib/account/pages-writer.js b/apps/cli/lib/account/pages-writer.js index 729e63c86..a6c8e8fb0 100644 --- a/apps/cli/lib/account/pages-writer.js +++ b/apps/cli/lib/account/pages-writer.js @@ -29,7 +29,8 @@ // key, or a crash between the append and the state write): the page is // paused for good and nothing more is appended ('pausada'). Only // mediaItem() and setFollow() write `media-core` and `follow` records, and a -// post, profile or listing may only point at items of the page's own item table. +// post (photos, a [poster, video] pair or a link card thumbnail), profile or +// listing may only point at items of the page's own item table. // // The link: one WebSocket to the loopback seeder (/seeder), wrapped as a // NoiseSecretStream initiator with the persistent pair, the admission @@ -73,9 +74,9 @@ const { refuseSymlinkDir, certForKey, seederCertForKey, isPlainObject } = requir const { attachAdmission, MAX_INVENTORY } = require('@varanda/core/lib/admission') const { generateNoiseKeyPair } = require('@varanda/core/lib/net') const { - MEDIA_BLOCK_BYTES, MAX_MEDIA_BLOCKS, MAX_MEDIA_BYTES, MAX_MEDIA_ITEM_BLOCKS, MEDIA_MIMES, + MEDIA_BLOCK_BYTES, MAX_MEDIA_BLOCKS, MAX_MEDIA_BYTES, MAX_MEDIA_ITEM_BLOCKS, MEDIA_MIMES, VIDEO_MIME, MAX_VIDEO_MS, AVATAR_SIDE, AVATAR_MIMES, MAX_AVATAR_BLOCKS, - memberCertRecord, mediaCoreRecord, followRecord, validDescriptor, validAvatar, validRecordCopy, validateRecord, isHex64 + memberCertRecord, mediaCoreRecord, followRecord, validDescriptor, validVideoDescriptor, validAvatar, validRecordCopy, validateRecord, isHex64 } = require('@varanda/core/lib/records') const { mediaHeader, latestMediaCores } = require('@varanda/core/lib/media') const { deletedSeqs, deletedRanges, clearDeleted: clearDeletedSeqs, clearRanges, overlaps } = require('@varanda/core/lib/deletion') @@ -83,7 +84,7 @@ const { engagementState } = require('@varanda/core/lib/engagement') const { stillImageSize } = require('@varanda/core/lib/still-image') const { MAX_PAGE_FOLLOWS } = require('@varanda/core/lib/page') const { pageLifecycle, verifyClose, verifyMoved } = require('@varanda/core/lib/page-lifecycle') -const { feira } = require('@varanda/rpc') +const { feira, videoBounds, stripVideoMetadata, VIDEO_MS_TOLERANCE } = require('@varanda/rpc') // Resolved from @varanda/core, as apps/cli/lib/seed-ws.js does: the // secret-stream the seeder itself speaks, with no dependency of our own. @@ -159,9 +160,10 @@ function readFileNoFollow (file) { } } +// A video item also has its duration (`ms`, absent on a still image). function sameItem (a, b) { return a.core === b.core && a.start === b.start && a.blocks === b.blocks && a.sha256 === b.sha256 && - a.mime === b.mime && a.bytes === b.bytes && a.width === b.width && a.height === b.height + a.mime === b.mime && a.bytes === b.bytes && a.width === b.width && a.height === b.height && a.ms === b.ms } // A plain JSON copy taken before any await, so a caller changing its object @@ -199,8 +201,26 @@ function closeBatches (records) { return batches } +// A still image, or a short video (only ever the second item of a post's +// [poster, video] pair): a page that stored a video must load it again. function validItem (it) { - return isPlainObject(it) && validDescriptor(it) + return isPlainObject(it) && (validDescriptor(it) || validVideoDescriptor(it)) +} + +// -> the container's duration of a short video the page may store, or +// null. The bytes must already be what every reader accepts (no udta, meta +// or uuid) and must come back unchanged from stripVideoMetadata: the +// service never rewrites what a member uploaded, so the stored copy is the +// one whose sha256 the member signed. The sides must be the container's and +// the given ms within VIDEO_MS_TOLERANCE of its samples' duration, which +// is what gets stored. Synchronous, on a private copy. +function videoMs (bytes, width, height, ms) { + if (!Number.isSafeInteger(ms) || ms < 1 || ms > MAX_VIDEO_MS) return null + const bounds = videoBounds(bytes, { maxMs: MAX_VIDEO_MS }) + if (bounds === null || bounds.width !== width || bounds.height !== height || Math.abs(ms - bounds.ms) > VIDEO_MS_TOLERANCE) return null + const stripped = stripVideoMetadata(bytes) + if (stripped === null || !b4a.equals(stripped, bytes)) return null + return bounds.ms } // -> { member, nonce } or null; a malformed one is a refusal. @@ -766,6 +786,7 @@ function createPagesWriter ({ dir, keys, association, seederWs = null, log = noo pointed.push(...r.media) } if (r.avatar !== undefined && r.avatar !== null) pointed.push(r.avatar) + if (isPlainObject(r.preview) && r.preview.image !== undefined && r.preview.image !== null) pointed.push(r.preview.image) for (const d of pointed) { if (!isPlainObject(d) || !p.items.some((it) => sameItem(it, d))) throw fail('midia-invalida') } @@ -859,13 +880,20 @@ function createPagesWriter ({ dir, keys, association, seederWs = null, log = noo // ---- media ---------------------------------------------------------- - async function mediaItem (key, { bytes: input, mime, width, height, sha256 } = {}, opts) { + // `ms` only for a video/mp4 (videoMs), never for a still image. + async function mediaItem (key, { bytes: input, mime, width, height, sha256, ms } = {}, opts) { const idem = idempotency(opts) if (!(input instanceof Uint8Array) || input.byteLength < 1 || input.byteLength > MAX_MEDIA_ITEM_BLOCKS * MEDIA_BLOCK_BYTES) throw fail('midia-invalida') const bytes = b4a.from(input) if (typeof sha256 !== 'string' || !HEX64_RE.test(sha256) || sha256Hex(bytes) !== sha256) throw fail('midia-invalida') - if (typeof mime !== 'string' || !MEDIA_MIMES.includes(mime)) throw fail('midia-invalida') - if (mime === 'image/jpeg' || mime === 'image/webp') { + const video = mime === VIDEO_MIME + if (typeof mime !== 'string' || (!video && !MEDIA_MIMES.includes(mime))) throw fail('midia-invalida') + if (!video && ms !== undefined) throw fail('midia-invalida') + let duration + if (video) { + duration = videoMs(bytes, width, height, ms) + if (duration === null) throw fail('midia-invalida') + } else if (mime === 'image/jpeg' || mime === 'image/webp') { const size = stillImageSize(bytes, mime) if (size === null || size.width !== width || size.height !== height) throw fail('midia-invalida') } else { @@ -873,8 +901,10 @@ function createPagesWriter ({ dir, keys, association, seederWs = null, log = noo if (bytes.byteLength < magic.byteLength || !b4a.equals(bytes.subarray(0, magic.byteLength), magic)) throw fail('midia-invalida') } const blocks = Math.ceil(bytes.byteLength / MEDIA_BLOCK_BYTES) - const shape = { core: '0'.repeat(64), mime, start: 1, blocks, bytes: bytes.byteLength, sha256, width, height } - if (!validDescriptor(shape)) throw fail('midia-invalida') + const valid = video ? validVideoDescriptor : validDescriptor + const withMs = (d) => video ? { ...d, ms: duration } : d + const shape = withMs({ core: '0'.repeat(64), mime, start: 1, blocks, bytes: bytes.byteLength, sha256, width, height }) + if (!valid(shape)) throw fail('midia-invalida') return withPage(key, async (p, row) => { const prior = recall(p, 'media', idem) @@ -886,8 +916,8 @@ function createPagesWriter ({ dir, keys, association, seederWs = null, log = noo const chunks = [] for (let i = 0; i < blocks; i++) chunks.push(b4a.from(bytes.subarray(i * MEDIA_BLOCK_BYTES, Math.min(bytes.byteLength, (i + 1) * MEDIA_BLOCK_BYTES)))) const start = p.mediaLength - const descriptor = { core: p.mediaKey, mime, start, blocks, bytes: bytes.byteLength, sha256, width, height } - if (!validDescriptor(descriptor)) throw fail('midia-invalida') + const descriptor = withMs({ core: p.mediaKey, mime, start, blocks, bytes: bytes.byteLength, sha256, width, height }) + if (!valid(descriptor)) throw fail('midia-invalida') check() stillKeyed(p) await media.append(chunks) diff --git a/apps/cli/test/account-pages.test.js b/apps/cli/test/account-pages.test.js index 1b2e59188..3c56dd1fb 100644 --- a/apps/cli/test/account-pages.test.js +++ b/apps/cli/test/account-pages.test.js @@ -538,13 +538,19 @@ test('account pages: create, admins, transfer, follows, media, replay and the AC t.alike(videoBounds(video), { width: 640, height: 480, ms: 3000, audio: false }, 'a valid short video container') const beforeVideo = ctx.writer.info(K).length const beforeItems = ctx.writer.items(K) - for (const bytes of [video, img]) { - const refused = await s.upload(bia, K, bytes, { ...op, mime: 'video/mp4', bytes: bytes.length, sha256: sha(bytes) }) - t.is(refused.status, 400, 'an authenticated admin cannot upload video') - t.is(refused.body.error, 'midia-invalida') - } + const missingMs = await s.upload(bia, K, video, { ...op, mime: 'video/mp4', bytes: video.length, sha256: sha(video) }) + t.is(missingMs.status, 400, 'a video without ms is refused') + t.is(missingMs.body.error, 'midia-invalida', 'the refusal is midia-invalida because ms is missing') + const labeled = await s.upload(bia, K, img, { ...op, mime: 'video/mp4', bytes: img.length, sha256: sha(img), ms: 3000 }) + t.is(labeled.status, 400, 'image bytes labeled video/mp4 are refused') + t.is(labeled.body.error, 'midia-invalida') t.is(ctx.writer.info(K).length, beforeVideo, 'a refused video appends no record') t.alike(ctx.writer.items(K), beforeItems, 'a refused video stores no media item') + const withMs = await s.upload(bia, K, video, { ...op, mime: 'video/mp4', bytes: video.length, sha256: sha(video), ms: 3000 }) + t.is(withMs.status, 200, JSON.stringify(withMs.body)) + t.is(withMs.body.descriptor.mime, 'video/mp4') + t.is(withMs.body.descriptor.ms, 3000, 'a video with a valid ms is stored') + t.ok(ctx.writer.items(K).some((it) => it.sha256 === sha(video) && it.ms === 3000)) t.is((await s.upload(bia, K, img, { ...op, sha256: 'ab'.repeat(32) })).body.error, 'midia-invalida', 'the body must hash to the op') t.is((await s.upload(dani, K, img, op)).body.error, 'nao-vinculado') const foreign = { ...d, core: F } diff --git a/apps/cli/test/pages-media.test.js b/apps/cli/test/pages-media.test.js new file mode 100644 index 000000000..7a3135b29 --- /dev/null +++ b/apps/cli/test/pages-media.test.js @@ -0,0 +1,434 @@ +'use strict' + +// A hosted page's post, reply and quote with a short video ([JPEG poster, +// video/mp4]) or a link card (the music card included), as a person's post +// carries them (apps/cli/lib/account/pages-routes.js media, post, reply, +// quote, delete and close; pages-writer.js mediaItem), end to end over +// loopback with the same account service and real pages writer as +// pages-listing.test.js. + +const nodeCrypto = require('node:crypto') +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, validateRecord } = require('@varanda/core/lib/records') +const { TERMS_VERSION } = require('@varanda/core/lib/terms') +const { stripVideoMetadata, videoBounds, 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 { MAX_MEDIA_BODY } = require('../lib/account/pages-routes') + +const ORIGIN = 'https://varanda.test' +const PAGE_KEYS = 'cd'.repeat(32) +const MUSIC_URL = 'https://open.spotify.com/track/4uLU6hMCjMI75M1A2tKUQC#varanda-musica' + +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 be16 (n) { + return [(n >> 8) & 0xff, n & 0xff] +} + +function jpeg (width, height, size, fill = 0x5a) { + const head = b4a.from([0xff, 0xd8, 0xff, 0xc0, ...be16(17), 8, ...be16(height), ...be16(width), 3, 1, 0x11, 0, 2, 0x11, 1, 3, 0x11, 1]) + const out = b4a.alloc(size, fill) + head.copy(out, 0) + out[size - 2] = 0xff + out[size - 1] = 0xd9 + return out +} + +// A synthetic short video (packages/web-member/test/session-media.test.js +// builder): ftyp, moov (mvhd, one H.264 avc1 track), mdat. Raw, it carries +// the encoder's compressorname (and a camera place tag with udta), which +// stripVideoMetadata clears; the app uploads the stripped copy. +function mp4 ({ ms = 3000, width = 640, height = 360, udta = false } = {}) { + const be32 = (v) => [(v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff] + const ascii = (str) => Array.from(str, (c) => c.charCodeAt(0)) + const zeros = (n) => new Array(n).fill(0) + const box = (kind, ...parts) => { const body = parts.flat(); return [...be32(8 + body.length), ...ascii(kind), ...body] } + const full = (kind, ...parts) => box(kind, [0, 0, 0, 0], ...parts) + const n = 30 + const q = Math.floor(ms / n) + const runs = [[n - 1, q], [1, ms - (n - 1) * q]] + const one = 0x10000 + const avcC = box('avcC', [1, 100, 0, 40, 0xff, 0xe1], be16(6), [0x67, 100, 0, 40, 0xac, 0xd9], [1], be16(4), [0x68, 0xeb, 0xe3, 0xcb]) + const entry = box('avc1', zeros(6), be16(1), zeros(16), be16(width), be16(height), be32(0x480000), be32(0x480000), be32(0), be16(1), + [4, ...ascii('x264'), ...zeros(27)], be16(0x18), be16(0xffff), avcC, box('pasp', be32(1), be32(1))) + const moovOf = (offset) => box('moov', + full('mvhd', be32(0), be32(0), be32(1000), be32(ms), zeros(16), ...[one, 0, 0, 0, one, 0, 0, 0, 0x40000000].map(be32), zeros(28)), + box('trak', + box('tkhd', [0, 0, 0, 7], be32(0), be32(0), be32(1), be32(0), be32(ms), zeros(16), + ...[one, 0, 0, 0, one, 0, 0, 0, 0x40000000].map(be32), be32(width * one), be32(height * one)), + box('mdia', + full('mdhd', be32(0), be32(0), be32(1000), be32(ms), [0x55, 0xc4, 0, 0]), + full('hdlr', be32(0), ascii('vide'), zeros(12), [0]), + box('minf', box('vmhd', [0, 0, 0, 1], zeros(8)), box('dinf', full('dref', be32(1), box('url ', [0, 0, 0, 1]))), + box('stbl', full('stsd', be32(1), entry), full('stts', be32(runs.length), ...runs.map(([c, d]) => [...be32(c), ...be32(d)])), + full('stsc', be32(1), be32(1), be32(n), be32(1)), full('stsz', be32(0), be32(n), ...new Array(n).fill(be32(10))), + full('stco', be32(1), be32(offset)))))), + ...(udta ? [box('udta', box('©xyz', be16(18), be16(0x15c7), ascii('+12.3456-045.6789/')))] : [])) + const head = box('ftyp', ascii('isom'), be32(0x200), ascii('isom'), ascii('avc1')) + const offset = head.length + moovOf(0).length + 8 + return b4a.from([...head, ...moovOf(offset), ...box('mdat', new Array(n * 10).fill(1))]) +} + +function clean (opts) { + return b4a.from(stripVideoMetadata(mp4(opts))) +} + +function sha (bytes) { + return nodeCrypto.createHash('sha256').update(bytes).digest('hex') +} + +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 restart () { + await listener.close() + await ctx.writer.close() + 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 upload (m, page, bytes, op) { + const { nonce } = await start(m, 'media') + return api('POST', '/account/pages/media', bytes, { + 'x-varanda-page-member': m.hex, + 'x-varanda-page-nonce': nonce, + 'x-varanda-page-page': page, + 'x-varanda-page-signature': sign(m, 'media', nonce, page, op), + 'x-varanda-page-op': JSON.stringify(op) + }) + } + + 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, upload, close, restart } +} + +function photoOp (bytes, width, height, extra = {}) { + return { sha256: sha(bytes), mime: 'image/jpeg', width, height, bytes: bytes.length, ...extra } +} + +function videoOp (bytes, extra = {}) { + return { sha256: sha(bytes), mime: 'video/mp4', width: 640, height: 360, bytes: bytes.length, ms: 3000, ...extra } +} + +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 deletesOf (ctx, page) { + return (await ctx.writer.readEntries(page)).filter((e) => e.record && e.record.type === 'delete').map((e) => e.record) +} + +function freed (dels, seq, d) { + return dels.some((r) => r.seq === seq && Array.isArray(r.media) && r.media.some((m) => m.core === d.core && m.start === d.start && m.blocks === d.blocks)) +} + +test('page media: a video pair and a link card as a person posts them, refusals, restart, delete and close', 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, 'cineclube') + 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)) + + // Uploads: a poster, the stripped video, a thumbnail of a card. + const posterBytes = jpeg(640, 360, 20 * 1024) + const poster = await s.upload(ana, K, posterBytes, photoOp(posterBytes, 640, 360)) + t.is(poster.status, 200, JSON.stringify(poster.body)) + const P = poster.body.descriptor + const videoBytes = clean() + t.ok(videoBytes.equals(b4a.from(stripVideoMetadata(videoBytes))), 'the fixture is already stripped') + // The app's own ms is within the tolerance; the container's is stored. + const video = await s.upload(ana, K, videoBytes, videoOp(videoBytes, { ms: 3400 })) + t.is(video.status, 200, JSON.stringify(video.body)) + const V = video.body.descriptor + t.is(V.mime, 'video/mp4') + t.is(V.ms, videoBounds(videoBytes).ms, 'the stored duration is the container\'s') + t.is(V.sha256, sha(videoBytes), 'the bytes are stored as uploaded') + const thumbBytes = jpeg(320, 180, 12 * 1024, 0x33) + const thumb = await s.upload(ana, K, thumbBytes, photoOp(thumbBytes, 320, 180)) + t.is(thumb.status, 200, JSON.stringify(thumb.body)) + const T = thumb.body.descriptor + + // Upload refusals store nothing. + const items = ctx.writer.items(K).length + let length = ctx.writer.info(K).length + const raw = mp4() + t.is((await s.upload(ana, K, raw, videoOp(raw))).body.error, 'midia-invalida', 'an mp4 the strip would change (encoder name)') + const tagged = mp4({ udta: true }) + t.is((await s.upload(ana, K, tagged, videoOp(tagged))).body.error, 'midia-invalida', 'an mp4 with a place tag') + const long = mp4({ ms: 30001 }) + t.is((await s.upload(ana, K, long, videoOp(long, { ms: 30000 }))).body.error, 'midia-invalida', 'a container past 30 s') + t.is((await s.upload(ana, K, videoBytes, videoOp(videoBytes, { ms: 30001 }))).body.error, 'midia-invalida', 'ms past 30 s') + t.is((await s.upload(ana, K, videoBytes, videoOp(videoBytes, { ms: 5000 }))).body.error, 'midia-invalida', 'ms far from the container') + t.is((await s.upload(ana, K, videoBytes, videoOp(videoBytes, { width: 360, height: 640 }))).body.error, 'midia-invalida', 'sides not the container\'s') + const noMs = videoOp(videoBytes) + delete noMs.ms + t.is((await s.upload(ana, K, videoBytes, noMs)).body.error, 'midia-invalida', 'a video without ms') + t.is((await s.upload(ana, K, posterBytes, photoOp(posterBytes, 640, 360, { ms: 3000 }))).body.error, 'midia-invalida', 'ms on a photo') + t.is((await s.upload(ana, K, posterBytes, videoOp(posterBytes))).body.error, 'midia-invalida', 'a jpeg labelled video') + const huge = await s.upload(ana, K, videoBytes, videoOp(videoBytes, { bytes: MAX_MEDIA_BODY + 1 })) + t.is(huge.body.error, 'midia-invalida', 'past the item cap') + t.is((await s.upload(caio, K, videoBytes, videoOp(videoBytes))).body.error, 'sem-permissao', 'a stranger') + t.is(ctx.writer.items(K).length, items, 'no item stored') + t.is(ctx.writer.info(K).length, length, 'nothing appended') + + // A video post: the same record a person's post would be. + const vpost = await s.act(ana, 'post', K, { text: 'trailer', media: [P, V] }) + t.is(vpost.status, 200, JSON.stringify(vpost.body)) + let rec = await recordAt(ctx, K, vpost.body.seq) + t.alike(rec, postRecord({ text: 'trailer', media: [P, V], at: rec.at })) + t.is(validateRecord(rec, vpost.body.seq), null) + t.alike(rec.media[1].ms, V.ms) + const vreply = await s.act(ana, 'reply', K, { to: K + ':' + vpost.body.seq, text: '', media: [P, V] }) + t.is(vreply.status, 200, JSON.stringify(vreply.body)) + rec = await recordAt(ctx, K, vreply.body.seq) + t.alike(rec, postRecord({ text: '', replyTo: { author: K, seq: vpost.body.seq }, media: [P, V], at: rec.at })) + const vquote = await s.act(ana, 'quote', K, { to: K + ':' + vpost.body.seq, text: 'olhem', media: [P, V] }) + t.is(vquote.status, 200, JSON.stringify(vquote.body)) + rec = await recordAt(ctx, K, vquote.body.seq) + t.alike(rec, postRecord({ text: 'olhem', quote: { author: K, seq: vpost.body.seq }, media: [P, V], at: rec.at })) + + // A link card and the music card. + const card = { url: 'https://example.com/filme?id=7', title: 'Filme da semana', desc: 'Sessão às 20h', image: T } + const lpost = await s.act(ana, 'post', K, { text: 'sessão hoje', preview: card }) + t.is(lpost.status, 200, JSON.stringify(lpost.body)) + rec = await recordAt(ctx, K, lpost.body.seq) + t.alike(rec, postRecord({ text: 'sessão hoje', preview: { ...card, host: 'example.com' }, at: rec.at })) + t.is(validateRecord(rec, lpost.body.seq), null) + const music = await s.act(ana, 'quote', K, { to: K + ':' + lpost.body.seq, text: 'trilha', preview: { url: MUSIC_URL, host: 'open.spotify.com', title: 'Trilha', image: T } }) + t.is(music.status, 200, JSON.stringify(music.body)) + rec = await recordAt(ctx, K, music.body.seq) + t.alike(rec, postRecord({ text: 'trilha', quote: { author: K, seq: lpost.body.seq }, preview: { url: MUSIC_URL, host: 'open.spotify.com', title: 'Trilha', desc: '', image: T }, at: rec.at })) + const bare = await s.act(ana, 'reply', K, { to: K + ':' + lpost.body.seq, text: 'link', preview: { url: 'https://example.org/' } }) + t.is(bare.status, 200, JSON.stringify(bare.body)) + rec = await recordAt(ctx, K, bare.body.seq) + t.alike(rec.preview, { url: 'https://example.org/', host: 'example.org', title: '', desc: '', image: null }) + + // Post refusals append nothing. + length = ctx.writer.info(K).length + const otherPoster = jpeg(640, 360, 20 * 1024, 0x44) + const foreignUp = await s.upload(caio, other.page, otherPoster, photoOp(otherPoster, 640, 360)) + t.is(foreignUp.status, 200, JSON.stringify(foreignUp.body)) + const F = foreignUp.body.descriptor + const big = jpeg(640, 360, 40 * 1024, 0x22) + const bigUp = await s.upload(ana, K, big, photoOp(big, 640, 360)) + t.is(bigUp.status, 200, JSON.stringify(bigUp.body)) + const B = bigUp.body.descriptor + length = ctx.writer.info(K).length + const refusals = [ + [{ text: 'x', media: [F, V] }, 'midia-invalida', 'a poster of another page'], + [{ text: 'x', media: [P, { ...V, sha256: 'ab'.repeat(32) }] }, 'midia-invalida', 'a video the page never stored'], + [{ text: 'x', media: [P, { ...V, ms: V.ms - 1 }] }, 'midia-invalida', 'another ms'], + [{ text: 'x', media: [V, P] }, 'midia-invalida', 'the video first'], + [{ text: 'x', media: [P, V, T] }, 'midia-invalida', 'three items with a video'], + [{ text: 'x', media: [V] }, 'midia-invalida', 'a video alone'], + [{ text: 'x', media: [{ ...P, ms: 3000 }] }, 'midia-invalida', 'ms on a photo descriptor'], + [{ text: 'x', media: [P, V], preview: card }, 'pedido-invalido', 'a video and a card'], + [{ text: 'x', media: [P], preview: card }, 'pedido-invalido', 'a photo and a card'], + [{ text: 'x', preview: { ...card, image: B } }, 'midia-invalida', 'a thumbnail past 32 KiB'], + [{ text: 'x', preview: { ...card, image: V } }, 'midia-invalida', 'a video thumbnail'], + [{ text: 'x', preview: { ...card, image: { ...T, core: F.core } } }, 'midia-invalida', 'a thumbnail of another page'], + [{ text: 'x', preview: { ...card, image: F } }, 'midia-invalida', 'another page\'s thumbnail'], + [{ text: 'x', preview: { ...card, host: 'evil.example' } }, 'pedido-invalido', 'a host that is not the URL\'s'], + [{ text: 'x', preview: { ...card, url: 'http://example.com/' } }, 'pedido-invalido', 'not https'], + [{ text: 'x', preview: { ...card, extra: 1 } }, 'pedido-invalido', 'an unknown card key'], + [{ text: 'x', preview: { ...card, title: 'a'.repeat(81) } }, 'pedido-invalido', 'a title past 80'], + [{ text: 'x', preview: { ...card, title: BLOCKED_TERMS[0] } }, 'termo-recusado', 'a blocked term in the title'], + [{ text: 'x', preview: { ...card, desc: BLOCKED_TERMS[0] } }, 'termo-recusado', 'a blocked term in the desc'], + [{ text: 'x', preview: { ...card, url: 'https://example.com/' + BLOCKED_TERMS[0] } }, 'termo-recusado', 'a blocked term in the url'], + [{ text: 'x', preview: 'https://example.com/' }, 'pedido-invalido', 'a card 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) + } + t.is(ctx.writer.info(K).length, length, 'no refusal appends') + + // After a restart the writer loads the video item and the page is not + // paused: the same pair still posts. + await s.restart() + t.absent(ctx.writer.info(K).paused, 'not paused after a restart') + t.ok(ctx.writer.items(K).some((it) => it.mime === 'video/mp4' && it.ms === V.ms && it.sha256 === V.sha256), 'the video item reloads') + const again = await s.act(ana, 'post', K, { text: 'reprise', media: [P, V] }) + t.is(again.status, 200, JSON.stringify(again.body)) + + // Delete frees the poster and the video, and a card's thumbnail. + const delV = await s.act(ana, 'delete', K, { to: K + ':' + vpost.body.seq }) + t.is(delV.status, 200, JSON.stringify(delV.body)) + const delL = await s.act(ana, 'delete', K, { to: K + ':' + lpost.body.seq }) + t.is(delL.status, 200, JSON.stringify(delL.body)) + let dels = await deletesOf(ctx, K) + t.ok(freed(dels, vpost.body.seq, P), 'the poster range') + t.ok(freed(dels, vpost.body.seq, V), 'the video range') + t.ok(freed(dels, lpost.body.seq, T), 'the thumbnail range') + + // Close frees what the page still shows: a new pair and a new card. + const p2Bytes = jpeg(640, 360, 20 * 1024, 0x66) + const P2 = (await s.upload(ana, K, p2Bytes, photoOp(p2Bytes, 640, 360))).body.descriptor + const v2Bytes = clean({ ms: 4000 }) + const V2 = (await s.upload(ana, K, v2Bytes, videoOp(v2Bytes, { ms: 4000 }))).body.descriptor + const t2Bytes = jpeg(320, 180, 10 * 1024, 0x77) + const T2 = (await s.upload(ana, K, t2Bytes, photoOp(t2Bytes, 320, 180))).body.descriptor + t.ok(P2 && V2 && T2, 'uploaded') + const last = await s.act(ana, 'post', K, { text: 'última', media: [P2, V2] }) + t.is(last.status, 200, JSON.stringify(last.body)) + const lastCard = await s.act(ana, 'post', K, { text: 'último link', preview: { url: MUSIC_URL, image: T2 } }) + t.is(lastCard.status, 200, JSON.stringify(lastCard.body)) + const closed = await s.close(ana, K) + t.is(closed.status, 200, JSON.stringify(closed.body)) + dels = await deletesOf(ctx, K) + t.ok(freed(dels, last.body.seq, P2), 'close frees the poster') + t.ok(freed(dels, last.body.seq, V2), 'close frees the video') + t.ok(freed(dels, lastCard.body.seq, T2), 'close frees the card thumbnail') +}) diff --git a/apps/cli/test/pages-writer.test.js b/apps/cli/test/pages-writer.test.js index f85c15f40..60439e0fa 100644 --- a/apps/cli/test/pages-writer.test.js +++ b/apps/cli/test/pages-writer.test.js @@ -256,9 +256,9 @@ test('pages-writer: a page is created, pushed, admitted and served; media, follo t.alike(videoBounds(video), { width: 1200, height: 800, ms: 3000, audio: false }, 'a valid short video container') const beforeVideo = writer.info(page.key).length const beforeItems = writer.items(page.key) - for (const bytes of [video, big]) { - await t.exception(writer.mediaItem(page.key, { bytes, mime: 'video/mp4', width: 1200, height: 800, sha256: sha(bytes) }), /midia-invalida/, 'video MIME is refused even with image bytes') - } + // The same valid container is stored below with its ms: without one it is refused. + await t.exception(writer.mediaItem(page.key, { bytes: video, mime: 'video/mp4', width: 1200, height: 800, sha256: sha(video) }), /midia-invalida/, 'a valid video without ms is refused') + await t.exception(writer.mediaItem(page.key, { bytes: big, mime: 'video/mp4', width: 1200, height: 800, sha256: sha(big), ms: 3000 }), /midia-invalida/, 'image bytes labeled video/mp4 are refused') t.is(writer.info(page.key).length, beforeVideo, 'a refused video appends no record') t.alike(writer.items(page.key), beforeItems, 'a refused video stores no media item') const notPng = b4a.from('not a png at all') @@ -269,6 +269,12 @@ test('pages-writer: a page is created, pushed, admitted and served; media, follo const pngItem = await writer.mediaItem(page.key, { bytes: png, mime: 'image/png', width: 10, height: 20, sha256: sha(png) }) t.is(pngItem.start, 33) t.is(pngItem.mime, 'image/png') + const storedVideo = await writer.mediaItem(page.key, { bytes: video, mime: 'video/mp4', width: 1200, height: 800, sha256: sha(video), ms: 3000 }) + t.is(storedVideo.mime, 'video/mp4') + t.is(storedVideo.ms, 3000, 'a video with a valid ms is stored') + t.is(storedVideo.width, 1200) + t.is(storedVideo.height, 800) + t.ok(writer.items(page.key).some((it) => it.sha256 === storedVideo.sha256 && it.ms === 3000)) const post = await writer.append(page.key, [postRecord({ text: 'foto', media: [item] })]) t.is(post.pushed, true) diff --git a/apps/site/public/privacidade/index.html b/apps/site/public/privacidade/index.html index b21ab2608..145124cd5 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

- - + +