Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Mark posts deleted on the network, and send webhooks when they go or come back (#464)
MrBeanDevc3b93ee89299
diff --git a/.ai/rules/post-hog.md b/.ai/rules/post-hog.mdindex a4cd03ceb..d6cb53fac 100644--- a/.ai/rules/post-hog.md+++ b/.ai/rules/post-hog.md@@ -6,4 +6,4 @@ paths:# Post Hog## Serialize account publishing snapshots at the final send-Publishing activity uses SyncAccountPublishingActivity with per-account debounce and overlap protection. It must re-query the latest confirmed published post (publish_status published) when it executes and send the group update in that same job; routing the snapshot through SendEvent can reorder payloads and regress the account's last publication. The backfill command must reuse this job.+Publishing activity uses SyncAccountPublishingActivity with per-account debounce and overlap protection. It must re-query the latest post that went out (`PublishStatus::wentOut()`: published, or deleted on the network) when it executes and send the group update in that same job; routing the snapshot through SendEvent can reorder payloads and regress the account's last publication. The backfill command must reuse this job.diff --git a/.ai/rules/post.md b/.ai/rules/post.mdindex 3356a6c48..43fc81df7 100644--- a/.ai/rules/post.md+++ b/.ai/rules/post.md@@ -9,7 +9,7 @@ paths:# Post## FinalizePostPublication is the only post settler-handle() takes the Post. Every path that can finish the post's publication must call it: PublishToSocialPlatform, ReconcileGoogleBusinessPost, RecoverStuckPosts, PublishPost (also for a post without a channel) and PublishPost::failed. It settles from `posts.publish_status` (published → Published; failed/rejected → Failed); a post without a channel whose publication is not finished is a no-op unless it is Publishing, which becomes Failed (with `posts.errors.choose_channel` when it still has a destination snapshot) so it does not sit non-editable forever. Do not mark the post Published / Failed by hand outside Finalize. Finalize keeps the publish time the publisher wrote (`markAsPublished()` only fills `published_at` when it is empty).+handle() takes the Post. Every path that can finish the post's publication must call it: PublishToSocialPlatform, ReconcileGoogleBusinessPost, RecoverStuckPosts, PublishPost (also for a post without a channel) and PublishPost::failed. It settles from `posts.publish_status` (published/deleted → Published, through `PublishStatus::wentOut()`; failed/rejected → Failed); a post without a channel whose publication is not finished is a no-op unless it is Publishing, which becomes Failed (with `posts.errors.choose_channel` when it still has a destination snapshot) so it does not sit non-editable forever. Do not mark the post Published / Failed by hand outside Finalize. Finalize keeps the publish time the publisher wrote (`markAsPublished()` only fills `published_at` when it is empty).## Finalize is idempotent once the post is settledhandle() lockForUpdates the post and returns without notifying when status is already Published or Failed (Status::isSettled()). RecoverStuckPosts and ReconcileGoogleBusinessPost can both finish the post at the 24h ceiling; the second call must not send a second email. Dispatch SendNotification only after the transaction commits.diff --git a/.env.example b/.env.exampleindex 193c44291..a3aea48c6 100644--- a/.env.example+++ b/.env.example@@ -286,7 +286,7 @@ NIGHTWATCH_TOKEN=UNSPLASH_ACCESS_KEY=UNSPLASH_SECRET_KEY=-# Composer media sources (Google Drive, Google Photos, Canva). Step-by-step setup: MEDIA_INTEGRATIONS_SETUP.md+# Composer media sources (Google Drive, Google Photos, Canva).# Each source is hidden until its flag is on AND its keys are set. Nothing falls back to GOOGLE_CLIENT_ID# or GOOGLE_BUSINESS_*. Canva and Google Photos are Cloud-only in practice (Canva needs an approved public# integration; Photos needs Google verification of a sensitive scope).diff --git a/AGENTS.md b/AGENTS.mdindex 55a578511..8079aa3d5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1050,10 +1050,60 @@ an `enabled` flag or posts with several channels. Posts created together share- **Two status columns.** `posts.status` is the lifecycle (draft,pending_approval, scheduled, publishing, published, failed). `posts.publish_status`(`App\Enums\Post\PublishStatus`) is the network side (pending, publishing,- retrying, pending_review, published, failed, rejected). Publishers write+ retrying, pending_review, published, failed, rejected, deleted). Publishers write`publish_status` through the `markPublication*()` methods; only`FinalizePostPublication` moves `status` to published or failed. There is no`partially_published`.+- **Deleted on the network.** `publish_status = deleted` means the network+ deleted a post it published; `status` stays published. Only a deletion the+ collector confirms moves the post+ (`AnalyticsCollectionException::deletedOnNetwork()`), always from the metrics+ read it already makes. Where the network's "does not exist" answer could also+ mean lost access, an account-level read (the list its discovery reads) must+ still work (`readUnlessDeleted()`, `readsMissing()` and `stillReads()` on+ `AbstractPublicationMetricsCollector`; a read that fails only for now is+ rethrown so the job retries):+ - YouTube: its own `videos.list` read no longer returns the video.+ - Facebook, Instagram, Threads (`AbstractMetaPublicationMetricsCollector`):+ code 100 / subcode 33 for the post, and the posts edge still reads; a+ story is never checked (it expires). A Facebook Page post is checked on+ its insights edge (`readPost()`): Graph answers its own node with #10,+ which also means a missing permission.+ - X: the documented `resource-not-found` problem naming the post, in the+ `errors` of the lookup's 200 (single and batch alike, checked against a+ real deleted post); no extra request (X bills each one).+ - Bluesky: `getPosts` leaves it out, its repository answers+ `RecordNotFound`, and `listRecords` still reads.+ - Mastodon: 404 or 410 on an owner read only (without `read`, 404 also+ means private), and the account's statuses still read.+ - Pinterest: 404 or 410 on the Pin analytics and on the Pin, and the Pins+ list still reads.++ Any other 404 or 410 only marks the analytics publication. TikTok cannot tell+ deleted from private; LinkedIn, Google Business, Telegram and Discord have no+ read after publishing (#481).+ `CollectPublicationMetrics` marks the post (`markPublicationDeleted()`) under+ the publication's row lock, unless a sync saw the post since the second the+ read started (`last_seen_at` at or after it; a sync earlier in that second+ only delays the deletion to the next read);+ a sync that sees it again restores it (`markPublicationRestored()`, which+ does not rerun the "just published" side effects) and queues a fresh metrics+ read so a stale discovery page cannot leave it published until the next day.+ Marking it deleted sends `post.deleted_on_network`, and restoring it sends+ `post.restored`, never for a post imported from the network, which sends no+ webhook at all (`ImportExternalPosts`); both also broadcast+ `post.platform.status.updated` so an open schedule reloads, imported or not. `Post::isDeletedOnNetwork()` is the rule:+ `PostStatusRules::blocksDeletion()` lets such a post be deleted in TryPost, it+ finalizes as published, and it still counts as published for the posting+ goal, the lifecycle and PostHog (`PublishStatus::wentOut()`,+ `Post::scopeWentOut()`), while live-only reads (Instagram grid, analytics+ sync, the importer's matching, TikTok video ids) keep+ `scopePublicationPublished()`. On the post cards, the calendar chip and the details+ dialog, `isDeletedOnNetwork()` and `postPermalink()`+ (`lib/postNetwork.ts`) decide the badge and the link, and+ `getPostCardStatusConfig()` (`usePostStatus.ts`) the status shown; the repurpose+ activity list labels `publish_status` directly. Insights keep the historical+ numbers and drop the network link (`PublicationAvailability::visiblePermalink()`).- **Publication writes have their own clock.** `writePublication()` (and every`markPublication*()`) sets `publication_updated_at` and leaves `updated_at`alone, so a publish attempt never moves the post's `updated_at` (API, webhooks)@@ -1251,6 +1301,7 @@ Whenever Laravel has a helper for something, use it instead of a native PHP func- Production code: `config('trypost.platforms.linkedin.oauth_api').'/oauth/v2/accessToken'`, never the literal URL.- Tests: use the same `config(...)` value in `Http::fake([...])` — `Http::fake([config('trypost.platforms.x.api').'/oauth2/token' => ...])`. Tests with hardcoded URLs drift silently when the config changes.- Path/route segments after the host (e.g. `/oauth/v2/accessToken`, `/xrpc/com.atproto.server.refreshSession`) are part of the provider's protocol spec — those stay inline next to the call. Only the host comes from config.+ - Every such URL in `config/trypost.php` goes through its `$url(...)` closure, which drops a trailing slash, so a reader appends the path to `config(...)` and never trims or casts it (`ThirdPartyUrlConfigTest`). A new URL key uses `$url('ENV_NAME', 'https://…')`, not `env()`. A server stored on an account (`SocialAccount::bluesky_service`, `mastodon_instance`) is never trimmed either: Bluesky stores the config value and Mastodon trims the instance when it connects.## Social Platform API Documentation (official sources)diff --git a/DEPLOYMENT.md b/DEPLOYMENT.mddeleted file mode 100644index 4acdc438f..000000000--- a/DEPLOYMENT.md+++ /dev/null@@ -1,161 +0,0 @@-# Deploy da fusão de `post_platforms` em `posts`--Roteiro para levar à produção a branch `feat/merge-post-platforms-into-posts`, na-ordem. Cada post passa a guardar o seu canal e o resultado da publicação na-própria linha de `posts`; a tabela `post_platforms` é copiada para `posts` e-removida no mesmo deploy.--> **Pré-requisito antes do merge:** marcar a `main` atual (o 2.0 que está no ar,-> `311767990`) com a tag e a release `v2.0.0`. Hoje a última tag é a `v1.1.0`, e-> sem a `v2.0.0` o self-hosted não tem por onde passar pelo `release:trypost-2`,-> que esta versão remove.--O roteiro do deploy do TryPost 2.0 (`release:trypost-2`) fica na tag `v2.0.0`.-Self-hosted que ainda está na `v1.1.0` **precisa passar por ela antes**: atualizar-para a `v2.0.0`, rodar `php artisan release:trypost-2 --force` e só então-atualizar para esta versão. A primeira migration desta versão para com uma-mensagem explicando isso se encontrar posts com mais de um canal.--Por ser um deploy só (sem releases intermediários), ele roda **em manutenção, com-todas as filas drenadas**: nenhum job antigo, guardando o id de um destino que-deixa de existir, pode sobrar para o código novo.-------## 1. Antes do deploy--1. **Ensaio numa cópia da produção** (banco e bucket próprios), com o código desta- branch:- ```bash- php artisan migrate --force- ```- As quatro migrations novas (`2026_10_08_2229*`) devem terminar sem erro. A- primeira resolve sozinha os restos do split do 2.0: apaga os destinos cuja- conta sumiu e os destinos desligados que nunca publicaram, transforma em rascunho os posts não- publicados sem canal, apaga (com a mídia, sem webhook) os posts publicados sem- canal (os arquivos só depois do commit, e só os que nenhuma outra mídia usa)- e resolve os `partially_published` com um destino só. Ela **para**, sem- mudar nada, se ainda houver: post com mais de um destino, destino desligado- que publicou, `partially_published` com destino em andamento ou destino de- outro workspace. A mensagem diz quantos de cada.-- Na cópia de produção de 09/10/2026 eram 45.520 destinos desligados, 478- rascunhos e 1 post com falha sem canal, e 139 posts publicados sem canal (em 4- workspaces, com 236 arquivos), apagados por decisão do Paulo.- Anote quanto tempo o `migrate` levou (estimativa: 20–60 s para ~20 mil posts).-2. **Se o ensaio parou na primeira migration**, resolva os casos na produção antes- do deploy (com o código que está no ar):- ```bash- php artisan posts:split-legacy-active- php artisan posts:audit-legacy --strict- ```- O que sobrar (alvo preso em revisão, mídia que não copiou) é tratado à mão.-3. **Script de deploy do Forge**: adicione, depois de `$RESTART_QUEUES()`,- ```bash- $FORGE_PHP artisan horizon:terminate- ```- Sem ele o Horizon reinicia os workers dentro da pasta do release antigo e- continua rodando o código antigo. Vale para todo deploy, não só este. Confira- também que `storage/` é compartilhado entre releases (`readlink releases/*/storage`).-4. **Comunicação**: avise os usuários do horário da janela (alguns minutos sem- publicar; os posts agendados para a janela saem logo depois). Avise quem usa a- API, o MCP ou webhooks sobre a mudança de contrato (seção 4) **antes** do deploy.--## 2. Deploy, na ordem--1. No release atual:- ```bash- php artisan down --retry=60 --secret=<token>- ```- Web, Horizon e scheduler param (nenhum agendamento usa `evenInMaintenanceMode`).-2. **Drene todas as filas** com o código antigo (o `--force` processa mesmo em- manutenção):- ```bash- php artisan queue:work redis --queue=social-linkedin,social-linkedin-page,social-x,social-tiktok,social-youtube,social-facebook,social-instagram,social-instagram-facebook,social-threads,social-pinterest,social-bluesky,social-mastodon,social-telegram,social-discord,social-google_business,default,posthog,broadcasts,analytics,webhooks,media-imports,media-adoption,rss-feeds --force --stop-when-empty- ```- Confira a lista de filas em `config/horizon.php`. Espere também os jobs com- atraso das filas `social-*`, `default`, `broadcasts`, `posthog` e `webhooks`- (até 10 minutos, os retries de rede indisponível) e rode o comando de novo até- o Redis não ter nada em `queues:<essas filas>:delayed` nem em- `queues:*:reserved`. Os atrasados da fila `analytics` (métricas de stories, até- 24 h) só carregam ids de publicação e podem ficar.- Os jobs que já falharam (`failed_jobs`) com o código antigo não podem ser- reexecutados depois do deploy (a classe `PostPlatform` deixa de existir):- reexecute-os antes ou descarte-os.- Confirme que não sobrou comando agendado rodando:- `ps -ef | grep "[a]rtisan" | grep -v horizon`.- E que nenhum post ficou publicando sem job (deve dar 0; o que sobrar o- `RecoverStuckPosts` falharia depois de 1 h). As consultas abaixo são de- PostgreSQL (Cloud); no MySQL troque `now() - interval '1 hour'` por- `now() - interval 1 hour`:- ```sql- select count(*) from post_platforms- where status in ('publishing', 'retrying') and retry_at is null- and updated_at > now() - interval '1 hour';- ```- E que nenhum post do Google Business está em revisão (deve dar 0; o JPEG de um- post em revisão tem o id do destino antigo no nome e ficaria órfão no bucket):- ```sql- select count(*) from post_platforms- where platform = 'google_business' and status = 'pending_review';- ```-3. Deploy pelo Forge, com o build **antes** do `migrate`, para um build quebrado- falhar antes de qualquer escrita:- `composer install` → `artisan optimize` → `npm ci && npm run build` →- `artisan migrate --force` → `$ACTIVATE_RELEASE()` → `$RESTART_QUEUES()` →- `artisan horizon:terminate` → `artisan reverb:restart`.-4. Teste rápido pelo link secreto, ainda em manutenção: abrir a página de publicar,- abrir um post enviado e um agendado, salvar um rascunho.-5. ```bash- php artisan up- ```--## 3. Depois do deploy--- Horizon sem jobs falhos novos.-- Um post de teste publicado em cada rede conectada no workspace de testes.-- Um webhook de teste (`post.published`) e o email de "publicado".-- Os posts agendados para os minutos da janela saíram.-- `post_platforms` não existe mais e `analytics_publications.post_platform_id` foi- removida.--### Se algo falhar--- **Antes do `up`** (migration, build ou teste rápido): ou corrija para frente com- o app em manutenção, ou apague a linha da migration que falhou em `migrations` e- volte o release; as migrations podem rodar de novo (a cópia é idempotente e limpa- cópias de destinos que sumiram).-- **Depois do `up`**: só correção para frente. O código novo grava a publicação só- em `posts`; voltar o código antigo republicaria posts que já saíram.--## 4. Mudança de contrato (API, MCP, webhooks)--Muda de uma vez, sem formato de compatibilidade:--- **Objeto Post** (API `GET/POST/PUT /posts`, tools de post do MCP): sem- `platforms[]`. No topo: `publish_status`, `social_account`, `platform`,- `content_type`, `meta`, `platform_url`, `error_message`, `display_name`,- `display_username`, `display_avatar`.-- **Criar post** (API `POST /posts`, `create-post-tool`): `social_account_id`,- `content_type` e `meta` no topo. Enviar `platforms` é erro de validação.-- **Editar post** (API `PUT /posts/{id}`, `update-post-tool`): `content_type` e- `meta` no topo; `platforms` é recusado.-- **Erros de validação**: `meta.*` e `content_type` (antes `platforms.0.*`); nos- lotes, `destinations.{i}.meta.*`.-- **Status**: `partially_published` deixa de existir; o resultado na rede fica em- `publish_status` (`pending`, `publishing`, `retrying`, `pending_review`,- `published`, `failed`, `rejected`).-- **Preview** (API e `preview-post-tool`) e **métricas** (API e- `get-post-metrics-tool`): um objeto só, sem `platforms[]` nem `post_platform_id`.-- **Analytics**: publicações e relatório trazem `post_id` (sem `post_platform_id`).-- **Repurpose**: cada post do item traz `platform` e `publish_status`.-- **Webhooks**: o payload `post.*` traz os campos do canal no topo (incluindo- `social_account_id` e `platform_post_id`, sem `error_context`). O evento- `post.partially_published` foi removido; webhooks que o assinavam passam a- assinar `post.published` e `post.failed`. Entregas que já estavam na fila e o- replay de logs antigos reenviam o payload no formato antigo.--Páginas da docs.trypost.it a atualizar: objeto Post e endpoints (create, update,-list, show, preview, attach media), erros de validação, status, Webhooks (payload e-lista de eventos), Repurpose items, métricas do post, publicações e relatório de-Analytics, e a página do MCP.diff --git a/MEDIA_INTEGRATIONS_SETUP.md b/MEDIA_INTEGRATIONS_SETUP.mddeleted file mode 100644index f1cb17bc0..000000000--- a/MEDIA_INTEGRATIONS_SETUP.md+++ /dev/null@@ -1,402 +0,0 @@-# Configurando as integrações de mídia do TryPost--Guia para o admin do TryPost: o que criar em cada console para ligar **Google Drive**, **Google Photos**,-**Canva** e **Unsplash** no composer, e como habilitar **HEIC** (fotos do iPhone).--Cada fonte é opcional. Ela só aparece no menu de mídia do composer (botão dividido ao lado do upload, seta ▾)-quando a flag dela está ligada **e** as chaves estão preenchidas. Nada reaproveita as credenciais do login-com Google/YouTube (`GOOGLE_CLIENT_ID`) nem do Google Business (`GOOGLE_BUSINESS_*`).--**URLs usadas neste guia**--| Ambiente | URL do app |-| --- | --- |-| Local (Herd) | `https://app.trypost.test` |-| Produção (Cloud) | `https://app.trypost.it` (padrão de `APP_URL` em `config/app.php`) |--Depois de mudar o `.env`, rode `php artisan config:clear` (e reinicie os workers em produção).--> Os valores de exemplo abaixo são **falsos**, só para mostrar o formato. Nunca commite chaves reais.-------## 1. Google Drive e Google Photos (um projeto Google só para mídia)--Drive e Photos usam o **mesmo** projeto e o mesmo OAuth client. O login roda no **servidor**, igual ao Google-Business e ao YouTube: o composer abre uma janela em `/integrations/google/start`, o Google pede consentimento e-volta para `GOOGLE_MEDIA_CLIENT_REDIRECT` (`/integrations/google/callback`), e o servidor troca o código pelo token-(PKCE S256, `state` de uso único preso ao usuário e ao workspace, `access_type=online`, um escopo por fonte). Por-isso o client precisa do **client secret** e do **URI de redirecionamento** cadastrado.--### 1.1 Criar o projeto--1. Acesse https://console.cloud.google.com e crie um projeto novo, ex.: **TryPost Media**. Não use o projeto- do login/YouTube nem o do Google Business (evita nova revisão dos escopos já aprovados).-2. Em **APIs e serviços → Biblioteca**, ative:- - **Google Picker API** (Drive)- - **Google Drive API** (Drive)- - **Photos Picker API** (Photos)--### 1.2 Tela de consentimento OAuth--1. **Google Auth Platform → Branding**: nome do app **TryPost**, e-mail de suporte, logo, links de política- de privacidade e termos (`https://trypost.it/terms`), domínio autorizado `trypost.it`.-2. **Público-alvo**: *Externo*. Enquanto estiver em *Teste*, adicione seu e-mail em **Usuários de teste**.-3. **Acesso a dados → Adicionar escopos**:- - `https://www.googleapis.com/auth/drive.file` — **não sensível**. Só os arquivos que o usuário escolher- no Picker ficam acessíveis. Publicar em produção não exige revisão por causa dele.- - `https://www.googleapis.com/auth/photospicker.mediaitems.readonly` — **sensível**. Em produção exige- **verificação do Google** (justificativa do escopo, vídeo demo do fluxo do Photos e URL da política de- privacidade). Sem verificação: tela "app não verificado" e limite de 100 usuários.- - **Nunca** adicione `drive.readonly`: é escopo **restrito** e exige auditoria CASA.-4. Quando for para produção: **Publicar app**. Para o Photos, envie a verificação e só depois ligue- `GOOGLE_PHOTOS_ENABLED=true` no Cloud.--### 1.3 OAuth client (tipo Web)--1. **Credenciais → Criar credenciais → ID do cliente OAuth → Aplicativo da Web**, nome "TryPost Media Web".-2. **URIs de redirecionamento autorizados**: o valor exato de `GOOGLE_MEDIA_CLIENT_REDIRECT` (protocolo,- subdomínio e sem barra no fim):- - `https://app.trypost.it/integrations/google/callback`- - local: o Google só aceita domínio público (`.test` é recusado). Como no Google Business, use uma URL pública- (ex.: `herd share`), cadastre `https://<host-publico>/integrations/google/callback` e troque o host de- `GOOGLE_MEDIA_CLIENT_REDIRECT` no `.env` à mão.-3. **Origens JavaScript autorizadas**: não são mais usadas pelo login (ele não roda no navegador). Pode deixar- vazio. A restrição por referenciador da **API key** (1.4) continua valendo para o Picker do Drive.-4. Copie o **ID do cliente** → `GOOGLE_MEDIA_CLIENT_ID` e a **chave secreta do cliente** (começa com `GOCSPX-`)- → `GOOGLE_MEDIA_CLIENT_SECRET`. O secret fica só no servidor.--### 1.4 API key (Picker)--1. **Credenciais → Criar credenciais → Chave de API**.-2. **Restrições de aplicativo → Sites (referenciadores HTTP)**:- - `https://app.trypost.it/*`- - `https://app.trypost.test/*`- - `https://docs.google.com/*` (o iframe do Picker roda nesse domínio)-3. **Restrições de API → Restringir chave → Google Picker API**.-4. Copie a chave → `GOOGLE_MEDIA_API_KEY`. Ela começa com `AIza`; não confunda com o client secret- (`GOCSPX-...`), que vai em `GOOGLE_MEDIA_CLIENT_SECRET`.--### 1.5 App ID--1. **IAM e administrador → Configurações** do mesmo projeto.-2. Copie o **Número do projeto** (só dígitos, não o ID do projeto) → `GOOGLE_MEDIA_APP_ID`.--### 1.6 Variáveis--```dotenv-# Exemplo FALSO-GOOGLE_MEDIA_CLIENT_ID=123456789012-abc123def456.apps.googleusercontent.com-GOOGLE_MEDIA_CLIENT_SECRET=GOCSPX-EXEMPLO-FALSO-000000000000-GOOGLE_MEDIA_CLIENT_REDIRECT="${APP_URL}/integrations/google/callback"-GOOGLE_MEDIA_API_KEY=AIzaSyEXEMPLO-FALSO-0000000000000000-GOOGLE_MEDIA_APP_ID=123456789012-GOOGLE_DRIVE_ENABLED=true # aparece com client id, secret, redirect, API key e App ID-GOOGLE_PHOTOS_ENABLED=false # ligue só depois da verificação do escopo sensível (precisa de id, secret e redirect)-# GOOGLE_PHOTOS_MAX_ITEMS=10 # itens por escolha no Photos; nunca passa de 10 (limite da bandeja de ideias)-```--### 1.7 Como testar--1. Abra o composer (Criar post) e clique na seta ▾ do botão de mídia.-2. **Google Drive**: aparece no menu → janela de login do Google (abre no clique) → a janela fecha sozinha →- Picker → escolha **um** arquivo → vira um tile no composer (primeiro "enviando", depois a miniatura).-3. **Google Photos**: com a flag ligada, a mesma janela faz o login e segue para o Photos Picker; marque e- desmarque à vontade (até `GOOGLE_PHOTOS_MAX_ITEMS`, padrão 10) e confirme com **Concluído**. Cada item vira- um tile próprio, na ordem escolhida; um item que falhar (ex.: vídeo ainda processando) mostra o erro só no- tile dele.--### 1.8 Erros comuns--| Sintoma | Causa / correção |-| --- | --- |-| Item não aparece no menu | Flag desligada ou alguma chave `GOOGLE_MEDIA_*` vazia (Photos precisa de id, secret e redirect; Drive também de API key e App ID); rode `php artisan config:clear` |-| `redirect_uri_mismatch` (erro 400 na janela do Google) | `GOOGLE_MEDIA_CLIENT_REDIRECT` diferente do URI cadastrado em **URIs de redirecionamento autorizados** (protocolo, subdomínio, barra final) |-| Console recusa `https://app.trypost.test/...` ("must end with a public top-level domain") | Use uma URL pública (`herd share`), cadastre o callback dela e troque o host de `GOOGLE_MEDIA_CLIENT_REDIRECT` |-| Janela mostra "Não foi possível conectar ao Google" | Client secret errado/vazio (`invalid_client`), ou a janela foi aberta por outro usuário/workspace; confira `GOOGLE_MEDIA_CLIENT_SECRET` |-| Picker abre em branco / `The API developer key is invalid` | API key sem `https://docs.google.com/*` nos referenciadores, ou sem a Google Picker API na restrição |-| Picker mostra "arquivo não pode ser aberto" / 403 no download | `GOOGLE_MEDIA_APP_ID` não é o número **deste** projeto |-| "Este app não foi verificado" no Photos | Escopo sensível sem verificação; use usuários de teste até aprovar |-| `access_denied` | Usuário fora da lista de testes enquanto o app está em *Teste* |--Docs oficiais:-- https://developers.google.com/identity/protocols/oauth2/web-server-- https://developers.google.com/workspace/drive/picker/guides/overview-- https://developers.google.com/workspace/drive/api/guides/api-specific-auth-- https://developers.google.com/photos/picker/guides/get-started-picker-- https://developers.google.com/photos/picker/guides/media-items-- https://developers.google.com/photos/picker/reference/rest/v1/sessions (`maxItemCount`)-- https://support.google.com/cloud/answer/13463073 (verificação)-------## 2. Canva (Connect API)--Na prática é **só Cloud**: exige uma integração **pública** aprovada pelo Canva. Integração privada só-funciona dentro do seu time e só no plano Enterprise.--### 2.1 Criar a integração--1. Ative **MFA** na conta Canva que vai ser dona da integração (o Developer Portal exige).-2. Acesse https://www.canva.com/developers/integrations/connect-api → **Create an integration** → escolha- **Public**.-3. **Configuration → Credentials**:- - copie o **Client ID** → `CANVA_CLIENT_ID`;- - gere o **Client secret** → `CANVA_CLIENT_SECRET` (aparece **uma vez só**; guarde num cofre).-4. **Scopes**: marque só- - `design:content:write` (criar design)- - `design:content:read` (exportar PNG)- - `design:meta:read` (return navigation e reabrir design com "Editar no Canva")-- Não marque `profile:read`, `asset:*` nem `folder:*`.-5. **Authentication → Redirect URLs** (rota `app.integrations.canva.callback`):- - `https://app.trypost.it/integrations/canva/callback`- - local: `https://app.trypost.test/integrations/canva/callback` (se o portal recusar, use- `http://127.0.0.1:<porta>/integrations/canva/callback`). **Remova as URLs locais antes de enviar para- revisão.**-6. **Return navigation**: ligue e defina a **Return URL** (rota `app.integrations.canva.return`):- - `https://app.trypost.it/integrations/canva/return`- - local: `https://app.trypost.test/integrations/canva/return` (sem isso o Canva responde **400** ao abrir o- design). Antes de enviar para revisão, deixe a de produção.-7. Nome **TryPost**, ícone, e rode o **Submission checklist** (nome público, redirect não local, nenhuma API- em preview, guia de marca do Canva: o item do menu se chama "Canva" e usa o logo).-8. **Submit for review**. O Canva abre um ticket (Jira Service Desk) e toda a conversa segue por lá. Não há- SLA publicado (conte com 1 a 3 semanas). Até aprovar, só membros do time dono conseguem conectar.--### 2.2 Variáveis--```dotenv-# Exemplo FALSO-CANVA_ENABLED=true-CANVA_CLIENT_ID=OC-EXEMPLOfalso123-CANVA_CLIENT_SECRET=cnvcaEXEMPLOfalsoNaoUse0000000000-```--As URLs de callback e retorno **não** vão no `.env`: vêm das rotas nomeadas (`APP_URL` + caminho).--### 2.3 Como testar--1. Composer → seta ▾ do botão de mídia → **Canva ▸** → escolha um tamanho (ex.: Quadrado 1:1).-2. Abre um popup: na primeira vez, login/autorização do Canva; depois, o editor do Canva.-3. Clique **Return to TryPost** no Canva → o popup fecha e o PNG aparece como tile.-4. Passe o mouse no tile → selo **Canva** ("Editar no Canva") reabre o mesmo design e substitui o tile ao- voltar.--### 2.4 Erros comuns--| Sintoma | Causa / correção |-| --- | --- |-| `invalid_redirect_uri` / redirect mismatch | URL em **Redirect URLs** diferente de `APP_URL` + `/integrations/canva/callback` (protocolo, subdomínio, barra final) |-| Volta do Canva não traz a imagem | Return navigation desligada ou Return URL errada |-| `invalid_scope` / 403 ao exportar | Falta `design:content:read` ou `design:meta:read` |-| "Popup bloqueado" | O navegador bloqueou; o usuário precisa permitir popups para o domínio |-| Outros usuários não conseguem conectar | Integração ainda não aprovada (só o time dono funciona) |-| "Editar no Canva" falha | O design pertence à conta Canva de outra pessoa (comportamento esperado) |--Docs oficiais:-- https://www.canva.dev/docs/connect/-- https://www.canva.dev/docs/connect/authentication/-- https://www.canva.dev/docs/connect/appendix/scopes/-- https://www.canva.dev/docs/connect/return-navigation-guide/-- https://www.canva.dev/docs/connect/creating-integrations/-- https://www.canva.dev/docs/connect/submitting-integrations/-- https://www.canva.dev/docs/connect/submission-checklist/-------## 3. Unsplash--Já integrado; a variável mantém o nome atual.--### 3.1 Passos--1. Acesse https://unsplash.com/oauth/applications → **New Application**, aceite as API Guidelines, nome- **TryPost**.-2. Copie a **Access Key** → `UNSPLASH_ACCESS_KEY`. A Secret Key não é usada (`UNSPLASH_SECRET_KEY` pode ficar- vazia).-3. O app começa em **Demo** (50 requisições/hora), suficiente para testar e para self-host pequeno.-4. Para produção, peça **Production** na página do app. O revisor confere:- - crédito ao fotógrafo e ao Unsplash com `?utm_source=trypost&utm_medium=referral`;- - uso direto (hotlink) das URLs de imagem que a API devolve;- - chamada ao `download_location` quando a foto é usada (download tracking).-- Mande screenshots do modal do Unsplash no composer mostrando o crédito.--```dotenv-# Exemplo FALSO-UNSPLASH_ACCESS_KEY=exemploFALSO_abc123DEF456ghi789-```--### 3.2 Como testar e erros comuns--- Composer → seta ▾ → **Unsplash** → busca → clique numa foto → vira tile com o crédito salvo.-- Item não aparece: `UNSPLASH_ACCESS_KEY` vazia.-- `401 OAuth error: The access token is invalid`: chave errada ou revogada.-- `403 Rate Limit Exceeded`: limite do modo Demo; peça Production.--Docs: https://unsplash.com/documentation · https://help.unsplash.com/en/articles/2511245-unsplash-api-guidelines-------## 4. HEIC (fotos do iPhone) com Imagick--HEIC/HEIF é aceito quando o PHP tem **Imagick com suporte a HEIC** e `MEDIA_HEIC_CONVERSION=true`. O arquivo é-convertido para JPEG no upload. Sem isso, o upload de `.heic` mostra "Este servidor não converte fotos HEIC.-Exporte como JPG e tente de novo."--### 4.1 Local (Herd)--O Herd já vem com Imagick + HEIC. Confira:--```bash-php -r 'var_dump(extension_loaded("imagick") && in_array("HEIC", Imagick::queryFormats("HEI*")));'-```--`bool(true)` = pronto.--### 4.2 Docker (`docker/Dockerfile`)--Na imagem Alpine, adicione os pacotes e a extensão (o plano de implementação faz essa mudança):--```dockerfile-RUN apk add --no-cache imagemagick imagemagick-heic \- && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS imagemagick-dev \- && pecl install imagick \- && docker-php-ext-enable imagick \- && apk del .build-deps-```--Depois do build, rode o mesmo `php -r` de 4.1 dentro do container.--### 4.3 Laravel Cloud--1. Confirme que a extensão **imagick** está ativa no ambiente e que `Imagick::queryFormats('HEI*')` lista- `HEIC` (rode o comando de 4.1 pelo console de comandos do Cloud).-2. Se listar: `MEDIA_HEIC_CONVERSION=true`. Se não: `MEDIA_HEIC_CONVERSION=false` até ter suporte (os usuários- recebem a mensagem "exporte como JPG").--### 4.4 Como testar--Arraste um `.heic` para o composer: o tile vira uma imagem JPEG normal e o editor (lápis) abre.-------## 5. Retenção (referência rápida)--| Variável | Padrão | Efeito |-| --- | --- | --- |-| `MEDIA_UPLOAD_RETENTION_HOURS` | `24` | Uploads temporários não usados são apagados depois disso (`media:prune-uploads`) |-| `POST_HISTORY_RETENTION_DAYS` | `730` | Posts publicados mais antigos são apagados com a mídia (`posts:prune-history`). `0`/vazio é recusado |-------## 6. Checklist final--- [ ] Projeto Google "TryPost Media" com Picker API, Drive API e Photos Picker API-- [ ] OAuth client **Web** com client secret em `GOOGLE_MEDIA_CLIENT_SECRET` e o URI de redirecionamento- `GOOGLE_MEDIA_CLIENT_REDIRECT` (`/integrations/google/callback`) cadastrado-- [ ] API key restrita a referenciadores (incluindo `https://docs.google.com/*`) e à Google Picker API-- [ ] `GOOGLE_MEDIA_APP_ID` = número do projeto-- [ ] Escopos: `drive.file` e `photospicker.mediaitems.readonly`; verificação enviada antes de ligar Photos-- [ ] Integração Canva **pública**, MFA ativo, 3 escopos, redirect `/integrations/canva/callback`, return- `/integrations/canva/return`, enviada para revisão-- [ ] Unsplash em Production (crédito + download tracking)-- [ ] Imagick com HEIC no Docker e no Laravel Cloud, ou `MEDIA_HEIC_CONVERSION=false`-- [ ] `php artisan config:clear` e teste de cada item pelo menu ▾ do composer-------## 7. Deploy deste release (fluxo de criar e agendar post)--Faça na ordem. Os passos 1 e 2 vêm **antes** do deploy, porque o passo 4 apaga arquivos de forma irreversível.--### 7.1 Antes do deploy--1. **Snapshot do storage.** Tire um snapshot do bucket (R2/S3) ou ligue o versionamento. O- `media:adopt-library` apaga os arquivos que só existiam na biblioteca de mídia, e não há ferramenta de export.-2. **Ensaio da migração da biblioteca.** Numa cópia da produção, rode `php artisan media:adopt-library --dry-run`- (mostra linhas da biblioteca, referências a copiar, órfãos a apagar, arquivos faltando e posts em Publishing que- vão adiar) e uma adoção real de um workspace grande, para confirmar que cabe no tempo do job.-3. **Imagem Docker.** Rebuild e publique a imagem com o `docker/Dockerfile` novo (`imagemagick`, `imagemagick-dev`,- `imagemagick-heic` e `pecl imagick`).-4. **HEIC no Laravel Cloud.** Confirme que o Imagick de lá converte HEIC (seção 4.3). Se não converter, defina- `MEDIA_HEIC_CONVERSION=false`; o upload de HEIC então é recusado com uma mensagem clara.--### 7.2 Variáveis de ambiente--Todas estão no `.env.example` e no `docker/.env.docker.example`. As obrigatórias para cada fonte estão nas seções-1–3. Novas neste release, com padrão seguro:--| Variável | Padrão | Para quê |-| --- | --- | --- |-| `MEDIA_UPLOAD_RETENTION_HOURS` | `24` | Uploads temporários não usados |-| `POST_HISTORY_RETENTION_DAYS` | `730` | Histórico de posts publicados (2 anos) |-| `MEDIA_HEIC_CONVERSION` | `true` | Converter HEIC/HEIF para JPEG |-| `GOOGLE_MEDIA_CLIENT_SECRET` | vazio | Client secret do OAuth client de mídia (login do Drive/Photos no servidor); obrigatório para as duas fontes |-| `GOOGLE_MEDIA_CLIENT_REDIRECT` | `${APP_URL}/integrations/google/callback` | Tem que bater com o URI cadastrado no Google |-| `GOOGLE_PHOTOS_MAX_ITEMS` | `10` | Itens por escolha no Photos (nunca acima de 10) |-| `GOOGLE_PHOTOS_DOWNLOAD_HOSTS` | `lh3`–`lh6.googleusercontent.com`, `video-downloads.googleusercontent.com` | Confirmar o host real dos vídeos no teste manual; ajustar se for outro |-| `CANVA_CODE_CHALLENGE_METHOD` | `s256` | A doc do Canva se contradiz (`s256`/`S256`); confirmar no primeiro login |-| `CANVA_DOWNLOAD_HOSTS` | `*.canva.com` | Hosts permitidos para baixar a exportação |-| `CANVA_EDITOR_HOSTS` | `*.canva.com` | Hosts permitidos no link "Editar no Canva" |--Depois de mudar variáveis: `php artisan config:clear`.--### 7.3 No deploy (Laravel Cloud)--1. **Comando de deploy, só neste release**, depois das migrations:- `php artisan release:trypost-2 --force` (a adoção da biblioteca é o passo 3 dele e termina no próprio processo;- roteiro em [`DEPLOYMENT.md` §3](DEPLOYMENT.md)). O `media:adopt-library` avulso fica em- `app/Console/Commands/Scripts/` (no Docker ele roda no `docker/entrypoint.sh` a cada boot e não faz nada depois- que tudo foi migrado).-2. **Filas novas.** Os workers/Horizon precisam consumir `media-imports` e `rss-feeds` (supervisores novos em- `config/horizon.php`). Em quem usa `queue:work`: `--queue=default,media-imports,rss-feeds,...`. Sem isso, Google- Drive, Google Photos e Canva nunca importam e os feeds RSS não atualizam.-3. **Scheduler** já agenda sozinho: `media:prune-uploads` (de hora em hora), `posts:prune-history` (diário) e- `rss-feeds:poll` (a cada 5 min). Só confirme que o scheduler está rodando.--### 7.4 Depois do deploy--1. Se o `release:trypost-2` deixou algum workspace para a fila, acompanhe os jobs `AdoptWorkspaceLibraryJob` no- Horizon até zerarem. Se algum workspace falhar de vez, aparece um erro no log; rode- `php artisan release:trypost-2 --force` de novo.-2. O `release:trypost-2` termina com `media:audit` (só leitura); confira que todas as checagens dão 0, ou rode- `php artisan media:audit` de novo depois que a fila drenar.-3. **Janela até a migração terminar:** duplicar um post ou recuperar um rascunho pode manter a mídia antiga da- biblioteca até ela ser migrada, e o texto alternativo por IA dá 404 nessas mídias. Some sozinho quando a adoção- termina.-4. **Proxy:** se o servidor usa `HTTP_PROXY`/`HTTPS_PROXY`, a fixação de IP contra DNS rebinding não vale (quem- resolve o DNS é o proxy). Vale para self-hosted.--### 7.5 Teste manual com as credenciais reais--- **Google Drive:** escolher um arquivo pelo menu ▾ no composer e no editor de ideias; o seletor do Google por cima- do composer recebe clique e teclado; testar com VoiceOver e só teclado; primeiro clique depois de recarregar a- página no Safari (a janela de login não pode ser bloqueada); recusar o escopo mostra o aviso certo; a URL da- janela nunca carrega o token.-- **Google Photos:** escolher várias fotos e um vídeo, desmarcar um e confirmar com **Concluído**; cada item vira- um tile na ordem escolhida; confirmar que o Picker para em `GOOGLE_PHOTOS_MAX_ITEMS`; cancelar um tile ainda- pendente; anotar o host do download do vídeo (ajustar `GOOGLE_PHOTOS_DOWNLOAD_HOSTS` se preciso); fechar a janela sem escolher não adiciona- nada.-- **Canva:** conectar a conta (confirmar `s256`); criar um design, clicar "Return to TryPost" e ver o bloco virar- imagem na bandeja; abrir um design existente pelo painel de projetos e voltar; revogar o acesso no Canva e ver a- reconexão pedida; conferir o host do download da exportação.-- **Editar no Canva:** num rascunho, num post agendado e numa cópia de post já publicado, editar a imagem e salvar;- um colega com outra conta do Canva recebe o erro claro; testar também num canal com mídia própria e no editor de- ideias.--### 7.6 Comunicação--- **Changelog + docs.trypost.it + instruções do MCP** (mudanças que quebram):- - saíram `GET /api/assets`, `GET /api/assets/{media}` e `POST /api/posts/{post}/media/from-asset`;- - saíram as ferramentas MCP `list-assets-tool`, `get-asset-tool` e `attach-existing-asset-tool`;- - um item de mídia agora é exatamente um de `upload_token`, `url` ou `id` (+ `alt`/`meta`); snapshots antigos- (`id` + `path` + `url`) são recusados;- - `upload_token` é de uso único e expira em 24 h; IDs de mídia são por post;- - um `id` de mídia antiga da biblioteca falha como ID desconhecido;- - posts publicados há mais de 2 anos são apagados com a mídia;- - apagar um post apaga os arquivos dele (TikTok/Instagram às vezes ainda buscam o arquivo logo após publicar);- - posts agendados com mídia fora das proporções da rede falham na publicação;- - novos: `POST /api/uploads`, `POST /api/posts/{post}/media/from-upload`, HEIC aceito.-- **E-mail do release:** histórico de 2 anos e fim da biblioteca de mídia (arquivos só da biblioteca foram apagados- no deploy, sem export).diff --git a/app/Actions/Analytics/BuildInsightsExport.php b/app/Actions/Analytics/BuildInsightsExport.phpindex e0067b0ac..6db68d5b3 100644--- a/app/Actions/Analytics/BuildInsightsExport.php+++ b/app/Actions/Analytics/BuildInsightsExport.php@@ -8,6 +8,7 @@ use App\Dto\Analytics\DateRange;use App\Dto\Analytics\PublicationFilter;use App\Enums\Analytics\MetricAvailability;use App\Enums\Analytics\MetricKey;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\SocialAccount\Platform;use App\Models\Workspace;use App\Support\Analytics\EngagementRate;@@ -171,7 +172,7 @@ class BuildInsightsExport$this->network($row->platform),__("analytics.detail.content_types.{$row->content_type}"),$row->excerpt,- $row->permalink,+ PublicationAvailability::from($row->availability)->visiblePermalink($row->permalink),...array_values($values),];}diff --git a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php b/app/Actions/Analytics/BuildPublicationAnalyticsReport.phpindex ae703ae39..74e587fa3 100644--- a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php+++ b/app/Actions/Analytics/BuildPublicationAnalyticsReport.php@@ -8,6 +8,7 @@ use App\Dto\Analytics\DateRange;use App\Dto\Analytics\PublicationFilter;use App\Enums\Analytics\MetricAvailability;use App\Enums\Analytics\MetricKey;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\User\WeekStart;use App\Models\Post;use App\Models\Workspace;@@ -329,7 +330,7 @@ class BuildPublicationAnalyticsReport'content_type' => $row->content_type,'availability' => $row->availability,'published_at' => $row->provider_published_at,- 'permalink' => $row->permalink,+ 'permalink' => PublicationAvailability::from($row->availability)->visiblePermalink($row->permalink),'excerpt' => $row->excerpt,'preview_metadata' => $row->preview_metadata ? json_decode((string) $row->preview_metadata, true) : null,'media' => $postMedia->get((string) $row->post_id),diff --git a/app/Actions/Analytics/ListChannelPublicationPerformance.php b/app/Actions/Analytics/ListChannelPublicationPerformance.phpindex dcd165390..f62c872d2 100644--- a/app/Actions/Analytics/ListChannelPublicationPerformance.php+++ b/app/Actions/Analytics/ListChannelPublicationPerformance.php@@ -8,6 +8,7 @@ use App\Dto\Analytics\DateRange;use App\Dto\Analytics\PublicationFilter;use App\Enums\Analytics\MetricAvailability;use App\Enums\Analytics\MetricKey;+use App\Enums\Analytics\PublicationAvailability;use App\Models\Post;use App\Models\SocialAccount;use App\Support\Analytics\ChannelMetrics;@@ -54,6 +55,7 @@ class ListChannelPublicationPerformance->when($filter !== null, fn (Builder $filtered): Builder => $filter->apply($filtered))->select(['publication.id', 'publication.post_id', 'publication.excerpt', 'publication.preview_metadata', 'publication.permalink',+ 'publication.availability','publication.provider_published_at', 'publication.content_type', 'destination.media as post_media','metric.reactions_count', 'metric.comments_count', 'metric.views_count', 'metric.shares_count','metric.saves_count', 'metric.reach_count', 'metric.engagement_count', 'metric.exposure_count',@@ -92,7 +94,7 @@ class ListChannelPublicationPerformance'excerpt' => $row->excerpt,'thumbnail_url' => $media?->isImage() ? $media->url : $this->thumbnail($row->preview_metadata),'media' => $media?->toArray(),- 'permalink' => $row->permalink,+ 'permalink' => PublicationAvailability::from($row->availability)->visiblePermalink($row->permalink),'published_at' => CarbonImmutable::parse($row->provider_published_at, 'UTC')->toIso8601String(),'content_type' => $row->content_type,'metrics' => [diff --git a/app/Actions/Analytics/ReadPublicationAnalytics.php b/app/Actions/Analytics/ReadPublicationAnalytics.phpindex 594558bfa..2af9b4d5b 100644--- a/app/Actions/Analytics/ReadPublicationAnalytics.php+++ b/app/Actions/Analytics/ReadPublicationAnalytics.php@@ -8,8 +8,10 @@ use App\Dto\Analytics\MetricValue;use App\Enums\Analytics\MetricAvailability;use App\Enums\Analytics\MetricKey;use App\Enums\Analytics\MetricPrecision;+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\Analytics\MetricTimeBasis;use App\Enums\Analytics\MetricUnit;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\Post\PublishStatus;use App\Enums\SocialAccount\Platform;use App\Models\AnalyticsPublication;@@ -26,7 +28,7 @@ class ReadPublicationAnalytics{$publication = AnalyticsPublication::query()->with('socialAccount')- ->available()+ ->whereIn('availability', [PublicationAvailability::Available, PublicationAvailability::Deleted])->whereBelongsTo($workspace)->whereIn('platform', Platform::analyticsValues())->findOrFail($publicationId);@@ -91,12 +93,14 @@ class ReadPublicationAnalytics}return $posts->mapWithKeys(function (Post $post) use ($publications, $snapshots): array {- if ($post->publish_status !== PublishStatus::Published || ! $post->platform_post_id) {- return [$post->id => $this->unavailable('not_published')];+ $unpublished = $this->unpublishedReason($post);++ if (filled($unpublished)) {+ return [$post->id => $this->unavailable($unpublished)];}if (! in_array($post->platform?->value, Platform::analyticsValues(), true)) {- return [$post->id => $this->unavailable('platform_not_supported')];+ return [$post->id => $this->unavailable(MetricsUnavailableReason::PlatformNotSupported)];}$publication = $publications->get($post->id)?->setRelation(@@ -106,19 +110,21 @@ class ReadPublicationAnalyticsreturn [$post->id => $publication? $this->detail($publication, $snapshots->get($publication->id))- : $this->unavailable('not_collected')];+ : $this->unavailable(MetricsUnavailableReason::NotCollected)];})->all();}/** @return array<string, mixed> */public function latestFor(Post $post): array{- if ($post->publish_status !== PublishStatus::Published || ! $post->platform_post_id) {- return $this->unavailable('not_published');+ $unpublished = $this->unpublishedReason($post);++ if (filled($unpublished)) {+ return $this->unavailable($unpublished);}if (! in_array($post->platform?->value, Platform::analyticsValues(), true)) {- return $this->unavailable('platform_not_supported');+ return $this->unavailable(MetricsUnavailableReason::PlatformNotSupported);}$publication = AnalyticsPublication::query()@@ -129,14 +135,14 @@ class ReadPublicationAnalytics->whereIn('platform', Platform::analyticsValues())->first();- return $publication ? $this->latestForPublication($publication) : $this->unavailable('not_collected');+ return $publication ? $this->latestForPublication($publication) : $this->unavailable(MetricsUnavailableReason::NotCollected);}/** @return array<string, mixed> */public function latestForPublication(AnalyticsPublication $publication): array{if (! in_array($publication->platform->value, Platform::analyticsValues(), true)) {- return $this->unavailable('platform_not_supported');+ return $this->unavailable(MetricsUnavailableReason::PlatformNotSupported);}$snapshot = $publication->dailySnapshots()->orderByDesc('date')->first();@@ -144,6 +150,15 @@ class ReadPublicationAnalyticsreturn $this->detail($publication, $snapshot);}+ private function unpublishedReason(Post $post): ?MetricsUnavailableReason+ {+ return match (true) {+ $post->isDeletedOnNetwork() => MetricsUnavailableReason::DeletedOnNetwork,+ $post->publish_status !== PublishStatus::Published || blank($post->platform_post_id) => MetricsUnavailableReason::NotPublished,+ default => null,+ };+ }+private function isCollectable(Post $post): bool{return $post->publish_status === PublishStatus::Published@@ -181,7 +196,7 @@ class ReadPublicationAnalytics'content_type' => $publication->content_type->value,'availability' => $publication->availability->value,'provider_published_at' => $publication->provider_published_at?->toIso8601String(),- 'permalink' => $publication->permalink,+ 'permalink' => $publication->availability->visiblePermalink($publication->permalink),'excerpt' => $publication->excerpt,'preview_metadata' => $publication->preview_metadata,'poll' => data_get($publication->provider_metadata, 'poll'),@@ -239,11 +254,11 @@ class ReadPublicationAnalytics}/** @return array{available: false, reason: string, publication: null, snapshot: null, metrics: array} */- private function unavailable(string $reason): array+ private function unavailable(MetricsUnavailableReason $reason): array{return ['available' => false,- 'reason' => $reason,+ 'reason' => $reason->value,'publication' => null,'snapshot' => null,'metrics' => [],diff --git a/app/Actions/Analytics/UpsertAnalyticsPublication.php b/app/Actions/Analytics/UpsertAnalyticsPublication.phpindex 8323a1291..01b61623b 100644--- a/app/Actions/Analytics/UpsertAnalyticsPublication.php+++ b/app/Actions/Analytics/UpsertAnalyticsPublication.php@@ -10,10 +10,14 @@ use App\Dto\Analytics\TryPostPublicationIdentity;use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;+use App\Enums\Post\PublishStatus;+use App\Jobs\Analytics\CollectPublicationMetrics;use App\Models\AnalyticsPublication;use App\Models\AnalyticsPublicationDailySnapshot;use App\Models\Post;use App\Models\SocialAccount;+use App\Support\Analytics\SyncCadence;+use Carbon\CarbonImmutable;use DateTimeInterface;use Illuminate\Database\UniqueConstraintViolationException;use Illuminate\Support\Arr;@@ -316,8 +320,14 @@ class UpsertAnalyticsPublication}}+ $wasDeleted = $publication->availability === PublicationAvailability::Deleted;$publication->fill($values)->save();+ if ($wasDeleted && $publication->post?->publish_status === PublishStatus::Deleted) {+ $publication->post->markPublicationRestored();+ $this->readAgain($publication);+ }+return $publication->refresh();});}@@ -339,4 +349,21 @@ class UpsertAnalyticsPublicationreturn [...$discovered, ...Arr::only($publication->provider_metadata ?? [], self::METRICS_ONLY_PROVIDER_METADATA)];}++ /**+ * A post listed again is read once more, so a stale discovery page cannot leave+ * it published: past its metrics window too (as a baseline read), and even when+ * today's read already ran.+ */+ private function readAgain(AnalyticsPublication $publication): void+ {+ $today = CarbonImmutable::now('UTC');++ CollectPublicationMetrics::dispatch(+ $publication->id,+ $today->toDateString(),+ baseline: $publication->provider_published_at->lessThan(SyncCadence::metricsWindowStart($publication->platform, $today)),+ refreshSameDay: true,+ )->afterCommit();+ }}diff --git a/app/Actions/Post/DeletePost.php b/app/Actions/Post/DeletePost.phpindex 8603827d1..752a25b7e 100644--- a/app/Actions/Post/DeletePost.php+++ b/app/Actions/Post/DeletePost.php@@ -18,6 +18,9 @@ use Illuminate\Validation\ValidationException;class DeletePost{/**+ * Locks the publication rows before the post, the same order the analytics+ * writers use, so a delete overlapping a metrics write cannot deadlock.+ ** @throws ValidationException*/public static function execute(Post $post, bool $respectStatus = false): void@@ -27,6 +30,12 @@ class DeletePost$isImported = $post->origin === Origin::Network;$deleted = DB::transaction(function () use ($post, $postId, $respectStatus): bool {+ AnalyticsPublication::query()+ ->where('post_id', $postId)+ ->orderBy('id')+ ->lockForUpdate()+ ->pluck('id');+$locked = Post::query()->whereKey($postId)->lockForUpdate()->first();if ($locked === null) {diff --git a/app/Actions/Post/FinalizePostPublication.php b/app/Actions/Post/FinalizePostPublication.phpindex c63a6267d..140dd7557 100644--- a/app/Actions/Post/FinalizePostPublication.php+++ b/app/Actions/Post/FinalizePostPublication.php@@ -5,7 +5,6 @@ declare(strict_types=1);namespace App\Actions\Post;use App\Enums\Notification\Type;-use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;use App\Jobs\PostHog\TrackPostFailed;use App\Jobs\PostHog\TrackPostPublished;@@ -53,7 +52,7 @@ class FinalizePostPublicationreturn null;}- $successful = $post->publish_status === PublishStatus::Published;+ $successful = $post->publish_status->wentOut();if ($successful) {$post->markAsPublished();diff --git a/app/Actions/SocialAccount/CountPostsSentThisWeek.php b/app/Actions/SocialAccount/CountPostsSentThisWeek.phpindex bbd848999..d17e4ae4d 100644--- a/app/Actions/SocialAccount/CountPostsSentThisWeek.php+++ b/app/Actions/SocialAccount/CountPostsSentThisWeek.php@@ -21,7 +21,7 @@ class CountPostsSentThisWeekreturn Post::query()->where('social_account_id', $channel->id)- ->publicationPublished()+ ->wentOut()->whereNotNull('published_at')->whereBetween('published_at', [$now->startOfWeek($weekStart->firstDay())->utc(),diff --git a/app/Actions/SocialAccount/GetInstagramAudio.php b/app/Actions/SocialAccount/GetInstagramAudio.phpindex 5ad07ba13..26711309a 100644--- a/app/Actions/SocialAccount/GetInstagramAudio.php+++ b/app/Actions/SocialAccount/GetInstagramAudio.php@@ -35,7 +35,7 @@ class GetInstagramAudio$response = Http::connectTimeout(3)->timeout(8)- ->get("{$account->platform->instagramGraphBaseUrl()}/{$audioId}", [+ ->get("{$account->platform->graphApiUrl()}/{$audioId}", ['user_id' => $account->platform_user_id,'access_token' => $account->access_token,])diff --git a/app/Actions/SocialAccount/SearchInstagramAudio.php b/app/Actions/SocialAccount/SearchInstagramAudio.phpindex 2aec1e60c..66e8b18ad 100644--- a/app/Actions/SocialAccount/SearchInstagramAudio.php+++ b/app/Actions/SocialAccount/SearchInstagramAudio.php@@ -72,7 +72,7 @@ class SearchInstagramAudio*/private static function search(SocialAccount $account, string $query, array $types): array{- $url = "{$account->platform->instagramGraphBaseUrl()}/ig_audio";+ $url = "{$account->platform->graphApiUrl()}/ig_audio";$responses = Http::pool(fn (Pool $pool): array => collect($types)->map(fn (string $type) => $pool->as($type)@@ -135,7 +135,7 @@ class SearchInstagramAudio->map(fn (string $id) => $pool->as($id)->connectTimeout(3)->timeout(5)- ->get("{$account->platform->instagramGraphBaseUrl()}/{$id}", [+ ->get("{$account->platform->graphApiUrl()}/{$id}", ['user_id' => $account->platform_user_id,'access_token' => $account->access_token,]))diff --git a/app/Enums/Analytics/MetricsUnavailableReason.php b/app/Enums/Analytics/MetricsUnavailableReason.phpnew file mode 100644index 000000000..6b46de82c--- /dev/null+++ b/app/Enums/Analytics/MetricsUnavailableReason.php@@ -0,0 +1,16 @@+<?php++declare(strict_types=1);++namespace App\Enums\Analytics;++/**+ * Why a post or publication has no metrics to show.+ */+enum MetricsUnavailableReason: string+{+ case NotPublished = 'not_published';+ case DeletedOnNetwork = 'deleted_on_network';+ case PlatformNotSupported = 'platform_not_supported';+ case NotCollected = 'not_collected';+}diff --git a/app/Enums/Analytics/PublicationAvailability.php b/app/Enums/Analytics/PublicationAvailability.phpindex 7c141757f..ba6fa6b8d 100644--- a/app/Enums/Analytics/PublicationAvailability.php+++ b/app/Enums/Analytics/PublicationAvailability.php@@ -9,4 +9,12 @@ enum PublicationAvailability: stringcase Available = 'available';case Deleted = 'deleted';case Unavailable = 'unavailable';++ /**+ * A publication the network deleted keeps its row, but loses its link.+ */+ public function visiblePermalink(?string $permalink): ?string+ {+ return $this === self::Deleted ? null : $permalink;+ }}diff --git a/app/Enums/Media/Source.php b/app/Enums/Media/Source.phpindex 9f17b0ffd..d53621628 100644--- a/app/Enums/Media/Source.php+++ b/app/Enums/Media/Source.php@@ -96,7 +96,7 @@ enum Source: stringself::GoogleDrive => ['api_key' => (string) config('services.google_media.api_key'),'app_id' => (string) config('services.google_media.app_id'),- 'picker_sdk' => (string) config('trypost.media_sources.google_drive.picker_sdk'),+ 'picker_sdk' => config('trypost.media_sources.google_drive.picker_sdk'),],default => [],};diff --git a/app/Enums/Post/PublishStatus.php b/app/Enums/Post/PublishStatus.phpindex d8c5fb9dc..99647fdfa 100644--- a/app/Enums/Post/PublishStatus.php+++ b/app/Enums/Post/PublishStatus.php@@ -13,18 +13,34 @@ enum PublishStatus: stringcase Published = 'published';case Failed = 'failed';case Rejected = 'rejected';+ case Deleted = 'deleted';public const self DEFAULT = self::Pending;- /** Published, failed, or rejected — the post can be settled. */+ /** Published, failed, rejected or deleted on the network — the post can be settled. */public function isFinished(): bool{return match ($this) {- self::Published, self::Failed, self::Rejected => true,+ self::Published, self::Failed, self::Rejected, self::Deleted => true,default => false,};}+ /** The network published the post, deleted there since or not. */+ public function wentOut(): bool+ {+ return match ($this) {+ self::Published, self::Deleted => true,+ default => false,+ };+ }++ /** @return list<self> */+ public static function wentOutCases(): array+ {+ return collect(self::cases())->filter(fn (self $status): bool => $status->wentOut())->values()->all();+ }+/** The publish job must not run again. Pending review waits on reconcile. */public function isClosed(): bool{diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.phpindex 2b08aa2ec..43ffe11a9 100644--- a/app/Enums/SocialAccount/Platform.php+++ b/app/Enums/SocialAccount/Platform.php@@ -474,11 +474,16 @@ enum Platform: string->all();}- public function instagramGraphBaseUrl(): string+ /**+ * The Graph API a Meta platform reads and publishes through.+ */+ public function graphApiUrl(): string{return match ($this) {- self::InstagramFacebook => (string) config('trypost.platforms.instagram-facebook.graph_api'),- default => (string) config('trypost.platforms.instagram.graph_api'),+ self::Facebook => config('trypost.platforms.facebook.graph_api'),+ self::Instagram => config('trypost.platforms.instagram.graph_api'),+ self::InstagramFacebook => config('trypost.platforms.instagram-facebook.graph_api'),+ self::Threads => config('trypost.platforms.threads.graph_api'),};}diff --git a/app/Enums/Webhook/EventType.php b/app/Enums/Webhook/EventType.phpindex 6116b1897..93b7aec46 100644--- a/app/Enums/Webhook/EventType.php+++ b/app/Enums/Webhook/EventType.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Enums\Webhook;+use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;enum EventType: string@@ -12,6 +13,8 @@ enum EventType: stringcase PostScheduled = 'post.scheduled';case PostUnscheduled = 'post.unscheduled';case PostPublished = 'post.published';+ case PostDeletedOnNetwork = 'post.deleted_on_network';+ case PostRestored = 'post.restored';case PostFailed = 'post.failed';case PostDeleted = 'post.deleted';@@ -26,4 +29,16 @@ enum EventType: stringdefault => null,};}++ /**+ * The network side of a post changed: deleted there, or listed there again.+ */+ public static function fromPublishStatus(PublishStatus $status, ?PublishStatus $previous = null): ?self+ {+ return match (true) {+ $status === PublishStatus::Deleted => self::PostDeletedOnNetwork,+ $status === PublishStatus::Published && $previous === PublishStatus::Deleted => self::PostRestored,+ default => null,+ };+ }}diff --git a/app/Enums/X/ProblemType.php b/app/Enums/X/ProblemType.phpnew file mode 100644index 000000000..88a00af21--- /dev/null+++ b/app/Enums/X/ProblemType.php@@ -0,0 +1,35 @@+<?php++declare(strict_types=1);++namespace App\Enums\X;++use Illuminate\Support\Arr;+use Illuminate\Support\Uri;++/**+ * The problem types X documents for its API errors, named by the `type` URI+ * `https://api.x.com/2/problems/<value>` (api.twitter.com before the move).+ *+ * @see https://docs.x.com/x-api/fundamentals/response-codes-and-errors+ */+enum ProblemType: string+{+ case ClientForbidden = 'client-forbidden';+ case InvalidRequest = 'invalid-request';+ case NotAuthorizedForResource = 'not-authorized-for-resource';+ case RateLimitExceeded = 'rate-limit-exceeded';+ case ResourceNotFound = 'resource-not-found';+ case UnsupportedAuthentication = 'unsupported-authentication';+ case UsageCapped = 'usage-capped';++ /**+ * The problem a response body, or one of its `errors`, names in its `type`.+ */+ public static function of(mixed $problem): ?self+ {+ $path = Uri::of((string) data_get($problem, 'type'))->path();++ return Arr::first(self::cases(), fn (self $case): bool => $path === "2/problems/{$case->value}");+ }+}diff --git a/app/Events/PostNetworkPresenceChanged.php b/app/Events/PostNetworkPresenceChanged.phpnew file mode 100644index 000000000..3eaade3f0--- /dev/null+++ b/app/Events/PostNetworkPresenceChanged.php@@ -0,0 +1,17 @@+<?php++declare(strict_types=1);++namespace App\Events;++use App\Enums\Webhook\EventType;+use App\Models\Post;+use Illuminate\Foundation\Events\Dispatchable;+use Illuminate\Queue\SerializesModels;++class PostNetworkPresenceChanged+{+ use Dispatchable, SerializesModels;++ public function __construct(public Post $post, public EventType $type) {}+}diff --git a/app/Exceptions/Analytics/AnalyticsCollectionException.php b/app/Exceptions/Analytics/AnalyticsCollectionException.phpindex 84146442f..da4c0acd4 100644--- a/app/Exceptions/Analytics/AnalyticsCollectionException.php+++ b/app/Exceptions/Analytics/AnalyticsCollectionException.php@@ -17,6 +17,8 @@ class AnalyticsCollectionException extends Exceptionstring $message,public readonly ?CarbonImmutable $retryAt = null,public readonly bool $gone = false,+ public readonly bool $missingObject = false,+ public readonly bool $deletedOnNetwork = false,) {parent::__construct($message);}@@ -31,9 +33,13 @@ class AnalyticsCollectionException extends Exceptionreturn new self('malformed', $message);}- public static function gone(string $message): self+ /**+ * The collector confirmed the network deleted the post, so the post itself is+ * marked deleted, not only its publication (a bare 404 or 410 is only `gone`).+ */+ public static function deletedOnNetwork(string $message): self{- return new self('malformed', $message, gone: true);+ return new self('malformed', $message, gone: true, deletedOnNetwork: true);}/**@@ -53,7 +59,11 @@ class AnalyticsCollectionException extends Exception}}- public static function fromResponse(Response $response, string $operation): self+ /**+ * `$missingObject` is set by a collector that recognises the network's documented+ * "this post does not exist" answer, to confirm a deletion before reporting it.+ */+ public static function fromResponse(Response $response, string $operation, bool $missingObject = false): self{$reason = (string) data_get($response->json(), 'error.errors.0.reason', '');$category = match (true) {@@ -70,6 +80,7 @@ class AnalyticsCollectionException extends Exception"{$operation} failed with HTTP {$response->status()}",RetryAfter::from($response),in_array($response->status(), [404, 410], true),+ $missingObject,);}}diff --git a/app/Exceptions/Social/XPublishException.php b/app/Exceptions/Social/XPublishException.phpindex c066d447f..dba01ecde 100644--- a/app/Exceptions/Social/XPublishException.php+++ b/app/Exceptions/Social/XPublishException.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Exceptions\Social;use App\Enums\SocialAccount\Platform;+use App\Enums\X\ProblemType;use App\Exceptions\TokenExpiredException;use Illuminate\Http\Client\Response;@@ -12,14 +13,16 @@ class XPublishException extends SocialPublishException{/*** Problem types X documents as caused by the account itself:- * not-authorized-for-resource is "No access to private/protected- * content". invalid-request (our request), resource-not-found (an id we- * sent), client-forbidden (our app's enrollment), usage-capped (our app's- * cap) and rate-limit-exceeded (per user or per app) stay reported.+ * {@see ProblemType::NotAuthorizedForResource} is "No access to+ * private/protected content". {@see ProblemType::InvalidRequest} (our+ * request), {@see ProblemType::ResourceNotFound} (an id we sent),+ * {@see ProblemType::ClientForbidden} (our app's enrollment),+ * {@see ProblemType::UsageCapped} (our app's cap) and+ * {@see ProblemType::RateLimitExceeded} (per user or per app) stay reported.*- * @var list<string>+ * @var list<ProblemType>*/- private const array USER_REJECTION_TYPES = ['not-authorized-for-resource'];+ private const array USER_REJECTION_TYPES = [ProblemType::NotAuthorizedForResource];public static function fromApiResponse(mixed $response): static{@@ -28,16 +31,15 @@ class XPublishException extends SocialPublishException$rawResponse = $response->body();$statusCode = $response->status();- $type = data_get($body, 'type', '');$title = data_get($body, 'title', '');$detail = data_get($body, 'detail', $title);-- $typeSuffix = $type !== '' ? basename((string) $type) : '';+ $problem = ProblemType::of($body);+ $problemCode = $problem?->value ?? data_get($body, 'type');if (self::isConfirmedDeadToken($response)) {throw new TokenExpiredException(message: $detail ?: 'Access token has expired or been revoked',- platformErrorCode: $typeSuffix ?: (string) $statusCode,+ platformErrorCode: $problemCode ?: (string) $statusCode,);}@@ -59,7 +61,7 @@ class XPublishException extends SocialPublishException);}- if ($statusCode === 429 && ! in_array($typeSuffix, ['usage-capped', 'rate-limit-exceeded'], true)) {+ if ($statusCode === 429 && ! in_array($problem, [ProblemType::UsageCapped, ProblemType::RateLimitExceeded], true)) {return (new static(userMessage: 'Rate limit exceeded. Please try again later.',category: ErrorCategory::RateLimit,@@ -68,22 +70,22 @@ class XPublishException extends SocialPublishException))->withNetworkReset($response);}- [$message, $category] = match ($typeSuffix) {- 'usage-capped' => ['Usage limit exceeded. Please try again later.', ErrorCategory::RateLimit],- 'rate-limit-exceeded' => ['Rate limit exceeded. Please try again later.', ErrorCategory::RateLimit],- 'invalid-request' => ['Invalid request. Check your post content.', ErrorCategory::ContentPolicy],- 'client-forbidden' => ['App not enrolled or lacks required access.', ErrorCategory::Permission],- 'not-authorized-for-resource' => ['Not authorized for this resource.', ErrorCategory::Permission],- 'resource-not-found' => ['Resource not found.', ErrorCategory::ContentPolicy],+ [$message, $category] = match ($problem) {+ ProblemType::UsageCapped => ['Usage limit exceeded. Please try again later.', ErrorCategory::RateLimit],+ ProblemType::RateLimitExceeded => ['Rate limit exceeded. Please try again later.', ErrorCategory::RateLimit],+ ProblemType::InvalidRequest => ['Invalid request. Check your post content.', ErrorCategory::ContentPolicy],+ ProblemType::ClientForbidden => ['App not enrolled or lacks required access.', ErrorCategory::Permission],+ ProblemType::NotAuthorizedForResource => ['Not authorized for this resource.', ErrorCategory::Permission],+ ProblemType::ResourceNotFound => ['Resource not found.', ErrorCategory::ContentPolicy],default => [self::providerMessage($response, 'detail', 'title') ?? __('posts.errors.unrecognized_error', ['platform' => Platform::X->label()]), ErrorCategory::Unknown],};return (new static(userMessage: $message,category: $category,- platformErrorCode: $typeSuffix ?: null,+ platformErrorCode: $problemCode ?: null,rawResponse: $rawResponse,- ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($typeSuffix, self::USER_REJECTION_TYPES, true));+ ))->withNetworkReset($response)->asNetworkRejectionIf(in_array($problem, self::USER_REJECTION_TYPES, true));}public function platform(): string@@ -99,8 +101,6 @@ class XPublishException extends SocialPublishException*/public static function isConfirmedDeadToken(Response $response): bool{- $type = (string) data_get($response->json(), 'type', '');-- return $response->status() === 401 || str_contains($type, 'unsupported-authentication');+ return $response->status() === 401 || ProblemType::of($response->json()) === ProblemType::UnsupportedAuthentication;}}diff --git a/app/Http/Controllers/Auth/BlueskyController.php b/app/Http/Controllers/Auth/BlueskyController.phpindex 11666dd07..568701990 100644--- a/app/Http/Controllers/Auth/BlueskyController.php+++ b/app/Http/Controllers/Auth/BlueskyController.php@@ -60,7 +60,7 @@ class BlueskyController extends SocialControllertry {// Authenticate with Bluesky- $response = Http::post("{$service}/xrpc/".BlueskyLexicon::CREATE_SESSION, [+ $response = Http::post(BlueskyLexicon::xrpc($service, BlueskyLexicon::CREATE_SESSION), ['identifier' => $request->identifier,'password' => $request->password,]);@@ -88,7 +88,7 @@ class BlueskyController extends SocialController// Get profile$profileResponse = Http::withToken($session->accessToken)- ->get("{$service}/xrpc/".BlueskyLexicon::GET_PROFILE, [+ ->get(BlueskyLexicon::xrpc($service, BlueskyLexicon::GET_PROFILE), ['actor' => $session->did,]);@@ -133,7 +133,7 @@ class BlueskyController extends SocialController$response = Http::withToken(data_get($identity, 'attributes.access_token'))->connectTimeout(10)->timeout(30)- ->get(config('trypost.platforms.bluesky.default_service').'/xrpc/'.BlueskyLexicon::GET_SESSION);+ ->get(BlueskyLexicon::xrpc(config('trypost.platforms.bluesky.default_service'), BlueskyLexicon::GET_SESSION));$session = ReadBlueskySession::execute($response);diff --git a/app/Http/Controllers/Auth/MastodonController.php b/app/Http/Controllers/Auth/MastodonController.phpindex 89af6995d..adc3b16d1 100644--- a/app/Http/Controllers/Auth/MastodonController.php+++ b/app/Http/Controllers/Auth/MastodonController.php@@ -7,6 +7,7 @@ namespace App\Http\Controllers\Auth;use App\Enums\SocialAccount\Platform as SocialPlatform;use App\Exceptions\SocialAccount\ConnectFlowException;use App\Services\Http\SafeHttpFetcher;+use App\Services\Social\Mastodon\MastodonApi;use App\Support\Social\PendingConnection;use Exception;use Illuminate\Http\RedirectResponse;@@ -68,7 +69,7 @@ class MastodonController extends SocialControllertry {// Register app on the instance- $appResponse = Http::post("{$instance}/api/v1/apps", [+ $appResponse = Http::post(MastodonApi::url($instance, 'apps'), ['client_name' => config('app.name'),'redirect_uris' => route('app.social.mastodon.callback'),'scopes' => self::SCOPES,@@ -170,7 +171,7 @@ class MastodonController extends SocialController$accessToken = data_get($tokenData, 'access_token');$profileResponse = Http::withToken($accessToken)- ->get("{$instance}/api/v1/accounts/verify_credentials");+ ->get(MastodonApi::url($instance, 'accounts/verify_credentials'));if ($profileResponse->failed()) {return $this->failConnection('failed_to_get_profile');diff --git a/app/Http/Controllers/Auth/TelegramController.php b/app/Http/Controllers/Auth/TelegramController.phpindex 5c4b70857..c1bfd5221 100644--- a/app/Http/Controllers/Auth/TelegramController.php+++ b/app/Http/Controllers/Auth/TelegramController.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Http\Controllers\Auth;use App\Enums\SocialAccount\Platform as SocialPlatform;+use App\Services\Social\Telegram\TelegramApi;use App\Services\Social\Telegram\TelegramConnectCode;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;@@ -36,9 +37,7 @@ class TelegramController extends SocialController'code' => $code,'nonce' => data_get(TelegramConnectCode::decode($code), 'nonce'),'bot_username' => config('trypost.platforms.telegram.bot_username'),- 'bot_url' => filled(config('trypost.platforms.telegram.bot_username'))- ? rtrim((string) config('trypost.platforms.telegram.deep_link'), '/').'/'.config('trypost.platforms.telegram.bot_username')- : null,+ 'bot_url' => TelegramApi::botUrl(),'expires_at' => $expiresAt->toIso8601String(),]);}diff --git a/app/Http/Middleware/App/HandleInertiaRequests.php b/app/Http/Middleware/App/HandleInertiaRequests.phpindex ba1967741..2874b8533 100644--- a/app/Http/Middleware/App/HandleInertiaRequests.php+++ b/app/Http/Middleware/App/HandleInertiaRequests.php@@ -105,8 +105,8 @@ class HandleInertiaRequests extends Middleware)->resolve();},'legal' => fn (): array => [- 'terms' => (string) config('trypost.legal.terms_url'),- 'privacy' => (string) config('trypost.legal.privacy_url'),+ 'terms' => config('trypost.legal.terms_url'),+ 'privacy' => config('trypost.legal.privacy_url'),],'languages' => fn (): array => Locale::options(),'aiEnabled' => fn (): bool => filled(config('ai.providers.'.config('ai.default').'.key')),diff --git a/app/Jobs/Analytics/CollectPublicationMetrics.php b/app/Jobs/Analytics/CollectPublicationMetrics.phpindex 78c07bb2e..b3d4905bc 100644--- a/app/Jobs/Analytics/CollectPublicationMetrics.php+++ b/app/Jobs/Analytics/CollectPublicationMetrics.php@@ -25,6 +25,7 @@ use Illuminate\Foundation\Queue\Queueable;use Illuminate\Http\Client\ConnectionException;use Illuminate\Queue\Middleware\RateLimited;use Illuminate\Queue\Middleware\WithoutOverlapping;+use Illuminate\Support\Facades\DB;class CollectPublicationMetrics implements ShouldQueue{@@ -108,6 +109,7 @@ class CollectPublicationMetrics implements ShouldQueue}$publication->setRelation('socialAccount', $channel);+ $readStartedAt = CarbonImmutable::now('UTC')->startOfSecond();try {$collector = $collectors->for($publication->platform);@@ -128,7 +130,7 @@ class CollectPublicationMetrics implements ShouldQueue}} catch (AnalyticsCollectionException $exception) {$log->record($channel, 'publication_metrics', $this->observationDate, $this->attempts(), $exception->category);- $this->recordTerminalFailure($publication, $exception);+ $this->recordTerminalFailure($publication, $exception, $readStartedAt);$this->retry($publication, $date, $exception->category, $exception->retryAt, $log);} catch (ConnectionException) {$log->record($channel, 'publication_metrics', $this->observationDate, $this->attempts(), 'transient');@@ -136,10 +138,10 @@ class CollectPublicationMetrics implements ShouldQueue}}- private function recordTerminalFailure(AnalyticsPublication $publication, AnalyticsCollectionException $exception): void+ private function recordTerminalFailure(AnalyticsPublication $publication, AnalyticsCollectionException $exception, CarbonImmutable $readStartedAt): void{if ($exception->gone) {- $publication->forceFill(['availability' => PublicationAvailability::Deleted])->save();+ $this->recordGone($publication, $exception, $readStartedAt);return;}@@ -158,6 +160,28 @@ class CollectPublicationMetrics implements ShouldQueue])->save();}+ /**+ * Under the row lock discovery writes with, so a sync that saw the post since+ * the second this read started wins over the deletion. A sync earlier in that+ * same second wins too: the deletion then waits for the next read.+ */+ private function recordGone(AnalyticsPublication $publication, AnalyticsCollectionException $exception, CarbonImmutable $readStartedAt): void+ {+ DB::transaction(function () use ($publication, $exception, $readStartedAt): void {+ $current = AnalyticsPublication::query()->lockForUpdate()->find($publication->id);++ if (blank($current) || $current->last_seen_at?->greaterThanOrEqualTo($readStartedAt)) {+ return;+ }++ $current->forceFill(['availability' => PublicationAvailability::Deleted])->save();++ if ($exception->deletedOnNetwork) {+ $current->post?->markPublicationDeleted();+ }+ });+ }+private function eligible(AnalyticsPublication $publication, SocialAccount $account, CarbonImmutable $date): bool{if ($account->workspace_id !== $publication->workspace_iddiff --git a/app/Jobs/PostHog/SyncAccountPublishingActivity.php b/app/Jobs/PostHog/SyncAccountPublishingActivity.phpindex 70cf4ad78..b3887a887 100644--- a/app/Jobs/PostHog/SyncAccountPublishingActivity.php+++ b/app/Jobs/PostHog/SyncAccountPublishingActivity.php@@ -67,7 +67,7 @@ class SyncAccountPublishingActivity implements ShouldBeUniqueUntilProcessing, Sh$latestPublication = $account->posts()->createdInTryPost()- ->publicationPublished()+ ->wentOut()->whereNotNull('posts.published_at')->latest('posts.published_at')->latest('posts.publication_updated_at')diff --git a/app/Listeners/Webhook/SendPostNetworkPresenceWebhook.php b/app/Listeners/Webhook/SendPostNetworkPresenceWebhook.phpnew file mode 100644index 000000000..54a27105a--- /dev/null+++ b/app/Listeners/Webhook/SendPostNetworkPresenceWebhook.php@@ -0,0 +1,29 @@+<?php++declare(strict_types=1);++namespace App\Listeners\Webhook;++use App\Enums\Post\Origin;+use App\Events\PostNetworkPresenceChanged;+use App\Services\WebhookService;++/**+ * A post imported from the network never sent a webhook (see ImportExternalPosts),+ * so it sends none when the network deletes it or lists it again either.+ */+class SendPostNetworkPresenceWebhook+{+ public function __construct(private WebhookService $webhooks) {}++ public function handle(PostNetworkPresenceChanged $event): void+ {+ $workspace = $event->post->workspace;++ if ($event->post->origin === Origin::Network || blank($workspace)) {+ return;+ }++ $this->webhooks->dispatch($workspace, $event->type, $this->webhooks->postPayload($event->post));+ }+}diff --git a/app/Mcp/Tools/Webhook/CreateWebhookTool.php b/app/Mcp/Tools/Webhook/CreateWebhookTool.phpindex 13403ec82..e5eee8c49 100644--- a/app/Mcp/Tools/Webhook/CreateWebhookTool.php+++ b/app/Mcp/Tools/Webhook/CreateWebhookTool.php@@ -59,12 +59,15 @@ class CreateWebhookTool extends Tool*/public function schema(JsonSchema $schema): array{+ $events = array_column(EventType::cases(), 'value');+ $eventList = implode(', ', $events);+return ['endpoint' => $schema->string()->required()->description('Public URL, up to 255 characters, that will receive signed webhook payloads. Private or local addresses are rejected.'),'events' => $schema->array()- ->items($schema->string()->enum(array_column(EventType::cases(), 'value')))+ ->items($schema->string()->enum($events))->required()- ->description('At least one event to subscribe to: post.created, post.scheduled, post.unscheduled, post.published, post.failed, post.deleted.'),+ ->description("At least one event to subscribe to: {$eventList}."),];}}diff --git a/app/Models/Account.php b/app/Models/Account.phpindex ba5c6276f..09724c9d4 100644--- a/app/Models/Account.php+++ b/app/Models/Account.php@@ -118,7 +118,7 @@ class Account extends Model*/public function scopeWithLifecycleActivity(Builder $query): Builder{- $publishedByTryPost = fn (Builder $posts): Builder => $posts->createdInTryPost()->publicationPublished();+ $publishedByTryPost = fn (Builder $posts): Builder => $posts->createdInTryPost()->wentOut();return $query->withExists('socialAccounts as has_social_account')diff --git a/app/Models/Post.php b/app/Models/Post.phpindex 6b71c8674..768414d52 100644--- a/app/Models/Post.php+++ b/app/Models/Post.php@@ -365,6 +365,15 @@ class Post extends Modelreturn $query->where('posts.publish_status', PublishStatus::Published);}+ /**+ * Posts the network published, including those deleted there since: they+ * still count as published by the user (posting goal, lifecycle).+ */+ public function scopeWentOut(Builder $query): Builder+ {+ return $query->whereIn('posts.publish_status', PublishStatus::wentOutCases());+ }+/*** Posts a network refused for a limit whose next attempt is due.*/@@ -524,6 +533,15 @@ class Post extends Model]);}+ /**+ * The network deleted the post after it was published.+ */+ public function isDeletedOnNetwork(): bool+ {+ return $this->status === PostStatus::Published+ && $this->publish_status === PublishStatus::Deleted;+ }+public function isPublicationWaitingForLimitRetry(): bool{return $this->publish_status === PublishStatus::Retrying && $this->retry_at?->isFuture() === true;@@ -581,6 +599,31 @@ class Post extends Model]);}+ /**+ * The network no longer returns a post it published (deleted there). Its id and+ * URL are kept for support; only a published post moves.+ *+ * Written in a transaction so its webhook, sent after commit, reads the post+ * once `writePublication()` gave its timestamps back.+ */+ public function markPublicationDeleted(): void+ {+ if ($this->publish_status === PublishStatus::Published) {+ DB::transaction(fn () => $this->writePublication(['publish_status' => PublishStatus::Deleted]));+ }+ }++ /**+ * A post marked deleted that the network lists again was never gone. Written in+ * a transaction for the same reason as {@see self::markPublicationDeleted()}.+ */+ public function markPublicationRestored(): void+ {+ if ($this->publish_status === PublishStatus::Deleted) {+ DB::transaction(fn () => $this->writePublication(['publish_status' => PublishStatus::Published]));+ }+ }+/*** @param array<string, mixed>|null $errorContext*/diff --git a/app/Models/SocialAccount.php b/app/Models/SocialAccount.phpindex d5a9bca1f..370a57ca3 100644--- a/app/Models/SocialAccount.php+++ b/app/Models/SocialAccount.php@@ -429,12 +429,19 @@ class SocialAccount extends Model}/**- * Base URL of the Mastodon instance this account lives on, without a- * trailing slash.+ * The Bluesky server (PDS) this account signed in through.*/- public function mastodonInstance(): string+ protected function blueskyService(): Attribute{- return rtrim((string) data_get($this->meta, 'instance', config('trypost.platforms.mastodon.default_instance')), '/');+ return Attribute::get(fn (): string => data_get($this->meta, 'service') ?? config('trypost.platforms.bluesky.default_service'));+ }++ /**+ * The Mastodon instance this account lives on.+ */+ protected function mastodonInstance(): Attribute+ {+ return Attribute::get(fn (): string => data_get($this->meta, 'instance') ?? config('trypost.platforms.mastodon.default_instance'));}/**diff --git a/app/Observers/PostObserver.php b/app/Observers/PostObserver.phpindex 484c48ca4..3c8018db5 100644--- a/app/Observers/PostObserver.php+++ b/app/Observers/PostObserver.php@@ -8,8 +8,11 @@ use App\Actions\Analytics\ResolveAnalyticsAccountKey;use App\Dto\Analytics\TryPostPublicationIdentity;use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;+use App\Enums\Webhook\EventType;use App\Events\PostCreated;+use App\Events\PostNetworkPresenceChanged;use App\Events\PostStatusChanged;+use App\Events\PostStatusUpdated;use App\Jobs\Analytics\SyncTryPostPublication;use App\Jobs\PostHog\SyncAccountPublishingActivity;use App\Models\Post;@@ -40,21 +43,36 @@ class PostObserver}}+ /**+ * The network side of the post moved: the network deleted it or listed it+ * again, or it just went live.+ */public function updated(Post $post): void{- if (! $this->wasJustPublished($post)) {+ if (! $post->wasChanged('publish_status')) {return;}- $this->syncPublicationAnalytics($post);- $this->syncPublishingActivity($post);+ $networkEvent = EventType::fromPublishStatus($post->publish_status, $post->getOriginal('publish_status'));++ if (filled($networkEvent)) {+ $this->announceNetworkPresence($post, $networkEvent);++ return;+ }++ if ($post->publish_status === PublishStatus::Published && filled($post->platform_post_id)) {+ $this->syncPublicationAnalytics($post);+ $this->syncPublishingActivity($post);+ }}- private function wasJustPublished(Post $post): bool+ private function announceNetworkPresence(Post $post, EventType $event): void{- return $post->wasChanged('publish_status')- && $post->publish_status === PublishStatus::Published- && filled($post->platform_post_id);+ DB::afterCommit(function () use ($post, $event): void {+ PostNetworkPresenceChanged::dispatch($post, $event);+ PostStatusUpdated::dispatch($post);+ });}/**diff --git a/app/Services/Analytics/Collectors/Followers/BlueskyFollowerCollector.php b/app/Services/Analytics/Collectors/Followers/BlueskyFollowerCollector.phpindex e65e771b7..4abee2e0c 100644--- a/app/Services/Analytics/Collectors/Followers/BlueskyFollowerCollector.php+++ b/app/Services/Analytics/Collectors/Followers/BlueskyFollowerCollector.php@@ -6,6 +6,7 @@ namespace App\Services\Analytics\Collectors\Followers;use App\Dto\Analytics\AccountDailyObservation;use App\Models\SocialAccount;+use App\Services\Social\BlueskyLexicon;use Carbon\CarbonImmutable;class BlueskyFollowerCollector extends AbstractFollowerCollector@@ -14,7 +15,7 @@ class BlueskyFollowerCollector extends AbstractFollowerCollector{$response = $this->get($account,- config('trypost.platforms.bluesky.public_appview').'/xrpc/app.bsky.actor.getProfile',+ BlueskyLexicon::xrpc(config('trypost.platforms.bluesky.public_appview'), BlueskyLexicon::GET_PROFILE),['actor' => $account->platform_user_id],);diff --git a/app/Services/Analytics/Collectors/Followers/InstagramFollowerCollector.php b/app/Services/Analytics/Collectors/Followers/InstagramFollowerCollector.phpindex 60cb9c32c..1ee0dc888 100644--- a/app/Services/Analytics/Collectors/Followers/InstagramFollowerCollector.php+++ b/app/Services/Analytics/Collectors/Followers/InstagramFollowerCollector.php@@ -20,7 +20,7 @@ class InstagramFollowerCollector extends AbstractFollowerCollector$response = $this->get($account,- "{$account->platform->instagramGraphBaseUrl()}/{$account->platform_user_id}",+ "{$account->platform->graphApiUrl()}/{$account->platform_user_id}",['fields' => 'followers_count'],meta: true,);diff --git a/app/Services/Analytics/Collectors/Followers/MastodonFollowerCollector.php b/app/Services/Analytics/Collectors/Followers/MastodonFollowerCollector.phpindex 304135ced..6c71a60a2 100644--- a/app/Services/Analytics/Collectors/Followers/MastodonFollowerCollector.php+++ b/app/Services/Analytics/Collectors/Followers/MastodonFollowerCollector.php@@ -6,18 +6,14 @@ namespace App\Services\Analytics\Collectors\Followers;use App\Dto\Analytics\AccountDailyObservation;use App\Models\SocialAccount;+use App\Services\Social\Mastodon\MastodonApi;use Carbon\CarbonImmutable;class MastodonFollowerCollector extends AbstractFollowerCollector{public function collect(SocialAccount $account, CarbonImmutable $date): AccountDailyObservation{- $instance = rtrim((string) data_get(- $account->meta,- 'instance',- config('trypost.platforms.mastodon.default_instance'),- ), '/');- $response = $this->get($account, "{$instance}/api/v1/accounts/{$account->platform_user_id}");+ $response = $this->get($account, MastodonApi::url($account->mastodon_instance, "accounts/{$account->platform_user_id}"));return $this->observation($date, data_get($response->json(), 'followers_count'));}diff --git a/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.phpindex 3da6bc728..76685b859 100644--- a/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php@@ -4,9 +4,13 @@ declare(strict_types=1);namespace App\Services\Analytics\Collectors\Metrics;+use App\Dto\Analytics\PublicationMetricObservation;+use App\Enums\Analytics\PublicationContentType;use App\Exceptions\Analytics\AnalyticsCollectionException;+use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Support\Analytics\MetaAnalyticsResponse;+use Carbon\CarbonImmutable;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Log;@@ -15,6 +19,79 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicati/** @var list<string> */protected array $refusals = [];+ /** Whether an optional read was refused with Graph's "object does not exist" answer. */+ protected bool $refusedMissingObject = false;++ abstract protected function read(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation;++ /**+ * The account's list of its own posts, the edge its discovery reads: reading it+ * proves the token still reads the account's posts.+ */+ abstract protected function postsEdge(): string;++ public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation+ {+ $this->refusals = [];+ $this->refusedMissingObject = false;++ return $this->readUnlessDeleted(+ fn (): PublicationMetricObservation => $this->read($publication, $date),+ fn (AnalyticsCollectionException $exception): bool => $this->mayBeDeleted($exception, $publication) && $this->confirmsDeletion($publication),+ $publication->platform,+ );+ }++ /**+ * A read that failed as malformed, or every read refused for permission while one+ * of them answered "object does not exist", may hide a deleted post. Otherwise the+ * failure stands as it is.+ */+ protected function mayBeDeleted(AnalyticsCollectionException $exception, AnalyticsPublication $publication): bool+ {+ return match ($exception->category) {+ 'malformed' => $exception->missingObject || $this->refusedMissingObject,+ 'permission' => $this->refusedMissingObject,+ default => false,+ };+ }++ /**+ * The post counts as deleted only when Graph says it does not exist (see+ * MetaAnalyticsResponse) while the account's posts still read with the same+ * token. A story is never checked: it disappears on its own when it expires.+ */+ private function confirmsDeletion(AnalyticsPublication $publication): bool+ {+ if ($publication->content_type === PublicationContentType::Story) {+ return false;+ }++ $account = $this->account($publication);+ $graph = $account->platform->graphApiUrl();++ return $this->readsMissing(+ fn (): Response => $this->readPost($account, $publication, $graph),+ fn (AnalyticsCollectionException $exception): bool => $exception->missingObject,+ ) && $this->stillReads(+ fn (): Response => $this->get($account, "{$graph}/{$account->platform_user_id}/{$this->postsEdge()}", ['fields' => 'id', 'limit' => '1']),+ );+ }++ /**+ * The read that answers "object does not exist" once the post is gone.+ */+ protected function readPost(SocialAccount $account, AnalyticsPublication $publication, string $graph): Response+ {+ return $this->get($account, "{$graph}/{$publication->remote_id}", ['fields' => 'id']);+ }++ protected function recordRefusal(AnalyticsCollectionException $exception): void+ {+ $this->refusals[] = $exception->category;+ $this->refusedMissingObject = $this->refusedMissingObject || $exception->missingObject;+ }+protected function successfulResponse(Response $response): Response{return MetaAnalyticsResponse::successful($response, 'publication metrics collection');@@ -41,7 +118,7 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicati));}- $this->refusals[] = $exception->category;+ $this->recordRefusal($exception);Log::info('analytics.meta_metric_rejected', ['platform' => $account->platform->value,'path' => parse_url($url, PHP_URL_PATH),diff --git a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.phpindex a11ade5e1..941fef8d9 100644--- a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php@@ -11,11 +11,14 @@ use App\Enums\Analytics\MetricKey;use App\Enums\Analytics\MetricPrecision;use App\Enums\Analytics\MetricTimeBasis;use App\Enums\Analytics\MetricUnit;+use App\Enums\SocialAccount\Platform;use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Publications\AbstractApiPublicationCollector;use Carbon\CarbonImmutable;+use Closure;+use Illuminate\Http\Client\Response;abstract class AbstractPublicationMetricsCollector extends AbstractApiPublicationCollector{@@ -32,6 +35,77 @@ abstract class AbstractPublicationMetricsCollector extends AbstractApiPublicatioreturn $account;}+ /**+ * Runs the post's read and, when it fails in a way `$confirmsDeletion` confirms,+ * reports the post deleted on the network instead of the failure.+ *+ * @template TResult+ *+ * @param Closure(): TResult $read+ * @param Closure(AnalyticsCollectionException): bool $confirmsDeletion+ * @return TResult+ */+ protected function readUnlessDeleted(Closure $read, Closure $confirmsDeletion, Platform $platform): mixed+ {+ try {+ return $read();+ } catch (AnalyticsCollectionException $exception) {+ if ($confirmsDeletion($exception)) {+ throw AnalyticsCollectionException::deletedOnNetwork("{$platform->label()} no longer returns this post.");+ }++ throw $exception;+ }+ }++ /**+ * Whether the post's own read says it is missing. Confirming a deletion takes+ * this and {@see self::stillReads()} on the account's posts, the list its+ * discovery reads, so a token that lost access is never taken for a deleted post.+ *+ * @param Closure(): Response $read+ * @param Closure(AnalyticsCollectionException): bool $isMissing+ */+ protected function readsMissing(Closure $read, Closure $isMissing): bool+ {+ try {+ $read();++ return false;+ } catch (AnalyticsCollectionException $exception) {+ $this->rethrowWhenTemporary($exception);++ return $isMissing($exception);+ }+ }++ /**+ * @param Closure(): Response $read+ */+ protected function stillReads(Closure $read): bool+ {+ try {+ $read();++ return true;+ } catch (AnalyticsCollectionException $exception) {+ $this->rethrowWhenTemporary($exception);++ return false;+ }+ }++ /**+ * A confirming read that failed only for now is rethrown, so the job retries+ * instead of settling the post's read without a confirmation.+ */+ private function rethrowWhenTemporary(AnalyticsCollectionException $exception): void+ {+ if (in_array($exception->category, ['rate_limited', 'transient'], true)) {+ throw $exception;+ }+ }+/*** @param list<MetricValue> $metrics* @param array<string, mixed>|null $providerMetadatadiff --git a/app/Services/Analytics/Collectors/Metrics/BlueskyPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/BlueskyPublicationMetricsCollector.phpindex 92f0c00be..feaa231bb 100644--- a/app/Services/Analytics/Collectors/Metrics/BlueskyPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/BlueskyPublicationMetricsCollector.php@@ -6,9 +6,12 @@ namespace App\Services\Analytics\Collectors\Metrics;use App\Dto\Analytics\PublicationMetricObservation;use App\Enums\Analytics\MetricKey;+use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;+use App\Models\SocialAccount;use App\Services\Social\BlueskyLexicon;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\Response;class BlueskyPublicationMetricsCollector extends AbstractPublicationMetricsCollector{@@ -17,13 +20,17 @@ class BlueskyPublicationMetricsCollector extends AbstractPublicationMetricsColle$account = $this->account($publication);$uri = "at://{$account->platform_user_id}/".BlueskyLexicon::FEED_POST."/{$publication->remote_id}";$response = $this->get($account,- rtrim((string) config('trypost.platforms.bluesky.public_appview'), '/').'/xrpc/'.BlueskyLexicon::GET_POSTS,+ BlueskyLexicon::xrpc(config('trypost.platforms.bluesky.public_appview'), BlueskyLexicon::GET_POSTS),['uris' => [$uri]],authenticated: false,);$post = (array) $response->json('posts.0', []);+ if (blank($post) && $this->confirmsDeletion($account, $publication)) {+ throw AnalyticsCollectionException::deletedOnNetwork('Bluesky no longer returns this post.');+ }+return $this->observation($date, $this->withEngagements($this->present([$this->count(MetricKey::Reactions, $post, 'likeCount'),$this->count(MetricKey::Comments, $post, 'replyCount'),@@ -31,4 +38,30 @@ class BlueskyPublicationMetricsCollector extends AbstractPublicationMetricsColle$this->count(MetricKey::Quotes, $post, 'quoteCount'),])));}++ protected function successfulResponse(Response $response): Response+ {+ if (! $response->successful() && $response->json('error') === 'RecordNotFound') {+ throw AnalyticsCollectionException::fromResponse($response, 'publication metrics collection', missingObject: true);+ }++ return parent::successfulResponse($response);+ }++ /**+ * The AppView also leaves out posts it hides (a moderation takedown), so the post+ * counts as deleted only when its own repository answers `RecordNotFound` while the+ * repository's posts, the list discovery reads, still read.+ */+ private function confirmsDeletion(SocialAccount $account, AnalyticsPublication $publication): bool+ {+ $repository = ['repo' => $account->platform_user_id, 'collection' => BlueskyLexicon::FEED_POST];++ return $this->readsMissing(+ fn (): Response => $this->get($account, BlueskyLexicon::xrpc($account->bluesky_service, BlueskyLexicon::GET_RECORD), [...$repository, 'rkey' => $publication->remote_id], authenticated: false),+ fn (AnalyticsCollectionException $exception): bool => $exception->missingObject,+ ) && $this->stillReads(+ fn (): Response => $this->get($account, BlueskyLexicon::xrpc($account->bluesky_service, BlueskyLexicon::LIST_RECORDS), [...$repository, 'limit' => 1], authenticated: false),+ );+ }}diff --git a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.phpindex 1d65f3da2..c989bd3a4 100644--- a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php@@ -11,7 +11,9 @@ use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;/*** Each read is optional on its own: Page insights are refused for small Pages,@@ -20,15 +22,54 @@ use Illuminate\Support\Facades\Log;*/class FacebookPublicationMetricsCollector extends AbstractMetaPublicationMetricsCollector{- public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation+ protected function postsEdge(): string+ {+ return 'published_posts';+ }++ /**+ * A post read by its bare video id makes no other read of the post, so a+ * permission refusal there may hide a deleted video: the confirmation reads it.+ * Only once its reads were refused, never when the Page did not grant reading+ * it at all, since nothing was read then.+ */+ protected function mayBeDeleted(AnalyticsCollectionException $exception, AnalyticsPublication $publication): bool+ {+ return parent::mayBeDeleted($exception, $publication)+ || ($exception->category === 'permission'+ && filled($this->refusals)+ && $this->isReadByVideoId($publication));+ }++ /**+ * Graph answers a deleted Page post's own node with #10, which also means a missing+ * permission, and only its insights edge with "object does not exist".+ */+ protected function readPost(SocialAccount $account, AnalyticsPublication $publication, string $graph): Response+ {+ if ($this->isReadByVideoId($publication)) {+ return parent::readPost($account, $publication, $graph);+ }++ return $this->get($account, "{$graph}/{$publication->remote_id}/insights", ['metric' => 'post_media_view', 'period' => 'lifetime']);+ }++ /**+ * A Page post id is `{page id}_{post id}`; a video or reel is known by its bare id.+ */+ private function isReadByVideoId(AnalyticsPublication $publication): bool+ {+ return ! Str::contains($publication->remote_id, '_');+ }++ protected function read(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation{- $this->refusals = [];$account = $this->account($publication);AnalyticsCollectionException::unlessGranted($account, 'pages_read_engagement');- $graph = rtrim((string) config('trypost.platforms.facebook.graph_api'), '/');+ $graph = $account->platform->graphApiUrl();$isStory = $publication->content_type === PublicationContentType::Story;$videoId = data_get($publication->provider_metadata, 'video_id');- $isVideo = ! $isStory && (filled($videoId) || ! str_contains($publication->remote_id, '_'));+ $isVideo = ! $isStory && (filled($videoId) || $this->isReadByVideoId($publication));$insightsId = $isVideo && filled($videoId) ? $videoId : $publication->remote_id;$edge = $isVideo ? 'video_insights' : 'insights';$fields = match (true) {@@ -46,7 +87,7 @@ class FacebookPublicationMetricsCollector extends AbstractMetaPublicationMetrics$this->refusals[] = 'permission';}- if (! $isStory && str_contains($publication->remote_id, '_')) {+ if (! $isStory && ! $this->isReadByVideoId($publication)) {$post = "{$graph}/{$publication->remote_id}";$details = array_merge($this->optional($account, $post, ['fields' => 'reactions.limit(0).summary(total_count),shares']),@@ -104,7 +145,7 @@ class FacebookPublicationMetricsCollector extends AbstractMetaPublicationMetricsthrow $exception;}- $this->refusals[] = $exception->category;+ $this->recordRefusal($exception);Log::info('analytics.facebook_read_refused', ['path' => parse_url($url, PHP_URL_PATH),'category' => $exception->category,diff --git a/app/Services/Analytics/Collectors/Metrics/InstagramPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/InstagramPublicationMetricsCollector.phpindex 9822dfa64..be1a0032c 100644--- a/app/Services/Analytics/Collectors/Metrics/InstagramPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/InstagramPublicationMetricsCollector.php@@ -23,9 +23,13 @@ class InstagramPublicationMetricsCollector extends AbstractMetaPublicationMetric'SWIPE_FORWARD' => 'swipes_forward',];- public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation+ protected function postsEdge(): string+ {+ return 'media';+ }++ protected function read(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation{- $this->refusals = [];$account = $this->account($publication);AnalyticsCollectionException::unlessGranted($account, ...$account->platform === Platform::InstagramFacebook? ['instagram_basic', 'instagram_manage_insights', 'pages_read_engagement']@@ -35,7 +39,7 @@ class InstagramPublicationMetricsCollector extends AbstractMetaPublicationMetric$fields = $isStory? ['reach', 'views', 'replies']: ['reach', 'views', 'likes', 'comments', 'shares', 'saved'];- $url = $account->platform->instagramGraphBaseUrl()."/{$publication->remote_id}/insights";+ $url = "{$account->platform->graphApiUrl()}/{$publication->remote_id}/insights";$response = $this->get($account, $url, ['metric' => implode(',', $fields)]);$items = $response->json('data');diff --git a/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.phpindex 173ad34ee..6fc8f2428 100644--- a/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php@@ -6,18 +6,27 @@ namespace App\Services\Analytics\Collectors\Metrics;use App\Dto\Analytics\PublicationMetricObservation;use App\Enums\Analytics\MetricKey;+use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;+use App\Models\SocialAccount;+use App\Services\Social\Mastodon\MastodonApi;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\Response;class MastodonPublicationMetricsCollector extends AbstractPublicationMetricsCollector{public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation{$account = $this->account($publication);- $response = $this->get(- $account,- "{$account->mastodonInstance()}/api/v1/statuses/{$publication->remote_id}",- authenticated: $account->canReadMastodonStatuses(),++ $response = $this->readUnlessDeleted(+ fn (): Response => $this->get(+ $account,+ MastodonApi::url($account->mastodon_instance, "statuses/{$publication->remote_id}"),+ authenticated: $account->canReadMastodonStatuses(),+ ),+ fn (AnalyticsCollectionException $exception): bool => $exception->gone && $this->confirmsDeletion($account),+ $publication->platform,);$status = (array) $response->json();@@ -28,4 +37,16 @@ class MastodonPublicationMetricsCollector extends AbstractPublicationMetricsColl$this->count(MetricKey::Shares, $status, 'reblogs_count'),])));}++ /**+ * Mastodon answers 404 both for a deleted status and for a private one read without+ * its owner's token, so only an owner read counts, and only while the account's+ * statuses, the list discovery reads, still read with that token.+ */+ private function confirmsDeletion(SocialAccount $account): bool+ {+ return $account->canReadMastodonStatuses() && $this->stillReads(+ fn (): Response => $this->get($account, MastodonApi::url($account->mastodon_instance, "accounts/{$account->platform_user_id}/statuses"), ['limit' => 1]),+ );+ }}diff --git a/app/Services/Analytics/Collectors/Metrics/PinterestPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/PinterestPublicationMetricsCollector.phpindex d3ef37b85..a842cb91b 100644--- a/app/Services/Analytics/Collectors/Metrics/PinterestPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/PinterestPublicationMetricsCollector.php@@ -11,7 +11,9 @@ use App\Enums\Analytics\MetricUnit;use App\Enums\Analytics\PublicationContentType;use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;+use App\Models\SocialAccount;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\Response;class PinterestPublicationMetricsCollector extends AbstractPublicationMetricsCollector{@@ -26,14 +28,18 @@ class PinterestPublicationMetricsCollector extends AbstractPublicationMetricsCol$fields = array_merge($fields, ['VIDEO_MRC_VIEW', 'VIDEO_AVG_WATCH_TIME', 'VIDEO_10S_VIEW', 'QUARTILE_95_PERCENT_VIEW', 'VIDEO_V50_WATCH_TIME']);}- $response = $this->get($account,- rtrim((string) config('trypost.platforms.pinterest.api'), '/')."/pins/{$publication->remote_id}/analytics",- [+ $api = config('trypost.platforms.pinterest.api');++ $response = $this->readUnlessDeleted(+ fn (): Response => $this->get($account, "{$api}/pins/{$publication->remote_id}/analytics", ['start_date' => $date->subDays(89)->toDateString(),'end_date' => $date->toDateString(),'metric_types' => implode(',', $fields),- ],+ ]),+ fn (AnalyticsCollectionException $exception): bool => $exception->gone && $this->confirmsDeletion($account, $publication, $api),+ $publication->platform,);+$values = $response->json('all.summary_metrics');if (! is_array($values)) {@@ -59,4 +65,19 @@ class PinterestPublicationMetricsCollector extends AbstractPublicationMetricsColreturn $this->observation($date, $this->withEngagements($metrics));}++ /**+ * Pinterest documents only the 404 status for a Pin it cannot find, so the Pin+ * itself must answer 404 too, while the account's Pins, the list discovery reads,+ * still read with the same token.+ */+ private function confirmsDeletion(SocialAccount $account, AnalyticsPublication $publication, string $api): bool+ {+ return $this->readsMissing(+ fn (): Response => $this->get($account, "{$api}/pins/{$publication->remote_id}"),+ fn (AnalyticsCollectionException $exception): bool => $exception->gone,+ ) && $this->stillReads(+ fn (): Response => $this->get($account, "{$api}/pins", ['page_size' => 1]),+ );+ }}diff --git a/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.phpindex cf985c4ae..b7223a6b1 100644--- a/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php@@ -12,12 +12,17 @@ use Carbon\CarbonImmutable;class ThreadsPublicationMetricsCollector extends AbstractMetaPublicationMetricsCollector{- public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation+ protected function postsEdge(): string+ {+ return 'threads';+ }++ protected function read(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation{$account = $this->account($publication);AnalyticsCollectionException::unlessGranted($account, 'threads_basic', 'threads_manage_insights');$response = $this->get($account,- rtrim((string) config('trypost.platforms.threads.graph_api'), '/')."/{$publication->remote_id}/insights",+ "{$account->platform->graphApiUrl()}/{$publication->remote_id}/insights",['metric' => 'views,likes,replies,reposts,quotes'],);$items = $response->json('data');diff --git a/app/Services/Analytics/Collectors/Metrics/TikTokPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/TikTokPublicationMetricsCollector.phpindex e4b26a992..81f17f2f7 100644--- a/app/Services/Analytics/Collectors/Metrics/TikTokPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/TikTokPublicationMetricsCollector.php@@ -19,7 +19,7 @@ class TikTokPublicationMetricsCollector extends AbstractPublicationMetricsCollec$videoId = $this->publicVideoId($publication);$response = $this->post($account,- rtrim((string) config('trypost.platforms.tiktok.api'), '/').'/video/query/?fields=id,view_count,like_count,comment_count,share_count',+ config('trypost.platforms.tiktok.api').'/video/query/?fields=id,view_count,like_count,comment_count,share_count',['filters' => ['video_ids' => [$videoId]]],);$errorCode = $response->json('error.code');@@ -57,7 +57,7 @@ class TikTokPublicationMetricsCollector extends AbstractPublicationMetricsCollecif (! ctype_digit($videoId)) {$status = $this->post($this->account($publication),- rtrim((string) config('trypost.platforms.tiktok.api'), '/').'/post/publish/status/fetch/',+ config('trypost.platforms.tiktok.api').'/post/publish/status/fetch/',['publish_id' => $videoId],);$videoId = (string) $status->json('data.publicaly_available_post_id.0', '');diff --git a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.phpindex f0822ec6d..8fc7dfe90 100644--- a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php@@ -6,12 +6,14 @@ namespace App\Services\Analytics\Collectors\Metrics;use App\Dto\Analytics\PublicationMetricObservation;use App\Enums\Analytics\MetricKey;+use App\Enums\X\ProblemType;use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Support\Social\XPoll;use App\Support\ThreadReplies;use Carbon\CarbonImmutable;+use Illuminate\Http\Client\Response;use Illuminate\Support\Arr;class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector@@ -77,7 +79,7 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector{$response = $this->get($account, config('trypost.platforms.x.api')."/tweets/{$id}", $this->lookupParameters($fields));- return [$response->json('data'), $response->json('includes.polls.0'), []];+ return [$this->postTweet($response, $id, $response->json('data')), $response->json('includes.polls.0'), []];}/**@@ -106,7 +108,34 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector->values()->all();- return [$tweets->get($id), $pollOf($tweets->get($id)), $threadPolls];+ $tweet = $this->postTweet($response, $id, $tweets->get($id));++ return [$tweet, $pollOf($tweet), $threadPolls];+ }++ /**+ * The post's tweet from a lookup. X leaves a deleted post out of `data` and names it+ * in `errors` with {@see ProblemType::ResourceNotFound}, in a 200; a token that lost+ * access gets 401/403 or {@see ProblemType::NotAuthorizedForResource} instead, so that+ * problem alone confirms the deletion, with no extra request.+ */+ private function postTweet(Response $response, string $id, mixed $tweet): mixed+ {+ if (blank($tweet) && $response->collect('errors')->contains(fn (array $error): bool => $this->namesDeletedPost($error, $id))) {+ throw AnalyticsCollectionException::deletedOnNetwork('X no longer returns this post.');+ }++ return $tweet;+ }++ /**+ * @param array<string, mixed> $error+ */+ private function namesDeletedPost(array $error, string $id): bool+ {+ return ProblemType::of($error) === ProblemType::ResourceNotFound+ && data_get($error, 'resource_type') === 'tweet'+ && data_get($error, 'resource_id') === $id;}/**diff --git a/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.phpindex ef7e1bc8b..ca99e95b3 100644--- a/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php@@ -58,27 +58,31 @@ class YouTubePublicationMetricsCollector extends AbstractPublicationMetricsColle/*** Reads `statistics` for this video together with up to 49 other videos of the channel* still due on the same day, so the daily pass spends one quota unit per 50 videos.+ * Only a cached statistics array is reused. A `false` left by an older batch is read+ * again, so a video is reported deleted by its own `videos.list` only.** @return array<string, mixed>*/private function statistics(SocialAccount $account, AnalyticsPublication $publication, CarbonImmutable $date): array{$key = $this->statisticsCacheKey($account, $date, $publication->remote_id);+ $cached = Cache::get($key);- if (! Cache::has($key)) {- $this->prefetchStatistics($account, $publication, $date);- }-- $statistics = Cache::get($key);+ $statistics = is_array($cached)+ ? $cached+ : $this->prefetchStatistics($account, $publication, $date);if (! is_array($statistics)) {- throw AnalyticsCollectionException::gone('YouTube no longer returns this video.');+ throw AnalyticsCollectionException::deletedOnNetwork('YouTube no longer returns this video.');}return $statistics;}- private function prefetchStatistics(SocialAccount $account, AnalyticsPublication $publication, CarbonImmutable $date): void+ /**+ * @return array<string, mixed>|false this video's statistics, false when YouTube no longer returns it+ */+ private function prefetchStatistics(SocialAccount $account, AnalyticsPublication $publication, CarbonImmutable $date): array|false{$ids = AnalyticsPublication::query()->available()@@ -97,19 +101,19 @@ class YouTubePublicationMetricsCollector extends AbstractPublicationMetricsColle->values();$videos = collect((array) $this->get($account,- rtrim((string) config('trypost.platforms.youtube.data_api'), '/').'/videos',+ config('trypost.platforms.youtube.data_api').'/videos',['part' => 'statistics', 'id' => $ids->implode(',')],)->json('items', []))->filter(fn (mixed $video): bool => is_array($video))->keyBy('id');- foreach ($ids as $id) {- $video = $videos->get($id);+ $statistics = $ids->mapWithKeys(fn (string $id): array => [+ $id => transform($videos->get($id), fn (array $video): array => (array) data_get($video, 'statistics', []), false),+ ]);- Cache::put(- $this->statisticsCacheKey($account, $date, $id),- is_array($video) ? (array) data_get($video, 'statistics', []) : false,- now()->addHours(self::STATISTICS_CACHE_HOURS),- );+ foreach ($statistics->filter(fn (array|false $videoStatistics): bool => is_array($videoStatistics)) as $id => $videoStatistics) {+ Cache::put($this->statisticsCacheKey($account, $date, (string) $id), $videoStatistics, now()->addHours(self::STATISTICS_CACHE_HOURS));}++ return $statistics->get($publication->remote_id, false);}private function statisticsCacheKey(SocialAccount $account, CarbonImmutable $date, string $videoId): string@@ -131,7 +135,7 @@ class YouTubePublicationMetricsCollector extends AbstractPublicationMetricsColletry {$response = $this->get($account,- rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/').'/reports',+ config('trypost.platforms.youtube.analytics_api').'/reports',['ids' => 'channel==MINE','startDate' => $publication->provider_published_at->toDateString(),diff --git a/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.phpindex 2c6352aaf..f8fd1a2e2 100644--- a/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php@@ -20,14 +20,9 @@ class BlueskyPublicationCollector extends AbstractPublicationHistoryCollectorpublic function page(SocialAccount $account, ?string $cursor, CarbonImmutable $cutoff): PublicationPage{- $pds = rtrim((string) data_get(- $account->meta,- 'service',- config('trypost.platforms.bluesky.default_service'),- ), '/');$response = $this->get($account,- "{$pds}/xrpc/".BlueskyLexicon::LIST_RECORDS,+ BlueskyLexicon::xrpc($account->bluesky_service, BlueskyLexicon::LIST_RECORDS),['repo' => $account->platform_user_id,'collection' => BlueskyLexicon::FEED_POST,@@ -89,13 +84,13 @@ class BlueskyPublicationCollector extends AbstractPublicationHistoryCollector*/private function hydrate(SocialAccount $account, Collection $uris): Collection{- $appView = rtrim((string) config('trypost.platforms.bluesky.public_appview'), '/');+ $appView = config('trypost.platforms.bluesky.public_appview');$posts = collect();foreach ($uris->chunk(self::HYDRATION_BATCH_SIZE) as $batch) {$response = $this->get($account,- "{$appView}/xrpc/".BlueskyLexicon::GET_POSTS,+ BlueskyLexicon::xrpc($appView, BlueskyLexicon::GET_POSTS),['uris' => $batch->values()->all()],authenticated: false,);diff --git a/app/Services/Analytics/Collectors/Publications/InstagramPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/InstagramPublicationCollector.phpindex 55cd861df..e240ae58e 100644--- a/app/Services/Analytics/Collectors/Publications/InstagramPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/InstagramPublicationCollector.php@@ -36,7 +36,7 @@ class InstagramPublicationCollector extends AbstractMetaPublicationCollector$response = $this->get($account,- "{$account->platform->instagramGraphBaseUrl()}/{$account->platform_user_id}/media",+ "{$account->platform->graphApiUrl()}/{$account->platform_user_id}/media",['fields' => $this->fields($account), 'limit' => self::PAGE_SIZE, 'after' => $cursor],);$publications = $cursor === null ? $this->liveStories($account) : [];@@ -76,7 +76,7 @@ class InstagramPublicationCollector extends AbstractMetaPublicationCollectortry {$response = $this->get($account,- "{$account->platform->instagramGraphBaseUrl()}/{$account->platform_user_id}/stories",+ "{$account->platform->graphApiUrl()}/{$account->platform_user_id}/stories",['fields' => $this->fields($account), 'limit' => self::STORIES_LIMIT],);} catch (AnalyticsCollectionException $exception) {diff --git a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.phpindex 0eb6292e5..b8290cb75 100644--- a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php@@ -8,6 +8,7 @@ use App\Dto\Analytics\DiscoveredPublication;use App\Dto\Analytics\PublicationPage;use App\Enums\Analytics\PublicationContentType;use App\Models\SocialAccount;+use App\Services\Social\Mastodon\MastodonApi;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Response;@@ -20,10 +21,10 @@ class MastodonPublicationCollector extends AbstractPublicationHistoryCollectorpublic function page(SocialAccount $account, ?string $cursor, CarbonImmutable $cutoff): PublicationPage{$hasPrivateHistoryScope = $account->canReadMastodonStatuses();- $instance = $account->mastodonInstance();+ $instance = $account->mastodon_instance;$response = $this->get($account,- "{$instance}/api/v1/accounts/{$account->platform_user_id}/statuses",+ MastodonApi::url($instance, "accounts/{$account->platform_user_id}/statuses"),['limit' => self::PAGE_SIZE,'exclude_reblogs' => true,diff --git a/app/Services/Media/Sources/CanvaClient.php b/app/Services/Media/Sources/CanvaClient.phpindex cbf7ebaf1..f9241eacc 100644--- a/app/Services/Media/Sources/CanvaClient.php+++ b/app/Services/Media/Sources/CanvaClient.php@@ -313,6 +313,6 @@ class CanvaClientprivate function apiUrl(string $path): string{- return rtrim((string) config('trypost.media_sources.canva.api'), '/').$path;+ return config('trypost.media_sources.canva.api').$path;}}diff --git a/app/Services/Media/Sources/GoogleDriveFiles.php b/app/Services/Media/Sources/GoogleDriveFiles.phpindex c7bb7803d..6ed972244 100644--- a/app/Services/Media/Sources/GoogleDriveFiles.php+++ b/app/Services/Media/Sources/GoogleDriveFiles.php@@ -28,7 +28,7 @@ class GoogleDriveFilesthrow new InvalidArgumentException('Invalid Google Drive file id.');}- $api = rtrim((string) config('trypost.media_sources.google_drive.api'), '/');+ $api = config('trypost.media_sources.google_drive.api');return new RemoteFile("{$api}/files/{$fileId}?alt=media&supportsAllDrives=true",diff --git a/app/Services/Media/Sources/GoogleMediaOAuth.php b/app/Services/Media/Sources/GoogleMediaOAuth.phpindex db081a9f4..e3e121ac9 100644--- a/app/Services/Media/Sources/GoogleMediaOAuth.php+++ b/app/Services/Media/Sources/GoogleMediaOAuth.php@@ -51,7 +51,7 @@ class GoogleMediaOAuth*/public function exchangeCode(string $code, string $verifier): array{- $tokenApi = rtrim((string) config('trypost.media_sources.google_oauth.token_api'), '/');+ $tokenApi = config('trypost.media_sources.google_oauth.token_api');$response = Http::asForm()->acceptJson()diff --git a/app/Services/Media/Sources/GooglePhotosPicker.php b/app/Services/Media/Sources/GooglePhotosPicker.phpindex 92e69b14b..6676cfb4c 100644--- a/app/Services/Media/Sources/GooglePhotosPicker.php+++ b/app/Services/Media/Sources/GooglePhotosPicker.php@@ -251,7 +251,7 @@ class GooglePhotosPickerprivate function client(string $accessToken): PendingRequest{- $api = rtrim((string) config('trypost.media_sources.google_photos.api'), '/');+ $api = config('trypost.media_sources.google_photos.api');return Http::baseUrl("{$api}/v1/")->withToken($accessToken)diff --git a/app/Services/Post/ExternalMedia/BlueskyMediaResolver.php b/app/Services/Post/ExternalMedia/BlueskyMediaResolver.phpindex ff7b5d668..51ade5eb4 100644--- a/app/Services/Post/ExternalMedia/BlueskyMediaResolver.php+++ b/app/Services/Post/ExternalMedia/BlueskyMediaResolver.php@@ -12,9 +12,9 @@ class BlueskyMediaResolver extends AbstractMediaResolver{public function files(SocialAccount $account, AnalyticsPublication $publication): array{- $appView = rtrim((string) config('trypost.platforms.bluesky.public_appview'), '/');+ $appView = config('trypost.platforms.bluesky.public_appview');$uri = "at://{$account->platform_user_id}/".BlueskyLexicon::FEED_POST."/{$publication->remote_id}";- $post = data_get($this->getJson($account, "{$appView}/xrpc/".BlueskyLexicon::GET_POSTS, ['uris' => [$uri]], authenticated: false), 'posts.0');+ $post = data_get($this->getJson($account, BlueskyLexicon::xrpc($appView, BlueskyLexicon::GET_POSTS), ['uris' => [$uri]], authenticated: false), 'posts.0');$images = data_get($post, 'embed.images') ?? data_get($post, 'embed.media.images') ?? [];return $this->remoteFiles(collect((array) $images)->map(fn (mixed $image): mixed => data_get($image, 'fullsize')));diff --git a/app/Services/Post/ExternalMedia/ExternalMediaResolverFactory.php b/app/Services/Post/ExternalMedia/ExternalMediaResolverFactory.phpindex 5a3d449d6..fea54c471 100644--- a/app/Services/Post/ExternalMedia/ExternalMediaResolverFactory.php+++ b/app/Services/Post/ExternalMedia/ExternalMediaResolverFactory.php@@ -11,8 +11,7 @@ class ExternalMediaResolverFactorypublic function for(Platform $platform): ExternalMediaResolver{return match ($platform) {- Platform::Instagram, Platform::InstagramFacebook => app(InstagramMediaResolver::class),- Platform::Threads => app(ThreadsMediaResolver::class),+ Platform::Instagram, Platform::InstagramFacebook, Platform::Threads => app(MetaCarouselResolver::class),Platform::Facebook => app(FacebookMediaResolver::class),Platform::X => app(XMediaResolver::class),Platform::Mastodon => app(MastodonMediaResolver::class),diff --git a/app/Services/Post/ExternalMedia/FacebookMediaResolver.php b/app/Services/Post/ExternalMedia/FacebookMediaResolver.phpindex 7d0f6e5cc..1d40726e9 100644--- a/app/Services/Post/ExternalMedia/FacebookMediaResolver.php+++ b/app/Services/Post/ExternalMedia/FacebookMediaResolver.php@@ -13,7 +13,7 @@ class FacebookMediaResolver extends AbstractMediaResolverpublic function files(SocialAccount $account, AnalyticsPublication $publication): array{- $api = (string) config('trypost.platforms.facebook.graph_api');+ $api = config('trypost.platforms.facebook.graph_api');$attachment = (array) data_get($this->getJson($account, "{$api}/{$publication->remote_id}", ['fields' => self::FIELDS]), 'attachments.data.0', []);$items = data_get($attachment, 'subattachments.data') ?: [$attachment];diff --git a/app/Services/Post/ExternalMedia/InstagramMediaResolver.php b/app/Services/Post/ExternalMedia/InstagramMediaResolver.phpdeleted file mode 100644index cad905bec..000000000--- a/app/Services/Post/ExternalMedia/InstagramMediaResolver.php+++ /dev/null@@ -1,15 +0,0 @@-<?php--declare(strict_types=1);--namespace App\Services\Post\ExternalMedia;--use App\Models\SocialAccount;--class InstagramMediaResolver extends AbstractMetaCarouselResolver-{- protected function baseUrl(SocialAccount $account): string- {- return $account->platform->instagramGraphBaseUrl();- }-}diff --git a/app/Services/Post/ExternalMedia/MastodonMediaResolver.php b/app/Services/Post/ExternalMedia/MastodonMediaResolver.phpindex 4679856ce..a31249293 100644--- a/app/Services/Post/ExternalMedia/MastodonMediaResolver.php+++ b/app/Services/Post/ExternalMedia/MastodonMediaResolver.php@@ -6,6 +6,7 @@ namespace App\Services\Post\ExternalMedia;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;+use App\Services\Social\Mastodon\MastodonApi;class MastodonMediaResolver extends AbstractMediaResolver{@@ -15,7 +16,7 @@ class MastodonMediaResolver extends AbstractMediaResolver{$status = $this->getJson($account,- "{$account->mastodonInstance()}/api/v1/statuses/{$publication->remote_id}",+ MastodonApi::url($account->mastodon_instance, "statuses/{$publication->remote_id}"),authenticated: $account->canReadMastodonStatuses(),);diff --git a/app/Services/Post/ExternalMedia/AbstractMetaCarouselResolver.php b/app/Services/Post/ExternalMedia/MetaCarouselResolver.phpsimilarity index 58%rename from app/Services/Post/ExternalMedia/AbstractMetaCarouselResolver.phprename to app/Services/Post/ExternalMedia/MetaCarouselResolver.phpindex 18cf446a9..f116b0099 100644--- a/app/Services/Post/ExternalMedia/AbstractMetaCarouselResolver.php+++ b/app/Services/Post/ExternalMedia/MetaCarouselResolver.php@@ -7,15 +7,17 @@ namespace App\Services\Post\ExternalMedia;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;-abstract class AbstractMetaCarouselResolver extends AbstractMediaResolver+/**+ * Instagram (both connections) and Threads list a carousel's media as the+ * children of the post on their Graph API.+ */+class MetaCarouselResolver extends AbstractMediaResolver{private const string FIELDS = 'media_type,media_url,children{media_type,media_url}';- abstract protected function baseUrl(SocialAccount $account): string;-public function files(SocialAccount $account, AnalyticsPublication $publication): array{- $media = $this->getJson($account, "{$this->baseUrl($account)}/{$publication->remote_id}", ['fields' => self::FIELDS]);+ $media = $this->getJson($account, "{$account->platform->graphApiUrl()}/{$publication->remote_id}", ['fields' => self::FIELDS]);return $this->remoteFiles(collect(data_get($media, 'children.data') ?: [$media])->pluck('media_url'));}diff --git a/app/Services/Post/ExternalMedia/ThreadsMediaResolver.php b/app/Services/Post/ExternalMedia/ThreadsMediaResolver.phpdeleted file mode 100644index bad61f83a..000000000--- a/app/Services/Post/ExternalMedia/ThreadsMediaResolver.php+++ /dev/null@@ -1,15 +0,0 @@-<?php--declare(strict_types=1);--namespace App\Services\Post\ExternalMedia;--use App\Models\SocialAccount;--class ThreadsMediaResolver extends AbstractMetaCarouselResolver-{- protected function baseUrl(SocialAccount $account): string- {- return (string) config('trypost.platforms.threads.graph_api');- }-}diff --git a/app/Services/Social/BlueskyLexicon.php b/app/Services/Social/BlueskyLexicon.phpindex 6e436edca..68d910d3b 100644--- a/app/Services/Social/BlueskyLexicon.php+++ b/app/Services/Social/BlueskyLexicon.php@@ -17,6 +17,8 @@ final class BlueskyLexiconpublic const LIST_RECORDS = 'com.atproto.repo.listRecords';+ public const GET_RECORD = 'com.atproto.repo.getRecord';+public const UPLOAD_BLOB = 'com.atproto.repo.uploadBlob';public const CREATE_SESSION = 'com.atproto.server.createSession';@@ -50,4 +52,12 @@ final class BlueskyLexiconpublic const FACET_MENTION = 'app.bsky.richtext.facet#mention';public const FACET_TAG = 'app.bsky.richtext.facet#tag';++ /**+ * The XRPC endpoint of a method on a Bluesky server, e.g. `https://bsky.social/xrpc/com.atproto.server.getSession`.+ */+ public static function xrpc(string $server, string $method): string+ {+ return "{$server}/xrpc/{$method}";+ }}diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.phpindex e1e045c2a..efc9f54f5 100644--- a/app/Services/Social/BlueskyPublisher.php+++ b/app/Services/Social/BlueskyPublisher.php@@ -59,7 +59,7 @@ class BlueskyPublisher$content = app(ContentSanitizer::class)->forPost($post);$account = $post->socialAccount;- $service = $account->meta['service'] ?? config('trypost.platforms.bluesky.default_service');+ $service = $account->bluesky_service;// Refresh token if neededif ($account->needsProactiveTokenRefresh()) {@@ -91,7 +91,7 @@ class BlueskyPublisherprivate function liveReply(SocialAccount $account, string $text, array $parent): ?array{try {- $response = $this->socialHttp()->get(config('trypost.platforms.bluesky.public_appview').'/xrpc/'.BlueskyLexicon::GET_POST_THREAD, [+ $response = $this->socialHttp()->get(BlueskyLexicon::xrpc(config('trypost.platforms.bluesky.public_appview'), BlueskyLexicon::GET_POST_THREAD), ['uri' => (string) data_get($parent, 'uri'),'depth' => 1,'parentHeight' => 0,@@ -252,7 +252,7 @@ class BlueskyPublisherprivate function createPostRecord(SocialAccount $account, string $service, array $record): array{$response = $this->socialHttp()->withToken($account->access_token)- ->post("{$service}/xrpc/".BlueskyLexicon::CREATE_RECORD, [+ ->post(BlueskyLexicon::xrpc($service, BlueskyLexicon::CREATE_RECORD), ['repo' => $account->platform_user_id,'collection' => BlueskyLexicon::FEED_POST,'record' => $record,@@ -359,7 +359,7 @@ class BlueskyPublisher$response = $this->socialHttp()->withToken($account->access_token)->withHeaders(['Content-Type' => $mimeType])->withBody($stream, $mimeType)- ->post("{$service}/xrpc/".BlueskyLexicon::UPLOAD_BLOB);+ ->post(BlueskyLexicon::xrpc($service, BlueskyLexicon::UPLOAD_BLOB));if (is_resource($stream)) {fclose($stream);@@ -541,9 +541,9 @@ class BlueskyPublisher}[$contentType, $extension] = $this->videoUploadFormat($mimeType);- $videoService = (string) config('trypost.platforms.bluesky.video_service');+ $videoService = config('trypost.platforms.bluesky.video_service');$name = bin2hex(random_bytes(8)).'.'.$extension;- $uploadUrl = "{$videoService}/xrpc/".BlueskyLexicon::VIDEO_UPLOAD+ $uploadUrl = BlueskyLexicon::xrpc($videoService, BlueskyLexicon::VIDEO_UPLOAD).'?did='.rawurlencode($account->platform_user_id).'&name='.rawurlencode($name);$response = $this->socialHttp()->withToken($uploadToken)@@ -596,7 +596,7 @@ class BlueskyPublisher*/private function pollVideoJob(string $statusToken, string $jobId, CarbonInterface $deadline): ?array{- $statusUrl = (string) config('trypost.platforms.bluesky.video_service').'/xrpc/'.BlueskyLexicon::VIDEO_GET_JOB_STATUS;+ $statusUrl = BlueskyLexicon::xrpc(config('trypost.platforms.bluesky.video_service'), BlueskyLexicon::VIDEO_GET_JOB_STATUS);// Processing usually finishes within seconds. State is checked before// sleeping so an already-complete job returns at once. The attempt cap// and the wall-clock deadline both bound the loop.@@ -685,7 +685,7 @@ class BlueskyPublisher{try {$response = $this->socialHttp()->withToken($account->access_token)- ->get("{$pds}/xrpc/".BlueskyLexicon::GET_SERVICE_AUTH, [+ ->get(BlueskyLexicon::xrpc($pds, BlueskyLexicon::GET_SERVICE_AUTH), ['aud' => $aud,'lxm' => $lxm,'exp' => now()->addMinutes(30)->timestamp,@@ -724,7 +724,7 @@ class BlueskyPublishertry {$docUrl = null;if (str_starts_with($did, 'did:plc:')) {- $directory = (string) config('trypost.platforms.bluesky.plc_directory');+ $directory = config('trypost.platforms.bluesky.plc_directory');$docUrl = "{$directory}/".rawurlencode($did);} elseif (str_starts_with($did, 'did:web:')) {// Per the did:web spec, colon-separated segments map to a host@@ -870,11 +870,11 @@ class BlueskyPublisher*/private function resolveHandleToDid(string $handle): ?string{- $appView = (string) config('trypost.platforms.bluesky.public_appview');+ $appView = config('trypost.platforms.bluesky.public_appview');try {$response = $this->socialHttp()->get(- "{$appView}/xrpc/".BlueskyLexicon::RESOLVE_HANDLE,+ BlueskyLexicon::xrpc($appView, BlueskyLexicon::RESOLVE_HANDLE),['handle' => $handle],);@@ -888,7 +888,7 @@ class BlueskyPublisherprivate function buildPostUrl(string $handle, string $postId): string{- $webApp = (string) config('trypost.platforms.bluesky.web_app');+ $webApp = config('trypost.platforms.bluesky.web_app');return "{$webApp}/profile/{$handle}/post/{$postId}";}diff --git a/app/Services/Social/ConnectionVerifier.php b/app/Services/Social/ConnectionVerifier.phpindex f8c6fcc14..f3d4385cd 100644--- a/app/Services/Social/ConnectionVerifier.php+++ b/app/Services/Social/ConnectionVerifier.php@@ -21,6 +21,7 @@ use App\Exceptions\Social\YouTubePublishException;use App\Exceptions\TokenExpiredException;use App\Models\SocialAccount;use App\Services\Social\Discord\DiscordClient;+use App\Services\Social\Mastodon\MastodonApi;use App\Services\Social\Meta\GraphError;use App\Services\Social\Telegram\TelegramApi;use App\Support\GoogleBusinessResourceName;@@ -338,7 +339,7 @@ class ConnectionVerifierprivate function refreshBlueskyToken(SocialAccount $account): void{- $service = $account->meta['service'] ?? config('trypost.platforms.bluesky.default_service');+ $service = $account->bluesky_service;$client = TokenRefreshClient::for(Platform::Bluesky);try {@@ -346,7 +347,7 @@ class ConnectionVerifier// still sends an empty JSON body, and bsky.social now rejects it// with "A request body was provided when none was expected".$response = $client->send(fn () => $this->refreshHttp()->withToken($account->refresh_token)- ->send('POST', "{$service}/xrpc/".BlueskyLexicon::REFRESH_SESSION));+ ->send('POST', BlueskyLexicon::xrpc($service, BlueskyLexicon::REFRESH_SESSION)));$this->updateBlueskySession($account, $response);@@ -357,7 +358,7 @@ class ConnectionVerifierif (isset($account->meta['password'])) {try {- $reauth = $client->send(fn () => $this->refreshHttp()->post("{$service}/xrpc/".BlueskyLexicon::CREATE_SESSION, [+ $reauth = $client->send(fn () => $this->refreshHttp()->post(BlueskyLexicon::xrpc($service, BlueskyLexicon::CREATE_SESSION), ['identifier' => $account->meta['identifier'],'password' => decrypt($account->meta['password']),]));@@ -656,7 +657,7 @@ class ConnectionVerifier*/private function verifyInstagram(SocialAccount $account): bool{- $response = Http::get("{$account->platform->instagramGraphBaseUrl()}/me", [+ $response = Http::get("{$account->platform->graphApiUrl()}/me", ['fields' => 'id,username,user_id','access_token' => $account->access_token,]);@@ -677,7 +678,7 @@ class ConnectionVerifier*/private function verifyInstagramFacebook(SocialAccount $account): bool{- $response = Http::get("{$account->platform->instagramGraphBaseUrl()}/me", [+ $response = Http::get("{$account->platform->graphApiUrl()}/me", ['fields' => 'id,username','access_token' => $account->access_token,]);@@ -813,10 +814,10 @@ class ConnectionVerifierprivate function verifyBluesky(SocialAccount $account): bool{- $service = $account->meta['service'] ?? config('trypost.platforms.bluesky.default_service');+ $service = $account->bluesky_service;$response = Http::withToken($account->access_token)- ->get("{$service}/xrpc/".BlueskyLexicon::GET_PROFILE, [+ ->get(BlueskyLexicon::xrpc($service, BlueskyLexicon::GET_PROFILE), ['actor' => $account->platform_user_id,]);@@ -870,10 +871,10 @@ class ConnectionVerifierprivate function verifyMastodon(SocialAccount $account): bool{- $instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');+ $instance = $account->mastodon_instance;$response = Http::withToken($account->access_token)- ->get("{$instance}/api/v1/accounts/verify_credentials");+ ->get(MastodonApi::url($instance, 'accounts/verify_credentials'));// 403 here (unlike a publish-time 403 on the write-scoped /statuses// endpoint) means even read access is gone — verify_credentials isdiff --git a/app/Services/Social/Discord/DiscordClient.php b/app/Services/Social/Discord/DiscordClient.phpindex 49c22d081..d1c230dc8 100644--- a/app/Services/Social/Discord/DiscordClient.php+++ b/app/Services/Social/Discord/DiscordClient.php@@ -35,7 +35,7 @@ class DiscordClientpublic function baseUrl(): string{- return (string) config('trypost.platforms.discord.api');+ return config('trypost.platforms.discord.api');}/**diff --git a/app/Services/Social/InstagramPublisher.php b/app/Services/Social/InstagramPublisher.phpindex bf9efb2fb..3bd27f885 100644--- a/app/Services/Social/InstagramPublisher.php+++ b/app/Services/Social/InstagramPublisher.php@@ -48,7 +48,7 @@ class InstagramPublisher$this->validateContentLength($post);$account = $post->socialAccount;- $this->baseUrl = $account->platform->instagramGraphBaseUrl();+ $this->baseUrl = $account->platform->graphApiUrl();if ($account->needsProactiveTokenRefresh()) {app(ConnectionVerifier::class)->refreshToken($account);diff --git a/app/Services/Social/Mastodon/MastodonApi.php b/app/Services/Social/Mastodon/MastodonApi.phpnew file mode 100644index 000000000..bba8b4e63--- /dev/null+++ b/app/Services/Social/Mastodon/MastodonApi.php@@ -0,0 +1,20 @@+<?php++declare(strict_types=1);++namespace App\Services\Social\Mastodon;++/**+ * Builds Mastodon REST API URLs on an account's instance, so the `/api/v1`+ * prefix lives in one place.+ */+class MastodonApi+{+ /**+ * Endpoint for an API path, e.g. `https://mastodon.social/api/v1/statuses`.+ */+ public static function url(string $instance, string $path): string+ {+ return "{$instance}/api/v1/{$path}";+ }+}diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.phpindex 85497a0f7..8d0cc9da3 100644--- a/app/Services/Social/MastodonPublisher.php+++ b/app/Services/Social/MastodonPublisher.php@@ -15,6 +15,7 @@ use App\Models\SocialAccount;use App\Services\Media\MediaOptimizer;use App\Services\Social\Concerns\HasSocialHttpClient;use App\Services\Social\Concerns\PublishesThreads;+use App\Services\Social\Mastodon\MastodonApi;use App\Support\Social\ThreadProgress;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;@@ -36,7 +37,7 @@ class MastodonPublisher$content = app(ContentSanitizer::class)->forPost($post);$account = $post->socialAccount;- $instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');+ $instance = $account->mastodon_instance;$rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());@@ -124,7 +125,7 @@ class MastodonPublisher{$response = $this->socialHttp()->withToken($account->access_token)->withHeaders(['Idempotency-Key' => $idempotencyKey])- ->post("{$instance}/api/v1/statuses", $payload);+ ->post(MastodonApi::url($instance, 'statuses'), $payload);if ($response->failed()) {Log::error('Mastodon post failed', [@@ -188,7 +189,7 @@ class MastodonPublisher}try {- $response = $request->post("{$instance}/api/v1/media");+ $response = $request->post(MastodonApi::url($instance, 'media'));} catch (ConnectionException $e) {throw new PlatformUnavailableException("Mastodon media upload failed to connect: {$e->getMessage()}");} finally {diff --git a/app/Services/Social/Telegram/TelegramApi.php b/app/Services/Social/Telegram/TelegramApi.phpindex dbe5d412e..e5575c7f4 100644--- a/app/Services/Social/Telegram/TelegramApi.php+++ b/app/Services/Social/Telegram/TelegramApi.php@@ -37,8 +37,18 @@ class TelegramApireturn "{$base}/file/bot{$token}/{$path}";}+ /**+ * The bot's `t.me` link, or null while no bot username is configured.+ */+ public static function botUrl(): ?string+ {+ $username = config('trypost.platforms.telegram.bot_username');++ return filled($username) ? config('trypost.platforms.telegram.deep_link')."/{$username}" : null;+ }+private static function baseUrl(): string{- return rtrim((string) config('trypost.platforms.telegram.api'), '/');+ return config('trypost.platforms.telegram.api');}}diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.phpindex 5a0b0c80b..11381cd5f 100644--- a/app/Services/Social/XPublisher.php+++ b/app/Services/Social/XPublisher.php@@ -483,7 +483,7 @@ class XPublisher// Videos/GIFs (and any finalize that reports processing_info) must finish// before we attach the media_id to a tweet — otherwise X returns- // invalid-request / invalid media IDs.+ // ProblemType::InvalidRequest / invalid media IDs.$processingInfo = data_get($finalizeData, 'data.processing_info')?? data_get($finalizeData, 'processing_info');diff --git a/app/Services/UnsplashService.php b/app/Services/UnsplashService.phpindex 5e329d183..4b44f8a6b 100644--- a/app/Services/UnsplashService.php+++ b/app/Services/UnsplashService.php@@ -23,7 +23,7 @@ class UnsplashServicepublic function __construct(){- $this->baseUrl = (string) config('trypost.media_sources.unsplash.api');+ $this->baseUrl = config('trypost.media_sources.unsplash.api');$this->accessKey = (string) config('services.unsplash.access_key', '');}@@ -173,7 +173,7 @@ class UnsplashServiceprivate function website(): string{- $website = rtrim((string) config('trypost.media_sources.unsplash.website'), '/');+ $website = config('trypost.media_sources.unsplash.website');return "{$website}/";}diff --git a/app/Support/Analytics/AnalyticsRateLimits.php b/app/Support/Analytics/AnalyticsRateLimits.phpindex 83d70754c..529b21d5a 100644--- a/app/Support/Analytics/AnalyticsRateLimits.php+++ b/app/Support/Analytics/AnalyticsRateLimits.php@@ -7,6 +7,7 @@ namespace App\Support\Analytics;use App\Enums\SocialAccount\Platform;use App\Models\SocialAccount;use Illuminate\Cache\RateLimiting\Limit;+use Illuminate\Support\Uri;/*** Queue rate limits for analytics jobs, keyed where each network enforces its limit.@@ -57,8 +58,8 @@ class AnalyticsRateLimitsreturn match ($account->platform) {Platform::X => Limit::perMinute(600)->by("{$network}:app"),Platform::TikTok => Limit::perMinute(500)->by("{$network}:app"),- Platform::Bluesky => Limit::perMinute(500)->by("{$network}:pds:".parse_url((string) data_get($account->meta, 'service', config('trypost.platforms.bluesky.default_service')), PHP_URL_HOST)),- Platform::Mastodon => Limit::perMinute(50)->by("{$network}:instance:{$account->mastodonInstance()}"),+ Platform::Bluesky => Limit::perMinute(500)->by("{$network}:pds:".Uri::of($account->bluesky_service)->host()),+ Platform::Mastodon => Limit::perMinute(50)->by("{$network}:instance:{$account->mastodon_instance}"),default => null,};}diff --git a/app/Support/Analytics/MetaAnalyticsResponse.php b/app/Support/Analytics/MetaAnalyticsResponse.phpindex 02428f3dc..e03d68188 100644--- a/app/Support/Analytics/MetaAnalyticsResponse.php+++ b/app/Support/Analytics/MetaAnalyticsResponse.php@@ -16,6 +16,7 @@ class MetaAnalyticsResponse}$code = (int) data_get($response->json(), 'error.code', 0);+ $subcode = (int) data_get($response->json(), 'error.error_subcode', 0);$category = match (true) {$response->status() === 429, in_array($code, [4, 17, 32, 80001, 80002], true) => 'rate_limited',$response->status() === 401, $code === 190 => 'authentication',@@ -28,6 +29,17 @@ class MetaAnalyticsResponse$category,"{$context} failed with HTTP {$response->status()} (Graph code {$code})",RetryAfter::from($response),+ missingObject: self::isMissingObject($code, $subcode),);}++ /**+ * Graph answers code 100, subcode 33 ("Object with ID ... does not exist, cannot be+ * loaded due to missing permissions, or does not support this operation") both when+ * the object was deleted and when the token can no longer read it.+ */+ private static function isMissingObject(int $code, int $subcode): bool+ {+ return $code === 100 && $subcode === 33;+ }}diff --git a/app/Support/GoogleBusinessResourceName.php b/app/Support/GoogleBusinessResourceName.phpindex 257a7c509..3e1205545 100644--- a/app/Support/GoogleBusinessResourceName.php+++ b/app/Support/GoogleBusinessResourceName.php@@ -19,7 +19,7 @@ class GoogleBusinessResourceName{public static function dashboardUrl(string $resourceName): string{- return (string) config('trypost.platforms.google_business.dashboard').'/dashboard/l/u'.self::locationId($resourceName);+ return config('trypost.platforms.google_business.dashboard').'/dashboard/l/u'.self::locationId($resourceName);}public static function toFullLocationName(string $accountName, string $shortLocationName): stringdiff --git a/app/Support/PostStatusRules.php b/app/Support/PostStatusRules.phpindex dd28c65ed..0cea5d4cc 100644--- a/app/Support/PostStatusRules.php+++ b/app/Support/PostStatusRules.php@@ -50,9 +50,14 @@ class PostStatusRulesreturn in_array($post->status, self::EDIT_BLOCKED_STATUSES, true);}+ /**+ * A published post the network deleted has nothing left to protect, so it may+ * be removed from TryPost too.+ */public static function blocksDeletion(Post $post): bool{- return in_array($post->status, self::DELETE_BLOCKED_STATUSES, true);+ return in_array($post->status, self::DELETE_BLOCKED_STATUSES, true)+ && ! $post->isDeletedOnNetwork();}public static function editBlockedMessage(): stringdiff --git a/config/trypost.php b/config/trypost.phpindex 8ded5b003..c75ef05ce 100644--- a/config/trypost.php+++ b/config/trypost.php@@ -2,6 +2,14 @@declare(strict_types=1);+use Illuminate\Support\Str;++/*+ * Every third-party URL goes through here, so a reader can append a path+ * without trimming: a value set with a trailing slash comes back without it.+ */+$url = static fn (string $key, string $default): string => Str::rtrim((string) env($key, $default), '/');+return [/*@@ -44,8 +52,8 @@ return [*/'legal' => [- 'terms_url' => env('LEGAL_TERMS_URL', 'https://trypost.it/terms'),- 'privacy_url' => env('LEGAL_PRIVACY_URL', 'https://trypost.it/privacy'),+ 'terms_url' => $url('LEGAL_TERMS_URL', 'https://trypost.it/terms'),+ 'privacy_url' => $url('LEGAL_PRIVACY_URL', 'https://trypost.it/privacy'),],/*@@ -77,7 +85,7 @@ return [|*/- 'mcp_chatgpt_ip_ranges_url' => env('MCP_CHATGPT_IP_RANGES_URL', 'https://openai.com/chatgpt-connectors.json'),+ 'mcp_chatgpt_ip_ranges_url' => $url('MCP_CHATGPT_IP_RANGES_URL', 'https://openai.com/chatgpt-connectors.json'),/*|--------------------------------------------------------------------------@@ -179,32 +187,32 @@ return ['media_sources' => ['unsplash' => [- 'api' => env('UNSPLASH_API_URL', 'https://api.unsplash.com'),- 'website' => env('UNSPLASH_WEBSITE_URL', 'https://unsplash.com'),+ 'api' => $url('UNSPLASH_API_URL', 'https://api.unsplash.com'),+ 'website' => $url('UNSPLASH_WEBSITE_URL', 'https://unsplash.com'),'download_hosts' => env('UNSPLASH_DOWNLOAD_HOSTS', 'images.unsplash.com'),'requests_per_user_per_minute' => (int) env('UNSPLASH_REQUESTS_PER_MINUTE', 30),],'google_oauth' => [- 'authorize_url' => env('GOOGLE_MEDIA_AUTHORIZE_URL', 'https://accounts.google.com/o/oauth2/v2/auth'),- 'token_api' => env('GOOGLE_MEDIA_OAUTH_API', 'https://oauth2.googleapis.com'),+ 'authorize_url' => $url('GOOGLE_MEDIA_AUTHORIZE_URL', 'https://accounts.google.com/o/oauth2/v2/auth'),+ 'token_api' => $url('GOOGLE_MEDIA_OAUTH_API', 'https://oauth2.googleapis.com'),],'google_drive' => ['enabled' => (bool) env('GOOGLE_DRIVE_ENABLED', true),- 'api' => env('GOOGLE_DRIVE_API_URL', 'https://www.googleapis.com/drive/v3'),- 'picker_sdk' => env('GOOGLE_PICKER_SDK_URL', 'https://apis.google.com/js/api.js'),+ 'api' => $url('GOOGLE_DRIVE_API_URL', 'https://www.googleapis.com/drive/v3'),+ 'picker_sdk' => $url('GOOGLE_PICKER_SDK_URL', 'https://apis.google.com/js/api.js'),'download_hosts' => env('GOOGLE_DRIVE_DOWNLOAD_HOSTS', 'www.googleapis.com,*.googleusercontent.com'),],'google_photos' => ['enabled' => (bool) env('GOOGLE_PHOTOS_ENABLED', false),- 'api' => env('GOOGLE_PHOTOS_PICKER_API_URL', 'https://photospicker.googleapis.com'),+ 'api' => $url('GOOGLE_PHOTOS_PICKER_API_URL', 'https://photospicker.googleapis.com'),'download_hosts' => env('GOOGLE_PHOTOS_DOWNLOAD_HOSTS', 'lh3.googleusercontent.com,lh4.googleusercontent.com,lh5.googleusercontent.com,lh6.googleusercontent.com,video-downloads.googleusercontent.com'),'polls_per_user_per_minute' => (int) env('GOOGLE_PHOTOS_POLLS_PER_MINUTE', 60),'max_items' => (int) env('GOOGLE_PHOTOS_MAX_ITEMS', 10),],'canva' => ['enabled' => (bool) env('CANVA_ENABLED', true),- 'api' => env('CANVA_API_URL', 'https://api.canva.com/rest/v1'),- 'authorize_url' => env('CANVA_AUTHORIZE_URL', 'https://www.canva.com/api/oauth/authorize'),+ 'api' => $url('CANVA_API_URL', 'https://api.canva.com/rest/v1'),+ 'authorize_url' => $url('CANVA_AUTHORIZE_URL', 'https://www.canva.com/api/oauth/authorize'),'code_challenge_method' => env('CANVA_CODE_CHALLENGE_METHOD', 's256'),'download_hosts' => env('CANVA_DOWNLOAD_HOSTS', '*.canva.com'),'editor_hosts' => env('CANVA_EDITOR_HOSTS', '*.canva.com'),@@ -319,7 +327,7 @@ return [*/'favicon' => [- 'api' => env('FAVICON_API', 'https://icons.duckduckgo.com'),+ 'api' => $url('FAVICON_API', 'https://icons.duckduckgo.com'),],/*@@ -477,26 +485,26 @@ return ['platforms' => ['linkedin' => ['enabled' => env('LINKEDIN_ENABLED', true),- 'api' => env('LINKEDIN_API', 'https://api.linkedin.com'),+ 'api' => $url('LINKEDIN_API', 'https://api.linkedin.com'),// OAuth host is different from the data API (api.linkedin.com).- 'oauth_api' => env('LINKEDIN_OAUTH_API', 'https://www.linkedin.com'),+ 'oauth_api' => $url('LINKEDIN_OAUTH_API', 'https://www.linkedin.com'),// Scopes for LinkedIn authentication'scopes' => array_values(array_filter(array_map('trim', explode(',', (string) env('LINKEDIN_SCOPES', 'openid,profile,email,w_member_social'))))),],'linkedin-page' => ['enabled' => env('LINKEDIN_PAGE_ENABLED', true),- 'api' => env('LINKEDIN_PAGE_API', 'https://api.linkedin.com'),+ 'api' => $url('LINKEDIN_PAGE_API', 'https://api.linkedin.com'),// Scopes for LinkedIn Page authentication'scopes' => array_values(array_filter(array_map('trim', explode(',', (string) env('LINKEDIN_PAGE_SCOPES', 'openid,profile,email,w_organization_social,r_organization_social,rw_organization_admin,w_member_social'))))),],'x' => ['enabled' => env('X_ENABLED', true),- 'api' => env('X_API', 'https://api.x.com/2'),+ 'api' => $url('X_API', 'https://api.x.com/2'),'defuse_links' => (bool) env('X_DEFUSE_LINKS', false),],'tiktok' => ['enabled' => env('TIKTOK_ENABLED', true),- 'api' => env('TIKTOK_API', 'https://open.tiktokapis.com/v2'),+ 'api' => $url('TIKTOK_API', 'https://open.tiktokapis.com/v2'),// OAuth scopes to request. Trim when the TikTok app lacks a product// (e.g. no Display API => drop user.info.profile, user.info.stats,// video.list; analytics degrade gracefully, username stays empty).@@ -504,48 +512,48 @@ return [],'youtube' => ['enabled' => env('YOUTUBE_ENABLED', true),- 'data_api' => env('YOUTUBE_DATA_API', 'https://www.googleapis.com/youtube/v3'),- 'analytics_api' => env('YOUTUBE_ANALYTICS_API', 'https://youtubeanalytics.googleapis.com/v2'),- 'oauth_api' => env('YOUTUBE_OAUTH_API', 'https://oauth2.googleapis.com'),+ 'data_api' => $url('YOUTUBE_DATA_API', 'https://www.googleapis.com/youtube/v3'),+ 'analytics_api' => $url('YOUTUBE_ANALYTICS_API', 'https://youtubeanalytics.googleapis.com/v2'),+ 'oauth_api' => $url('YOUTUBE_OAUTH_API', 'https://oauth2.googleapis.com'),],'facebook' => ['enabled' => env('FACEBOOK_ENABLED', true),- 'graph_api' => env('FACEBOOK_GRAPH_API', 'https://graph.facebook.com/v25.0'),+ 'graph_api' => $url('FACEBOOK_GRAPH_API', 'https://graph.facebook.com/v25.0'),'rupload_host' => env('FACEBOOK_RUPLOAD_HOST', 'rupload.facebook.com'),],'instagram' => ['enabled' => env('INSTAGRAM_ENABLED', true),- 'graph_api' => env('INSTAGRAM_GRAPH_API', 'https://graph.instagram.com/v25.0'),+ 'graph_api' => $url('INSTAGRAM_GRAPH_API', 'https://graph.instagram.com/v25.0'),// graph.instagram.com (no version) is the auth/refresh host.- 'auth_api' => env('INSTAGRAM_AUTH_API', 'https://graph.instagram.com'),- 'oauth_url' => env('INSTAGRAM_OAUTH_URL', 'https://www.instagram.com'),- 'oauth_api' => env('INSTAGRAM_OAUTH_API', 'https://api.instagram.com'),+ 'auth_api' => $url('INSTAGRAM_AUTH_API', 'https://graph.instagram.com'),+ 'oauth_url' => $url('INSTAGRAM_OAUTH_URL', 'https://www.instagram.com'),+ 'oauth_api' => $url('INSTAGRAM_OAUTH_API', 'https://api.instagram.com'),],'instagram-facebook' => ['enabled' => env('INSTAGRAM_FACEBOOK_ENABLED', true),- 'graph_api' => env('INSTAGRAM_FACEBOOK_GRAPH_API', 'https://graph.facebook.com/v25.0'),+ 'graph_api' => $url('INSTAGRAM_FACEBOOK_GRAPH_API', 'https://graph.facebook.com/v25.0'),],'threads' => ['enabled' => env('THREADS_ENABLED', true),- 'graph_api' => env('THREADS_GRAPH_API', 'https://graph.threads.net/v1.0'),+ 'graph_api' => $url('THREADS_GRAPH_API', 'https://graph.threads.net/v1.0'),// graph.threads.net (no version) is the auth/refresh host.- 'auth_api' => env('THREADS_AUTH_API', 'https://graph.threads.net'),- 'oauth_url' => env('THREADS_OAUTH_URL', 'https://threads.net'),+ 'auth_api' => $url('THREADS_AUTH_API', 'https://graph.threads.net'),+ 'oauth_url' => $url('THREADS_OAUTH_URL', 'https://threads.net'),],'pinterest' => ['enabled' => env('PINTEREST_ENABLED', true),- 'api' => env('PINTEREST_API', 'https://api.pinterest.com/v5'),+ 'api' => $url('PINTEREST_API', 'https://api.pinterest.com/v5'),],'bluesky' => ['enabled' => env('BLUESKY_ENABLED', true),- 'public_appview' => env('BLUESKY_PUBLIC_APPVIEW', 'https://public.api.bsky.app'),+ 'public_appview' => $url('BLUESKY_PUBLIC_APPVIEW', 'https://public.api.bsky.app'),// Default PDS used when the account has no `meta.service` override.- 'default_service' => env('BLUESKY_DEFAULT_SERVICE', 'https://bsky.social'),+ 'default_service' => $url('BLUESKY_DEFAULT_SERVICE', 'https://bsky.social'),// Web client where published posts are viewed (profile/post URLs).- 'web_app' => env('BLUESKY_WEB_APP', 'https://bsky.app'),+ 'web_app' => $url('BLUESKY_WEB_APP', 'https://bsky.app'),// Video upload service (separate from the PDS). Videos are processed// here, then the resulting blob is embedded in the post record.- 'video_service' => env('BLUESKY_VIDEO_SERVICE', 'https://video.bsky.app'),+ 'video_service' => $url('BLUESKY_VIDEO_SERVICE', 'https://video.bsky.app'),'video_service_did' => env('BLUESKY_VIDEO_SERVICE_DID', 'did:web:video.bsky.app'),// Seconds between transcode job-status polls.'video_poll_seconds' => env('BLUESKY_VIDEO_POLL_SECONDS', 2),@@ -554,20 +562,20 @@ return [// Bluesky rejects videos over 300 MB (app.bsky.embed.video maxSize = 300000000).'video_max_bytes' => env('BLUESKY_VIDEO_MAX_BYTES', 300_000_000),// PLC directory, used to resolve an account's real PDS host from its DID.- 'plc_directory' => env('BLUESKY_PLC_DIRECTORY', 'https://plc.directory'),+ 'plc_directory' => $url('BLUESKY_PLC_DIRECTORY', 'https://plc.directory'),],'mastodon' => ['enabled' => env('MASTODON_ENABLED', true),// Default instance used when the account has no `meta.instance` override.- 'default_instance' => env('MASTODON_DEFAULT_INSTANCE', 'https://mastodon.social'),+ 'default_instance' => $url('MASTODON_DEFAULT_INSTANCE', 'https://mastodon.social'),],'telegram' => ['enabled' => env('TELEGRAM_ENABLED', true),// Single shared bot (BotFather). Users add it as admin to their channel.'bot_token' => env('TELEGRAM_BOT_TOKEN'),'bot_username' => env('TELEGRAM_BOT_USERNAME'),- 'deep_link' => env('TELEGRAM_DEEP_LINK', 'https://t.me'),- 'api' => env('TELEGRAM_API', 'https://api.telegram.org'),+ 'deep_link' => $url('TELEGRAM_DEEP_LINK', 'https://t.me'),+ 'api' => $url('TELEGRAM_API', 'https://api.telegram.org'),// Secret-token header Telegram echoes on every webhook call.'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),],@@ -577,8 +585,8 @@ return [// bot to the user's server; channel listing, mentions and posting all// use this bot token, not the user's OAuth token.'bot_token' => env('DISCORD_BOT_TOKEN'),- 'api' => env('DISCORD_API', 'https://discord.com/api/v10'),- 'oauth_api' => env('DISCORD_OAUTH_API', 'https://discord.com/api/oauth2'),+ 'api' => $url('DISCORD_API', 'https://discord.com/api/v10'),+ 'oauth_api' => $url('DISCORD_OAUTH_API', 'https://discord.com/api/oauth2'),// Permission bitfield requested for the bot: VIEW_CHANNEL (1<<10) +// SEND_MESSAGES (1<<11) + EMBED_LINKS (1<<14) + ATTACH_FILES (1<<15) +// READ_MESSAGE_HISTORY (1<<16) + MENTION_EVERYONE (1<<17) = 248832.@@ -588,15 +596,15 @@ return ['google_business' => ['enabled' => env('GOOGLE_BUSINESS_ENABLED', true),// Account Management API — lists the Business accounts a user administers.- 'account_management_api' => env('GOOGLE_BUSINESS_ACCOUNT_MANAGEMENT_API', 'https://mybusinessaccountmanagement.googleapis.com/v1'),+ 'account_management_api' => $url('GOOGLE_BUSINESS_ACCOUNT_MANAGEMENT_API', 'https://mybusinessaccountmanagement.googleapis.com/v1'),// Business Information API — lists locations under an account.- 'business_information_api' => env('GOOGLE_BUSINESS_BUSINESS_INFORMATION_API', 'https://mybusinessbusinessinformation.googleapis.com/v1'),+ 'business_information_api' => $url('GOOGLE_BUSINESS_BUSINESS_INFORMATION_API', 'https://mybusinessbusinessinformation.googleapis.com/v1'),// Legacy but still-active v4 API — the only home for Local Post create/update/delete.- 'local_posts_api' => env('GOOGLE_BUSINESS_LOCAL_POSTS_API', 'https://mybusiness.googleapis.com/v4'),+ 'local_posts_api' => $url('GOOGLE_BUSINESS_LOCAL_POSTS_API', 'https://mybusiness.googleapis.com/v4'),// OAuth token endpoint, same host Google uses for every OAuth2 client.- 'oauth_api' => env('GOOGLE_BUSINESS_OAUTH_API', 'https://oauth2.googleapis.com'),+ 'oauth_api' => $url('GOOGLE_BUSINESS_OAUTH_API', 'https://oauth2.googleapis.com'),// Business Profile web UI — post URL fallback and the social-account profile link.- 'dashboard' => env('GOOGLE_BUSINESS_DASHBOARD', 'https://business.google.com'),+ 'dashboard' => $url('GOOGLE_BUSINESS_DASHBOARD', 'https://business.google.com'),],],diff --git a/database/factories/AnalyticsPublicationFactory.php b/database/factories/AnalyticsPublicationFactory.phpindex e8c9ddd44..2a6623178 100644--- a/database/factories/AnalyticsPublicationFactory.php+++ b/database/factories/AnalyticsPublicationFactory.php@@ -44,8 +44,8 @@ class AnalyticsPublicationFactory extends Factory'account_display_name' => fake()->name(),'account_username' => fake()->userName(),'account_avatar_url' => fake()->imageUrl(),- 'first_seen_at' => now(),- 'last_seen_at' => now(),+ 'first_seen_at' => now()->subHour(),+ 'last_seen_at' => now()->subHour(),'provider_synced_at' => now(),'provider_metadata' => null,];diff --git a/database/factories/PostFactory.php b/database/factories/PostFactory.phpindex 61e6ed4e1..98fef8544 100644--- a/database/factories/PostFactory.php+++ b/database/factories/PostFactory.php@@ -98,6 +98,16 @@ class PostFactory extends Factory]);}+ /**+ * Published, then deleted on the network.+ */+ public function deletedOnNetwork(): static+ {+ return $this->published()->state(fn (array $attributes) => [+ 'publish_status' => PublishStatus::Deleted,+ ]);+ }+public function imported(): static{return $this->state(fn (array $attributes) => [diff --git a/docker/.env.docker.example b/docker/.env.docker.exampleindex 5e6ca99c2..b2515ca37 100644--- a/docker/.env.docker.example+++ b/docker/.env.docker.example@@ -198,7 +198,7 @@ NIGHTWATCH_TOKEN=UNSPLASH_ACCESS_KEY=UNSPLASH_SECRET_KEY=-# Composer media sources (Google Drive, Google Photos, Canva). Step-by-step setup: MEDIA_INTEGRATIONS_SETUP.md+# Composer media sources (Google Drive, Google Photos, Canva).# Each source is hidden until its flag is on AND its keys are set. Nothing falls back to GOOGLE_CLIENT_ID# or GOOGLE_BUSINESS_*. Canva and Google Photos are Cloud-only in practice (Canva needs an approved public# integration; Photos needs Google verification of a sensitive scope).diff --git a/lang/ar/calendar.php b/lang/ar/calendar.phpindex 4a9ebf45d..df9251aa0 100644--- a/lang/ar/calendar.php+++ b/lang/ar/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'متكرر','publishing' => 'قيد النشر','published' => 'منشور',+ 'deleted' => 'محذوف','failed' => 'فشل',],'status' => [diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex cb5eb9ae1..dbbc8d6bb 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'تعديل التسميات','edit_labels_failed' => 'تعذّر تحديث التسميات. حاول مرة أخرى.',],+ 'deleted_on_network' => [+ 'badge' => 'محذوف',+ 'title' => 'محذوف على :network',+ 'hint' => 'أُزيل بعد نشره، لذلك لم يعد رابطه ولا Insights الخاصة به متاحة.',+ ],'created_by' => 'أنشأه :name :when','welcome' => ['title' => 'مرحبًا بك في TryPost 👋',diff --git a/lang/ar/webhooks.php b/lang/ar/webhooks.phpindex 8695382bd..3d3908aaf 100644--- a/lang/ar/webhooks.php+++ b/lang/ar/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'نُشر المنشور جزئيًا','post_failed' => 'فشل المنشور','post_deleted' => 'تم حذف المنشور',+ 'post_deleted_on_network' => 'حُذف المنشور على الشبكة',+ 'post_restored' => 'عاد المنشور إلى الشبكة',],'event_descriptions' => ['post_created' => 'عند إنشاء منشور جديد.',@@ -98,6 +100,8 @@ return ['post_published' => 'عند نشر منشور على قناة.','post_failed' => 'عند فشل نشر منشور.','post_deleted' => 'عند حذف منشور.',+ 'post_deleted_on_network' => 'عند حذف منشور على شبكته بعد نشره.',+ 'post_restored' => 'عند عودة منشور محذوف إلى شبكته.',],'http_reasons' => ['unknown' => 'غير معروف',diff --git a/lang/de/calendar.php b/lang/de/calendar.phpindex 3eed9a386..d6748f79c 100644--- a/lang/de/calendar.php+++ b/lang/de/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Wiederkehrend','publishing' => 'Wird veröffentlicht','published' => 'Veröffentlicht',+ 'deleted' => 'Gelöscht','failed' => 'Fehlgeschlagen',],'status' => [diff --git a/lang/de/posts.php b/lang/de/posts.phpindex d8e7f69bc..a066ea139 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Labels bearbeiten','edit_labels_failed' => 'Labels konnten nicht aktualisiert werden. Versuche es erneut.',],+ 'deleted_on_network' => [+ 'badge' => 'Gelöscht',+ 'title' => 'Auf :network gelöscht',+ 'hint' => 'Er wurde nach der Veröffentlichung entfernt, daher sind Link und Insights nicht mehr verfügbar.',+ ],'created_by' => 'Erstellt von :name :when','welcome' => ['title' => 'Willkommen bei TryPost 👋',diff --git a/lang/de/webhooks.php b/lang/de/webhooks.phpindex e28f490f7..cf73712e2 100644--- a/lang/de/webhooks.php+++ b/lang/de/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Beitrag teilweise veröffentlicht','post_failed' => 'Beitrag fehlgeschlagen','post_deleted' => 'Beitrag gelöscht',+ 'post_deleted_on_network' => 'Beitrag im Netzwerk gelöscht',+ 'post_restored' => 'Beitrag wieder im Netzwerk',],'event_descriptions' => ['post_created' => 'Wenn ein neuer Beitrag erstellt wird.',@@ -98,6 +100,8 @@ return ['post_published' => 'Wenn ein Beitrag auf einem Kanal live geht.','post_failed' => 'Wenn ein Beitrag nicht veröffentlicht werden kann.','post_deleted' => 'Wenn ein Beitrag gelöscht wird.',+ 'post_deleted_on_network' => 'Wenn ein Beitrag in seinem Netzwerk gelöscht wird.',+ 'post_restored' => 'Wenn ein gelöschter Beitrag wieder im Netzwerk ist.',],'http_reasons' => ['unknown' => 'Unbekannt',diff --git a/lang/el/calendar.php b/lang/el/calendar.phpindex 13ec6a4b1..2017b4244 100644--- a/lang/el/calendar.php+++ b/lang/el/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Επαναλαμβανόμενη','publishing' => 'Δημοσιεύεται','published' => 'Δημοσιεύτηκε',+ 'deleted' => 'Διαγράφηκε','failed' => 'Απέτυχε',],'status' => [diff --git a/lang/el/posts.php b/lang/el/posts.phpindex 68d52a600..c7c49741d 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Επεξεργασία ετικετών','edit_labels_failed' => 'Δεν ήταν δυνατή η ενημέρωση των ετικετών. Δοκιμάστε ξανά.',],+ 'deleted_on_network' => [+ 'badge' => 'Διαγράφηκε',+ 'title' => 'Διαγράφηκε στο :network',+ 'hint' => 'Αφαιρέθηκε μετά τη δημοσίευση, οπότε ο σύνδεσμος και τα στατιστικά της δεν είναι πλέον διαθέσιμα.',+ ],'created_by' => 'Δημιουργήθηκε από :name :when','welcome' => ['title' => 'Καλώς ήρθες στο TryPost 👋',diff --git a/lang/el/webhooks.php b/lang/el/webhooks.phpindex 7587498aa..c27338ec5 100644--- a/lang/el/webhooks.php+++ b/lang/el/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Μερική δημοσίευση','post_failed' => 'Η ανάρτηση απέτυχε','post_deleted' => 'Η ανάρτηση διαγράφηκε',+ 'post_deleted_on_network' => 'Η ανάρτηση διαγράφηκε στο δίκτυο',+ 'post_restored' => 'Η ανάρτηση επανήλθε στο δίκτυο',],'event_descriptions' => ['post_created' => 'Όταν δημιουργείται μια νέα ανάρτηση.',@@ -98,6 +100,8 @@ return ['post_published' => 'Όταν μια ανάρτηση δημοσιεύεται σε ένα κανάλι.','post_failed' => 'Όταν μια ανάρτηση αποτυγχάνει να δημοσιευτεί.','post_deleted' => 'Όταν διαγράφεται μια ανάρτηση.',+ 'post_deleted_on_network' => 'Όταν μια ανάρτηση διαγράφεται στο δίκτυό της.',+ 'post_restored' => 'Όταν μια διαγραμμένη ανάρτηση επανέρχεται στο δίκτυο.',],'http_reasons' => ['unknown' => 'Άγνωστο',diff --git a/lang/en/calendar.php b/lang/en/calendar.phpindex 894281057..5f01de648 100644--- a/lang/en/calendar.php+++ b/lang/en/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Recurring','publishing' => 'Publishing','published' => 'Published',+ 'deleted' => 'Deleted','failed' => 'Failed',],'status' => [diff --git a/lang/en/posts.php b/lang/en/posts.phpindex 7a23c8ad9..6ffda5b67 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Edit labels','edit_labels_failed' => 'Couldn\'t update labels. Try again.',],+ 'deleted_on_network' => [+ 'badge' => 'Deleted',+ 'title' => 'Deleted on :network',+ 'hint' => 'It was removed after it was published, so its link and insights are no longer available.',+ ],'created_by' => 'Created by :name :when','welcome' => ['title' => 'Welcome to TryPost 👋',diff --git a/lang/en/webhooks.php b/lang/en/webhooks.phpindex 1cd83d8d8..ee76c0a00 100644--- a/lang/en/webhooks.php+++ b/lang/en/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post partially published','post_failed' => 'Post failed','post_deleted' => 'Post deleted',+ 'post_deleted_on_network' => 'Post deleted on network',+ 'post_restored' => 'Post back on network',],'event_descriptions' => ['post_created' => 'When a new post is created.',@@ -98,6 +100,8 @@ return ['post_published' => 'When a post goes live on a channel.','post_failed' => 'When a post fails to publish.','post_deleted' => 'When a post is deleted.',+ 'post_deleted_on_network' => 'When a published post is deleted on its network.',+ 'post_restored' => 'When a post marked deleted is back on its network.',],'http_reasons' => ['unknown' => 'Unknown',diff --git a/lang/es/calendar.php b/lang/es/calendar.phpindex 3de20e401..46d6c4120 100644--- a/lang/es/calendar.php+++ b/lang/es/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Recurrente','publishing' => 'Publicando','published' => 'Publicado',+ 'deleted' => 'Eliminado','failed' => 'Fallido',],'status' => [diff --git a/lang/es/posts.php b/lang/es/posts.phpindex 4bee2ecf6..3b4c44d83 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -1068,6 +1068,11 @@ return ['edit_labels' => 'Editar etiquetas','edit_labels_failed' => 'No se pudieron actualizar las etiquetas. Inténtalo de nuevo.',],+ 'deleted_on_network' => [+ 'badge' => 'Eliminado',+ 'title' => 'Eliminado en :network',+ 'hint' => 'Se eliminó después de publicarse, así que su enlace y sus insights ya no están disponibles.',+ ],'created_by' => 'Creado por :name :when','welcome' => ['title' => 'Bienvenido a TryPost 👋',diff --git a/lang/es/webhooks.php b/lang/es/webhooks.phpindex 0a49be334..883ab8e9b 100644--- a/lang/es/webhooks.php+++ b/lang/es/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post parcialmente publicado','post_failed' => 'Post fallido','post_deleted' => 'Post eliminado',+ 'post_deleted_on_network' => 'Post eliminado en la red',+ 'post_restored' => 'Post de vuelta en la red',],'event_descriptions' => ['post_created' => 'Cuando se crea un nuevo post.',@@ -98,6 +100,8 @@ return ['post_published' => 'Cuando un post se publica en un canal.','post_failed' => 'Cuando un post no se puede publicar.','post_deleted' => 'Cuando se elimina un post.',+ 'post_deleted_on_network' => 'Cuando un post publicado se elimina en su red.',+ 'post_restored' => 'Cuando un post marcado como eliminado vuelve a su red.',],'http_reasons' => ['unknown' => 'Desconocido',diff --git a/lang/fr/calendar.php b/lang/fr/calendar.phpindex c98c9995a..4f0280303 100644--- a/lang/fr/calendar.php+++ b/lang/fr/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Récurrent','publishing' => 'Publication en cours','published' => 'Publiée',+ 'deleted' => 'Supprimée','failed' => 'Échec',],'status' => [diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex 652dbed4a..13a5fb380 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Modifier les étiquettes','edit_labels_failed' => 'Impossible de mettre à jour les étiquettes. Réessayez.',],+ 'deleted_on_network' => [+ 'badge' => 'Supprimée',+ 'title' => 'Supprimée sur :network',+ 'hint' => 'Elle a été retirée après sa publication : son lien et ses statistiques ne sont plus disponibles.',+ ],'created_by' => 'Créé par :name :when','welcome' => ['title' => 'Bienvenue sur TryPost 👋',diff --git a/lang/fr/webhooks.php b/lang/fr/webhooks.phpindex 7d5c9aad8..8b017ae18 100644--- a/lang/fr/webhooks.php+++ b/lang/fr/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Publication partiellement publiée','post_failed' => 'Échec de publication','post_deleted' => 'Publication supprimée',+ 'post_deleted_on_network' => 'Publication retirée du réseau',+ 'post_restored' => 'Publication revenue sur le réseau',],'event_descriptions' => ['post_created' => 'Quand une publication est créée.',@@ -98,6 +100,8 @@ return ['post_published' => 'Quand une publication est en ligne sur un canal.','post_failed' => 'Quand une publication échoue.','post_deleted' => 'Quand une publication est supprimée.',+ 'post_deleted_on_network' => 'Quand une publication est supprimée sur son réseau.',+ 'post_restored' => 'Quand une publication supprimée revient sur le réseau.',],'http_reasons' => ['unknown' => 'Inconnu',diff --git a/lang/it/calendar.php b/lang/it/calendar.phpindex 68989d06a..b68298ed6 100644--- a/lang/it/calendar.php+++ b/lang/it/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Ricorrente','publishing' => 'In pubblicazione','published' => 'Pubblicato',+ 'deleted' => 'Eliminato','failed' => 'Non riuscito',],'status' => [diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 2dcad2943..bccbe772c 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Modifica etichette','edit_labels_failed' => 'Impossibile aggiornare le etichette. Riprova.',],+ 'deleted_on_network' => [+ 'badge' => 'Eliminato',+ 'title' => 'Eliminato su :network',+ 'hint' => 'È stato rimosso dopo la pubblicazione, quindi il link e gli insight non sono più disponibili.',+ ],'created_by' => 'Creato da :name :when','welcome' => ['title' => 'Benvenuto su TryPost 👋',diff --git a/lang/it/webhooks.php b/lang/it/webhooks.phpindex 456a3ec30..6fb06652a 100644--- a/lang/it/webhooks.php+++ b/lang/it/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post pubblicato parzialmente','post_failed' => 'Post non riuscito','post_deleted' => 'Post eliminato',+ 'post_deleted_on_network' => 'Post eliminato sulla rete',+ 'post_restored' => 'Post di nuovo sulla rete',],'event_descriptions' => ['post_created' => 'Quando viene creato un nuovo post.',@@ -98,6 +100,8 @@ return ['post_published' => 'Quando un post va online su un canale.','post_failed' => 'Quando la pubblicazione di un post non riesce.','post_deleted' => 'Quando un post viene eliminato.',+ 'post_deleted_on_network' => 'Quando un post pubblicato viene eliminato sulla rete.',+ 'post_restored' => 'Quando un post eliminato torna sulla sua rete.',],'http_reasons' => ['unknown' => 'Sconosciuto',diff --git a/lang/ja/calendar.php b/lang/ja/calendar.phpindex e204208ab..10d42d077 100644--- a/lang/ja/calendar.php+++ b/lang/ja/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => '繰り返し','publishing' => '公開中','published' => '公開済み',+ 'deleted' => '削除済み','failed' => '失敗',],'status' => [diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex 748223f88..16839da5c 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'ラベルを編集','edit_labels_failed' => 'ラベルを更新できませんでした。もう一度お試しください。',],+ 'deleted_on_network' => [+ 'badge' => '削除済み',+ 'title' => ':network で削除済み',+ 'hint' => '公開後に削除されたため、リンクと Insights は利用できなくなりました。',+ ],'created_by' => '作成者: :name :when','welcome' => ['title' => 'TryPostへようこそ 👋',diff --git a/lang/ja/webhooks.php b/lang/ja/webhooks.phpindex 7ff7d14f2..321fa2720 100644--- a/lang/ja/webhooks.php+++ b/lang/ja/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => '一部公開','post_failed' => '投稿に失敗','post_deleted' => '投稿を削除',+ 'post_deleted_on_network' => 'ネットワークで投稿を削除',+ 'post_restored' => '投稿がネットワークに復帰',],'event_descriptions' => ['post_created' => '新しい投稿が作成されたとき。',@@ -98,6 +100,8 @@ return ['post_published' => '投稿がチャンネルで公開されたとき。','post_failed' => '投稿の公開に失敗したとき。','post_deleted' => '投稿が削除されたとき。',+ 'post_deleted_on_network' => '公開済みの投稿がネットワークで削除されたとき。',+ 'post_restored' => '削除された投稿がネットワークに再び表示されたとき。',],'http_reasons' => ['unknown' => '不明',diff --git a/lang/ko/calendar.php b/lang/ko/calendar.phpindex 0bbc56121..9e1d1be9e 100644--- a/lang/ko/calendar.php+++ b/lang/ko/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => '반복','publishing' => '게시 중','published' => '게시됨',+ 'deleted' => '삭제됨','failed' => '실패',],'status' => [diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex 6de1ad404..cdf398e94 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => '라벨 편집','edit_labels_failed' => '라벨을 업데이트하지 못했습니다. 다시 시도해 주세요.',],+ 'deleted_on_network' => [+ 'badge' => '삭제됨',+ 'title' => ':network에서 삭제됨',+ 'hint' => '게시 후 삭제되어 링크와 Insights를 더 이상 사용할 수 없습니다.',+ ],'created_by' => '작성자: :name :when','welcome' => ['title' => 'TryPost에 오신 것을 환영합니다 👋',diff --git a/lang/ko/webhooks.php b/lang/ko/webhooks.phpindex 67cd2cd23..368fadb81 100644--- a/lang/ko/webhooks.php+++ b/lang/ko/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => '부분 게시됨','post_failed' => '게시 실패','post_deleted' => '게시물 삭제됨',+ 'post_deleted_on_network' => '네트워크에서 게시물 삭제됨',+ 'post_restored' => '게시물이 네트워크에 복귀함',],'event_descriptions' => ['post_created' => '새 게시물이 생성될 때.',@@ -98,6 +100,8 @@ return ['post_published' => '게시물이 채널에 게시될 때.','post_failed' => '게시물 게시에 실패할 때.','post_deleted' => '게시물이 삭제될 때.',+ 'post_deleted_on_network' => '게시된 게시물이 네트워크에서 삭제될 때.',+ 'post_restored' => '삭제된 게시물이 네트워크에 다시 표시될 때.',],'http_reasons' => ['unknown' => '알 수 없음',diff --git a/lang/nl/calendar.php b/lang/nl/calendar.phpindex 1a337d575..a39eae51a 100644--- a/lang/nl/calendar.php+++ b/lang/nl/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Terugkerend','publishing' => 'Publiceren','published' => 'Gepubliceerd',+ 'deleted' => 'Verwijderd','failed' => 'Mislukt',],'status' => [diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex d8d3a8d8b..c50326ce3 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Labels bewerken','edit_labels_failed' => 'Labels konden niet worden bijgewerkt. Probeer het opnieuw.',],+ 'deleted_on_network' => [+ 'badge' => 'Verwijderd',+ 'title' => 'Verwijderd op :network',+ 'hint' => 'Hij is na publicatie verwijderd, dus de link en de berichtinzichten zijn niet meer beschikbaar.',+ ],'created_by' => 'Gemaakt door :name :when','welcome' => ['title' => 'Welkom bij TryPost 👋',diff --git a/lang/nl/webhooks.php b/lang/nl/webhooks.phpindex b7a48786f..a2ca4495f 100644--- a/lang/nl/webhooks.php+++ b/lang/nl/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post gedeeltelijk gepubliceerd','post_failed' => 'Post mislukt','post_deleted' => 'Post verwijderd',+ 'post_deleted_on_network' => 'Post verwijderd op netwerk',+ 'post_restored' => 'Post terug op netwerk',],'event_descriptions' => ['post_created' => 'Wanneer een nieuwe post wordt aangemaakt.',@@ -98,6 +100,8 @@ return ['post_published' => 'Wanneer een post live gaat op een kanaal.','post_failed' => 'Wanneer het publiceren van een post mislukt.','post_deleted' => 'Wanneer een post wordt verwijderd.',+ 'post_deleted_on_network' => 'Wanneer een post op zijn netwerk wordt verwijderd.',+ 'post_restored' => 'Wanneer een verwijderde post terug is op zijn netwerk.',],'http_reasons' => ['unknown' => 'Onbekend',diff --git a/lang/pl/calendar.php b/lang/pl/calendar.phpindex 9d02fa836..8e13f728f 100644--- a/lang/pl/calendar.php+++ b/lang/pl/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Cykliczny','publishing' => 'Publikowanie','published' => 'Opublikowany',+ 'deleted' => 'Usunięto','failed' => 'Nieudany',],'status' => [diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex d303d171a..2cd6e7601 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Edytuj etykiety','edit_labels_failed' => 'Nie udało się zaktualizować etykiet. Spróbuj ponownie.',],+ 'deleted_on_network' => [+ 'badge' => 'Usunięto',+ 'title' => 'Usunięto na :network',+ 'hint' => 'Został usunięty po publikacji, więc jego link i statystyki nie są już dostępne.',+ ],'created_by' => 'Utworzone przez :name :when','welcome' => ['title' => 'Witaj w TryPost 👋',diff --git a/lang/pl/webhooks.php b/lang/pl/webhooks.phpindex d32f9f7ab..bc3adf345 100644--- a/lang/pl/webhooks.php+++ b/lang/pl/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post częściowo opublikowany','post_failed' => 'Post nieudany','post_deleted' => 'Post usunięty',+ 'post_deleted_on_network' => 'Post usunięty w sieci',+ 'post_restored' => 'Post wrócił do sieci',],'event_descriptions' => ['post_created' => 'Gdy zostanie utworzony nowy post.',@@ -98,6 +100,8 @@ return ['post_published' => 'Gdy post zostanie opublikowany na kanale.','post_failed' => 'Gdy publikacja posta się nie powiedzie.','post_deleted' => 'Gdy post zostanie usunięty.',+ 'post_deleted_on_network' => 'Gdy opublikowany post zostanie usunięty w sieci.',+ 'post_restored' => 'Gdy usunięty post wróci do swojej sieci.',],'http_reasons' => ['unknown' => 'Nieznany',diff --git a/lang/pt-BR/calendar.php b/lang/pt-BR/calendar.phpindex 5c19ff6d2..5ca3a0267 100644--- a/lang/pt-BR/calendar.php+++ b/lang/pt-BR/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Recorrente','publishing' => 'Publicando','published' => 'Publicado',+ 'deleted' => 'Excluído','failed' => 'Falhou',],'status' => [diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex e7580b9e0..cf31415b5 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Editar labels','edit_labels_failed' => 'Não foi possível atualizar as labels. Tente novamente.',],+ 'deleted_on_network' => [+ 'badge' => 'Excluído',+ 'title' => 'Excluído no :network',+ 'hint' => 'Foi removido depois de publicado, então o link e os insights dele não estão mais disponíveis.',+ ],'created_by' => 'Criado por :name :when','welcome' => ['title' => 'Boas-vindas ao TryPost 👋',diff --git a/lang/pt-BR/webhooks.php b/lang/pt-BR/webhooks.phpindex e8a67001f..2c8ac7311 100644--- a/lang/pt-BR/webhooks.php+++ b/lang/pt-BR/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Post parcialmente publicado','post_failed' => 'Post falhou','post_deleted' => 'Post excluído',+ 'post_deleted_on_network' => 'Post excluído na rede',+ 'post_restored' => 'Post de volta na rede',],'event_descriptions' => ['post_created' => 'Quando um novo post é criado.',@@ -98,6 +100,8 @@ return ['post_published' => 'Quando um post é publicado em um canal.','post_failed' => 'Quando um post falha ao publicar.','post_deleted' => 'Quando um post é excluído.',+ 'post_deleted_on_network' => 'Quando um post publicado é excluído na rede.',+ 'post_restored' => 'Quando um post marcado como excluído volta à rede.',],'http_reasons' => ['unknown' => 'Desconhecido',diff --git a/lang/ru/calendar.php b/lang/ru/calendar.phpindex 39b33c192..f620ea1b5 100644--- a/lang/ru/calendar.php+++ b/lang/ru/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Повторяется','publishing' => 'Публикуется','published' => 'Опубликован',+ 'deleted' => 'Удалён','failed' => 'Ошибка',],'status' => [diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex d482e056c..89ac3bff9 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Изменить метки','edit_labels_failed' => 'Не удалось обновить метки. Попробуйте ещё раз.',],+ 'deleted_on_network' => [+ 'badge' => 'Удалён',+ 'title' => 'Удалён в :network',+ 'hint' => 'Его удалили после публикации, поэтому ссылка и Insights больше недоступны.',+ ],'created_by' => 'Создано: :name :when','welcome' => ['title' => 'Добро пожаловать в TryPost 👋',diff --git a/lang/ru/webhooks.php b/lang/ru/webhooks.phpindex 9520180e5..f517849e5 100644--- a/lang/ru/webhooks.php+++ b/lang/ru/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Пост частично опубликован','post_failed' => 'Ошибка публикации','post_deleted' => 'Пост удалён',+ 'post_deleted_on_network' => 'Пост удалён в сети',+ 'post_restored' => 'Пост снова в сети',],'event_descriptions' => ['post_created' => 'Когда создаётся новый пост.',@@ -98,6 +100,8 @@ return ['post_published' => 'Когда пост публикуется в канале.','post_failed' => 'Когда пост не удаётся опубликовать.','post_deleted' => 'Когда пост удалён.',+ 'post_deleted_on_network' => 'Когда опубликованный пост удалён в сети.',+ 'post_restored' => 'Когда удалённый пост снова появился в сети.',],'http_reasons' => ['unknown' => 'Неизвестно',diff --git a/lang/tr/calendar.php b/lang/tr/calendar.phpindex 89e68b4ed..e97fc8c4a 100644--- a/lang/tr/calendar.php+++ b/lang/tr/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Yinelenen','publishing' => 'Yayınlanıyor','published' => 'Yayınlandı',+ 'deleted' => 'Silindi','failed' => 'Başarısız',],'status' => [diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex 492858198..358c4e732 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Etiketleri düzenle','edit_labels_failed' => 'Etiketler güncellenemedi. Tekrar deneyin.',],+ 'deleted_on_network' => [+ 'badge' => 'Silindi',+ 'title' => ':network üzerinde silindi',+ 'hint' => 'Yayınlandıktan sonra kaldırıldı, bu yüzden bağlantısı ve Insights verileri artık kullanılamıyor.',+ ],'created_by' => 'Oluşturan: :name :when','welcome' => ['title' => 'TryPost\'a hoş geldin 👋',diff --git a/lang/tr/webhooks.php b/lang/tr/webhooks.phpindex 1ee9a6719..8ae308643 100644--- a/lang/tr/webhooks.php+++ b/lang/tr/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Gönderi kısmen yayınlandı','post_failed' => 'Gönderi başarısız','post_deleted' => 'Gönderi silindi',+ 'post_deleted_on_network' => 'Gönderi ağda silindi',+ 'post_restored' => 'Gönderi ağa geri döndü',],'event_descriptions' => ['post_created' => 'Yeni bir gönderi oluşturulduğunda.',@@ -98,6 +100,8 @@ return ['post_published' => 'Bir gönderi bir kanalda yayınlandığında.','post_failed' => 'Bir gönderi yayınlanamadığında.','post_deleted' => 'Bir gönderi silindiğinde.',+ 'post_deleted_on_network' => 'Yayınlanmış bir gönderi ağında silindiğinde.',+ 'post_restored' => 'Silinen bir gönderi ağına geri döndüğünde.',],'http_reasons' => ['unknown' => 'Bilinmiyor',diff --git a/lang/uk/calendar.php b/lang/uk/calendar.phpindex d2f5f7184..79fc47b76 100644--- a/lang/uk/calendar.php+++ b/lang/uk/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => 'Повторюваний','publishing' => 'Публікується','published' => 'Опубліковано',+ 'deleted' => 'Видалено','failed' => 'Помилка',],'status' => [diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex a32fa654c..aa1d9eaf4 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => 'Редагувати мітки','edit_labels_failed' => 'Не вдалося оновити мітки. Спробуйте ще раз.',],+ 'deleted_on_network' => [+ 'badge' => 'Видалено',+ 'title' => 'Видалено в :network',+ 'hint' => 'Його видалили після публікації, тому посилання та Insights більше недоступні.',+ ],'created_by' => 'Створено: :name :when','welcome' => ['title' => 'Вітаємо в TryPost 👋',diff --git a/lang/uk/webhooks.php b/lang/uk/webhooks.phpindex 5538af5a4..ceafb2540 100644--- a/lang/uk/webhooks.php+++ b/lang/uk/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => 'Пост частково опубліковано','post_failed' => 'Помилка публікації','post_deleted' => 'Пост видалено',+ 'post_deleted_on_network' => 'Пост видалено в мережі',+ 'post_restored' => 'Пост знову в мережі',],'event_descriptions' => ['post_created' => 'Коли створено новий пост.',@@ -98,6 +100,8 @@ return ['post_published' => 'Коли пост опубліковано в каналі.','post_failed' => 'Коли пост не вдалося опублікувати.','post_deleted' => 'Коли пост видалено.',+ 'post_deleted_on_network' => 'Коли опублікований пост видалено в мережі.',+ 'post_restored' => 'Коли видалений пост знову з’явився в мережі.',],'http_reasons' => ['unknown' => 'Невідомо',diff --git a/lang/zh/calendar.php b/lang/zh/calendar.phpindex 871392ec2..d316cf27b 100644--- a/lang/zh/calendar.php+++ b/lang/zh/calendar.php@@ -23,6 +23,7 @@ return ['recurring' => '重复','publishing' => '发布中','published' => '已发布',+ 'deleted' => '已删除','failed' => '已失败',],'status' => [diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex 07370d4af..22d72e9cc 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -1067,6 +1067,11 @@ return ['edit_labels' => '编辑标签','edit_labels_failed' => '无法更新标签。请重试。',],+ 'deleted_on_network' => [+ 'badge' => '已删除',+ 'title' => '已在 :network 删除',+ 'hint' => '该帖子发布后已被删除,链接和 Insights 不再可用。',+ ],'created_by' => '创建者::name :when','welcome' => ['title' => '欢迎使用 TryPost 👋',diff --git a/lang/zh/webhooks.php b/lang/zh/webhooks.phpindex 176f305c8..83038d958 100644--- a/lang/zh/webhooks.php+++ b/lang/zh/webhooks.php@@ -90,6 +90,8 @@ return ['post_partially_published' => '帖子部分发布','post_failed' => '帖子失败','post_deleted' => '帖子已删除',+ 'post_deleted_on_network' => '帖子已在网络上删除',+ 'post_restored' => '帖子已回到网络',],'event_descriptions' => ['post_created' => '创建新帖子时。',@@ -98,6 +100,8 @@ return ['post_published' => '帖子在频道上发布时。','post_failed' => '帖子发布失败时。','post_deleted' => '帖子被删除时。',+ 'post_deleted_on_network' => '已发布的帖子在网络上被删除时。',+ 'post_restored' => '已删除的帖子重新出现在网络上时。',],'http_reasons' => ['unknown' => '未知',diff --git a/resources/js/components/publish/CalendarPostChip.vue b/resources/js/components/publish/CalendarPostChip.vueindex 631b079f3..626467708 100644--- a/resources/js/components/publish/CalendarPostChip.vue+++ b/resources/js/components/publish/CalendarPostChip.vue@@ -9,6 +9,7 @@ import {IconPlayerPlayFilled,IconRepeat,IconSend,+ IconTrashX,} from '@tabler/icons-vue';import { computed, nextTick, ref, type Component } from 'vue';@@ -23,6 +24,7 @@ import { useCalendarDragContext } from '@/composables/calendar/useCalendarDrag';import { getPlatformLabel } from '@/composables/usePlatformLogo';import date from '@/date';import { isImage, isVideo } from '@/lib/mediaType';+import { isDeletedOnNetwork } from '@/lib/postNetwork';import { htmlToPlainText } from '@/lib/utils';import { videoFrameUrl } from '@/lib/videoFrame';import { PostStatus, ScheduleMode } from '@/types/post';@@ -100,6 +102,7 @@ type StatusKey =| 'recurring'| 'publishing'| 'published'+ | 'deleted'| 'failed';interface StatusMarker {@@ -116,10 +119,15 @@ const STATUS_MARKERS: Record<StatusKey, StatusMarker> = {recurring: { icon: IconRepeat, tone: 'text-muted-foreground', testId: 'calendar-post-recurring' },publishing: { icon: IconSend, tone: 'text-muted-foreground', testId: 'calendar-post-publishing' },published: { icon: IconCircleCheck, tone: 'text-success', testId: 'calendar-post-published' },+ deleted: { icon: IconTrashX, tone: 'text-destructive', testId: 'calendar-post-deleted' },failed: { icon: IconAlertCircle, tone: 'text-destructive', testId: 'calendar-post-failed' },};const statusKey = computed((): StatusKey => {+ if (isDeletedOnNetwork(props.post)) {+ return 'deleted';+ }+const { status, schedule_mode, recurrence_frequency } = props.post;if (status !== PostStatus.Scheduled) {diff --git a/resources/js/components/publish/PostCardMenu.vue b/resources/js/components/publish/PostCardMenu.vueindex b569159e4..62218a929 100644--- a/resources/js/components/publish/PostCardMenu.vue+++ b/resources/js/components/publish/PostCardMenu.vue@@ -25,6 +25,7 @@ import {} from '@/components/ui/dropdown-menu';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';+import { postPermalink } from '@/lib/postNetwork';import { isRecurring } from '@/lib/recurrence';import { PostStatus, ScheduleMode } from '@/types/post';import type { PostCard, PostCardMenuAction } from '@/types/publish';@@ -124,7 +125,7 @@ const isQueued = computed(<IconArrowsMaximize class="size-4" />{{ $t('posts.show.title') }}</DropdownMenuItem>- <template v-if="post.platform_url">+ <template v-if="postPermalink(post)"><DropdownMenuSeparator /><DropdownMenuItem:data-testid="`post-share-link-${testKey}`"diff --git a/resources/js/components/publish/PostDeletedOnNetworkBadge.vue b/resources/js/components/publish/PostDeletedOnNetworkBadge.vuenew file mode 100644index 000000000..dd5a23555--- /dev/null+++ b/resources/js/components/publish/PostDeletedOnNetworkBadge.vue@@ -0,0 +1,13 @@+<script setup lang="ts">+import { Badge } from '@/components/ui/badge';+import { getDeletedOnNetworkStatusConfig } from '@/composables/usePostStatus';++const status = getDeletedOnNetworkStatusConfig();+</script>++<template>+ <Badge :variant="status.variant" class="h-6 gap-1 px-2 [&>svg]:size-4">+ <component :is="status.icon" />+ {{ status.label }}+ </Badge>+</template>diff --git a/resources/js/components/publish/PostDeletedOnNetworkPopover.vue b/resources/js/components/publish/PostDeletedOnNetworkPopover.vuenew file mode 100644index 000000000..383c769ce--- /dev/null+++ b/resources/js/components/publish/PostDeletedOnNetworkPopover.vue@@ -0,0 +1,55 @@+<script setup lang="ts">+import { computed } from 'vue';++import PostDeletedOnNetworkBadge from '@/components/publish/PostDeletedOnNetworkBadge.vue';+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover';+import { getPlatformLabel } from '@/composables/usePlatformLogo';+import { transform } from '@/lib/helpers';+import type { PostCard } from '@/types/publish';++const props = defineProps<{+ post: PostCard;+ testKey: string;+}>();++const network = computed(() =>+ transform(props.post.platform, getPlatformLabel, ''),+);+</script>++<template>+ <Popover>+ <PopoverTrigger as-child>+ <button+ type="button"+ class="rounded-full focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"+ :aria-label="+ $t('posts.publish.deleted_on_network.title', { network })+ "+ :data-testid="`post-deleted-on-network-${testKey}`"+ >+ <PostDeletedOnNetworkBadge class="cursor-pointer" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ :collision-padding="16"+ class="flex w-80 flex-col gap-2"+ :data-testid="`post-deleted-on-network-popover-${testKey}`"+ >+ <p class="text-sm font-emphasis text-foreground">+ {{ $t('posts.publish.deleted_on_network.title', { network }) }}+ </p>+ <p+ class="text-sm text-foreground"+ :data-testid="`post-deleted-on-network-hint-${testKey}`"+ >+ {{ $t('posts.publish.deleted_on_network.hint') }}+ </p>+ </PopoverContent>+ </Popover>+</template>diff --git a/resources/js/components/publish/PostDetailsDialog.vue b/resources/js/components/publish/PostDetailsDialog.vueindex bee31d732..6fa4d9c36 100644--- a/resources/js/components/publish/PostDetailsDialog.vue+++ b/resources/js/components/publish/PostDetailsDialog.vue@@ -16,6 +16,7 @@ import PlatformBrandIcon from '@/components/PlatformBrandIcon.vue';import ThreadView from '@/components/posts/ThreadView.vue';import PostCardLabels from '@/components/publish/PostCardLabels.vue';import PostCardMenu from '@/components/publish/PostCardMenu.vue';+import PostDeletedOnNetworkBadge from '@/components/publish/PostDeletedOnNetworkBadge.vue';import PostDetailsMedia from '@/components/publish/PostDetailsMedia.vue';import PostMetricsBand from '@/components/publish/PostMetricsBand.vue';import PostPollResults from '@/components/publish/PostPollResults.vue';@@ -35,12 +36,18 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/compimport {getPlatformLabel,} from '@/composables/usePlatformLogo';-import { schedulePostCard } from '@/composables/usePostCardActions';-import { getPostStatusConfig } from '@/composables/usePostStatus';+import {+ schedulePostCard,+} from '@/composables/usePostCardActions';+import {+ getPostCardStatusConfig,+ getPostStatusConfig,+} from '@/composables/usePostStatus';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';import date from '@/date';import dayjs from '@/dayjs';import { filled } from '@/lib/helpers';+import { isDeletedOnNetwork, postPermalink } from '@/lib/postNetwork';import { postThreadOf } from '@/lib/postThread';import { compactPublicationMetrics } from '@/lib/publicationMetrics';import { isRecurring } from '@/lib/recurrence';@@ -134,6 +141,16 @@ const currentStatusConfig = computed(() =>),);+/** Each sibling's status in the rail; a post the network deleted reads as deleted. */+const railStatuses = computed(() =>+ Object.fromEntries(+ siblings.value.map((sibling) => [+ sibling.id,+ getPostCardStatusConfig(sibling),+ ]),+ ),+);+const currentKey = computed(() =>current.value.id === props.post.id ? props.testKey : current.value.id,);@@ -147,7 +164,7 @@ const channel = computed(() =>: null,);-const permalink = computed(() => current.value.platform_url ?? null);+const permalink = computed(() => postPermalink(current.value));const metricsDetail = computed(() => {const detail = current.value.metrics ?? null;@@ -305,10 +322,11 @@ const siblingMoment = (sibling: PostCard): string | null => {:data-status="sibling.status"><component- :is="getPostStatusConfig(sibling.status).icon"- :class="getPostStatusConfig(sibling.status).iconClass"+ :is="railStatuses[sibling.id].icon"+ :class="railStatuses[sibling.id].iconClass"class="size-3.5 shrink-0"- :aria-label="$t(`posts.status.${sibling.status}`)"+ :aria-label="railStatuses[sibling.id].label"+ :data-testid="`post-details-rail-status-icon-${sibling.id}`"/>{{siblingMoment(sibling) ??@@ -338,7 +356,12 @@ const siblingMoment = (sibling: PostCard): string | null => {class="flex flex-wrap items-center gap-2"as="div">+ <PostDeletedOnNetworkBadge+ v-if="isDeletedOnNetwork(current)"+ :data-testid="`post-details-deleted-on-network-${testKey}`"+ /><Badge+ v-else:variant="currentStatusConfig.variant"class="h-6 gap-1 px-2 [&>svg]:size-4":data-testid="`post-details-status-${testKey}`"diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vueindex 4df07451c..3d59749a4 100644--- a/resources/js/components/publish/PostTimelineCard.vue+++ b/resources/js/components/publish/PostTimelineCard.vue@@ -34,6 +34,7 @@ import ApprovePostButton from '@/components/publish/ApprovePostButton.vue';import PostCardLabels from '@/components/publish/PostCardLabels.vue';import PostCardMenu from '@/components/publish/PostCardMenu.vue';import PostCardThread from '@/components/publish/PostCardThread.vue';+import PostDeletedOnNetworkPopover from '@/components/publish/PostDeletedOnNetworkPopover.vue';import PostDetailsDialog from '@/components/publish/PostDetailsDialog.vue';import PostFailurePopover from '@/components/publish/PostFailurePopover.vue';import PostMetricsBand from '@/components/publish/PostMetricsBand.vue';@@ -73,6 +74,7 @@ import date from '@/date';import dayjs from '@/dayjs';import { blank, filled } from '@/lib/helpers';import { isImage, isVideo } from '@/lib/mediaType';+import { isDeletedOnNetwork, postPermalink } from '@/lib/postNetwork';import { postThreadOf } from '@/lib/postThread';import { compactPublicationMetrics } from '@/lib/publicationMetrics';import { recurrenceRuleOf } from '@/lib/recurrence';@@ -285,7 +287,9 @@ const contentTypeKey = computed(() =>: null,);-const permalink = computed(() => props.post.platform_url ?? null);+const deletedOnNetwork = computed(() => isDeletedOnNetwork(props.post));++const permalink = computed(() => postPermalink(props.post));const metricsDetail = computed(() => {const detail = props.post.metrics ?? null;@@ -494,6 +498,11 @@ defineExpose({ openDetails });:mode="scheduleMode"plain/>+ <PostDeletedOnNetworkPopover+ v-if="deletedOnNetwork"+ :post="post"+ :test-key="post.id"+ /><PostFailurePopoverv-if="showStatus && hasFailure":post="post"diff --git a/resources/js/components/publish/PublicationDetailsDialog.vue b/resources/js/components/publish/PublicationDetailsDialog.vueindex 5aca1fb9c..d4ea10812 100644--- a/resources/js/components/publish/PublicationDetailsDialog.vue+++ b/resources/js/components/publish/PublicationDetailsDialog.vue@@ -4,6 +4,7 @@ import { computed, ref } from 'vue';import ChannelAvatar from '@/components/ChannelAvatar.vue';import MediaLightbox from '@/components/media/MediaLightbox.vue';+import PostDeletedOnNetworkBadge from '@/components/publish/PostDeletedOnNetworkBadge.vue';import PostDetailsMedia from '@/components/publish/PostDetailsMedia.vue';import PostMetricsBand from '@/components/publish/PostMetricsBand.vue';import { Badge } from '@/components/ui/badge';@@ -19,7 +20,10 @@ import {import { getPlatformLabel } from '@/composables/usePlatformLogo';import { getPostStatusConfig } from '@/composables/usePostStatus';import date from '@/date';-import type { PublicationAnalyticsDetail } from '@/types/analytics';+import {+ PublicationAvailability,+ type PublicationAnalyticsDetail,+} from '@/types/analytics';import type { MediaItem } from '@/types/media';import { PostStatus } from '@/types/post';@@ -38,6 +42,10 @@ const publication = computed(() => props.detail.publication);const status = getPostStatusConfig(PostStatus.Published);+const isDeletedOnNetwork = computed(+ () => publication.value.availability === PublicationAvailability.Deleted,+);+const accountName = computed(() =>publication.value.account_display_name ||@@ -79,7 +87,12 @@ const openMediaPreview = (): void => {class="flex flex-wrap items-center gap-2"as="div">+ <PostDeletedOnNetworkBadge+ v-if="isDeletedOnNetwork"+ :data-testid="`publication-details-deleted-on-network-${publication.id}`"+ /><Badge+ v-else:variant="status.variant"class="h-6 gap-1 px-2 [&>svg]:size-4">diff --git a/resources/js/components/repurpose/RepurposeItemList.vue b/resources/js/components/repurpose/RepurposeItemList.vueindex 2fff3ce48..a4683a9a9 100644--- a/resources/js/components/repurpose/RepurposeItemList.vue+++ b/resources/js/components/repurpose/RepurposeItemList.vue@@ -13,6 +13,7 @@ import type { Component } from 'vue';import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';import date from '@/date';+import { transform } from '@/lib/helpers';import { edit } from '@/routes/app/posts';import { PublishStatus, type PublishStatusValue } from '@/types/post';import type { RepurposeItem, RepurposeItemPost } from '@/types/repurpose';@@ -33,12 +34,25 @@ const marks: Record<RepurposeItemStatusValue, { icon: Component; class: string }const detail = (item: RepurposeItem): string | null => item.error ?? null;+/** States whose label is not the plain status name. */+const POST_STATE_LABEL_KEYS: Partial<Record<PublishStatusValue, string>> = {+ [PublishStatus.PendingReview]: 'posts.publish.in_google_review',+ [PublishStatus.Deleted]: 'posts.publish.deleted_on_network.badge',+};+const postState = (post: RepurposeItemPost): PublishStatusValue | null =>post.platform? post.publish_status === PublishStatus.Rejected? PublishStatus.Failed: post.publish_status: null;++const postStateLabelKey = (post: RepurposeItemPost): string =>+ transform(+ postState(post),+ (state) => POST_STATE_LABEL_KEYS[state] ?? `posts.status.${state}`,+ '',+ );</script><template>@@ -116,6 +130,7 @@ const postState = (post: RepurposeItemPost): PublishStatusValue | null =><spanv-if="postState(post)"+ :data-testid="`repurpose-item-post-state-${post.id}`":class="['rounded px-1 py-px text-[10px] font-semibold uppercase tracking-wide',postState(post) === PublishStatus.Failed@@ -123,11 +138,7 @@ const postState = (post: RepurposeItemPost): PublishStatusValue | null =>: 'bg-foreground/10 text-foreground/60',]">- {{- postState(post) === PublishStatus.PendingReview- ? $t('posts.publish.in_google_review')- : $t(`posts.status.${postState(post)}`)- }}+ {{ $t(postStateLabelKey(post)) }}</span><IconChevronRight class="size-3.5 text-muted-foreground transition-colors group-hover/post:text-foreground" />diff --git a/resources/js/components/webhook/webhook-events.ts b/resources/js/components/webhook/webhook-events.tsindex cfe796333..93f39c790 100644--- a/resources/js/components/webhook/webhook-events.ts+++ b/resources/js/components/webhook/webhook-events.ts@@ -8,6 +8,8 @@ export const webhookEventGroups = ['post.scheduled','post.unscheduled','post.published',+ 'post.deleted_on_network',+ 'post.restored','post.failed','post.deleted',],diff --git a/resources/js/composables/usePostCardActions.ts b/resources/js/composables/usePostCardActions.tsindex be874deb6..d2f836be4 100644--- a/resources/js/composables/usePostCardActions.ts+++ b/resources/js/composables/usePostCardActions.ts@@ -7,6 +7,8 @@ import { duplicate as duplicatePost } from '@/actions/App/Http/Controllers/App/Pimport { update as updatePostLabels } from '@/actions/App/Http/Controllers/App/PostLabelController';import { update as updatePostSchedule } from '@/actions/App/Http/Controllers/App/PostScheduleController';import { openPostComposer } from '@/composables/useGlobalPostComposer';+import { filled } from '@/lib/helpers';+import { postPermalink } from '@/lib/postNetwork';import { copyToClipboard } from '@/lib/utils';import type { SidebarChannel } from '@/types/channel';import type {@@ -80,14 +82,16 @@ export const duplicatePostCard = (post: PostCard): void => {/** Opens the composer with the sent post's link and every channel of the workspace. */export const sharePostCardLink = (post: PostCard): void => {- if (!post.platform_url) return;+ const permalink = postPermalink(post);++ if (!filled(permalink)) return;const channels = (usePage().props.channels as SidebarChannel[] | undefined) ?? [];openPostComposer({socialAccountIds: channels.map((channel) => channel.id),draft: {- content: post.platform_url,+ content: permalink,media: [],scheduled_at: null,label_ids: [],@@ -96,8 +100,10 @@ export const sharePostCardLink = (post: PostCard): void => {};export const copyPostCardLink = (post: PostCard): void => {- if (post.platform_url) {- void copyToClipboard(post.platform_url, undefined, {+ const permalink = postPermalink(post);++ if (filled(permalink)) {+ void copyToClipboard(permalink, undefined, {showSuccessToast: false,});}diff --git a/resources/js/composables/usePostStatus.ts b/resources/js/composables/usePostStatus.tsindex 07fcfa7e6..87262575c 100644--- a/resources/js/composables/usePostStatus.ts+++ b/resources/js/composables/usePostStatus.ts@@ -7,9 +7,13 @@ import {IconFileText,IconHourglass,IconLoader2,+ IconTrashX,} from '@tabler/icons-vue';import { trans } from 'laravel-vue-i18n';+import { isDeletedOnNetwork } from '@/lib/postNetwork';+import type { PostCard } from '@/types/publish';+type BadgeVariant = 'default' | 'secondary' | 'destructive' | 'destructive-subtle' | 'success' | 'warning' | 'info' | 'outline';interface StatusConfig {@@ -36,3 +40,15 @@ export const getPostStatusConfig = (status: string): StatusConfig => {const config = CONFIGS[status] ?? CONFIGS.draft;return { ...config, label: trans(`posts.status.${status}`) };};++export const getDeletedOnNetworkStatusConfig = (): StatusConfig => ({+ variant: 'destructive-subtle',+ icon: IconTrashX,+ label: trans('posts.publish.deleted_on_network.badge'),+});++/** A post's status, reading as deleted once the network deleted it. */+export const getPostCardStatusConfig = (post: PostCard): StatusConfig =>+ isDeletedOnNetwork(post)+ ? getDeletedOnNetworkStatusConfig()+ : getPostStatusConfig(post.status);diff --git a/resources/js/lib/postNetwork.ts b/resources/js/lib/postNetwork.tsnew file mode 100644index 000000000..4a2c5481c--- /dev/null+++ b/resources/js/lib/postNetwork.ts@@ -0,0 +1,11 @@+import { PostStatus, PublishStatus } from '@/types/post';+import type { PostCard } from '@/types/publish';++/** Whether the network deleted the post after it was published. */+export const isDeletedOnNetwork = (post: PostCard): boolean =>+ post.status === PostStatus.Published &&+ post.publish_status === PublishStatus.Deleted;++/** The post's link on the network, none once the network deleted it. */+export const postPermalink = (post: PostCard): string | null =>+ isDeletedOnNetwork(post) ? null : (post.platform_url ?? null);diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.tsindex 55bb1ab35..d3640d3c7 100644--- a/resources/js/types/analytics.ts+++ b/resources/js/types/analytics.ts@@ -287,6 +287,21 @@ export interface PublicationThreadPoll extends PublicationPoll {reply: number;}+export const PublicationAvailability = {+ Available: 'available',+ Deleted: 'deleted',+ Unavailable: 'unavailable',+} as const;++export type PublicationAvailabilityValue =+ (typeof PublicationAvailability)[keyof typeof PublicationAvailability];++export type MetricsUnavailableReason =+ | 'not_published'+ | 'deleted_on_network'+ | 'platform_not_supported'+ | 'not_collected';+export interface PublicationAnalyticsDetail {available: true;reason: null;@@ -297,7 +312,7 @@ export interface PublicationAnalyticsDetail {platform: string;origin: string;content_type: string;- availability: string;+ availability: PublicationAvailabilityValue;provider_published_at: string | null;permalink: string | null;excerpt: string | null;diff --git a/resources/js/types/post.ts b/resources/js/types/post.tsindex b63bf0e49..29424e200 100644--- a/resources/js/types/post.ts+++ b/resources/js/types/post.ts@@ -17,6 +17,7 @@ export const PublishStatus = {Retrying: 'retrying',Rejected: 'rejected',PendingReview: 'pending_review',+ Deleted: 'deleted',} as const;export type PublishStatusValue = (typeof PublishStatus)[keyof typeof PublishStatus];diff --git a/resources/js/types/publish.ts b/resources/js/types/publish.tsindex 3aaed3eb1..413721d07 100644--- a/resources/js/types/publish.ts+++ b/resources/js/types/publish.ts@@ -1,5 +1,8 @@import type { RecurrenceFrequency } from '@/lib/recurrence';-import type { PublicationAnalyticsDetail } from '@/types/analytics';+import type {+ MetricsUnavailableReason,+ PublicationAnalyticsDetail,+} from '@/types/analytics';import type { MediaItem } from '@/types/media';import type { PlatformValue } from '@/types/platform';import type {@@ -48,7 +51,7 @@ export interface PostCardLabel {export interface UnavailablePostMetrics {available: false;- reason: string | null;+ reason: MetricsUnavailableReason;}export type PostCardMetrics = PublicationAnalyticsDetail | UnavailablePostMetrics;diff --git a/tests/Browser/CalendarPageTest.php b/tests/Browser/CalendarPageTest.phpindex fb85ac538..24fa33c8c 100644--- a/tests/Browser/CalendarPageTest.php+++ b/tests/Browser/CalendarPageTest.php@@ -416,6 +416,33 @@ test('a calendar opened by its link asks for its posting times only once its pag->assertNoJavaScriptErrors();});+test('in the month a post the network deleted shows the deleted mark instead of the published one', function () {+ [$user, $linkedin] = calendarPageSetup();+ $day = now('UTC')->subMonthNoOverflow()->startOfMonth()->addDays(14);+ $published = Post::factory()->forAccount($linkedin)->published()->create([+ 'user_id' => $user->id,+ 'scheduled_at' => $day->setTime(10, 0),+ 'published_at' => $day->setTime(10, 0),+ ]);+ $deleted = Post::factory()->forAccount($linkedin)->deletedOnNetwork()->create([+ 'user_id' => $user->id,+ 'scheduled_at' => $day->setTime(12, 0),+ 'published_at' => $day->setTime(12, 0),+ ]);++ $this->actingAs($user);++ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]))->resize(1440, 900);+ waitFor($page, "@calendar-post-{$deleted->id}");++ $page->assertPresent("@calendar-post-deleted-{$deleted->id}")+ ->assertMissing("@calendar-post-published-{$deleted->id}")+ ->assertAttribute("@calendar-post-deleted-{$deleted->id}", 'aria-label', __('calendar.post_status.deleted'))+ ->assertPresent("@calendar-post-published-{$published->id}")+ ->assertMissing("@calendar-post-deleted-{$published->id}")+ ->assertNoJavaScriptErrors();+});+test('in the month a post shows its network in color and a status icon with a tooltip, and a free posting time reads as a hatched empty slot', function () {[$user, $linkedin] = calendarPageSetup();$schedule = PostingSchedule::empty();diff --git a/tests/Browser/ComposerGooglePhotosTest.php b/tests/Browser/ComposerGooglePhotosTest.phpindex dd5e536b2..84ef09bc5 100644--- a/tests/Browser/ComposerGooglePhotosTest.php+++ b/tests/Browser/ComposerGooglePhotosTest.php@@ -92,7 +92,7 @@ function enableOnlyGooglePhotosForComposer(bool $mediaItemsSet = true): stringtest()->mock(HostResolver::class)->shouldReceive('addresses')->andReturn(['142.250.0.10']);- $api = rtrim((string) config('trypost.media_sources.google_photos.api'), '/').'/v1';+ $api = config('trypost.media_sources.google_photos.api').'/v1';Http::fake(['https://oauth2.google.test/token' => Http::response([diff --git a/tests/Browser/DeletedOnNetworkCardTest.php b/tests/Browser/DeletedOnNetworkCardTest.phpnew file mode 100644index 000000000..a9f5a9370--- /dev/null+++ b/tests/Browser/DeletedOnNetworkCardTest.php@@ -0,0 +1,102 @@+<?php++declare(strict_types=1);++use App\Enums\Post\PublishStatus;+use App\Enums\Post\Status as PostStatus;+use App\Jobs\Analytics\BootstrapAccountAnalytics;+use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++test('a post deleted on the network shows as deleted and offers no link to it', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);++ $user = User::factory()->create(['timezone' => 'UTC']);+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);+ connectAiTo($user);+ $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);++ $groupId = (string) Str::uuid();+ $sentPost = fn (PublishStatus $publishStatus, int $hoursAgo): Post => Post::factory()->forAccount($account)->published()->create([+ 'user_id' => $user->id,+ 'post_group_id' => $groupId,+ 'publish_status' => $publishStatus,+ 'platform_url' => 'https://www.instagram.com/p/abc/',+ 'published_at' => now()->subHours($hoursAgo),+ ]);+ $deleted = $sentPost(PublishStatus::Deleted, 1);+ $live = $sentPost(PublishStatus::Published, 2);++ $this->actingAs($user);+ $page = visit(route('app.posts.index', ['tab' => 'sent']));++ waitFor($page, "@post-deleted-on-network-{$deleted->id}");+ waitFor($page, "@post-view-{$live->id}");++ $page->assertVisible("@post-view-{$live->id}")+ ->assertMissing("@post-view-{$deleted->id}")+ ->assertMissing("@post-deleted-on-network-{$live->id}");++ $page->click("@post-deleted-on-network-{$deleted->id}");+ waitFor($page, "@post-deleted-on-network-popover-{$deleted->id}");++ $page->assertSeeIn("@post-deleted-on-network-popover-{$deleted->id}", __('posts.publish.deleted_on_network.title', ['network' => 'Instagram']))+ ->assertVisible("@post-deleted-on-network-hint-{$deleted->id}");+ $page->keys("@post-deleted-on-network-popover-{$deleted->id}", 'Escape');+ waitForGone($page, "@post-deleted-on-network-popover-{$deleted->id}");+ $page->assertMissing("@post-deleted-on-network-popover-{$deleted->id}");++ $page->click("@post-card-menu-{$deleted->id}");+ waitFor($page, "@post-card-menu-content-{$deleted->id}");++ $page->assertVisible("@post-delete-{$deleted->id}")+ ->assertVisible("@post-duplicate-{$deleted->id}")+ ->assertMissing("@post-share-link-{$deleted->id}")+ ->assertMissing("@post-copy-link-{$deleted->id}");++ $page->click("@post-details-open-{$deleted->id}");+ waitFor($page, "@post-details-{$deleted->id}");++ waitFor($page, "@post-details-rail-status-{$deleted->id}");++ $page->assertAttribute("@post-details-rail-status-icon-{$deleted->id}", 'aria-label', __('posts.publish.deleted_on_network.badge'))+ ->assertAttribute("@post-details-rail-status-icon-{$live->id}", 'aria-label', __('posts.status.published'))+ ->assertVisible("@post-details-deleted-on-network-{$deleted->id}")+ ->assertMissing("@post-details-status-{$deleted->id}")+ ->assertMissing("@post-details-view-{$deleted->id}")+ ->assertNoJavaScriptErrors();+});++test('a post still publishing is never shown as deleted, even when the network side says so', function () {+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);++ $user = User::factory()->create(['timezone' => 'UTC']);+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);+ connectAiTo($user);+ $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);+ $publishing = Post::factory()->forAccount($account)->create([+ 'user_id' => $user->id,+ 'status' => PostStatus::Publishing,+ 'publish_status' => PublishStatus::Deleted,+ 'scheduled_at' => now()->subMinute(),+ ]);++ $this->actingAs($user);+ $page = visit(route('app.posts.index', ['tab' => 'queue']));++ waitFor($page, "@post-card-{$publishing->id}");++ $page->assertMissing("@post-deleted-on-network-{$publishing->id}")+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/RepurposeTest.php b/tests/Browser/RepurposeTest.phpindex f6b8ccbc8..55756aeb0 100644--- a/tests/Browser/RepurposeTest.php+++ b/tests/Browser/RepurposeTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Post\PublishStatus;use App\Enums\PostPlatform\ContentType;use App\Enums\Repurpose\ItemReason;use App\Enums\Repurpose\ItemStatus;@@ -12,6 +13,7 @@ use App\Enums\SocialAccount\Status as AccountStatus;use App\Enums\TikTok\PrivacyLevel;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Models\Post;use App\Models\Repurpose;use App\Models\RepurposeItem;use App\Models\SocialAccount;@@ -215,6 +217,57 @@ test('the activity list reads as what happened, never as a database id', functio->assertNoJavaScriptErrors();});+test('a repurposed post deleted on the network reads as deleted in the activity list', function () {+ [$user, $workspace, $source] = repurposeOwnerWithAccounts();++ $repurpose = Repurpose::factory()->active()->create([+ 'workspace_id' => $workspace->id,+ 'source_social_account_id' => $source->id,+ ]);+ $item = RepurposeItem::factory()->for($repurpose)->create(['source_created_at' => now()->subHour()]);+ $post = Post::factory()->forAccount($source)->deletedOnNetwork()->create([+ 'repurpose_item_id' => $item->id,+ ]);++ $this->actingAs($user);++ $page = visit(route('app.repurposes.show', $repurpose));++ waitFor($page, '@tab-activity');+ $page->click('@tab-activity');+ waitFor($page, "@repurpose-item-post-state-{$post->id}");++ $page->assertSeeIn("@repurpose-item-post-state-{$post->id}", __('posts.publish.deleted_on_network.badge'))+ ->assertDontSeeIn("@repurpose-item-post-state-{$post->id}", 'posts.')+ ->assertNoJavaScriptErrors();+});++test('a repurposed post in Google review reads as in review in the activity list', function () {+ [$user, $workspace, $source] = repurposeOwnerWithAccounts();++ $repurpose = Repurpose::factory()->active()->create([+ 'workspace_id' => $workspace->id,+ 'source_social_account_id' => $source->id,+ ]);+ $item = RepurposeItem::factory()->for($repurpose)->create(['source_created_at' => now()->subHour()]);+ $post = Post::factory()->forAccount($source)->published()->create([+ 'repurpose_item_id' => $item->id,+ 'publish_status' => PublishStatus::PendingReview,+ ]);++ $this->actingAs($user);++ $page = visit(route('app.repurposes.show', $repurpose));++ waitFor($page, '@tab-activity');+ $page->click('@tab-activity');+ waitFor($page, "@repurpose-item-post-state-{$post->id}");++ $page->assertSeeIn("@repurpose-item-post-state-{$post->id}", __('posts.publish.in_google_review'))+ ->assertDontSeeIn("@repurpose-item-post-state-{$post->id}", 'posts.')+ ->assertNoJavaScriptErrors();+});+test('a destination missing its required meta saves anyway but blocks activating', function () {[$user, $workspace, $source, $tiktok] = repurposeOwnerWithAccounts();diff --git a/tests/Browser/WebhookCreateDialogTest.php b/tests/Browser/WebhookCreateDialogTest.phpindex d102e8e01..cfbdf1b11 100644--- a/tests/Browser/WebhookCreateDialogTest.php+++ b/tests/Browser/WebhookCreateDialogTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Webhook\EventType;use App\Models\User;use App\Models\Webhook;use App\Models\Workspace;@@ -71,26 +72,27 @@ test('creating a webhook happens in a centered dialog with cancel before the pri->assertDisabled('@create-webhook-submit');$checkedCount = "document.querySelectorAll('[data-testid=\"create-webhook-events\"] [role=\"checkbox\"][data-state=\"checked\"]').length";+ $events = count(EventType::cases());- $page->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')+ $page->assertSeeIn('@create-webhook-events-count', "0 of {$events} selected")->assertSeeIn('@create-webhook-events-toggle-all', __('posts.composer.select_all'))->assertSeeIn('@create-webhook-events-post-published-description', __('webhooks.event_descriptions.post_published'))->assertSeeIn('@create-webhook-endpoint-help', __('webhooks.create.endpoint_help'))->click('@create-webhook-events-toggle-all')- ->assertScript($checkedCount, 6)- ->assertSeeIn('@create-webhook-events-count', '6 of 6 selected')+ ->assertScript($checkedCount, $events)+ ->assertSeeIn('@create-webhook-events-count', "{$events} of {$events} selected")->assertSeeIn('@create-webhook-events-toggle-all', __('posts.composer.deselect_all'))->assertEnabled('@create-webhook-submit')->click('@create-webhook-events-toggle-all')->assertScript($checkedCount, 0)- ->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')+ ->assertSeeIn('@create-webhook-events-count', "0 of {$events} selected")->assertDisabled('@create-webhook-submit')->click('@create-webhook-events-post-failed-description')->assertScript("document.querySelector('[data-testid=\"create-webhook-events-post-failed-checkbox\"]').getAttribute('data-state')", 'checked')- ->assertSeeIn('@create-webhook-events-count', '1 of 6 selected')+ ->assertSeeIn('@create-webhook-events-count', "1 of {$events} selected")->click('@create-webhook-events-post-failed-checkbox')->assertScript("document.querySelector('[data-testid=\"create-webhook-events-post-failed-checkbox\"]').getAttribute('data-state')", 'unchecked')- ->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')+ ->assertSeeIn('@create-webhook-events-count', "0 of {$events} selected")->click('@create-webhook-events-post-published')->click('@cancel-create-webhook');waitForWebhookCreateTestIdGone($page, 'create-webhook-dialog');diff --git a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php b/tests/Feature/Actions/Post/FinalizePostPublicationTest.phpindex 4e3aaee22..337de4729 100644--- a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php+++ b/tests/Feature/Actions/Post/FinalizePostPublicationTest.php@@ -34,6 +34,22 @@ function finalizeWorkspaceOf(User $owner): Workspacereturn $workspace;}+test('a post the network deleted before it was finalized still counts as published', function () {+ $owner = User::factory()->create();+ $account = SocialAccount::factory()->facebook()->create(['workspace_id' => finalizeWorkspaceOf($owner)->id]);+ $post = Post::factory()->forAccount($account)->facebook()->scheduled()->create([+ 'user_id' => $owner->id,+ 'publish_status' => PublishStatus::Deleted,+ 'platform_post_id' => 'fb-1',+ ]);++ app(FinalizePostPublication::class)->handle($post);++ expect($post->fresh()->status)->toBe(PostStatus::Published);+ Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::PostPublished);+ Queue::assertNotPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::PostFailed);+});+test('a published post queues the published email for the owner', function () {$owner = User::factory()->create(['locale' => Locale::PortugueseBrazil]);$workspace = finalizeWorkspaceOf($owner);diff --git a/tests/Feature/Analytics/ChannelInsightsPageTest.php b/tests/Feature/Analytics/ChannelInsightsPageTest.phpindex 7361841d4..bfb653bd7 100644--- a/tests/Feature/Analytics/ChannelInsightsPageTest.php+++ b/tests/Feature/Analytics/ChannelInsightsPageTest.php@@ -5,6 +5,7 @@ declare(strict_types=1);use App\Actions\Analytics\ListChannelPublicationPerformance;use App\Actions\Analytics\ResolveAnalyticsAccountKey;use App\Dto\Analytics\DateRange;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\SocialAccount\Platform;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;@@ -435,3 +436,21 @@ test('the coverage poll reloads the report without recomputing the available met->missing('availableMetrics')->missing('publications')));});++test('a publication the network deleted stays in the table without its link', function () {+ $live = channelInsightsPublication($this->instagram, now('UTC')->subDays(4)->toDateTimeString(), ['reactions_count' => 9]);+ $deleted = channelInsightsPublication($this->instagram, now('UTC')->subDays(5)->toDateTimeString(), ['reactions_count' => 3], [+ 'availability' => PublicationAvailability::Deleted,+ ]);++ $this->actingAs($this->user)+ ->get(route('app.channels.insights', $this->instagram))+ ->assertOk()+ ->assertInertia(fn (Assert $page) => $page+ ->has('publications.data', 2)+ ->where('publications.data.0.id', $live->id)+ ->where('publications.data.0.permalink', $live->permalink)+ ->where('publications.data.1.id', $deleted->id)+ ->where('publications.data.1.permalink', null)+ ->etc());+});diff --git a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.phpindex ed9546651..5304553ab 100644--- a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php@@ -24,12 +24,16 @@ use App\Services\Analytics\Collectors\Metrics\TikTokPublicationMetricsCollector;use App\Services\Analytics\Collectors\Metrics\XPublicationMetricsCollector;use App\Services\Analytics\Collectors\Metrics\YouTubePublicationMetricsCollector;use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;+use App\Services\Social\BlueskyLexicon;use App\Support\Social\XPoll;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Request;use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;+use Illuminate\Support\Uri;+use Pest\Expectation;test('the metric factory includes every v1 platform and excludes v2 and messaging platforms', function (Platform $platform, string $collector) {expect(app(PublicationMetricsCollectorFactory::class)->for($platform))->toBeInstanceOf($collector);@@ -150,8 +154,8 @@ test('pinterest preserves its rolling window basis', function () {});test('youtube falls back to current video statistics before Analytics has processed a new video', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$analyticsApi}/reports*" => Http::response(['columnHeaders' => [['name' => 'views'], ['name' => 'likes']],@@ -256,7 +260,7 @@ test('an optional Instagram Reel insight rate limit stays retryable', function (expect(fn () => app(InstagramPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))- ->toThrow(fn (AnalyticsCollectionException $exception) => expect($exception->category)->toBe('rate_limited'));+ ->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('rate_limited'));Http::assertSentCount(2);});@@ -282,7 +286,7 @@ test('an unsupported optional Instagram insight does not discard base metrics',});test('an imported Facebook video fetches video insights through its attachment target', function () {- $graph = rtrim((string) config('trypost.platforms.facebook.graph_api'), '/');+ $graph = config('trypost.platforms.facebook.graph_api');$account = SocialAccount::factory()->facebook()->create();Http::fake(["{$graph}/{$account->platform_user_id}/published_posts*" => Http::response(['data' => [[@@ -345,7 +349,7 @@ test('Meta rate limiting in HTTP 400 is classified as retryable', function () {]);expect(fn () => app(InstagramPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))- ->toThrow(fn (AnalyticsCollectionException $exception) => expect($exception->category)->toBe('rate_limited'));+ ->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('rate_limited'));});test('Meta publication metrics classify missing permission on HTTP 400', function () {@@ -360,7 +364,7 @@ test('Meta publication metrics classify missing permission on HTTP 400', functioexpect(fn () => app(InstagramPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))- ->toThrow(fn (AnalyticsCollectionException $exception) => expect($exception->category)->toBe('permission'));+ ->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission'));});test('TikTok resolves a TryPost publish id before collecting the public video', function () {@@ -395,9 +399,80 @@ test('TikTok resolves a TryPost publish id before collecting the public video',Http::assertSentCount(2);});+test('a youtube video the cache could not keep is read from the response, never reported deleted', function () {+ config()->set('cache.default', 'null');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');+ Http::fake([+ "{$analyticsApi}/reports*" => Http::response(['columnHeaders' => [['name' => 'views']], 'rows' => []]),+ "{$dataApi}/videos*" => Http::response(['items' => [['id' => 'video-live', 'statistics' => ['viewCount' => '12']]]]),+ ]);+ $account = SocialAccount::factory()->create(['platform' => Platform::YouTube]);+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::YouTube,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => 'video-live',+ ]);++ $observation = app(YouTubePublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect(collect($observation->metrics)->firstWhere('key', MetricKey::Views)?->value)->toBe(12);+});++test('a youtube video missing from another batch is read again before it is reported deleted', function () {+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');+ Http::fake([+ "{$analyticsApi}/reports*" => Http::response(['columnHeaders' => [['name' => 'views']], 'rows' => []]),+ "{$dataApi}/videos*" => Http::sequence()+ ->push(['items' => [['id' => 'video-a', 'statistics' => ['viewCount' => '3']]]])+ ->push(['items' => [['id' => 'video-b', 'statistics' => ['viewCount' => '7']]]]),+ ]);+ $account = SocialAccount::factory()->create(['platform' => Platform::YouTube]);+ $publications = collect(['video-a', 'video-b'])->map(fn (string $video): AnalyticsPublication => AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::YouTube,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => $video,+ ]));+ $collector = app(YouTubePublicationMetricsCollector::class);++ $collector->collect($publications[0], CarbonImmutable::today('UTC'));+ $observation = $collector->collect($publications[1], CarbonImmutable::today('UTC'));++ expect(collect($observation->metrics)->firstWhere('key', MetricKey::Views)?->value)->toBe(7);+});++test('a youtube video cached as missing is read again before it is reported deleted', function () {+ $date = CarbonImmutable::today('UTC');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');+ $account = SocialAccount::factory()->create(['platform' => Platform::YouTube]);+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::YouTube,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => 'video-live',+ ]);+ Cache::put("analytics:youtube-statistics:{$account->id}:{$date->toDateString()}:video-live", false);+ Http::fake([+ "{$analyticsApi}/reports*" => Http::response(['columnHeaders' => [['name' => 'views']], 'rows' => []]),+ "{$dataApi}/videos*" => Http::response(['items' => [['id' => 'video-live', 'statistics' => ['viewCount' => '12']]]]),+ ]);++ $observation = app(YouTubePublicationMetricsCollector::class)->collect($publication, $date);++ expect(collect($observation->metrics)->firstWhere('key', MetricKey::Views)?->value)->toBe(12);+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/videos'));+});+test('youtube collects current statistics and every Analytics metric for a short', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$analyticsApi}/reports*" => Http::response(['kind' => 'youtubeAnalytics#resultTable',@@ -445,8 +520,8 @@ test('youtube collects current statistics and every Analytics metric for a short});test('youtube keeps current video statistics when Analytics refuses the report', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$analyticsApi}/reports*" => Http::response(['error' => ['code' => 403,@@ -476,8 +551,8 @@ test('youtube keeps current video statistics when Analytics refuses the report',});test('an expired youtube token is refreshed before publication metrics are requested', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake([config('trypost.platforms.youtube.oauth_api').'/token' => Http::response(['access_token' => 'fresh-token',@@ -526,7 +601,7 @@ test('a rejected token refresh is classified as an authentication failure', funcexpect(fn () => app(YouTubePublicationMetricsCollector::class)->collect($publication, CarbonImmutable::parse('2026-09-23', 'UTC')))- ->toThrow(fn (AnalyticsCollectionException $exception) => expect($exception->category)->toBe('authentication'));+ ->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('authentication'));Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/videos')|| str_contains($request->url(), '/reports'));});@@ -563,7 +638,7 @@ test('mastodon reads a public status without a token that lacks read scope', fun]);test('facebook keeps public post counts when Page insights are not available', function () {- $graph = rtrim((string) config('trypost.platforms.facebook.graph_api'), '/');+ $graph = config('trypost.platforms.facebook.graph_api');$account = SocialAccount::factory()->facebook()->create();Http::fake(["{$graph}/page_post/insights*" => Http::response(['error' => [@@ -596,7 +671,7 @@ test('facebook keeps public post counts when Page insights are not available', f});test('pinterest requests only documented pin metric types and keeps lifetime comments and reactions', function () {- $api = rtrim((string) config('trypost.platforms.pinterest.api'), '/');+ $api = config('trypost.platforms.pinterest.api');Http::fake(["{$api}/pins/*/analytics*" => Http::response(['all' => ['daily_metrics' => [],'summary_metrics' => ['IMPRESSION' => 240, 'SAVE' => 20, 'PIN_CLICK' => 37, 'OUTBOUND_CLICK' => 3, 'SAVE_RATE' => 0.0833],@@ -668,7 +743,7 @@ test('facebook reports permission and logs the Graph code when every read is refLog::spy();$account = SocialAccount::factory()->facebook()->createQuietly();Http::fake([- rtrim((string) config('trypost.platforms.facebook.graph_api'), '/').'/page_post/insights*' => Http::response(['error' => [+ config('trypost.platforms.facebook.graph_api').'/page_post/insights*' => Http::response(['error' => ['message' => '(#100) The value must be a valid insights metric','type' => 'OAuthException','code' => 100,@@ -690,7 +765,7 @@ test('facebook reports permission and logs the Graph code when every read is refexpect(fn () => app(FacebookPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::parse('2026-09-23', 'UTC')))- ->toThrow(fn (AnalyticsCollectionException $exception) => expect($exception->category)->toBe('permission'));+ ->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission'));Log::shouldHaveReceived('info')->withArgs(fn (string $message, array $context): bool => $message === 'analytics.meta_metric_rejected'&& data_get($context, 'metric') === 'post_clicks'&& str_contains((string) data_get($context, 'reason'), 'Graph code 100'));@@ -835,8 +910,8 @@ test('an Instagram story collects profile metrics and its navigation breakdown',});test('youtube reads statistics for every due video of the channel in one videos call', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$analyticsApi}/reports*" => Http::response(['columnHeaders' => [], 'rows' => []]),"{$dataApi}/videos*" => fn (Request $request) => Http::response(['items' => collect(explode(',', (string) $request['id']))@@ -865,8 +940,8 @@ test('youtube reads statistics for every due video of the channel in one videos});test('youtube keeps current video statistics when Analytics rejects the report as malformed', function () {- $analyticsApi = rtrim((string) config('trypost.platforms.youtube.analytics_api'), '/');- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $analyticsApi = config('trypost.platforms.youtube.analytics_api');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$analyticsApi}/reports*" => Http::response(['error' => ['code' => 400,@@ -895,7 +970,7 @@ test('youtube keeps current video statistics when Analytics rejects the report a});test('youtube reports a video it no longer returns as gone', function () {- $dataApi = rtrim((string) config('trypost.platforms.youtube.data_api'), '/');+ $dataApi = config('trypost.platforms.youtube.data_api');Http::fake(["{$dataApi}/videos*" => Http::response(['items' => []])]);$account = SocialAccount::factory()->youtube()->create();$publication = AnalyticsPublication::factory()->create([@@ -929,6 +1004,476 @@ test('TikTok classifies an invalid access token as an authentication failure', f->toThrow(fn (AnalyticsCollectionException $exception): bool => $exception->category === 'authentication');});+/**+ * @return array<string, mixed>+ */+function metaMissingObject(string $id): array+{+ return ['error' => [+ 'message' => "Unsupported get request. Object with ID '{$id}' does not exist, cannot be loaded due to missing permissions, or does not support this operation.",+ 'type' => 'GraphMethodException',+ 'code' => 100,+ 'error_subcode' => 33,+ ]];+}++function metaGraphBase(Platform $platform): string+{+ return match ($platform) {+ Platform::Instagram, Platform::InstagramFacebook => $platform->graphApiUrl(),+ Platform::Facebook => config('trypost.platforms.facebook.graph_api'),+ Platform::Threads => config('trypost.platforms.threads.graph_api'),+ };+}++/**+ * @param array<string, mixed> $attributes+ */+function networkPublication(SocialAccount $account, string $remoteId, array $attributes = []): AnalyticsPublication+{+ return AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => $account->platform,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => $remoteId,+ ...$attributes,+ ]);+}++function collectFrom(AnalyticsPublication $publication): Closure+{+ return fn () => app(PublicationMetricsCollectorFactory::class)+ ->for($publication->platform)+ ->collect($publication, CarbonImmutable::today('UTC'));+}++/**+ * @param array<string, mixed> $attributes+ */+function metaMetricsPublication(Platform $platform, array $attributes = []): AnalyticsPublication+{+ return networkPublication(+ SocialAccount::factory()->create(['platform' => $platform, 'platform_user_id' => '17841400000000001']),+ '17897891718416700',+ ['content_type' => PublicationContentType::Reel, ...$attributes],+ );+}++test('a Meta post the network no longer returns is reported deleted while the account posts still read', function (Platform $platform, string $postsEdge) {+ $publication = metaMetricsPublication($platform);+ $graph = metaGraphBase($platform);+ Http::fake([+ "{$graph}/17841400000000001/{$postsEdge}*" => Http::response(['data' => [['id' => '1']]]),+ '*' => Http::response(metaMissingObject('17897891718416700'), 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->gone)->toBeTrue()->and($exception->deletedOnNetwork)->toBeTrue());+})->with([+ 'instagram via facebook' => [Platform::InstagramFacebook, 'media'],+ 'instagram login' => [Platform::Instagram, 'media'],+ 'facebook' => [Platform::Facebook, 'published_posts'],+ 'threads' => [Platform::Threads, 'threads'],+]);++test('a Facebook post is reported deleted even when the Page never granted insights', function () {+ $publication = metaMetricsPublication(Platform::Facebook, [+ 'remote_id' => '17841400000000001_17897891718416700',+ 'content_type' => PublicationContentType::Image,+ ]);+ $publication->socialAccount->update(['scopes' => ['pages_read_engagement']]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake([+ "{$graph}/17841400000000001/published_posts*" => Http::response(['data' => [['id' => '1']]]),+ '*' => Http::response(metaMissingObject('17841400000000001_17897891718416700'), 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+});++test('a Facebook Page post is reported deleted when its insights say it no longer exists, though its own node answers #10', function () {+ $publication = metaMetricsPublication(Platform::Facebook, [+ 'remote_id' => '17841400000000001_17897891718416700',+ 'content_type' => PublicationContentType::Text,+ ]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake([+ "{$graph}/17841400000000001/published_posts*" => Http::response(['data' => [['id' => '1']]]),+ "{$graph}/17841400000000001_17897891718416700/insights*" => Http::response(metaMissingObject('17841400000000001_17897891718416700'), 400),+ '*' => Http::response(['error' => [+ 'message' => "(#10) Object does not exist, cannot be loaded due to missing permission or reviewable feature, or does not support this operation. This endpoint requires the 'pages_read_engagement' permission or the 'Page Public Content Access' feature.",+ 'type' => 'OAuthException',+ 'code' => 10,+ ]], 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+});++test('a Meta post is not reported deleted when the account posts cannot be read either', function (Platform $platform) {+ $publication = metaMetricsPublication($platform);+ Http::fake(['*' => Http::response(metaMissingObject('17897891718416700'), 400)]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([Platform::InstagramFacebook, Platform::Instagram, Platform::Facebook, Platform::Threads]);++test('a Meta post is not reported deleted when reading it fails for another reason', function (array $postRead) {+ $publication = metaMetricsPublication(Platform::InstagramFacebook);+ $graph = metaGraphBase(Platform::InstagramFacebook);+ Http::fake([+ "{$graph}/17897891718416700/insights*" => Http::response(metaMissingObject('17897891718416700'), 400),+ "{$graph}/17897891718416700*" => Http::response(...$postRead),+ '*' => Http::response(['data' => [['id' => '1']]]),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'the post still reads' => [[['id' => '17897891718416700']]],+ 'a server error' => [[['error' => ['code' => 2]], 500]],+ 'code 100 without subcode 33' => [[['error' => ['code' => 100, 'message' => 'Unsupported']], 400]],+]);++test('a Facebook post whose metrics are refused for another reason never checks whether it was deleted', function () {+ $publication = metaMetricsPublication(Platform::Facebook);+ Http::fake(['*' => Http::response(['error' => ['code' => 100, 'message' => 'Unsupported metric']], 400)]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+ Http::assertNotSent(fn (Request $request): bool => data_get($request->data(), 'fields') === 'id');+});++test('a Meta deletion check that fails only for now is retried before anything is reported', function (array $post, array $posts, string $category) {+ $publication = metaMetricsPublication(Platform::InstagramFacebook);+ $graph = metaGraphBase(Platform::InstagramFacebook);+ Http::fake([+ "{$graph}/17897891718416700/insights*" => Http::response(metaMissingObject('17897891718416700'), 400),+ "{$graph}/17897891718416700*" => Http::response(...$post),+ "{$graph}/17841400000000001/media*" => Http::response(...$posts),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe($category)->and($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'the post read is rate limited' => [[['error' => ['code' => 4]], 400], [['data' => []]], 'rate_limited'],+ 'the post read is throttled' => [[[], 429], [['data' => []]], 'rate_limited'],+ 'the posts read fails on the server' => [[metaMissingObject('17897891718416700'), 400], [['error' => ['code' => 2]], 500], 'transient'],+]);++test('a Meta read that fails for a reason other than a missing post never checks whether it was deleted', function () {+ $publication = metaMetricsPublication(Platform::Facebook, [+ 'remote_id' => '17841400000000001_17897891718416700',+ 'content_type' => PublicationContentType::Image,+ ]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake(fn (Request $request) => str_contains($request->url(), '/insights')+ ? Http::response(metaMissingObject('17841400000000001_17897891718416700'), 400)+ : Http::response(['error' => ['code' => 4]], 400));++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('rate_limited'));+ Http::assertNotSent(fn (Request $request): bool => data_get($request->data(), 'fields') === 'id');+});++test('a Facebook post on a Page without insights keeps its permission refusal when the deletion is not confirmed', function () {+ $publication = metaMetricsPublication(Platform::Facebook, [+ 'remote_id' => '17841400000000001_17897891718416700',+ 'content_type' => PublicationContentType::Image,+ ]);+ $publication->socialAccount->update(['scopes' => ['pages_read_engagement']]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake([+ "{$graph}/17841400000000001/published_posts*" => Http::response(['error' => ['code' => 10]], 403),+ '*' => Http::response(metaMissingObject('17841400000000001_17897891718416700'), 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission')->and($exception->deletedOnNetwork)->toBeFalse());+});++test('a Facebook reel without insights is reported deleted when the video itself is missing', function () {+ $publication = metaMetricsPublication(Platform::Facebook);+ $publication->socialAccount->update(['scopes' => ['pages_read_engagement']]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake([+ "{$graph}/17841400000000001/published_posts*" => Http::response(['data' => [['id' => '1']]]),+ '*' => Http::response(metaMissingObject('17897891718416700'), 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue())+ ->and(Http::recorded(fn (Request $request): bool => Uri::of($request->url())->path() === Uri::of("{$graph}/17897891718416700")->path()))->toHaveCount(1);+});++test('a Facebook reel without insights stays published when the video still reads', function () {+ $publication = metaMetricsPublication(Platform::Facebook);+ $publication->socialAccount->update(['scopes' => ['pages_read_engagement']]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake([+ "{$graph}/17897891718416700*" => Http::response(['id' => '17897891718416700']),+ '*' => Http::response(metaMissingObject('17897891718416700'), 400),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission')->and($exception->deletedOnNetwork)->toBeFalse());+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), '/published_posts'));+});++test('a Facebook reel on a Page that never granted reading it never checks whether it was deleted', function () {+ $publication = metaMetricsPublication(Platform::Facebook);+ $publication->socialAccount->update(['scopes' => ['read_insights']]);+ Http::fake(['*' => Http::response(metaMissingObject('17897891718416700'), 400)]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission')->and($exception->deletedOnNetwork)->toBeFalse());+ Http::assertNothingSent();+});++test('a Meta collector reused for another post forgets the first one\'s refusals', function () {+ $collector = app(FacebookPublicationMetricsCollector::class);+ $deleted = metaMetricsPublication(Platform::Facebook);+ $live = networkPublication($deleted->socialAccount, '17841400000000001_17897891718416799', ['content_type' => PublicationContentType::Image]);+ $live->socialAccount->update(['scopes' => ['pages_read_engagement']]);+ $graph = metaGraphBase(Platform::Facebook);+ Http::fake(fn (Request $request) => match (true) {+ str_contains($request->url(), '/published_posts') => Http::response(['data' => [['id' => '1']]]),+ str_contains($request->url(), '17897891718416700') => Http::response(metaMissingObject('17897891718416700'), 400),+ data_get($request->data(), 'fields') === 'id' => Http::response(metaMissingObject('17841400000000001_17897891718416799'), 400),+ default => Http::response(['error' => ['code' => 10]], 403),+ });++ expect(fn () => $collector->collect($deleted, CarbonImmutable::today('UTC')))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue())+ ->and(fn () => $collector->collect($live, CarbonImmutable::today('UTC')))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission')->and($exception->deletedOnNetwork)->toBeFalse());+});++test('a Meta read refused for permission never checks whether the post was deleted', function () {+ $publication = metaMetricsPublication(Platform::Threads);+ $graph = metaGraphBase(Platform::Threads);+ Http::fake([+ "{$graph}/17897891718416700/insights*" => Http::response(['error' => ['code' => 10]], 403),+ '*' => Http::response(['data' => [['id' => '1']]]),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('permission')->and($exception->deletedOnNetwork)->toBeFalse());+ Http::assertSentCount(1);+});++test('a story is never reported deleted, since stories expire on their own', function () {+ $publication = metaMetricsPublication(Platform::InstagramFacebook, ['content_type' => PublicationContentType::Story]);+ Http::fake(['*' => Http::response(metaMissingObject('17897891718416700'), 400)]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+ Http::assertSentCount(1);+});++/**+ * @return array<string, mixed>+ */+function xNotFoundProblem(string $id, string $host = 'https://api.x.com'): array+{+ return [+ 'type' => "{$host}/2/problems/resource-not-found",+ 'title' => 'Not Found Error',+ 'detail' => "Could not find tweet with id: [{$id}].",+ 'resource_type' => 'tweet',+ 'resource_id' => $id,+ ];+}++test('an X post the network deleted is reported deleted from the lookup itself', function (string $host) {+ $publication = networkPublication(SocialAccount::factory()->x()->create(), '1900000000000000001');+ Http::fake(['*' => Http::response(['errors' => [xNotFoundProblem('1900000000000000001', $host)]])]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+ Http::assertSentCount(1);+})->with([+ 'api.x.com' => ['https://api.x.com'],+ 'api.twitter.com' => ['https://api.twitter.com'],+]);++test('an X problem that does not name this post as deleted is not reported deleted', function (array $error) {+ $publication = networkPublication(SocialAccount::factory()->x()->create(), '1900000000000000001');+ Http::fake(['*' => Http::response(['errors' => [$error]])]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'not authorized' => [['type' => 'https://api.x.com/2/problems/not-authorized-for-resource', 'resource_type' => 'tweet', 'resource_id' => '1900000000000000001']],+ 'another post' => [xNotFoundProblem('1900000000000000002')],+ 'not a post' => [[...xNotFoundProblem('1900000000000000001'), 'resource_type' => 'user']],+ 'no resource id' => [collect(xNotFoundProblem('1900000000000000001'))->except('resource_id')->all()],+]);++test('an X post read with its reply polls is reported deleted when the lookup names the post itself', function () {+ $account = SocialAccount::factory()->x()->create();+ $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440], 'thread_replies' => [+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],+ ]],+ ]);+ $post->forceFill(['thread_reply_ids' => ['1900000000000000002']])->save();+ $publication = networkPublication($account, '1900000000000000001', ['post_id' => $post->id]);+ Http::fake([config('trypost.platforms.x.api').'/tweets*' => Http::response([+ 'data' => [['id' => '1900000000000000002', 'public_metrics' => ['impression_count' => 3]]],+ 'errors' => [xNotFoundProblem('1900000000000000001')],+ ])]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+ Http::assertSent(fn (Request $request): bool => $request['ids'] === '1900000000000000001,1900000000000000002');+});++test('a Bluesky post the AppView returns is read once, with no deletion check', function () {+ $publication = networkPublication(SocialAccount::factory()->bluesky()->create(['platform_user_id' => 'did:plc:trypost']), '3kpost');+ $appView = config('trypost.platforms.bluesky.public_appview');+ Http::fake(["{$appView}/xrpc/app.bsky.feed.getPosts*" => Http::response(['posts' => [['likeCount' => 2, 'replyCount' => 1]]])]);++ collectFrom($publication)();++ Http::assertSentCount(1);+});++test('a Bluesky post its repository no longer holds is reported deleted while the repository still reads', function (?string $service) {+ $account = SocialAccount::factory()->bluesky()->create(['platform_user_id' => 'did:plc:trypost']);+ $account->update(['meta' => [...$account->meta, 'service' => $service ?? data_get($account->meta, 'service')]]);+ $pds = data_get($account->fresh()->meta, 'service');+ $publication = networkPublication($account, '3kpost');+ $appView = config('trypost.platforms.bluesky.public_appview');+ Http::fake([+ "{$appView}/xrpc/app.bsky.feed.getPosts*" => Http::response(['posts' => []]),+ "{$pds}/xrpc/com.atproto.repo.getRecord*" => Http::response(['error' => 'RecordNotFound', 'message' => 'Could not locate record'], 400),+ "{$pds}/xrpc/com.atproto.repo.listRecords*" => Http::response(['records' => [['uri' => 'at://did:plc:trypost/app.bsky.feed.post/3kother']]]),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), BlueskyLexicon::GET_RECORD)+ && data_get($request->data(), 'repo') === 'did:plc:trypost'+ && data_get($request->data(), 'collection') === BlueskyLexicon::FEED_POST+ && data_get($request->data(), 'rkey') === '3kpost'+ && ! $request->hasHeader('Authorization'));+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), BlueskyLexicon::LIST_RECORDS)+ && data_get($request->data(), 'repo') === 'did:plc:trypost'+ && data_get($request->data(), 'collection') === BlueskyLexicon::FEED_POST+ && (int) data_get($request->data(), 'limit') === 1+ && ! $request->hasHeader('Authorization'));+})->with([+ 'the account PDS' => [null],+ 'a self-hosted PDS' => ['https://pds.example.test'],+]);++test('a Bluesky post the AppView hides, or one whose repository cannot be read, is not reported deleted', function (array $record, array $list) {+ $account = SocialAccount::factory()->bluesky()->create(['platform_user_id' => 'did:plc:trypost']);+ $publication = networkPublication($account, '3kpost');+ $appView = config('trypost.platforms.bluesky.public_appview');+ $pds = $account->bluesky_service;+ Http::fake([+ "{$appView}/xrpc/app.bsky.feed.getPosts*" => Http::response(['posts' => []]),+ "{$pds}/xrpc/com.atproto.repo.getRecord*" => Http::response(...$record),+ "{$pds}/xrpc/com.atproto.repo.listRecords*" => Http::response(...$list),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'the record still exists' => [[['uri' => 'at://did:plc:trypost/app.bsky.feed.post/3kpost']], [['records' => []]]],+ 'the repository is deactivated' => [[['error' => 'RepoDeactivated'], 400], [['records' => []]]],+ 'the repository does not list' => [[['error' => 'RecordNotFound'], 400], [['error' => 'RepoNotFound'], 400]],+]);++test('a Mastodon status the owner can no longer read is reported deleted while the account statuses still read', function (int $status) {+ $account = SocialAccount::factory()->mastodon()->create(['scopes' => ['read', 'write']]);+ $publication = networkPublication($account, '113000000000000001');+ Http::fake([+ "{$account->mastodon_instance}/api/v1/statuses/113000000000000001" => Http::response(['error' => 'Record not found'], $status),+ "{$account->mastodon_instance}/api/v1/accounts/*" => Http::response([['id' => '113000000000000002']]),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+ Http::assertSent(fn (Request $request): bool => Uri::of($request->url())->path() === "api/v1/accounts/{$account->platform_user_id}/statuses"+ && data_get($request->data(), 'limit') === 1+ && $request->hasHeader('Authorization'));+})->with(['404' => [404], '410' => [410]]);++test('a Mastodon status is not reported deleted without an owner read, an error other than 404, or an account that no longer reads', function (array $scopes, int $status, int $accountStatus) {+ $account = SocialAccount::factory()->mastodon()->create(['scopes' => $scopes]);+ $publication = networkPublication($account, '113000000000000001');+ Http::fake([+ "{$account->mastodon_instance}/api/v1/statuses/*" => Http::response(['error' => 'Record not found'], $status),+ "{$account->mastodon_instance}/api/v1/accounts/*" => Http::response([], $accountStatus),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'without read access' => [['write'], 404, 200],+ 'a server error' => [['read', 'write'], 500, 200],+ 'a refusal' => [['read', 'write'], 403, 200],+ 'the account no longer reads' => [['read', 'write'], 404, 401],+]);++test('a deletion check that fails only for now is retried before anything is reported', function (Closure $account, Closure $fakes, string $category) {+ $publication = networkPublication($account(), '113000000000000001');+ Http::fake($fakes($publication->socialAccount));++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe($category)->and($exception->gone)->toBeFalse());+})->with([+ 'mastodon statuses fail on the server' => [+ fn (): SocialAccount => SocialAccount::factory()->mastodon()->create(['scopes' => ['read']]),+ fn (SocialAccount $account): array => [+ "{$account->mastodon_instance}/api/v1/accounts/*" => Http::response([], 503),+ '*' => Http::response([], 404),+ ],+ 'transient',+ ],+ 'pinterest Pins fail on the server' => [+ fn (): SocialAccount => SocialAccount::factory()->pinterest()->create(),+ fn (): array => [+ config('trypost.platforms.pinterest.api').'/pins?*' => Http::response([], 503),+ '*' => Http::response(['code' => 2], 404),+ ],+ 'transient',+ ],+ 'pinterest Pin read is rate limited' => [+ fn (): SocialAccount => SocialAccount::factory()->pinterest()->create(),+ fn (): array => [+ config('trypost.platforms.pinterest.api').'/pins/113000000000000001/analytics*' => Http::response(['code' => 2], 404),+ '*' => Http::response([], 429),+ ],+ 'rate_limited',+ ],+ 'bluesky record read fails on the server' => [+ fn (): SocialAccount => SocialAccount::factory()->bluesky()->create(['platform_user_id' => 'did:plc:trypost']),+ fn (SocialAccount $account): array => [+ config('trypost.platforms.bluesky.public_appview').'/xrpc/app.bsky.feed.getPosts*' => Http::response(['posts' => []]),+ '*' => Http::response([], 503),+ ],+ 'transient',+ ],+]);++test('a Pinterest Pin the account no longer has is reported deleted while its Pins still read', function () {+ $publication = networkPublication(SocialAccount::factory()->pinterest()->create(), '900000000000000001');+ $api = config('trypost.platforms.pinterest.api');+ Http::fake([+ "{$api}/pins/900000000000000001*" => Http::response(['code' => 2, 'message' => 'Pin not found.'], 404),+ "{$api}/pins?page_size=1" => Http::response(['items' => [['id' => '900000000000000002']]]),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeTrue());+});++test('a Pinterest Pin that still reads, is refused, or whose Pins do not read, is not reported deleted', function (array $pin, array $pins) {+ $publication = networkPublication(SocialAccount::factory()->pinterest()->create(), '900000000000000001');+ $api = config('trypost.platforms.pinterest.api');+ Http::fake([+ "{$api}/pins/900000000000000001/analytics*" => Http::response(['code' => 2], 404),+ "{$api}/pins/900000000000000001" => Http::response(...$pin),+ "{$api}/pins?page_size=1" => Http::response(...$pins),+ ]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->deletedOnNetwork)->toBeFalse());+})->with([+ 'the Pin still reads' => [[['id' => '900000000000000001']], [['items' => []]]],+ 'the Pin read is refused' => [[['code' => 3], 401], [['items' => []]]],+ 'the Pins do not read' => [[['code' => 2], 404], [['code' => 3], 401]],+]);++test('a Pinterest read refused for authentication never checks whether the Pin was deleted', function () {+ $publication = networkPublication(SocialAccount::factory()->pinterest()->create(), '900000000000000001');+ Http::fake(['*' => Http::response(['code' => 3], 401)]);++ expect(collectFrom($publication))->toThrow(fn (AnalyticsCollectionException $exception): Expectation => expect($exception->category)->toBe('authentication'));+ Http::assertSentCount(1);+});+/*** @return array<string, mixed>*/diff --git a/tests/Feature/Analytics/InsightsExportTest.php b/tests/Feature/Analytics/InsightsExportTest.phpindex 772d364b8..c10ca9f87 100644--- a/tests/Feature/Analytics/InsightsExportTest.php+++ b/tests/Feature/Analytics/InsightsExportTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Analytics\PublicationAvailability;use App\Enums\SocialAccount\Platform;use App\Enums\User\Locale;use App\Jobs\Analytics\BootstrapAccountAnalytics;@@ -295,3 +296,13 @@ test('the export lists posts by the viewer local day', function () {->not->toContain('early-post')->not->toContain('alpha-reel');});++test('the export keeps a post the network deleted without its link', function () {+ AnalyticsPublication::query()->where('excerpt', 'alpha-reel')->update(['availability' => PublicationAvailability::Deleted]);++ $rows = collect(insightsCsvRows($this->actingAs($this->user)->get(insightsExportRoute('csv'))->streamedContent()))+ ->keyBy(fn (array $row): string => (string) data_get($row, 4));++ expect(data_get($rows->get('alpha-reel'), 5))->toBe('')+ ->and(data_get($rows->get('bravo-post'), 5))->toBe('https://example.com/bravo-post');+});diff --git a/tests/Feature/Analytics/InstagramStoriesImportTest.php b/tests/Feature/Analytics/InstagramStoriesImportTest.phpindex add91a790..bc7e7ce90 100644--- a/tests/Feature/Analytics/InstagramStoriesImportTest.php+++ b/tests/Feature/Analytics/InstagramStoriesImportTest.php@@ -46,7 +46,7 @@ beforeEach(function () {*/function fakeInstagramHistory(SocialAccount $account, array $media, array $stories): void{- $graph = $account->platform->instagramGraphBaseUrl();+ $graph = $account->platform->graphApiUrl();Http::fake(["{$graph}/{$account->platform_user_id}/media*" => Http::response(['data' => $media]),@@ -203,7 +203,7 @@ test('story metrics are scheduled once however many runs see the story', functiotest('a stories permission error does not stop the feed page', function () {$account = SocialAccount::factory()->instagram()->create();- $graph = $account->platform->instagramGraphBaseUrl();+ $graph = $account->platform->graphApiUrl();Http::fake(["{$graph}/{$account->platform_user_id}/media*" => Http::response(['data' => [['id' => 'feed-1', 'media_type' => 'IMAGE', 'timestamp' => '2026-09-28T12:00:00+0000'],diff --git a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php b/tests/Feature/Analytics/PersistedPostMetricsReadTest.phpindex f0012e674..1e4071395 100644--- a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php+++ b/tests/Feature/Analytics/PersistedPostMetricsReadTest.php@@ -3,6 +3,7 @@declare(strict_types=1);use App\Actions\Analytics\ReadPublicationAnalytics;+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\Analytics\PublicationContentType;use App\Enums\SocialAccount\Platform;use App\Jobs\Analytics\BootstrapAccountAnalytics;@@ -85,7 +86,7 @@ test('excluded destinations expose no analytics and a foreign post cannot be rea->assertOk()->assertStructuredContent(fn (AssertableJson $json) => $json->where('metrics.unsupported', true)- ->where('metrics.reason', 'platform_not_supported')+ ->where('metrics.reason', MetricsUnavailableReason::PlatformNotSupported->value)->etc());$foreignPost = Post::factory()->linkedin()->published()->create();diff --git a/tests/Feature/Analytics/PublicationMetricsJobsTest.php b/tests/Feature/Analytics/PublicationMetricsJobsTest.phpindex f6e5f6e9e..afb017478 100644--- a/tests/Feature/Analytics/PublicationMetricsJobsTest.php+++ b/tests/Feature/Analytics/PublicationMetricsJobsTest.php@@ -10,6 +10,7 @@ use App\Dto\Analytics\PublicationPage;use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;+use App\Enums\Post\PublishStatus;use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Enums\SocialAccount\Status;@@ -17,6 +18,8 @@ use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;use App\Jobs\Analytics\CollectPublicationMetrics;use App\Jobs\Analytics\ScheduleInstagramStoryMetrics;+use App\Jobs\Analytics\SyncTryPostPublication as SyncTryPostPublicationJob;+use App\Jobs\PostHog\SyncAccountPublishingActivity;use App\Models\AnalyticsPublication;use App\Models\AnalyticsPublicationDailySnapshot;use App\Models\Post;@@ -24,8 +27,11 @@ use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Metrics\MastodonPublicationMetricsCollector;use App\Services\Analytics\Collectors\Metrics\PublicationMetricsCollectorFactory;use App\Support\Analytics\SyncCadence;+use App\Support\PostStatusRules;use Carbon\CarbonImmutable;+use GuzzleHttp\Promise\PromiseInterface;use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;@@ -541,6 +547,194 @@ test('the daily run leaves a fresh post to its first read an hour after publishiBus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $settled->id);})->with([Platform::X, Platform::Instagram]);+test('a post deleted on Instagram is marked deleted and can then be deleted in TryPost', function () {+ $account = SocialAccount::factory()->create(['platform' => Platform::InstagramFacebook, 'platform_user_id' => '17841400000000001']);+ $post = Post::factory()->forAccount($account)->published()->create(['platform_post_id' => '17897891718416700']);+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'post_id' => $post->id,+ 'platform' => Platform::InstagramFacebook,+ 'network' => Platform::InstagramFacebook->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => '17897891718416700',+ 'provider_published_at' => now()->subHours(2),+ ]);+ $graph = Platform::InstagramFacebook->graphApiUrl();+ Http::fake([+ "{$graph}/17841400000000001*" => Http::response(['id' => '17841400000000001']),+ '*' => Http::response(['error' => ['code' => 100, 'error_subcode' => 33, 'type' => 'GraphMethodException']], 400),+ ]);++ expect(PostStatusRules::blocksDeletion($post))->toBeTrue();++ app()->call([new CollectPublicationMetrics($publication->id, now('UTC')->toDateString()), 'handle']);++ expect($publication->fresh()->availability)->toBe(PublicationAvailability::Deleted)+ ->and($post->fresh()->publish_status)->toBe(PublishStatus::Deleted)+ ->and(PostStatusRules::blocksDeletion($post->fresh()))->toBeFalse();+});++test('a post marked deleted that the network lists again is published again', function () {+ Queue::fake();+ $publication = metricJobPublication(Platform::Instagram, now('UTC')->subDay());+ $post = Post::factory()->forAccount($publication->socialAccount)->deletedOnNetwork()->create();+ $publication->forceFill(['post_id' => $post->id, 'availability' => PublicationAvailability::Deleted])->save();++ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, discoveredFor($publication));++ expect($publication->refresh()->availability)->toBe(PublicationAvailability::Available)+ ->and($post->refresh()->publish_status)->toBe(PublishStatus::Published);+ Queue::assertNotPushed(SyncTryPostPublicationJob::class);+ Queue::assertNotPushed(SyncAccountPublishingActivity::class);+ Queue::assertPushed(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $publication->id);+});++test('a post a stale discovery lists again after its metrics window is read again and stays deleted', function () {+ Queue::fake();+ $publication = metricJobPublication(Platform::Instagram, SyncCadence::metricsWindowStart(Platform::Instagram, now('UTC'))->subDays(3));+ $post = Post::factory()->forAccount($publication->socialAccount)->deletedOnNetwork()->create(['platform_post_id' => $publication->remote_id]);+ $publication->forceFill(['post_id' => $post->id, 'availability' => PublicationAvailability::Deleted, 'last_seen_at' => now()->subDay()])->save();++ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, discoveredFor($publication));++ expect($post->refresh()->publish_status)->toBe(PublishStatus::Published);++ $publication->forceFill(['last_seen_at' => now()->subHour()])->save();+ $graph = Platform::Instagram->graphApiUrl();+ Http::fake([+ "{$graph}/{$publication->platform_user_id}/media*" => Http::response(['data' => [['id' => '1']]]),+ '*' => Http::response(['error' => ['code' => 100, 'error_subcode' => 33]], 400),+ ]);++ Queue::pushed(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $publication->id)+ ->each(fn (CollectPublicationMetrics $job) => app()->call([$job, 'handle']));++ expect($post->refresh()->publish_status)->toBe(PublishStatus::Deleted);+});++test('a discovery of a live publication never reads its post', function () {+ Queue::fake();+ $publication = metricJobPublication(Platform::Instagram, now('UTC')->subDay());+ $post = Post::factory()->forAccount($publication->socialAccount)->published()->create();+ $publication->forceFill(['post_id' => $post->id])->save();+ $postsRead = 0;+ Event::listen('eloquent.retrieved: '.Post::class, function () use (&$postsRead): void {+ $postsRead++;+ });++ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, discoveredFor($publication));++ expect($postsRead)->toBe(0)+ ->and($post->fresh()->publish_status)->toBe(PublishStatus::Published);+});++test('a discovery during the deletion check keeps the post published, even in the same second', function () {+ $this->travelTo(now()->startOfSecond());+ $publication = metricJobPublication(Platform::InstagramFacebook, now('UTC')->subHours(2));+ $publication->forceFill(['last_seen_at' => now()->subHour()])->save();+ $post = Post::factory()->forAccount($publication->socialAccount)->published()->create(['platform_post_id' => $publication->remote_id]);+ $publication->forceFill(['post_id' => $post->id])->save();+ $graph = Platform::InstagramFacebook->graphApiUrl();+ Http::fake([+ "{$graph}/{$publication->platform_user_id}/media*" => function () use ($publication) {+ app(UpsertAnalyticsPublication::class)->external($publication->socialAccount, discoveredFor($publication));++ return Http::response(['data' => [['id' => '1']]]);+ },+ '*' => Http::response(['error' => ['code' => 100, 'error_subcode' => 33]], 400),+ ]);++ app()->call([new CollectPublicationMetrics($publication->id, now('UTC')->toDateString()), 'handle']);++ expect($publication->fresh()->availability)->toBe(PublicationAvailability::Available)+ ->and($post->fresh()->publish_status)->toBe(PublishStatus::Published);+});++test('a confirmed deletion moves the post, while a bare 404 only marks its publication', function (Platform $platform, array $response, PublishStatus $expected) {+ $publication = metricJobPublication($platform, now('UTC')->subHours(2));+ $post = Post::factory()->forAccount($publication->socialAccount)->published()->create(['platform_post_id' => $publication->remote_id]);+ $publication->forceFill(['post_id' => $post->id])->save();+ Http::fake(['*' => Http::response(...$response)]);++ app()->call([new CollectPublicationMetrics($publication->id, now('UTC')->toDateString()), 'handle']);++ expect($publication->fresh()->availability)->toBe(PublicationAvailability::Deleted)+ ->and($post->fresh()->publish_status)->toBe($expected);+})->with([+ 'youtube no longer lists the video' => [Platform::YouTube, [['items' => []]], PublishStatus::Deleted],+ 'x answers 404' => [Platform::X, [[], 404], PublishStatus::Published],+]);++test('a deletion X, Bluesky, Mastodon or Pinterest confirms moves the post', function (Platform $platform, array $scopes, Closure $fakes) {+ $publication = metricJobPublication($platform, now('UTC')->subHours(2));+ $account = $publication->socialAccount;+ $account->update(['scopes' => $scopes]);+ $post = Post::factory()->forAccount($account)->published()->create(['platform_post_id' => $publication->remote_id]);+ $publication->forceFill(['post_id' => $post->id])->save();+ Http::fake($fakes($publication, $account->fresh()));++ app()->call([new CollectPublicationMetrics($publication->id, now('UTC')->toDateString()), 'handle']);++ expect($publication->fresh()->availability)->toBe(PublicationAvailability::Deleted)+ ->and($post->fresh()->publish_status)->toBe(PublishStatus::Deleted);+})->with([+ 'x' => [Platform::X, ['tweet.read', 'users.read'], fn (AnalyticsPublication $publication): array => ['*' => Http::response(['errors' => [[+ 'type' => 'https://api.x.com/2/problems/resource-not-found',+ 'resource_type' => 'tweet',+ 'resource_id' => $publication->remote_id,+ ]]])]],+ 'bluesky' => [Platform::Bluesky, [], fn (AnalyticsPublication $publication, SocialAccount $account): array => [+ config('trypost.platforms.bluesky.public_appview').'/xrpc/app.bsky.feed.getPosts*' => Http::response(['posts' => []]),+ "{$account->bluesky_service}/xrpc/com.atproto.repo.getRecord*" => Http::response(['error' => 'RecordNotFound'], 400),+ "{$account->bluesky_service}/xrpc/com.atproto.repo.listRecords*" => Http::response(['records' => []]),+ ]],+ 'mastodon' => [Platform::Mastodon, ['read'], fn (AnalyticsPublication $publication, SocialAccount $account): array => [+ "{$account->mastodon_instance}/api/v1/statuses/*" => Http::response([], 404),+ "{$account->mastodon_instance}/api/v1/accounts/*" => Http::response([]),+ ]],+ 'pinterest' => [Platform::Pinterest, ['pins:read', 'boards:read'], function (AnalyticsPublication $publication): array {+ $api = config('trypost.platforms.pinterest.api');++ return [+ "{$api}/pins/{$publication->remote_id}*" => Http::response(['code' => 2], 404),+ "{$api}/pins?page_size=1" => Http::response(['items' => []]),+ ];+ }],+]);++test('a publication removed while its deletion is being checked is left alone', function () {+ $publication = metricJobPublication(Platform::Mastodon, now('UTC')->subHours(2));+ $account = $publication->socialAccount;+ $account->update(['scopes' => ['read']]);+ $post = Post::factory()->forAccount($account)->published()->create(['platform_post_id' => $publication->remote_id]);+ $publication->forceFill(['post_id' => $post->id])->save();+ Http::fake([+ "{$account->mastodon_instance}/api/v1/statuses/*" => Http::response([], 404),+ "{$account->mastodon_instance}/api/v1/accounts/*" => function () use ($publication): PromiseInterface {+ $publication->delete();++ return Http::response([]);+ },+ ]);++ app()->call([new CollectPublicationMetrics($publication->id, now('UTC')->toDateString()), 'handle']);++ expect($post->fresh()->publish_status)->toBe(PublishStatus::Published);+});++test('only a published post is marked deleted, and only a deleted one is restored', function () {+ $inReview = Post::factory()->published()->create(['publish_status' => PublishStatus::PendingReview]);+ $failed = Post::factory()->published()->create(['publish_status' => PublishStatus::Failed]);++ $inReview->markPublicationDeleted();+ $failed->markPublicationRestored();++ expect($inReview->fresh()->publish_status)->toBe(PublishStatus::PendingReview)+ ->and($failed->fresh()->publish_status)->toBe(PublishStatus::Failed);+});+test('collecting x metrics stores the poll on the publication', function () {$date = CarbonImmutable::now('UTC');$publication = metricJobPublication(Platform::X, $date->subDay());diff --git a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.phpindex ab0e6f02a..ca5eb5e8c 100644--- a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php+++ b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php@@ -6,7 +6,9 @@ use App\Actions\Analytics\BuildWorkspaceAnalyticsReport;use App\Actions\Analytics\GetAnalyticsBounds;use App\Actions\Analytics\ReadPublicationAnalytics;use App\Dto\Analytics\DateRange;+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\Analytics\ObservationProvenance;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\SyncStatus;use App\Enums\SocialAccount\Platform;@@ -22,6 +24,7 @@ use App\Models\SocialAccount;use App\Models\Workspace;use App\Support\Analytics\PeriodBuckets;use Carbon\CarbonImmutable;+use Illuminate\Database\Eloquent\ModelNotFoundException;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;@@ -397,7 +400,7 @@ test('publication detail remains scoped to the post workspace and excludes unsupexpect(app(ReadPublicationAnalytics::class)->latestFor($post)['available'])->toBeFalse();$post->update(['platform' => Platform::LinkedIn]);- expect(app(ReadPublicationAnalytics::class)->latestFor($post)['reason'])->toBe('platform_not_supported');+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['reason'])->toBe(MetricsUnavailableReason::PlatformNotSupported->value);});test('external YouTube upload stays a video and not a short without authoritative metadata', function () {@@ -500,3 +503,42 @@ test('publication detail shows the current avatar of a live account', function (expect(data_get($detail, 'publication.account_avatar_url'))->toBe('https://current-cdn.test/social-accounts/avatar.jpg');});++test('top posts drop the link of a publication the network deleted', function () {+ $workspace = Workspace::factory()->create();+ $account = analyticsReportAccount($workspace, Platform::Instagram);+ $start = now('UTC')->subDays(10)->startOfDay();+ $live = analyticsReportPublication($account, $start->addDays(2)->toDateTimeString(), 9, 1, 10, 100);+ $deleted = analyticsReportPublication($account, $start->addDays(3)->toDateTimeString(), 5, 1, 6, 100);+ $deleted->update(['availability' => PublicationAvailability::Deleted]);++ $report = app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, new DateRange($start, $start->addDays(9)));+ $top = collect($report['top_posts']['reactions'])->keyBy('id');++ expect(data_get($top->get($live->id), 'permalink'))->toBe($live->permalink)+ ->and($top->has($deleted->id))->toBeTrue()+ ->and(data_get($top->get($deleted->id), 'permalink'))->toBeNull();+});++test('publication detail opens a publication the network deleted, without its link', function () {+ $workspace = Workspace::factory()->create();+ $account = analyticsReportAccount($workspace, Platform::Instagram);+ $publication = analyticsReportPublication($account, now('UTC')->subDays(3)->toDateTimeString(), 5, 1, 6, 100);+ $publication->update(['availability' => PublicationAvailability::Deleted]);++ $detail = app(ReadPublicationAnalytics::class)->latestForWorkspacePublication($workspace, $publication->id);++ expect(data_get($detail, 'publication.availability'))->toBe(PublicationAvailability::Deleted->value)+ ->and(data_get($detail, 'publication.permalink'))->toBeNull()+ ->and(data_get($detail, 'metrics'))->not->toBeEmpty();+});++test('publication detail never opens a publication that is no longer available', function () {+ $workspace = Workspace::factory()->create();+ $account = analyticsReportAccount($workspace, Platform::Instagram);+ $publication = analyticsReportPublication($account, now('UTC')->subDays(3)->toDateTimeString(), 5, 1, 6, 100);+ $publication->update(['availability' => PublicationAvailability::Unavailable]);++ expect(fn () => app(ReadPublicationAnalytics::class)->latestForWorkspacePublication($workspace, $publication->id))+ ->toThrow(ModelNotFoundException::class);+});diff --git a/tests/Feature/Api/PostMediaApiTest.php b/tests/Feature/Api/PostMediaApiTest.phpindex 6afdb5e9c..141093717 100644--- a/tests/Feature/Api/PostMediaApiTest.php+++ b/tests/Feature/Api/PostMediaApiTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\SocialAccount\Platform;use App\Models\Media;use App\Models\Post;@@ -172,7 +173,7 @@ it('returns metrics shape including unsupported reason for an unpublished post','metrics',])->assertJsonPath('metrics.unsupported', true)- ->assertJsonPath('metrics.reason', 'not_published');+ ->assertJsonPath('metrics.reason', MetricsUnavailableReason::NotPublished->value);});it('returns platform_not_supported for a published google business target', function () {@@ -189,7 +190,7 @@ it('returns platform_not_supported for a published google business target', func->assertOk()->assertJsonPath('platform', Platform::GoogleBusiness->value)->assertJsonPath('metrics.unsupported', true)- ->assertJsonPath('metrics.reason', 'platform_not_supported');+ ->assertJsonPath('metrics.reason', MetricsUnavailableReason::PlatformNotSupported->value);});it('cannot get metrics from another workspace post', function () {diff --git a/tests/Feature/InstagramFacebookIntegrationTest.php b/tests/Feature/InstagramFacebookIntegrationTest.phpindex 479ca9736..4c5de8c0a 100644--- a/tests/Feature/InstagramFacebookIntegrationTest.php+++ b/tests/Feature/InstagramFacebookIntegrationTest.php@@ -33,13 +33,14 @@ beforeEach(function () {]);});-test('instagram facebook platform uses graph.facebook.com base url', function () {- expect(Platform::InstagramFacebook->instagramGraphBaseUrl())- ->toContain('graph.facebook.com');-- expect(Platform::Instagram->instagramGraphBaseUrl())- ->toContain('graph.instagram.com');-});+test('each Meta platform reads its own Graph API', function (Platform $platform, string $configKey, string $host) {+ expect($platform->graphApiUrl())->toBe(config($configKey))->toContain($host);+})->with([+ 'instagram via facebook' => [Platform::InstagramFacebook, 'trypost.platforms.instagram-facebook.graph_api', 'graph.facebook.com'],+ 'instagram login' => [Platform::Instagram, 'trypost.platforms.instagram.graph_api', 'graph.instagram.com'],+ 'facebook' => [Platform::Facebook, 'trypost.platforms.facebook.graph_api', 'graph.facebook.com'],+ 'threads' => [Platform::Threads, 'trypost.platforms.threads.graph_api', 'graph.threads.net'],+]);test('instagram facebook platform has correct label', function () {expect(Platform::InstagramFacebook->label())diff --git a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.phpindex 33ec5693d..1e43aed18 100644--- a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php+++ b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php@@ -70,6 +70,27 @@ test('handle sends the latest confirmed account publication directly to PostHog'$job->handle($postHog);});+test('a post the network deleted after publishing still counts as the latest publication and for the lifecycle', function () {+ $workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $post = Post::factory()->linkedin()->deletedOnNetwork()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $this->user->id,+ 'published_at' => now()->subHour(),+ ]);++ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldReceive('groupIdentifyNow')+ ->once()+ ->withArgs(fn (string $groupType, string $groupKey, array $properties): bool => $properties['last_published_post_id'] === $post->id);++ (new SyncAccountPublishingActivity((string) $this->account->id))->handle($postHog);++ expect(Account::query()->withLifecycleActivity()->find($this->account->id)->last_published_at)->not->toBeNull();+});+test('handle clears publishing activity when the account has no confirmed publication', function () {$workspace = Workspace::factory()->create(['account_id' => $this->account->id,diff --git a/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php b/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.phpindex ee5197459..b4d0a253b 100644--- a/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php+++ b/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php@@ -58,8 +58,8 @@ test('a scheduled instagram feed image that became too wide fails without callin->and($this->post->fresh()->status)->toBe(PostStatus::Failed);Http::assertNotSent(fn (Request $request): bool => $request->method() !== 'GET'- && (str_starts_with($request->url(), (string) config('trypost.platforms.instagram.graph_api'))- || str_starts_with($request->url(), (string) config('trypost.platforms.instagram-facebook.graph_api'))));+ && (str_starts_with($request->url(), config('trypost.platforms.instagram.graph_api'))+ || str_starts_with($request->url(), config('trypost.platforms.instagram-facebook.graph_api'))));});test('a still valid instagram feed image reaches the publisher', function () {diff --git a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.phpindex e9ab6cdd9..282a9e4b8 100644--- a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php+++ b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php@@ -210,7 +210,7 @@ test('a dead token during review is refreshed before the post is deferred', funcreturn Http::response(['access_token' => 'rotated-token', 'expires_in' => 3600]);}- if (str_contains($url, (string) config('trypost.platforms.google_business.business_information_api'))) {+ if (str_contains($url, config('trypost.platforms.google_business.business_information_api'))) {$info++;if ($info === 1) {diff --git a/tests/Feature/Jobs/SocialPublishingPipelineTest.php b/tests/Feature/Jobs/SocialPublishingPipelineTest.phpindex b7e4e554a..4749bc31f 100644--- a/tests/Feature/Jobs/SocialPublishingPipelineTest.php+++ b/tests/Feature/Jobs/SocialPublishingPipelineTest.php@@ -169,7 +169,7 @@ test('instagram does not duplicate a captionless publication after losing its me]);$account = $target->socialAccount;$account->update(['scopes' => [...$account->scopes, 'instagram_basic', 'instagram_business_basic']]);- $base = $platform->instagramGraphBaseUrl();+ $base = $platform->graphApiUrl();$story = $contentType === ContentType::InstagramStory;$discovered = [['id' => 'media-123',diff --git a/tests/Feature/Media/GoogleDriveImportTest.php b/tests/Feature/Media/GoogleDriveImportTest.phpindex 169e38b1b..ccefbe9a8 100644--- a/tests/Feature/Media/GoogleDriveImportTest.php+++ b/tests/Feature/Media/GoogleDriveImportTest.php@@ -299,7 +299,10 @@ test('google drive is not importable or offered with only the login google clien});test('the drive url is built only from the configured host and a plain id', function () {- config()->set('trypost.media_sources.google_drive.api', 'https://drive.example.test/drive/v3/');+ config()->set('trypost.media_sources.google_drive.api', data_get(+ trypostConfigWith(['GOOGLE_DRIVE_API_URL' => 'https://drive.example.test/drive/v3/']),+ 'media_sources.google_drive.api',+ ));$file = GoogleDriveFiles::toRemoteFile('token', ['id' => 'abc-1_2', 'name' => 'a.png']);diff --git a/tests/Feature/Media/GoogleMediaOAuthTest.php b/tests/Feature/Media/GoogleMediaOAuthTest.phpindex 72606ab7d..f7db7320e 100644--- a/tests/Feature/Media/GoogleMediaOAuthTest.php+++ b/tests/Feature/Media/GoogleMediaOAuthTest.php@@ -73,7 +73,7 @@ function googleMediaTokenUrl(): stringfunction googleMediaPhotosApi(): string{- return rtrim((string) config('trypost.media_sources.google_photos.api'), '/').'/v1';+ return config('trypost.media_sources.google_photos.api').'/v1';}/**diff --git a/tests/Feature/Media/GooglePhotosTest.php b/tests/Feature/Media/GooglePhotosTest.phpindex 055697bd1..19db674d0 100644--- a/tests/Feature/Media/GooglePhotosTest.php+++ b/tests/Feature/Media/GooglePhotosTest.php@@ -56,7 +56,7 @@ beforeEach(function () {function googlePhotosApi(): string{- return rtrim((string) config('trypost.media_sources.google_photos.api'), '/').'/v1';+ return config('trypost.media_sources.google_photos.api').'/v1';}/**diff --git a/tests/Feature/Parity/FullPostParityTest.php b/tests/Feature/Parity/FullPostParityTest.phpindex 75cfa4571..f3acf06f1 100644--- a/tests/Feature/Parity/FullPostParityTest.php+++ b/tests/Feature/Parity/FullPostParityTest.php@@ -46,6 +46,7 @@ function fullPostRouter(): Closure$discord = config('trypost.platforms.discord.api');$telegram = config('trypost.platforms.telegram.api');$google = config('trypost.platforms.google_business.local_posts_api');+ $youtube = config('trypost.platforms.youtube.data_api');return match (true) {str_contains($url, 'storage/') && str_ends_with($url, '.mp4') => Http::response(str_repeat("\x00\xff", 2048), 200, ['Content-Type' => 'video/mp4']),@@ -86,6 +87,7 @@ function fullPostRouter(): Closurestr_starts_with($url, $tiktok) && str_contains($url, '/status/fetch/') => Http::response(['data' => ['status' => 'PUBLISH_COMPLETE', 'publicaly_available_post_id' => ['7000000000000000001']], 'error' => ['code' => 'ok']], 200),str_contains($url, 'youtube.googleapis.com/upload') || str_contains($url, 'googleapis.com/upload/youtube') => Http::response('', 200, ['Location' => 'https://upload.example.test/session']),str_contains($url, 'upload.example.test/session') => Http::response(['id' => 'yt-short-id']),+ str_starts_with($url, "{$youtube}/videos") && $method === 'GET' => Http::response(['items' => [['id' => 'yt-short-id', 'statistics' => ['viewCount' => '0']]]], 200),str_starts_with($url, $discord) && str_contains($url, '/guilds/') && str_ends_with($url, '/channels') => Http::response([['id' => '444555666', 'name' => 'general', 'type' => 0]], 200),str_starts_with($url, $discord) && str_contains($url, '/roles') => Http::response([['id' => '999000111', 'name' => '@everyone', 'permissions' => '248832']], 200),str_starts_with($url, $discord) && str_contains($url, '/members/') => Http::response(['roles' => []], 200),diff --git a/tests/Feature/Parity/PostsParityTest.php b/tests/Feature/Parity/PostsParityTest.phpindex 882bf94a1..a057977be 100644--- a/tests/Feature/Parity/PostsParityTest.php+++ b/tests/Feature/Parity/PostsParityTest.php@@ -3,12 +3,14 @@declare(strict_types=1);use App\Actions\Post\DeleteChannelPosts;+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\Post\Status;use App\Enums\SocialAccount\Platform;use App\Mcp\Servers\TryPostServer;use App\Mcp\Tools\Post\CreatePostsTool;use App\Mcp\Tools\Post\CreatePostTool;use App\Mcp\Tools\Post\DeletePostTool;+use App\Mcp\Tools\Post\GetPostMetricsTool;use App\Mcp\Tools\Post\GetPostTool;use App\Mcp\Tools\Post\ListPostsTool;use App\Mcp\Tools\Post\PreviewPostTool;@@ -248,6 +250,43 @@ test('deleting a publishing, published or failed post is refused with the web meexpect(Post::query()->whereKey($post->id)->exists())->toBeTrue();})->with([Status::Publishing, Status::Published, Status::Failed]);+test('a published post the network no longer returns can be deleted on the web, the api and mcp', function () {+ $posts = Post::factory()->count(3)->forAccount($this->account)->deletedOnNetwork()->create([+ 'user_id' => $this->user->id,+ ]);++ $this->actingAs($this->user)->delete(route('app.posts.destroy', $posts[0]))->assertRedirect();++ auth()->forgetGuards();++ $this->withHeaders(parityApi($this->token))+ ->deleteJson(route('api.posts.destroy', $posts[1]))+ ->assertNoContent();++ auth()->forgetGuards();++ TryPostServer::actingAs($this->user)->tool(DeletePostTool::class, ['post_id' => $posts[2]->id])->assertOk();++ expect(Post::query()->whereKey($posts->pluck('id'))->exists())->toBeFalse();+});++test('the metrics of a post the network deleted say so on the api and mcp', function () {+ $post = Post::factory()->forAccount($this->account)->deletedOnNetwork()->create([+ 'user_id' => $this->user->id,+ ]);++ $this->withHeaders(parityApi($this->token))+ ->getJson(route('api.posts.metrics', $post))+ ->assertOk()+ ->assertJsonPath('metrics.reason', MetricsUnavailableReason::DeletedOnNetwork->value);++ auth()->forgetGuards();++ TryPostServer::actingAs($this->user)->tool(GetPostMetricsTool::class, ['post_id' => $post->id])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json): AssertableJson => $json->where('metrics.reason', MetricsUnavailableReason::DeletedOnNetwork->value)->etc());+});+test('a channel disconnect still deletes published posts', function () {$post = Post::factory()->forAccount($this->account)->published()->create(['user_id' => $this->user->id]);diff --git a/tests/Feature/Posts/ExternalMediaResolversTest.php b/tests/Feature/Posts/ExternalMediaResolversTest.phpindex b1a43f272..fe049be4c 100644--- a/tests/Feature/Posts/ExternalMediaResolversTest.php+++ b/tests/Feature/Posts/ExternalMediaResolversTest.php@@ -12,10 +12,9 @@ use App\Services\Post\ExternalMedia\BlueskyMediaResolver;use App\Services\Post\ExternalMedia\CoverOnlyResolver;use App\Services\Post\ExternalMedia\ExternalMediaResolverFactory;use App\Services\Post\ExternalMedia\FacebookMediaResolver;-use App\Services\Post\ExternalMedia\InstagramMediaResolver;use App\Services\Post\ExternalMedia\MastodonMediaResolver;+use App\Services\Post\ExternalMedia\MetaCarouselResolver;use App\Services\Post\ExternalMedia\PinterestMediaResolver;-use App\Services\Post\ExternalMedia\ThreadsMediaResolver;use App\Services\Post\ExternalMedia\XMediaResolver;use Illuminate\Http\Client\Request;use Illuminate\Http\Client\RequestException;@@ -50,9 +49,9 @@ function resolvedUrls(array $files): arraytest('the factory picks one resolver per network', function (Platform $platform, string $resolver) {expect(app(ExternalMediaResolverFactory::class)->for($platform))->toBeInstanceOf($resolver);})->with([- [Platform::Instagram, InstagramMediaResolver::class],- [Platform::InstagramFacebook, InstagramMediaResolver::class],- [Platform::Threads, ThreadsMediaResolver::class],+ [Platform::Instagram, MetaCarouselResolver::class],+ [Platform::InstagramFacebook, MetaCarouselResolver::class],+ [Platform::Threads, MetaCarouselResolver::class],[Platform::Facebook, FacebookMediaResolver::class],[Platform::TikTok, CoverOnlyResolver::class],[Platform::YouTube, CoverOnlyResolver::class],@@ -69,7 +68,7 @@ test('instagram returns carousel children in order and drops items without a fil]],])]);- $files = app(InstagramMediaResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-carousel']));+ $files = app(MetaCarouselResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-carousel']));expect(resolvedUrls($files))->toBe(['https://scontent.example.test/a.jpg', 'https://scontent.example.test/b.mp4']);Http::assertSent(fn ($request): bool => str_contains((string) $request['fields'], 'children{media_type,media_url}'));@@ -82,7 +81,7 @@ test('instagram through facebook uses the facebook graph host for a single reel''media_url' => 'https://scontent.example.test/reel.mp4',])]);- $files = app(InstagramMediaResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-reel']));+ $files = app(MetaCarouselResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-reel']));expect(resolvedUrls($files))->toBe(['https://scontent.example.test/reel.mp4']);});@@ -91,7 +90,7 @@ test('instagram media with copyrighted audio exposes no file', function () {$account = SocialAccount::factory()->instagram()->create();Http::fake([config('trypost.platforms.instagram.graph_api').'/ig-music*' => Http::response(['media_type' => 'VIDEO'])]);- expect(app(InstagramMediaResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-music'])))->toBe([]);+ expect(app(MetaCarouselResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'ig-music'])))->toBe([]);});test('threads returns carousel children in order', function () {@@ -104,7 +103,7 @@ test('threads returns carousel children in order', function () {]],])]);- $files = app(ThreadsMediaResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'th-1']));+ $files = app(MetaCarouselResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'th-1']));expect(resolvedUrls($files))->toBe(['https://scontent.example.test/t1.jpg', 'https://scontent.example.test/t2.jpg']);});@@ -163,7 +162,7 @@ test('a graph error surfaces as a request exception', function () {$account = SocialAccount::factory()->instagram()->create();Http::fake([config('trypost.platforms.instagram.graph_api').'/*' => Http::response(['error' => ['code' => 4]], 429)]);- expect(fn () => app(InstagramMediaResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'x'])))+ expect(fn () => app(MetaCarouselResolver::class)->files($account, resolverPublication($account, ['remote_id' => 'x'])))->toThrow(RequestException::class);});@@ -201,7 +200,7 @@ test('the factory covers the open networks', function (Platform $platform, strintest('mastodon returns image video and gifv attachments in order', function () {$account = SocialAccount::factory()->mastodon()->create(['scopes' => ['read']]);- $instance = $account->mastodonInstance();+ $instance = $account->mastodon_instance;Http::fake(["{$instance}/api/v1/statuses/1100" => Http::response(['media_attachments' => [['type' => 'image', 'url' => 'https://files.example.test/a.png'],['type' => 'audio', 'url' => 'https://files.example.test/b.mp3'],@@ -217,7 +216,7 @@ test('mastodon returns image video and gifv attachments in order', function () {test('mastodon reads a public status without a token when the account lacks a read scope', function () {$account = SocialAccount::factory()->mastodon()->create(['scopes' => ['write:statuses'], 'meta' => []]);- $instance = rtrim((string) config('trypost.platforms.mastodon.default_instance'), '/');+ $instance = config('trypost.platforms.mastodon.default_instance');Http::fake(["{$instance}/api/v1/statuses/1200" => Http::response(['media_attachments' => [['type' => 'image', 'url' => 'https://files.example.test/d.png'],]])]);@@ -230,7 +229,7 @@ test('mastodon reads a public status without a token when the account lacks a retest('bluesky returns full size images and nothing for a video', function () {$account = SocialAccount::factory()->bluesky()->create();- $appView = rtrim((string) config('trypost.platforms.bluesky.public_appview'), '/');+ $appView = config('trypost.platforms.bluesky.public_appview');Http::fake(["{$appView}/xrpc/app.bsky.feed.getPosts*" => Http::sequence()->push(['posts' => [['embed' => ['images' => [['fullsize' => 'https://cdn.bsky.example.test/1.jpg'],diff --git a/tests/Feature/Posts/PublishPageTest.php b/tests/Feature/Posts/PublishPageTest.phpindex 100ec724f..7cd7c46ec 100644--- a/tests/Feature/Posts/PublishPageTest.php+++ b/tests/Feature/Posts/PublishPageTest.php@@ -3,6 +3,7 @@declare(strict_types=1);use App\Actions\Post\BuildPublishPageProps;+use App\Enums\Analytics\MetricsUnavailableReason;use App\Enums\Post\Origin;use App\Enums\Post\PublishStatus as PlatformStatus;use App\Enums\Post\ScheduleMode;@@ -192,7 +193,24 @@ test('the sent tab returns settled posts newest first with metrics', function ()->where('posts.data.0.can_delete', false)->where('posts.data.2.can_delete', false)->has('posts.data.0.metrics')- ->where('posts.data.2.metrics.reason', 'not_published')));+ ->where('posts.data.2.metrics.reason', MetricsUnavailableReason::NotPublished->value)));+});++test('the sent tab lets a post deleted on the network be deleted, and keeps other published posts', function () {+ $live = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDays(2)], ['publish_status' => PlatformStatus::Published]);+ $deleted = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDay()], ['publish_status' => PlatformStatus::Deleted]);++ $this->actingAs($this->user)+ ->get(route('app.posts.index', ['tab' => 'sent']))+ ->assertOk()+ ->assertInertia(fn (AssertableInertia $page) => $page+ ->loadDeferredProps(fn ($reload) => $reload+ ->where('posts.data.0.id', $deleted->id)+ ->where('posts.data.0.publish_status', PlatformStatus::Deleted->value)+ ->where('posts.data.0.can_delete', true)+ ->where('posts.data.0.metrics.reason', MetricsUnavailableReason::DeletedOnNetwork->value)+ ->where('posts.data.1.id', $live->id)+ ->where('posts.data.1.can_delete', false)));});test('the sent tab places a failed post at the time it was attempted, not when its row was last touched', function () {@@ -431,6 +449,19 @@ test('an invalid time zone and an oversized queue window fall back safely', func->where('queue.queueDays', 14)));});+test('sent this week still counts a post the network deleted afterwards', function () {+ foreach ([PlatformStatus::Published, PlatformStatus::Deleted] as $publishStatus) {+ publishPagePost($this->channel, PostStatus::Published, [], [+ 'publish_status' => $publishStatus,+ 'published_at' => now()->subMinutes(5),+ ]);+ }++ $this->actingAs($this->user)+ ->get(route('app.channels.publish', $this->channel))+ ->assertInertia(fn (AssertableInertia $page) => $page->where('channel.sent_this_week', 2));+});+test("sent this week starts on the viewer's week start in the channel time zone", function (WeekStart $weekStart, int $expected) {$this->travelTo(CarbonImmutable::parse('2026-09-30 12:00:00', 'America/Sao_Paulo'));$this->channel->update(['timezone' => 'America/Sao_Paulo']);diff --git a/tests/Feature/Services/Social/ConnectionVerifierEndpointsTest.php b/tests/Feature/Services/Social/ConnectionVerifierEndpointsTest.phpindex a0457cf29..99b54cc0c 100644--- a/tests/Feature/Services/Social/ConnectionVerifierEndpointsTest.php+++ b/tests/Feature/Services/Social/ConnectionVerifierEndpointsTest.php@@ -40,8 +40,8 @@ function verifierEndpointCase(string $case): array'tiktok' => [SocialAccount::factory()->tiktok()->create($future), config('trypost.platforms.tiktok.api').'/user/info/'],'youtube' => [SocialAccount::factory()->youtube()->create($future), config('trypost.platforms.youtube.data_api').'/channels'],'facebook' => [SocialAccount::factory()->facebook()->create($future), config('trypost.platforms.facebook.graph_api').'/me'],- 'instagram' => [SocialAccount::factory()->instagram()->create($future), Platform::Instagram->instagramGraphBaseUrl().'/me'],- 'instagram via facebook' => [SocialAccount::factory()->create(['platform' => Platform::InstagramFacebook, ...$future]), Platform::InstagramFacebook->instagramGraphBaseUrl().'/me'],+ 'instagram' => [SocialAccount::factory()->instagram()->create($future), Platform::Instagram->graphApiUrl().'/me'],+ 'instagram via facebook' => [SocialAccount::factory()->create(['platform' => Platform::InstagramFacebook, ...$future]), Platform::InstagramFacebook->graphApiUrl().'/me'],'threads' => [SocialAccount::factory()->threads()->create($future), config('trypost.platforms.threads.graph_api').'/me'],'pinterest' => [SocialAccount::factory()->pinterest()->create($future), config('trypost.platforms.pinterest.api').'/user_account'],'bluesky' => [SocialAccount::factory()->bluesky()->create($future), 'https://bsky.social/xrpc/app.bsky.actor.getProfile'],diff --git a/tests/Feature/Services/Social/ConnectionVerifierTest.php b/tests/Feature/Services/Social/ConnectionVerifierTest.phpindex 60be48a78..d36fce4dc 100644--- a/tests/Feature/Services/Social/ConnectionVerifierTest.php+++ b/tests/Feature/Services/Social/ConnectionVerifierTest.php@@ -1361,7 +1361,7 @@ test('bluesky verify throws TokenExpiredException when getProfile reports Expiretest('mastodon verify treats a 5xx as platform unavailable, not a disconnect', function () {$account = SocialAccount::factory()->mastodon()->create();- $instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');+ $instance = $account->mastodon_instance;Http::fake(["{$instance}/api/v1/accounts/verify_credentials" => Http::response(['error' => 'Internal Server Error'], 503),@@ -1373,7 +1373,7 @@ test('mastodon verify treats a 5xx as platform unavailable, not a disconnect', ftest('mastodon verify throws TokenExpiredException on a bare 401, with no refresh attempt (mastodon tokens do not expire)', function () {$account = SocialAccount::factory()->mastodon()->create();- $instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');+ $instance = $account->mastodon_instance;Http::fake(["{$instance}/api/v1/accounts/verify_credentials" => Http::response(['error' => 'The access token was revoked'], 401),@@ -1395,7 +1395,7 @@ test('mastodon verify throws TokenExpiredException on a bare 403 from verify_cre// revoked. MastodonPublishException::isConfirmedDeadToken() is 401-only// by design — this is ConnectionVerifier's own additional check.$account = SocialAccount::factory()->mastodon()->create();- $instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');+ $instance = $account->mastodon_instance;Http::fake(["{$instance}/api/v1/accounts/verify_credentials" => Http::response(['error' => 'This action is not allowed'], 403),diff --git a/tests/Feature/Services/Social/InstagramPublisherTest.php b/tests/Feature/Services/Social/InstagramPublisherTest.phpindex 798511333..e2f74aec1 100644--- a/tests/Feature/Services/Social/InstagramPublisherTest.php+++ b/tests/Feature/Services/Social/InstagramPublisherTest.php@@ -1605,7 +1605,7 @@ test('instagram facebook publisher recovers a published container on graph.faceb])->save();$this->post->setRelation('socialAccount', $account);- $graph = (string) config('trypost.platforms.instagram-facebook.graph_api');+ $graph = config('trypost.platforms.instagram-facebook.graph_api');Http::fake(function (Request $request) use ($graph) {expect($request->url())->toStartWith($graph)@@ -2359,7 +2359,7 @@ test('instagram reel sends the chosen cover frame as thumb_offset in millisecond'meta' => array_filter(['duration' => 10, 'cover_offset_ms' => $coverOffsetMs], fn (mixed $value): bool => $value !== null),]],]);- $graph = Platform::Instagram->instagramGraphBaseUrl();+ $graph = Platform::Instagram->graphApiUrl();Http::fake(["{$graph}/ig_123456789/media" => Http::response(['id' => 'container-123']),@@ -2398,7 +2398,7 @@ test('instagram carousel video child sends its cover frame as thumb_offset', fun],],]);- $graph = Platform::Instagram->instagramGraphBaseUrl();+ $graph = Platform::Instagram->graphApiUrl();Http::fake(["{$graph}/ig_123456789/media" => Http::sequence()diff --git a/tests/Feature/ThirdPartyUrlConfigTest.php b/tests/Feature/ThirdPartyUrlConfigTest.phpnew file mode 100644index 000000000..eff78a5eb--- /dev/null+++ b/tests/Feature/ThirdPartyUrlConfigTest.php@@ -0,0 +1,36 @@+<?php++declare(strict_types=1);++test('a third-party URL set with a trailing slash comes back without it', function () {+ $config = trypostConfigWith([+ 'FACEBOOK_GRAPH_API' => 'https://graph.facebook.com/v25.0/',+ 'BLUESKY_DEFAULT_SERVICE' => 'https://pds.example.test/',+ ]);++ expect(data_get($config, 'platforms.facebook.graph_api'))->toBe('https://graph.facebook.com/v25.0')+ ->and(data_get($config, 'platforms.bluesky.default_service'))->toBe('https://pds.example.test');+});++test('a third-party URL left unset keeps its default', function () {+ expect(data_get(trypostConfigWith([]), 'platforms.x.api'))->toBe('https://api.x.com/2');+});++test('loading the config with a variable puts the environment back as it was', function () {+ putenv('TELEGRAM_API=https://telegram.example.test');+ $_ENV['TELEGRAM_API'] = $_SERVER['TELEGRAM_API'] = 'https://telegram.example.test';++ try {+ trypostConfigWith(['TELEGRAM_API' => 'https://other.example.test/', 'CANVA_API_URL' => 'https://canva.example.test/']);++ expect(getenv('TELEGRAM_API'))->toBe('https://telegram.example.test')+ ->and($_ENV['TELEGRAM_API'])->toBe('https://telegram.example.test')+ ->and($_SERVER['TELEGRAM_API'])->toBe('https://telegram.example.test')+ ->and(getenv('CANVA_API_URL'))->toBeFalse()+ ->and(array_key_exists('CANVA_API_URL', $_ENV))->toBeFalse()+ ->and(array_key_exists('CANVA_API_URL', $_SERVER))->toBeFalse();+ } finally {+ putenv('TELEGRAM_API');+ unset($_ENV['TELEGRAM_API'], $_SERVER['TELEGRAM_API']);+ }+});diff --git a/tests/Feature/Webhook/WebhookListenersTest.php b/tests/Feature/Webhook/WebhookListenersTest.phpindex f2d1c9f06..cc946d077 100644--- a/tests/Feature/Webhook/WebhookListenersTest.php+++ b/tests/Feature/Webhook/WebhookListenersTest.php@@ -3,11 +3,13 @@declare(strict_types=1);use App\Actions\Post\DeletePost;+use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;use App\Enums\Webhook\EventType;use App\Events\PostCreated;use App\Events\PostDeleted;use App\Events\PostStatusChanged;+use App\Events\PostStatusUpdated;use App\Jobs\DispatchWebhook;use App\Listeners\Webhook\SendPostCreatedWebhook;use App\Listeners\Webhook\SendPostDeletedWebhook;@@ -191,6 +193,47 @@ test('deleting a post dispatches the deleted webhook', function () {});});+test('a post deleted on the network sends its webhook and refreshes open schedules', function () {+ $post = Post::factory()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);+ Event::fake([PostStatusUpdated::class]);++ $post->markPublicationDeleted();++ Queue::assertPushed(DispatchWebhook::class, fn (DispatchWebhook $job): bool => $job->eventType === EventType::PostDeletedOnNetwork->value+ && data_get($job->payload, 'id') === $post->id+ && data_get($job->payload, 'publish_status') === PublishStatus::Deleted->value);+ Event::assertDispatched(PostStatusUpdated::class, fn (PostStatusUpdated $event): bool => $event->post->is($post));+});++test('a post the network lists again sends post.restored, never post.published', function () {+ $post = Post::factory()->deletedOnNetwork()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);+ Event::fake([PostStatusUpdated::class]);++ $post->markPublicationRestored();++ Queue::assertPushed(DispatchWebhook::class, fn (DispatchWebhook $job): bool => $job->eventType === EventType::PostRestored->value+ && data_get($job->payload, 'id') === $post->id);+ Queue::assertNotPushed(DispatchWebhook::class, fn (DispatchWebhook $job): bool => $job->eventType === EventType::PostPublished->value);+ Event::assertDispatched(PostStatusUpdated::class, fn (PostStatusUpdated $event): bool => $event->post->is($post));+});++test('a post imported from the network sends no webhook when deleted or listed again there, but still refreshes open schedules', function () {+ $post = Post::factory()->imported()->createQuietly(['workspace_id' => $this->workspace->id]);+ Event::fake([PostStatusUpdated::class]);++ $post->markPublicationDeleted();+ $post->markPublicationRestored();++ Queue::assertNotPushed(DispatchWebhook::class);+ Event::assertDispatchedTimes(PostStatusUpdated::class, 2);+});+test('post created listener is wired via auto-discovery', function () {$post = Post::factory()->create(['workspace_id' => $this->workspace->id,diff --git a/tests/Feature/Webhook/WebhookPostLifecycleTest.php b/tests/Feature/Webhook/WebhookPostLifecycleTest.phpindex 325e61b99..008ae6688 100644--- a/tests/Feature/Webhook/WebhookPostLifecycleTest.php+++ b/tests/Feature/Webhook/WebhookPostLifecycleTest.php@@ -12,10 +12,12 @@ use App\Enums\SocialAccount\Platform;use App\Enums\Webhook\EventType;use App\Events\PostCreated;use App\Events\PostDeleted;+use App\Events\PostNetworkPresenceChanged;use App\Events\PostStatusChanged;use App\Jobs\DispatchWebhook;use App\Listeners\Webhook\SendPostCreatedWebhook;use App\Listeners\Webhook\SendPostDeletedWebhook;+use App\Listeners\Webhook\SendPostNetworkPresenceWebhook;use App\Listeners\Webhook\SendPostStatusWebhook;use App\Models\Post;use App\Models\SocialAccount;@@ -72,6 +74,7 @@ test('webhook listeners are registered for the post lifecycle events', functionEvent::assertListening(PostCreated::class, SendPostCreatedWebhook::class);Event::assertListening(PostStatusChanged::class, SendPostStatusWebhook::class);Event::assertListening(PostDeleted::class, SendPostDeletedWebhook::class);+ Event::assertListening(PostNetworkPresenceChanged::class, SendPostNetworkPresenceWebhook::class);});test('creating a channel post queues a post.created webhook', function () {diff --git a/tests/Pest.php b/tests/Pest.phpindex 6efea06fe..18039042b 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -932,3 +932,41 @@ function recordCanvasDrawing(mixed $page): void})();JS);}++/**+ * Loads config/trypost.php again with the given environment, the way the+ * framework reads it at boot and when it builds the config cache, then puts+ * every variable back as it was.+ *+ * @param array<string, string> $environment+ * @return array<string, mixed>+ */+function trypostConfigWith(array $environment): array+{+ $previous = collect($environment)->map(fn (string $value, string $key): array => [getenv($key), $_ENV[$key] ?? null, $_SERVER[$key] ?? null]);++ foreach ($environment as $key => $value) {+ putenv("{$key}={$value}");+ $_ENV[$key] = $_SERVER[$key] = $value;+ }++ try {+ return require config_path('trypost.php');+ } finally {+ foreach ($previous as $key => [$env, $envArray, $server]) {+ putenv($env === false ? $key : "{$key}={$env}");++ if ($envArray === null) {+ unset($_ENV[$key]);+ } else {+ $_ENV[$key] = $envArray;+ }++ if ($server === null) {+ unset($_SERVER[$key]);+ } else {+ $_SERVER[$key] = $server;+ }+ }+ }+}diff --git a/tests/Unit/Enums/Media/SourceTest.php b/tests/Unit/Enums/Media/SourceTest.phpindex 8a2d47a64..da9b5fbf5 100644--- a/tests/Unit/Enums/Media/SourceTest.php+++ b/tests/Unit/Enums/Media/SourceTest.php@@ -89,7 +89,7 @@ test('labels, download hosts and public config', function () {expect(Source::GoogleDrive->label())->toBe('Google Drive')->and(Source::Canva->downloadHosts())->toBe(['*.canva.com', 'export.example.com'])- ->and(Source::GoogleDrive->publicConfig())->toBe(['api_key' => 'key', 'app_id' => 'app', 'picker_sdk' => (string) config('trypost.media_sources.google_drive.picker_sdk')])+ ->and(Source::GoogleDrive->publicConfig())->toBe(['api_key' => 'key', 'app_id' => 'app', 'picker_sdk' => config('trypost.media_sources.google_drive.picker_sdk')])->and(Source::GooglePhotos->publicConfig())->toBe([])->and(Source::Canva->publicConfig())->toBe([])->and(Source::Unsplash->publicConfig())->toBe([]);diff --git a/tests/Unit/Enums/WebhookEventTypeTest.php b/tests/Unit/Enums/WebhookEventTypeTest.phpindex f34526ae0..7e6565723 100644--- a/tests/Unit/Enums/WebhookEventTypeTest.php+++ b/tests/Unit/Enums/WebhookEventTypeTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;use App\Enums\Webhook\EventType;@@ -12,6 +13,8 @@ test('every webhook event has the expected value', function (EventType $event, s[EventType::PostScheduled, 'post.scheduled'],[EventType::PostUnscheduled, 'post.unscheduled'],[EventType::PostPublished, 'post.published'],+ [EventType::PostDeletedOnNetwork, 'post.deleted_on_network'],+ [EventType::PostRestored, 'post.restored'],[EventType::PostFailed, 'post.failed'],[EventType::PostDeleted, 'post.deleted'],]);@@ -29,3 +32,14 @@ test('fromPostStatus maps publishable statuses and ignores the rest', function ([PostStatus::Draft, null, PostStatus::Published],[PostStatus::Publishing, null],]);++test('fromPublishStatus maps a deletion on the network and its return, and ignores the rest', function (PublishStatus $status, ?PublishStatus $previous, ?EventType $event) {+ expect(EventType::fromPublishStatus($status, $previous))->toBe($event);+})->with([+ [PublishStatus::Deleted, PublishStatus::Published, EventType::PostDeletedOnNetwork],+ [PublishStatus::Published, PublishStatus::Deleted, EventType::PostRestored],+ [PublishStatus::Published, PublishStatus::Publishing, null],+ [PublishStatus::Published, null, null],+ [PublishStatus::Failed, PublishStatus::Published, null],+ [PublishStatus::Retrying, PublishStatus::Deleted, null],+]);diff --git a/tests/Unit/Models/SocialAccountTest.php b/tests/Unit/Models/SocialAccountTest.phpnew file mode 100644index 000000000..dfdd37d5d--- /dev/null+++ b/tests/Unit/Models/SocialAccountTest.php@@ -0,0 +1,21 @@+<?php++declare(strict_types=1);++use App\Models\SocialAccount;++test('a channel server is read from the account, else from the config when it is missing or null', function (string $factoryState, string $metaKey, string $attribute, string $configKey) {+ $account = SocialAccount::factory()->{$factoryState}()->make();++ $account->meta = [...$account->meta, $metaKey => 'https://server.example.test'];+ expect($account->{$attribute})->toBe('https://server.example.test');++ $account->meta = collect($account->meta)->except($metaKey)->all();+ expect($account->{$attribute})->toBe(config($configKey));++ $account->meta = [...$account->meta, $metaKey => null];+ expect($account->{$attribute})->toBe(config($configKey));+})->with([+ 'bluesky' => ['bluesky', 'service', 'bluesky_service', 'trypost.platforms.bluesky.default_service'],+ 'mastodon' => ['mastodon', 'instance', 'mastodon_instance', 'trypost.platforms.mastodon.default_instance'],+]);diff --git a/tests/Unit/Services/Social/TelegramApiTest.php b/tests/Unit/Services/Social/TelegramApiTest.phpindex 8ae35841b..e5f14db2d 100644--- a/tests/Unit/Services/Social/TelegramApiTest.php+++ b/tests/Unit/Services/Social/TelegramApiTest.php@@ -21,9 +21,21 @@ it('builds a file download url', function () {->toBe('https://api.telegram.org/file/botTESTTOKEN/photos/file_1.jpg');});-it('trims a trailing slash from the configured host', function () {- config(['trypost.platforms.telegram.api' => 'https://api.telegram.org/']);+it('builds the endpoint from a host configured with a trailing slash', function () {+ config(['trypost.platforms.telegram.api' => data_get(trypostConfigWith(['TELEGRAM_API' => 'https://api.telegram.org/']), 'platforms.telegram.api')]);expect(TelegramApi::endpoint('getChat'))->toBe('https://api.telegram.org/botTESTTOKEN/getChat');});++it('links to the bot from the deep link host and the bot username', function () {+ config(['trypost.platforms.telegram.bot_username' => 'TryPostBot']);++ expect(TelegramApi::botUrl())->toBe(config('trypost.platforms.telegram.deep_link').'/TryPostBot');+});++it('has no bot link while no bot username is configured', function () {+ config(['trypost.platforms.telegram.bot_username' => null]);++ expect(TelegramApi::botUrl())->toBeNull();+});diff --git a/tests/Unit/Social/Meta/ManagedPagesTest.php b/tests/Unit/Social/Meta/ManagedPagesTest.phpindex afa13f43a..09c1adcbe 100644--- a/tests/Unit/Social/Meta/ManagedPagesTest.php+++ b/tests/Unit/Social/Meta/ManagedPagesTest.php@@ -16,7 +16,7 @@ beforeEach(function () {function managedPagesGraphApi(): string{- return (string) config('trypost.platforms.facebook.graph_api');+ return config('trypost.platforms.facebook.graph_api');}function managedPagesWalk(array $extraFakes = [], array $granted = ['business_management']): ManagedPageListdiff --git a/tests/Unit/Support/PostStatusRulesTest.php b/tests/Unit/Support/PostStatusRulesTest.phpindex 6bb7b08b0..49efee0fe 100644--- a/tests/Unit/Support/PostStatusRulesTest.php+++ b/tests/Unit/Support/PostStatusRulesTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;use App\Models\Post;use App\Support\PostStatusRules;@@ -62,3 +63,12 @@ test('does not require explicit schedule for non scheduled statuses', function (expect(PostStatusRules::requiresExplicitSchedule($post, PostStatus::Draft->value))->toBeFalse()->and(PostStatusRules::requiresExplicitSchedule(null, PostStatus::Scheduled->value))->toBeTrue();});++test('allows deleting a published post the network deleted, but not one still publishing', function (PostStatus $status, bool $blocked) {+ $post = Post::factory()->make(['status' => $status, 'publish_status' => PublishStatus::Deleted]);++ expect(PostStatusRules::blocksDeletion($post))->toBe($blocked);+})->with([+ 'published' => [PostStatus::Published, false],+ 'publishing' => [PostStatus::Publishing, true],+]);diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.phpindex 8b66dcd9f..656faa27a 100644--- a/tests/fixtures/single-line-copy.php+++ b/tests/fixtures/single-line-copy.php@@ -167,6 +167,7 @@ return ['posts.publish.actions.queue_setup.action' => 20,'posts.publish.actions.queue_setup.not_now' => 11,'posts.publish.actions.share_link' => 29,+ 'posts.publish.deleted_on_network.badge' => 10,'posts.publish.in_google_review' => 28,'posts.publish.no_time' => 13,'posts.publish.pending_slot.next' => 14,@@ -201,8 +202,10 @@ return ['webhooks.description' => 49,'webhooks.event_descriptions.post_created' => 41,'webhooks.event_descriptions.post_deleted' => 36,+ 'webhooks.event_descriptions.post_deleted_on_network' => 53,'webhooks.event_descriptions.post_failed' => 50,'webhooks.event_descriptions.post_published' => 48,+ 'webhooks.event_descriptions.post_restored' => 54,'webhooks.event_descriptions.post_scheduled' => 51,'webhooks.event_descriptions.post_unscheduled' => 54,'webhooks.rotate.submit' => 23,