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
Add Mastodon and Threads polls, with results read like X (#512)
Paulo Castellano05367855fb21
diff --git a/AGENTS.md b/AGENTS.mdindex e8195fd83..d0965b7a7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -203,6 +203,14 @@ Vue components must have a single root element.# Project-Specific Rules+## One type per parameter (PHP and TypeScript)++A parameter takes one type, nullable at most (`?ContentType`, `string | null`) (owner decision November 2026). A union of types (`array|string`, `ContentType|string|null`, `string | number`) or a `mixed` for a value the caller could settle means a step before it handed over something it should have resolved: fix that step instead of widening the parameter.++- Resolve where the value comes in: a content type sent as a string becomes `ContentType::resolve()` once, at the entry point, and every method after it takes `?ContentType` (`ContentType::poll()`, `PostPlatformMetaRules::formatErrors()`).+- Shape a value where it is built, not where it is used: a Mastodon query that repeats a key (`id[]=`) is built by `MastodonApi::url($instance, $path, $query)` from an array, so the HTTP helper keeps `array $query` instead of also taking a prebuilt string.+- A union is a strict exception, for a value whose shape genuinely varies at its source (a decoded JSON payload, a framework callback), never a convenience; its docblock says why. Code written before this rule moves to it when touched, not in a sweep.+## Branching reads top to bottom (PHP and TypeScript)A function that decides between several outcomes is a list of early returns, one case per `if`, read from top to bottom (owner decision November 2026). Never a ternary inside a ternary, a ternary inside an `if`, or a ternary whose condition joins several checks with `||` / `&&`.@@ -1181,7 +1189,7 @@ an `enabled` flag or posts with several channels. Posts created together share- Why: `FormRequest::validated()` (and MCP `$request->validate()`) STRIPS any key without a rule. A meta field defined in only one entry point is silently dropped everywhere else — which is exactly how Discord/Pinterest/TikTok meta was lost via API/MCP before this was centralized.- Required-on-publish (meta a platform needs to publish, e.g. Discord `channel_id`) also lives there: `addRequiredOnPublishErrors()` for request-driven flows (web/API update `withValidator`), `assertStoredPostPublishable()` for flows that publish stored state without resubmitting platforms (MCP `PublishPostTool`). Add new required-meta rules to `requiredMetaViolation()`, not inline.- When adding a new platform's meta field, add it (and any publish requirement) to `PostPlatformMetaRules` ONLY, and cover it in `tests/Feature/Api/PostApiPlatformMetaTest.php` + `tests/Feature/Mcp/PostPlatformMetaToolTest.php`.-- `PostPlatformMetaRules::formatViolation()` holds meta no post may store, even as a draft (a YouTube title with `<` or `>`). Every create and update path (web, API, MCP, repurpose) goes through `App\Support\PostCompositionValidator`, which runs it and, once the post is scheduled or published, the content limits below.+- `PostPlatformMetaRules::formatErrors()` holds meta no post may store, even as a draft (a YouTube title with `<` or `>`). Every create and update path (web, API, MCP, repurpose) goes through `App\Support\PostCompositionValidator`, which runs it and, once the post is scheduled or published, the content limits below.- **What a post stores in `meta` goes through `App\Support\PostMeta::forChannel($account, $meta, $stored)`, on create (`CreateChannelPost`) and on update (`UpdatePost`, passing the post's current meta as `$stored`).** It normalizes the meta, keeps the system keys the post already had (`PostPlatformMetaRules::SYSTEM_KEYS`, today Telegram `reactions`) and has one `match` arm per network that derives something. Never write `posts.meta` from a request without it, and never add a second helper next to it.- **A derived value is never taken from the request.** Only the id comes in; the server resolves what it names. The Discord `channel_name` has no validation rule: `PostMeta` drops any sent value and reads the name of `channel_id` from the guild's channel list in the cache (`DiscordClient::cachedChannels()`, warmed by the composer, the API, MCP and publishing). Without a cached list the post stores no name; that is accepted (owner decision October 2026). The composer may keep the name in its local meta for the live preview; the server ignores it.- **Saving never calls a network.** `PostMeta` runs inside the post's transaction and the channel queue lock, so a lookup there reads a cache only, never HTTP. A save never fails over a display name.@@ -1198,7 +1206,7 @@ an `enabled` flag or posts with several channels. Posts created together share## Thread replies- Bluesky, Mastodon, X and LinkedIn (`App\Support\ThreadReplies`), in `meta.thread_replies`: up to 24 replies, one on LinkedIn (`ThreadReplies::maxReplies()`, mirrored by `threadMaxReplies()`; see "LinkedIn comment"). Each reply is measured against the **account's** limit (`SocialAccount::maxContentLength()`), so an X account with long posts gets 25000 per reply; pass the account to `ThreadReplies::violation()` / `PostPlatformMetaRules::requiredMetaViolation()` whenever it is known.-- Each reply is `{text, media}`, plus `poll` on an X reply that is a poll (see "X polls") (a stored plain string is a text-only reply; `ThreadReplies::of()` normalizes both, `PostPlatformMetaRules::normalize()` stores objects). Its media belongs to that reply only, never to the root: it publishes as `ThreadReplies::replyContentType()` (X → `XPost`, Bluesky → `BlueskyPost`, Mastodon → `MastodonPost`, LinkedIn profile and page → `LinkedInComment`), so it follows that type's media rules (`ThreadReplies::mediaErrors()`, at save and at publish), and a reply needs text or media. The frontend mirror is `THREAD_REPLY_CONTENT_TYPES`. Adding a network means one entry in each map plus a reply callback in its publisher.+- Each reply is `{text, media}`, plus `poll` on an X or Mastodon reply that is a poll (see "Polls (X, Mastodon, Threads)") (a stored plain string is a text-only reply; `ThreadReplies::of()` normalizes both, `PostPlatformMetaRules::normalize()` stores objects). Its media belongs to that reply only, never to the root: it publishes as `ThreadReplies::replyContentType()` (X → `XPost`, Bluesky → `BlueskyPost`, Mastodon → `MastodonPost`, LinkedIn profile and page → `LinkedInComment`), so it follows that type's media rules (`ThreadReplies::mediaErrors()`, at save and at publish), and a reply needs text or media. The frontend mirror is `THREAD_REPLY_CONTENT_TYPES`. Adding a network means one entry in each map plus a reply callback in its publisher.- Reply media rows are owned by the post like its root media. `SyncOwnedMedia` resolves them from the post's stored `meta.thread_replies` and writes the canonical items back, so write the target's meta **before** calling it; it never deletes a row a reply still uses. Every segment's checkpoint hash covers its media ids.- In the composer each post of a thread shows its own media under it; the toolbar, paste, drop and the toolbar upload button add to the active post.- X replies go through `POST /2/tweets` with `reply.in_reply_to_tweet_id` on the previous segment. X restricts API replies (February 2026) to posts whose author summoned the replier; replying to your own post is the case that stays allowed. Each reply is billed as a post.@@ -1216,21 +1224,27 @@ A LinkedIn post (profile or page) takes one thread reply, published as a comment- **A post not ready yet:** LinkedIn can answer 404 to a comment sent right after its post (seen on a profile post with an image: "Unable to obtain activity"). A 404 on the comment throws `PlatformUnavailableException` with its own policy (30 seconds, 10 tries), so the job waits in Retrying and resumes from the checkpoint for up to five minutes before failing like any thread.- **Composer:** "Add comment" (`posts.form.thread.add_comment`) replaces "Start thread" where replies are comments (`repliesAreComments()`), and the preview shows the comment under the post (`LinkedInPreviewComment`) instead of as a post of its own.-## X polls+## Polls (X, Mastodon, Threads)-- A poll is its own content type, `ContentType::XPoll` (`x_poll`), with `meta.poll = {options, duration_minutes}` (owner decision November 2026). `App\Support\Social\XPoll` is the one home for its rules (constants, `limits()`, `options()` / `choices()`, `normalize()`, `violation()`, `optionsCountViolation()`, `choiceLengthViolation()`, `requiredViolation()`, `questionViolation()`, `payload()`, `result()`, `fromPublication()`); `PostPlatformMetaRules`, `PostMeta::forChannel()` / `PostMeta::merge()`, `PostCompositionValidator`, `ContentType::maxContentLengthFor()`, `ThreadReplies` and `XPublisher` call it, never a copy of the numbers or messages. X's `voting_status` values are `App\Enums\X\PollVotingStatus`.-- 2–4 choices of 1–25 characters counted as X counts them (UTF-16 units, so an emoji like 🐧 counts two: `XPoll::choiceLength()`, mirrored by `pollChoiceLength()`; X refused a choice of 25 code points holding one), a duration of 5–10080 minutes, and a question (the post text) of at most 280 characters, even on an account with long posts. Blank choices are dropped and duplicates refused. `PostMeta::forChannel()` drops `poll` on any other type.-- A poll carries no media. A poll with fewer than two choices, or without a question, is a draft that cannot be scheduled (the question error replaces the generic "content or media" one); `XPublisher` refuses it, and refuses stored media with `posts.errors.media_not_accepted`.-- **Any post of a thread can be a poll, several in one thread** (owner decision November 2026: X allows a poll on a reply). The root is a poll through its content type (`x_poll`, `meta.poll`); a reply stays `XPost` and carries its poll in the reply itself: `meta.thread_replies.*` is `{text, media, poll}`, `poll` under the same rules as `meta.poll` (`PostPlatformMetaRules`), the reply text as its question (at most 280 characters even with long posts), no media (refused at every save by `ThreadReplies::pollMediaErrors()`). `ThreadReplies` holds the reply rules (`pollFormatViolation()` at every save, `violation()` before scheduling), calling `XPoll`, whose helpers read `poll.*` from a post's meta or a reply alike. Off X, `PostMeta::forChannel()` drops reply polls (`ThreadReplies::withoutPolls()`). `PublishesThreads` passes each reply's poll to the publisher and into its checkpoint hash (a reply without one keeps its old hash). In the composer the root keeps the Post | Poll picker; an active X reply turns into a poll with the toolbar's poll button (`ComposerEditorToolbar`, off with the media reason while the reply has media), and its poll editor (`XPollField` with `field-prefix` `thread_replies.{n}.` and its own test ids) shows while that reply is edited.+- A poll is its own content type per network, `x_poll`, `mastodon_poll` and `threads_poll` (`ContentType::isPoll()`), with `meta.poll` (owner decision November 2026). `App\Support\Social\Poll` holds the rules every network shares (`options()` / `choices()`, `normalize()`, `forNetwork()`, `optionsCountViolation()`, `formatErrors()`, `requiredViolation()`, `firstViolation()`, `questionViolation()`, `publishViolation()`, `preview()`, `limits()`; the checks `formatErrors()` runs, duplicates, choice length and length range, are protected); each network's subclass (`XPoll`, `MastodonPoll`, `ThreadsPoll`) sets its constants and its `payload()`, `result()` and `fromPublication()`. `Poll::for($platform)` and `ContentType::poll()` pick one. `PostPlatformMetaRules`, `PostMeta::forChannel()` / `PostMeta::merge()`, `PostCompositionValidator`, `ContentType::maxContentLengthFor()`, `ThreadReplies` and the publishers call them, never a copy of the numbers or messages. The stored `voting_status` values are `App\Enums\Analytics\PollVotingStatus`.+- Every network: 2–4 choices, blank ones dropped and duplicates refused, the post text as the question. Each choice is counted in UTF-16 units (`Poll::choiceLength()`, mirrored by `pollChoiceLength()`), as X counts it (X refused a choice of 25 code points holding a 🐧): the strictest reading, used on every network.+ - X: choices of up to 25 characters, `duration_minutes` 5–10080 (default 1440), the question at most 280 characters even on an account with long posts.+ - Mastodon: choices of up to 50 characters, `duration_minutes` 5–43200 (30 days, default 1440), and `multiple` and `hide_totals` (default false). These are Mastodon's own limits, which every instance accepts; an instance's higher limits are not read. Published as `poll[options]`, `poll[expires_in]` (seconds), `poll[multiple]` and `poll[hide_totals]`. The root poll is part of the root hash, which is the status's `Idempotency-Key`, so a poll edited before a retry is never answered with the status Mastodon kept from the attempt before.+ - Threads: choices of up to 25 characters and no length (Threads sets it), on a text post only, published as `poll_attachment` (`option_a` to `option_d`).+- `rules()` cannot know the network, so it checks only the shape (four choices at most, text, an integer length); the length of each choice and of the poll is checked per network by `PostPlatformMetaRules::formatErrors()` at every save, drafts included. `Poll::normalize()` keeps every choice at the position it was sent, blank ones included, so a choice's error lands on its own field (an update normalizes the meta before validating it); `PostMeta::forChannel()` then stores only what the network takes (`Poll::forNetwork()`: blank choices dropped, no length on Threads, no switches off Mastodon) and drops `poll` on any other type.+- A poll carries no media. A poll with fewer than two choices, without a question, or (X, Mastodon) without a length, is a draft that cannot be scheduled (the question error replaces the generic "content or media" one); each publisher refuses it through `publishViolation()`, and refuses stored media with `posts.errors.media_not_accepted`.+- **Any post of a thread can be a poll on X and Mastodon, several in one thread** (owner decision November 2026). The root is a poll through its content type; a reply stays the network's post type and carries its poll in the reply itself: `meta.thread_replies.*` is `{text, media, poll}`, `poll` under that network's rules, the reply text as its question, no media (refused at every save by `ThreadReplies::pollMediaErrors()`). `ThreadReplies::replyPoll($platform)` says which rules a reply follows (null on Bluesky and LinkedIn, whose replies drop their polls through `ThreadReplies::forNetwork()`; Threads has no thread replies). `ThreadReplies` holds the reply rules (`pollFormatErrors()` and `pollMediaErrors()` at every save, `violation()` before scheduling; `mediaErrors()` leaves reply polls to `pollMediaErrors()`, so media on one gives one error). Before publishing, `HasSocialHttpClient::validateContentLength()` refuses a reply poll with media through `pollMediaErrors()`, so nothing goes out. `PublishesThreads` passes each reply's poll to the publisher and into its checkpoint hash (a reply without one keeps its old hash). In the composer the root keeps the Post | Poll picker; an active X or Mastodon reply turns into a poll with the toolbar's poll button (`ComposerEditorToolbar`, off with the media reason while the reply has media), and its poll editor (`PollField` with `field-prefix` `thread_replies.{n}.` and its own test ids) shows while that reply is edited. A reply poll's preview type is `THREAD_REPLY_POLL_CONTENT_TYPES`.- Attaching media through the API or MCP to a poll is refused by one guard, `AppendPostMedia::ensureAcceptsMedia()`: `execute()` always runs it, and the entry points that store or download a file first (`PostController::storeMedia`, `MediaAttacher::attachFromUrls`) call it before doing so.-- **Cost rule (owner decision):** polls and their votes ride on requests X already makes. Never add a request, job or schedule for polls.- - Results are read by `XPublicationMetricsCollector` in the existing X metrics read (`GET /2/tweets/{id}`), on its usual schedule (about an hour after publishing, then at the ages in `SyncCadence::X_METRICS_DAYS`), into `analytics_publications.provider_metadata.poll`, without moving `updated_at`. A read without a poll leaves the stored one alone.- - When TryPost published reply polls, the same read becomes one `GET /2/tweets?ids={post},{replies with a poll}` (owner decision November 2026: still one request, though X bills each extra post it returns), and their results go to `provider_metadata.thread_polls`, a list of `{reply, ...result}` where `reply` is the reply's position from 0 (matched through `posts.thread_reply_ids`). Discovery excludes replies, so it never sees them; `UpsertAnalyticsPublication` merges `provider_metadata` key by key so a rediscovery keeps them.- - A poll made on x.com is found by `XPublicationCollector`'s existing discovery request, which writes the same `provider_metadata.poll`, and typed `PublicationContentType::Poll`, which `ContentType::fromPublication()` maps to `x_poll` for the importer and the insights type filter (a poll TryPost published is stored as `Poll` by `SyncTryPostPublication`). `provider_metadata.poll` is the one home of a poll's result; there is no column of its own.-- Results are exposed as `publication.poll` and `publication.thread_polls` (read from `provider_metadata`) by `ReadPublicationAnalytics` (web, API, MCP) and shown by `PostPollResults.vue` in the Sent tab and post details, a reply's poll captioned with its post number (`posts.poll_results.thread_post`). The API and MCP post preview (`PostPreviewer`) shows the post's poll and each reply's. Because results are not read daily, it says "Final results" only when the stored `voting_status` is `closed`; an open poll whose end has passed says "Voting ended", and one still running says when it ends.-- The duration defaults to 1440 minutes (one day, `XPoll::DEFAULT_DURATION`). The limits reach the composer through `Platform::publishConfig()` (`publishConfig.poll`, from `XPoll::limits()`), read from `platformConfigs[account.id]` by `XPollField.vue`, the X preview and the question cap; do not copy them into TypeScript. `resources/js/lib/xPoll.ts` keeps only pure helpers that take the limits as arguments; the poll types (`XPoll`, `XPollLimits`, `XPollDuration`) are in `resources/js/types/x.ts`. The composer's poll state, its limits, the type switch (`setGroupContentType`), Remove poll and the reply text limit live in `composables/composer/useComposerPoll.ts`; the media button's reason stays in `PostComposerDialog.vue`, and the medialess types (poll, Threads ghost post) with their reasons in `MEDIALESS_CONTENT_TYPE_REASONS` (`types/content-type.ts`, next to `CAPTIONLESS_CONTENT_TYPES`; `maxMediaCount()` is 0 for both on the server).-- **The poll's media rules are X poll only** (owner decision November 2026): refusing media on a draft (`PostCompositionValidator`), refusing an attach (`AppendPostMedia::ensureAcceptsMedia()`), turning a card back into a post when the shared step opens (`watch(sharedStep)` in `PostComposerDialog.vue`) and leaving the type out of the repurpose picker all test `ContentType::XPoll`, never "a type that takes no media": a Threads ghost post keeps the behaviour it had before polls (its media is refused when it is scheduled or published).-- A poll is never a repurpose destination: the repurpose requests refuse `x_poll` (`RepurposeRules`, `supportsVideo()`), and the repurpose picker (`ChannelConfigurator.vue`) leaves it out.+- **Results are read like X's (owner decision November 2026):** on each network's usual metrics read, never with a job or schedule of their own. On X and Mastodon they ride on the read the collector already makes; Threads needs one more read, and only for a poll (below).+ - X: results are read by `XPublicationMetricsCollector` in the existing X metrics read (`GET /2/tweets/{id}`), on its usual schedule (about an hour after publishing, then at the ages in `SyncCadence::X_METRICS_DAYS`), into `analytics_publications.provider_metadata.poll`, without moving `updated_at`. A read without a poll leaves the stored one alone. When TryPost published reply polls, the same read becomes one `GET /2/tweets?ids={post},{replies with a poll}` (owner decision November 2026: still one request, though X bills each extra post it returns), and their results go to `provider_metadata.thread_polls`, a list of `{reply, ...result}` where `reply` is the reply's position from 0 (matched through `posts.thread_reply_ids`). Discovery excludes replies, so it never sees them; `UpsertAnalyticsPublication` merges `provider_metadata` key by key so a rediscovery keeps them.+ - Mastodon: the root poll's result comes with the status `MastodonPublicationMetricsCollector` already reads (`GET statuses/{id}`) and with discovery (`MastodonPublicationCollector`), both through `MastodonPoll::metadataFrom()`, with `voters` (the base of a multiple-choice poll's shares) and `totals_hidden` (votes Mastodon hides until the end, read as 0 and shown as hidden). A Mastodon post is read for 31 days instead of 30 (`SyncCadence::MASTODON_METRICS_WINDOW_DAYS`), so a 30-day poll gets a read after it ends. When TryPost published reply polls, the same read becomes `GET /api/v1/statuses?id[]={status}&id[]={replies with a poll}` (Mastodon 4.3, owner decision November 2026: as on X), 20 statuses per request with the status in the first, and their results go to `provider_metadata.thread_polls`. The repeated `id[]=` is built by `MastodonApi::url($instance, 'statuses', ['id[]' => [...]])`, since the HTTP client sends an array query as `id[0]=`; `AbstractApiPublicationCollector::get()` sends no query of its own when it has no parameters, so the URL's is kept. A server before 4.3, or a read that leaves the status out (deleted or private), falls back to the status read alone, where a deletion is confirmed as before; there the reply polls keep their choices with no votes. The reply ids are found by `AbstractPublicationMetricsCollector::replyPollIds()`, shared with X.+ - Threads: the insights edge the metrics read uses carries no poll, so `ThreadsPublicationMetricsCollector` reads a publication typed `Poll` once more for its `poll_attachment` (`ThreadsPoll::LOOKUP_FIELDS`, through the shared optional Meta read), on the same daily cadence as its metrics, until its stored result is closed (it can no longer change); no other post makes that read, and a refused one keeps the metrics measured. Threads documents each choice's share as a decimal (`0.10` for 10%), which is the only shape read. Discovery (`ThreadsPublicationCollector`) asks for the same fields in its existing list read. Threads gives each choice a share of `total_votes`, so the votes are worked out from it, and the poll is closed once its `expiration_timestamp` has passed.+ - A poll made on the network is found by that network's discovery, which writes the same `provider_metadata.poll` and types it `PublicationContentType::Poll`, which `ContentType::fromPublication()` maps to the network's poll type for the importer and the insights type filter (a poll TryPost published is stored as `Poll` by `SyncTryPostPublication`). `provider_metadata.poll` is the one home of a poll's result; there is no column of its own.+- Results are exposed as `publication.poll` and `publication.thread_polls` (read from `provider_metadata`) by `ReadPublicationAnalytics` (web, API, MCP) and shown by `PostPollResults.vue` in the Sent tab and post details, a reply's poll captioned with its post number (`posts.poll_results.thread_post`). The API and MCP post preview (`PostPreviewer`) shows the post's poll and each reply's (`Poll::preview()`). Because results are not read daily, it says "Final results" only when the stored `voting_status` is `closed`; an open poll whose end has passed says "Voting ended", and one still running says when it ends.+- The limits reach the composer through `Platform::publishConfig()` (`publishConfig.poll`, from `Poll::limits()`: a null length on Threads, `multipleChoice` and `hideTotals` on Mastodon), read from `platformConfigs[account.id]` by `PollField.vue`, the network previews (`XPreviewPoll`, `MastodonPreviewPoll`, `ThreadsPreviewPoll`) and the question cap; do not copy them into TypeScript. `resources/js/lib/poll.ts` keeps only pure helpers that take the limits as arguments; the poll types (`Poll`, `PollLimits`, `PollDuration`) are in `resources/js/types/poll.ts`. The composer's poll state, its limits, the type switch (`setGroupContentType`), Remove poll (back to the network's post type, `POLL_POST_CONTENT_TYPES`) and the reply text limit live in `composables/composer/useComposerPoll.ts`; the media button's reason stays in `PostComposerDialog.vue`, and the medialess types (polls, Threads ghost post) with their reasons in `MEDIALESS_CONTENT_TYPE_REASONS` (`types/content-type.ts`, next to `CAPTIONLESS_CONTENT_TYPES` and `POLL_CONTENT_TYPES`; `maxMediaCount()` is 0 for them on the server). The poll field's test ids start with the network (`x-poll`, `mastodon-poll`, `threads-poll`).+- **The poll's media rules are for polls only** (owner decision November 2026): refusing media on a draft (`PostCompositionValidator`), refusing an attach (`AppendPostMedia::ensureAcceptsMedia()`), turning a card back into a post when the shared step opens (`watch(sharedStep)` in `PostComposerDialog.vue`) and leaving the type out of the repurpose picker all test `ContentType::isPoll()` / `POLL_CONTENT_TYPES`, never "a type that takes no media": a Threads ghost post keeps the behaviour it had before polls (its media is refused when it is scheduled or published).+- A poll is never a repurpose destination: the repurpose requests refuse every poll type (`RepurposeRules`, `supportsVideo()`), and the repurpose picker (`ChannelConfigurator.vue`) leaves them out.+- LinkedIn polls are tracked in #468 (create only, no results); Bluesky has no poll in the AT Protocol.## Composer stepsdiff --git a/app/Actions/Analytics/SyncTryPostPublication.php b/app/Actions/Analytics/SyncTryPostPublication.phpindex 840d65db0..a470ad6c7 100644--- a/app/Actions/Analytics/SyncTryPostPublication.php+++ b/app/Actions/Analytics/SyncTryPostPublication.php@@ -59,10 +59,13 @@ class SyncTryPostPublicationContentType::YouTubeShort => PublicationContentType::Short,ContentType::TikTokVideo, ContentType::PinterestVideoPin => PublicationContentType::Video,ContentType::TikTokPhoto, ContentType::PinterestCarousel => PublicationContentType::Carousel,- ContentType::XPoll => PublicationContentType::Poll,default => null,};+ if ($post->content_type?->isPoll() === true) {+ return PublicationContentType::Poll;+ }+if ($specializedType) {return $specializedType;}diff --git a/app/Actions/Post/AppendPostMedia.php b/app/Actions/Post/AppendPostMedia.phpindex 7ecbcf23e..75b90d7c9 100644--- a/app/Actions/Post/AppendPostMedia.php+++ b/app/Actions/Post/AppendPostMedia.php@@ -22,7 +22,7 @@ class AppendPostMedia* again from the new media. Changing an approved, scheduled post goes back* through UpdatePost, so a member who needs approval sends it back for* approval like any other edit, even when the approval landed just before.- * An X poll, which takes no media, is refused.+ * A poll, which takes no media, is refused.** @param list<array<string, mixed>> $items*@@ -50,7 +50,7 @@ class AppendPostMedia}/**- * Refuses media on an X poll, which carries none. `execute()` always checks+ * Refuses media on a poll, which carries none. `execute()` always checks* it; an entry point that stores or downloads a file first calls it before* doing so.*@@ -58,7 +58,7 @@ class AppendPostMedia*/public static function ensureAcceptsMedia(Post $post, string $field = 'media'): void{- if ($post->content_type === ContentType::XPoll) {+ if ($post->content_type?->isPoll() === true) {throw ValidationException::withMessages([$field => trans('posts.errors.media_not_accepted')]);}}diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.phpindex 6d813d9f5..97e5d51b6 100644--- a/app/Actions/Post/ImportExternalPosts.php+++ b/app/Actions/Post/ImportExternalPosts.php@@ -17,9 +17,9 @@ use App\Models\Post;use App\Models\SocialAccount;use App\Services\Social\ContentSanitizer;use App\Support\PostHistoryRetention;+use App\Support\Social\Poll;use App\Support\Social\PublishCheckpoint;use App\Support\Social\ThreadProgress;-use App\Support\Social\XPoll;use Carbon\CarbonImmutable;use Carbon\CarbonInterface;use Illuminate\Database\Eloquent\Builder;@@ -430,10 +430,26 @@ class ImportExternalPosts&& Str::startsWith($sent, $truncated);}- private static function createPost(SocialAccount $account, AnalyticsPublication $publication): Post+ /**+ * The type an imported post is shown as. A poll found before its choices+ * were read (a Mastodon poll discovered before polls were supported) stays+ * a plain post, so it never shows as a poll without choices.+ */+ private static function importedContentType(SocialAccount $account, AnalyticsPublication $publication): ContentType{$contentType = ContentType::fromPublication($account->platform, $publication->content_type);+ if ($contentType->isPoll() && blank(data_get($publication->provider_metadata, 'poll.options'))) {+ return ContentType::defaultFor($account->platform);+ }++ return $contentType;+ }++ private static function createPost(SocialAccount $account, AnalyticsPublication $publication): Post+ {+ $contentType = self::importedContentType($account, $publication);+return Post::query()->forceCreate(['workspace_id' => $account->workspace_id,'post_group_id' => (string) Str::uuid7(),@@ -450,7 +466,7 @@ class ImportExternalPosts'publish_status' => PublishStatus::Published,'platform_post_id' => $publication->remote_id,'platform_url' => $publication->permalink,- 'meta' => $contentType === ContentType::XPoll ? ['poll' => XPoll::fromPublication($publication)] : [],+ 'meta' => transform($contentType?->poll(), fn (string $poll): array => ['poll' => $poll::fromPublication($publication)], []),]);}}diff --git a/app/Actions/Repurpose/ActivateRepurpose.php b/app/Actions/Repurpose/ActivateRepurpose.phpindex 4aeae2a29..b4f30c7f1 100644--- a/app/Actions/Repurpose/ActivateRepurpose.php+++ b/app/Actions/Repurpose/ActivateRepurpose.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Actions\Repurpose;+use App\Enums\PostPlatform\ContentType;use App\Enums\Repurpose\Status;use App\Enums\SocialAccount\Status as AccountStatus;use App\Jobs\PostHog\TrackRepurposeActivated;@@ -88,7 +89,7 @@ class ActivateRepurposecontinue;}- $violation = PostPlatformMetaRules::requiredMetaViolation($account, data_get($destination, 'meta'), data_get($destination, 'content_type'));+ $violation = PostPlatformMetaRules::requiredMetaViolation($account, data_get($destination, 'meta'), ContentType::resolve(data_get($destination, 'content_type')));if ($violation !== null) {throw ValidationException::withMessages(['destinations' => $violation[1]]);diff --git a/app/Enums/Analytics/PollVotingStatus.php b/app/Enums/Analytics/PollVotingStatus.phpnew file mode 100644index 000000000..78d31c5a5--- /dev/null+++ b/app/Enums/Analytics/PollVotingStatus.php@@ -0,0 +1,17 @@+<?php++declare(strict_types=1);++namespace App\Enums\Analytics;++/**+ * Whether a published poll still takes votes, as stored with its result. X+ * reports it (`voting_status`); Mastodon says it through `expired`, and Threads+ * through the end of the poll (`expiration_timestamp`). Anything else is+ * stored as unknown (null).+ */+enum PollVotingStatus: string+{+ case Open = 'open';+ case Closed = 'closed';+}diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.phpindex 9d162e77b..c9d63b927 100644--- a/app/Enums/PostPlatform/ContentType.php+++ b/app/Enums/PostPlatform/ContentType.php@@ -9,6 +9,9 @@ use App\Enums\Analytics\PublicationContentType;use App\Enums\Media\Type as MediaType;use App\Enums\SocialAccount\Platform as SocialPlatform;use App\Models\SocialAccount;+use App\Support\Social\MastodonPoll;+use App\Support\Social\Poll;+use App\Support\Social\ThreadsPoll;use App\Support\Social\XPoll;use App\Support\ThreadReplies;use Illuminate\Support\Str;@@ -48,6 +51,7 @@ enum ContentType: string// Threadscase ThreadsPost = 'threads_post';case ThreadsGhostPost = 'threads_ghost_post';+ case ThreadsPoll = 'threads_poll';case PinterestPin = 'pinterest_pin';@@ -59,6 +63,7 @@ enum ContentType: string// Mastodoncase MastodonPost = 'mastodon_post';+ case MastodonPoll = 'mastodon_poll';// Telegramcase TelegramPost = 'telegram_post';@@ -84,6 +89,34 @@ enum ContentType: stringreturn in_array($this, [self::FacebookStory, self::InstagramStory], true);}+ /**+ * The rules of a network's poll (its question is the post text and it+ * takes no media), or null for any other type.+ *+ * @return class-string<Poll>|null+ */+ public function poll(): ?string+ {+ return match ($this) {+ self::XPoll => XPoll::class,+ self::MastodonPoll => MastodonPoll::class,+ self::ThreadsPoll => ThreadsPoll::class,+ self::InstagramFeed, self::InstagramReel, self::InstagramStory,+ self::LinkedInPost, self::LinkedInPagePost, self::LinkedInComment,+ self::FacebookPost, self::FacebookReel, self::FacebookStory,+ self::TikTokVideo, self::TikTokPhoto, self::YouTubeShort, self::XPost,+ self::ThreadsPost, self::ThreadsGhostPost,+ self::PinterestPin, self::PinterestVideoPin, self::PinterestCarousel,+ self::BlueskyPost, self::MastodonPost, self::TelegramPost, self::DiscordMessage,+ self::GoogleBusinessPost => null,+ };+ }++ public function isPoll(): bool+ {+ return filled($this->poll());+ }+public function label(): string{return match ($this) {@@ -102,25 +135,26 @@ enum ContentType: stringself::XPoll => 'Poll',self::ThreadsPost => 'Thread',self::ThreadsGhostPost => 'Ghost post',+ self::ThreadsPoll => 'Poll',self::PinterestPin => 'Pin',self::PinterestVideoPin => 'Video Pin',self::PinterestCarousel => 'Carousel',self::BlueskyPost => 'Post',self::MastodonPost => 'Post',+ self::MastodonPoll => 'Poll',self::TelegramPost => 'Post',self::DiscordMessage => 'Message',self::GoogleBusinessPost => 'Post',};}+ /**+ * The type's description; a poll's names how many choices it takes, and+ * every other description has no placeholder to fill.+ */public function description(): string{- $replacements = match ($this) {- self::XPoll => ['min' => XPoll::MIN_OPTIONS, 'max' => XPoll::MAX_OPTIONS],- default => [],- };-- return (string) trans("posts.content_types.{$this->value}.description", $replacements);+ return (string) trans("posts.content_types.{$this->value}.description", ['min' => Poll::MIN_OPTIONS, 'max' => Poll::MAX_OPTIONS]);}public function platform(): SocialPlatform@@ -133,10 +167,10 @@ enum ContentType: stringself::TikTokVideo, self::TikTokPhoto => SocialPlatform::TikTok,self::YouTubeShort => SocialPlatform::YouTube,self::XPost, self::XPoll => SocialPlatform::X,- self::ThreadsPost, self::ThreadsGhostPost => SocialPlatform::Threads,+ self::ThreadsPost, self::ThreadsGhostPost, self::ThreadsPoll => SocialPlatform::Threads,self::PinterestPin, self::PinterestVideoPin, self::PinterestCarousel => SocialPlatform::Pinterest,self::BlueskyPost => SocialPlatform::Bluesky,- self::MastodonPost => SocialPlatform::Mastodon,+ self::MastodonPost, self::MastodonPoll => SocialPlatform::Mastodon,self::TelegramPost => SocialPlatform::Telegram,self::DiscordMessage => SocialPlatform::Discord,self::GoogleBusinessPost => SocialPlatform::GoogleBusiness,@@ -226,11 +260,12 @@ enum ContentType: stringself::XPost => 4,self::XPoll => 0,self::ThreadsPost => 10,- self::ThreadsGhostPost => 0,+ self::ThreadsGhostPost, self::ThreadsPoll => 0,self::PinterestPin, self::PinterestVideoPin => 1,self::PinterestCarousel => 5,self::BlueskyPost => 4,self::MastodonPost => 4,+ self::MastodonPoll => 0,self::TelegramPost => 10,self::DiscordMessage => 10,self::GoogleBusinessPost => 1,@@ -489,8 +524,8 @@ enum ContentType: stringself::FacebookPost, self::LinkedInPost, self::LinkedInPagePost => ['1:1', '1.91:1'],self::PinterestPin, self::PinterestCarousel => ['2:3', '1:1'],self::PinterestVideoPin => ['2:3'],- self::ThreadsPost, self::ThreadsGhostPost => ['1:1', '4:5', '1.91:1'],- self::BlueskyPost, self::MastodonPost => ['1:1', '16:9'],+ self::ThreadsPost, self::ThreadsGhostPost, self::ThreadsPoll => ['1:1', '4:5', '1.91:1'],+ self::BlueskyPost, self::MastodonPost, self::MastodonPoll => ['1:1', '16:9'],self::GoogleBusinessPost => ['4:3', '1:1'],self::TelegramPost, self::DiscordMessage, self::LinkedInComment => self::defaultCropPresets(),};@@ -771,11 +806,12 @@ enum ContentType: stringself::XPost => true,self::XPoll => false,self::ThreadsPost => true,- self::ThreadsGhostPost => false,+ self::ThreadsGhostPost, self::ThreadsPoll => false,self::PinterestVideoPin => true,self::PinterestPin, self::PinterestCarousel => false,self::BlueskyPost => true,self::MastodonPost => true,+ self::MastodonPoll => false,self::TelegramPost => true,self::DiscordMessage => true,self::GoogleBusinessPost => false,@@ -791,7 +827,7 @@ enum ContentType: stringself::TikTokPhoto => true,self::YouTubeShort => false,self::ThreadsGhostPost => false,- self::XPoll => false,+ self::XPoll, self::MastodonPoll, self::ThreadsPoll => false,self::PinterestVideoPin => false,self::LinkedInComment => false,default => true,@@ -846,9 +882,9 @@ enum ContentType: stringreturn match ($this) {self::LinkedInPost, self::LinkedInPagePost, self::LinkedInComment => false,self::XPost, self::XPoll => false,- self::ThreadsPost, self::ThreadsGhostPost => false,+ self::ThreadsPost, self::ThreadsGhostPost, self::ThreadsPoll => false,self::BlueskyPost => false,- self::MastodonPost => false,+ self::MastodonPost, self::MastodonPoll => false,self::TelegramPost => false,self::FacebookPost => false,self::DiscordMessage => false,@@ -1005,6 +1041,14 @@ enum ContentType: stringPublicationContentType::Poll => self::XPoll,default => self::XPost,},+ SocialPlatform::Mastodon => match ($type) {+ PublicationContentType::Poll => self::MastodonPoll,+ default => self::MastodonPost,+ },+ SocialPlatform::Threads => match ($type) {+ PublicationContentType::Poll => self::ThreadsPoll,+ default => self::ThreadsPost,+ },default => self::defaultFor($platform),};}diff --git a/app/Enums/SocialAccount/Platform.php b/app/Enums/SocialAccount/Platform.phpindex 13d91760a..c2eada63d 100644--- a/app/Enums/SocialAccount/Platform.php+++ b/app/Enums/SocialAccount/Platform.php@@ -8,6 +8,8 @@ use App\Enums\Media\Type as MediaType;use App\Enums\TikTok\PrivacyLevel;use App\Enums\YouTube\Category;use App\Support\Hashtags;+use App\Support\Social\MastodonPoll;+use App\Support\Social\ThreadsPoll;use App\Support\Social\XPoll;use Illuminate\Support\Str;@@ -599,9 +601,9 @@ enum Platform: string'categoryOptions' => Category::options(),'defaultCategoryId' => Category::DEFAULT->value,],- self::X => [- 'poll' => XPoll::limits(),- ],+ self::X => ['poll' => XPoll::limits()],+ self::Mastodon => ['poll' => MastodonPoll::limits()],+ self::Threads => ['poll' => ThreadsPoll::limits()],default => [],};}diff --git a/app/Enums/X/PollVotingStatus.php b/app/Enums/X/PollVotingStatus.phpdeleted file mode 100644index 89e5fc642..000000000--- a/app/Enums/X/PollVotingStatus.php+++ /dev/null@@ -1,14 +0,0 @@-<?php--declare(strict_types=1);--namespace App\Enums\X;--/**- * The poll `voting_status` values X reports; anything else is stored as unknown (null).- */-enum PollVotingStatus: string-{- case Open = 'open';- case Closed = 'closed';-}diff --git a/app/Http/Requests/App/Post/UpdatePostRequest.php b/app/Http/Requests/App/Post/UpdatePostRequest.phpindex 757400313..f8eff005c 100644--- a/app/Http/Requests/App/Post/UpdatePostRequest.php+++ b/app/Http/Requests/App/Post/UpdatePostRequest.php@@ -107,7 +107,7 @@ class UpdatePostRequest extends FormRequestreturn;}- PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, $this->effectiveMeta(), contentType: $this->input('content_type') ?? $post->content_type);+ PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, $this->effectiveMeta(), contentType: ContentType::resolve($this->input('content_type')) ?? $post->content_type);});}diff --git a/app/Mcp/Tools/Platform/ListContentTypesTool.php b/app/Mcp/Tools/Platform/ListContentTypesTool.phpindex 9a301640c..f5e48b7a0 100644--- a/app/Mcp/Tools/Platform/ListContentTypesTool.php+++ b/app/Mcp/Tools/Platform/ListContentTypesTool.php@@ -20,7 +20,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[IsReadOnly(true)]#[IsDestructive(false)]#[IsOpenWorld(false)]-#[Description('List every platform with its content types and their rules. Per content type: max/min media count, requires_media, accept_images/accept_videos/accept_documents, accepts_gif, accepts_mov, forbids_mixed_media, max_video_duration_sec (null = no cap), max_image_bytes / max_video_bytes / max_document_bytes, aspect_ratio_min / aspect_ratio_max for images and video_aspect_ratio_min / video_aspect_ratio_max for videos (width / height, null = not checked; GIFs are never checked; auto_fits_image when images are fitted into the frame on publish instead), image_min_width / image_min_height / image_max_width / image_max_height in pixels, supports_alt_text (alt_text on images), supports_video_alt_text (alt_text on videos too: Mastodon, Bluesky, Threads and Discord), supports_user_tags (Instagram tags in media meta.user_tags), supports_video_cover (meta.cover_offset_ms), supports_custom_video_cover (an image as the video cover, media meta.cover; Instagram Reels and YouTube Shorts), captionless (stories publish no text, so the text is neither sent nor measured), document_must_be_alone (a PDF must be the only attachment), supports_thread_replies and max_thread_replies (meta.thread_replies: a thread on X, Bluesky or Mastodon, or one comment on LinkedIn). Per platform: allowed_media_types, default_content_type, max_content_length (the default text limit of the network; the limit of each account, such as 25000 for an X account with long posts, is max_content_length in list-social-accounts-tool), max_hashtags (Instagram: 5), alt_text_max_length and required_meta (meta every post of the platform needs before it is scheduled or published; some needs depend on the content type and are not listed: Google Business events and offers also need meta.event, a YouTube post needs meta.title or text, and an X poll (x_poll) needs meta.poll with at least 2 options and duration_minutes, plus text as its question). Media rules never block a draft: they are checked when a post is scheduled, queued or published (create-post-tool, create-posts-tool, update-post-tool, publish-post-tool), and a post whose media breaks a rule of its content_type is rejected with a per-platform error. The exception is an X poll (content_type x_poll, or a reply in meta.thread_replies with a poll): media, a repeated choice, more than 4 choices, a choice over 25 characters or a duration_minutes outside 5–10080 is refused on every save, drafts included, and the attach media tools refuse it too. Call this before attaching media or choosing a content_type.')]+#[Description('List every platform with its content types and their rules. Per content type: max/min media count, requires_media, accept_images/accept_videos/accept_documents, accepts_gif, accepts_mov, forbids_mixed_media, max_video_duration_sec (null = no cap), max_image_bytes / max_video_bytes / max_document_bytes, aspect_ratio_min / aspect_ratio_max for images and video_aspect_ratio_min / video_aspect_ratio_max for videos (width / height, null = not checked; GIFs are never checked; auto_fits_image when images are fitted into the frame on publish instead), image_min_width / image_min_height / image_max_width / image_max_height in pixels, supports_alt_text (alt_text on images), supports_video_alt_text (alt_text on videos too: Mastodon, Bluesky, Threads and Discord), supports_user_tags (Instagram tags in media meta.user_tags), supports_video_cover (meta.cover_offset_ms), supports_custom_video_cover (an image as the video cover, media meta.cover; Instagram Reels and YouTube Shorts), captionless (stories publish no text, so the text is neither sent nor measured), document_must_be_alone (a PDF must be the only attachment), supports_thread_replies and max_thread_replies (meta.thread_replies: a thread on X, Bluesky or Mastodon, or one comment on LinkedIn). Per platform: allowed_media_types, default_content_type, max_content_length (the default text limit of the network; the limit of each account, such as 25000 for an X account with long posts, is max_content_length in list-social-accounts-tool), max_hashtags (Instagram: 5), alt_text_max_length and required_meta (meta every post of the platform needs before it is scheduled or published; some needs depend on the content type and are not listed: Google Business events and offers also need meta.event, a YouTube post needs meta.title or text, and a poll (x_poll, mastodon_poll, threads_poll) needs meta.poll with at least 2 options, plus duration_minutes on X and Mastodon, and text as its question). Media rules never block a draft: they are checked when a post is scheduled, queued or published (create-post-tool, create-posts-tool, update-post-tool, publish-post-tool), and a post whose media breaks a rule of its content_type is rejected with a per-platform error. The exception is a poll (content_type x_poll, mastodon_poll or threads_poll, or a reply in meta.thread_replies with a poll on X or Mastodon): media, a repeated choice, more than 4 choices, a choice longer than the network allows (25 characters on X and Threads, 50 on Mastodon) or a duration_minutes outside the network\'s range (5–10080 on X, 5–43200 on Mastodon) is refused on every save, drafts included, and the attach media tools refuse it too. Call this before attaching media or choosing a content_type.')]class ListContentTypesTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.phpindex ee47072ac..31d0b9078 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php@@ -26,7 +26,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[IsReadOnly(false)]#[IsDestructive(true)]#[IsOpenWorld(false)]-#[Description('Attach a file uploaded with request-media-upload-tool to a post. The upload_token is the value request-media-upload-tool returned; the file is resolved by that token within the current workspace, then appended after the post media (to reorder or remove media, call update-post-tool with the media ids in the new order). The file type must be one the post channel accepts (allowed_media_types in list-content-types-tool). Posts that are publishing, published or failed cannot change; a scheduled post edited by a member who needs approval goes back to pending_approval. Size, video duration, GIF and MOV caps per content_type (see list-content-types-tool) are checked when the post is scheduled or published, not here. An X poll (content_type x_poll) takes no media, so attaching to one is refused whatever its status. Media is added to the post itself; to give a thread reply its own media, pass the upload_token in meta.thread_replies with update-post-tool.')]+#[Description('Attach a file uploaded with request-media-upload-tool to a post. The upload_token is the value request-media-upload-tool returned; the file is resolved by that token within the current workspace, then appended after the post media (to reorder or remove media, call update-post-tool with the media ids in the new order). The file type must be one the post channel accepts (allowed_media_types in list-content-types-tool). Posts that are publishing, published or failed cannot change; a scheduled post edited by a member who needs approval goes back to pending_approval. Size, video duration, GIF and MOV caps per content_type (see list-content-types-tool) are checked when the post is scheduled or published, not here. A poll (content_type x_poll, mastodon_poll or threads_poll) takes no media, so attaching to one is refused whatever its status. Media is added to the post itself; to give a thread reply its own media, pass the upload_token in meta.thread_replies with update-post-tool.')]class AttachMediaFromUploadTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.phpindex 110229817..e88e34378 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php@@ -24,7 +24,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[IsReadOnly(false)]#[IsDestructive(true)]#[IsOpenWorld(true)]-#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. The media is appended after the post\'s current media. Each URL must serve the file itself: redirects are not followed, and web pages, private-network hosts and files over the type\'s size ceiling are refused. Only the types the post\'s channel accepts are kept. URLs that could not be attached are listed in failed_urls, and failures gives the reason of each (unreachable, type_not_allowed, too_large, host_not_allowed) with a message. Video duration is measured on the server. Per-network size, duration, GIF and MOV caps (see list-content-types-tool) are enforced when the post is scheduled or published. An X poll (content_type x_poll) takes no media, so attaching to one is refused whatever its status. Supported files: JPEG, PNG, GIF and WebP images (HEIC and HEIF too when the server can convert them), MP4 and MOV videos, and PDF. Each download must finish within 20 seconds and fit the server limits (by default 10 MB and 67 megapixels for an image, 1 GB for a video, 100 MB for a PDF). Media is added to the post itself; to give a thread reply its own media, pass it in meta.thread_replies with update-post-tool.')]+#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. The media is appended after the post\'s current media. Each URL must serve the file itself: redirects are not followed, and web pages, private-network hosts and files over the type\'s size ceiling are refused. Only the types the post\'s channel accepts are kept. URLs that could not be attached are listed in failed_urls, and failures gives the reason of each (unreachable, type_not_allowed, too_large, host_not_allowed) with a message. Video duration is measured on the server. Per-network size, duration, GIF and MOV caps (see list-content-types-tool) are enforced when the post is scheduled or published. A poll (content_type x_poll, mastodon_poll or threads_poll) takes no media, so attaching to one is refused whatever its status. Supported files: JPEG, PNG, GIF and WebP images (HEIC and HEIF too when the server can convert them), MP4 and MOV videos, and PDF. Each download must finish within 20 seconds and fit the server limits (by default 10 MB and 67 megapixels for an image, 1 GB for a video, 100 MB for a PDF). Media is added to the post itself; to give a thread reply its own media, pass it in meta.thread_replies with update-post-tool.')]class AttachMediaFromUrlTool extends Tool{use AuthorizesMcpTool;diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.phpindex d60daaef7..c16d893df 100644--- a/app/Rules/ContentTypeCompatibleWithMedia.php+++ b/app/Rules/ContentTypeCompatibleWithMedia.php@@ -144,7 +144,7 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule$media = $this->media();- if ($contentType === ContentType::XPoll) {+ if ($contentType->isPoll()) {if ($media !== []) {$fail(trans('posts.errors.media_not_accepted'));}diff --git a/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.phpindex 76685b859..fabea25fa 100644--- a/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/AbstractMetaPublicationMetricsCollector.php@@ -13,6 +13,7 @@ use App\Support\Analytics\MetaAnalyticsResponse;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Log;+use Illuminate\Support\Uri;abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicationMetricsCollector{@@ -86,10 +87,29 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicatireturn $this->get($account, "{$graph}/{$publication->remote_id}", ['fields' => 'id']);}- protected function recordRefusal(AnalyticsCollectionException $exception): void+ /**+ * Keeps a read the token was refused (its category, and whether the object+ * was missing) and logs it under `$event`.+ *+ * @param array<string, mixed> $context+ */+ private function recordRefusal(AnalyticsCollectionException $exception, string $event, array $context): void{$this->refusals[] = $exception->category;$this->refusedMissingObject = $this->refusedMissingObject || $exception->missingObject;++ Log::info($event, [...$context, 'category' => $exception->category, 'reason' => $exception->getMessage()]);+ }++ /**+ * An optional read fails for good only when the token was not refused it+ * (a field its permissions do not cover, or one Meta calls malformed).+ */+ private function rethrowUnlessRefused(AnalyticsCollectionException $exception): void+ {+ if (! collect(['permission', 'malformed'])->containsStrict($exception->category)) {+ throw $exception;+ }}protected function successfulResponse(Response $response): Response@@ -97,6 +117,26 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicatireturn MetaAnalyticsResponse::successful($response, 'publication metrics collection');}+ /**+ * A read the token may be refused (a field its permissions do not cover):+ * a refusal is recorded and reads as nothing, so the metrics already+ * measured are kept; any other failure is rethrown.+ *+ * @param array<string, string> $query+ * @return array<string, mixed>+ */+ protected function optional(SocialAccount $account, string $url, array $query): array+ {+ try {+ return (array) $this->get($account, $url, $query)->json();+ } catch (AnalyticsCollectionException $exception) {+ $this->rethrowUnlessRefused($exception);+ $this->recordRefusal($exception, "analytics.{$account->platform->value}_read_refused", ['path' => Uri::of($url)->path()]);++ return [];+ }+ }+/*** @param list<string> $metrics* @param array<string, string> $query@@ -107,9 +147,7 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicatitry {$response = $this->get($account, $url, ['metric' => implode(',', $metrics), ...$query]);} catch (AnalyticsCollectionException $exception) {- if (! in_array($exception->category, ['permission', 'malformed'], true)) {- throw $exception;- }+ $this->rethrowUnlessRefused($exception);if (count($metrics) > 1) {return array_merge(...array_map(@@ -118,20 +156,15 @@ abstract class AbstractMetaPublicationMetricsCollector extends AbstractPublicati));}- $this->recordRefusal($exception);- Log::info('analytics.meta_metric_rejected', [+ $this->recordRefusal($exception, 'analytics.meta_metric_rejected', ['platform' => $account->platform->value,- 'path' => parse_url($url, PHP_URL_PATH),+ 'path' => Uri::of($url)->path(),'metric' => data_get($metrics, 0),- 'category' => $exception->category,- 'reason' => $exception->getMessage(),]);return [];}- $data = $response->json('data');-- return is_array($data) ? array_values(array_filter($data, 'is_array')) : [];+ return collect($response->json('data'))->filter(fn (mixed $item): bool => is_array($item))->values()->all();}}diff --git a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.phpindex 941fef8d9..e698f75cd 100644--- a/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/AbstractPublicationMetricsCollector.php@@ -16,6 +16,8 @@ use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Publications\AbstractApiPublicationCollector;+use App\Support\Social\Poll;+use App\Support\ThreadReplies;use Carbon\CarbonImmutable;use Closure;use Illuminate\Http\Client\Response;@@ -24,6 +26,72 @@ abstract class AbstractPublicationMetricsCollector extends AbstractApiPublicatio{abstract public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation;+ /**+ * The network ids of the thread replies TryPost published with a poll,+ * keyed by reply position, so their votes come in the same read as the+ * post's (X and Mastodon).+ *+ * @return array<int, string>+ */+ protected function replyPollIds(AnalyticsPublication $publication): array+ {+ if (blank($publication->post_id)) {+ return [];+ }++ $post = $publication->post()->first(['id', 'meta', 'thread_reply_ids']);+ $replyIds = (array) $post?->thread_reply_ids;++ return collect(ThreadReplies::of($post?->meta))+ ->filter(fn (array $reply, int $index): bool => ThreadReplies::hasPoll($reply) && is_string(data_get($replyIds, $index)))+ ->map(fn (array $reply, int $index): string => (string) data_get($replyIds, $index))+ ->all();+ }++ /**+ * The results of the reply polls a read returned, as `thread_polls` keeps+ * them: each with its reply position, a reply the read left out skipped.+ *+ * @param array<int, string> $replyPolls network ids keyed by reply position+ * @param Closure(string): mixed $pollOf the poll the read returned for one reply id+ * @param class-string<Poll> $poll+ * @return list<array<string, mixed>>+ */+ protected function threadPolls(array $replyPolls, Closure $pollOf, string $poll): array+ {+ return collect($replyPolls)+ ->map(fn (string $replyId, int $reply): ?array => transform(+ $poll::resultOf($pollOf($replyId)),+ fn (array $result): array => ['reply' => $reply, ...$result],+ ))+ ->filter()+ ->values()+ ->all();+ }++ /**+ * What a read stores in `provider_metadata`: the post's poll result+ * (`Poll::metadataFrom()`) and its reply polls; null when there is none.+ *+ * @param array{poll?: array<string, mixed>} $poll+ * @param list<array<string, mixed>> $threadPolls+ * @return array<string, mixed>|null+ */+ protected function pollMetadata(array $poll, array $threadPolls = []): ?array+ {+ $metadata = $poll;++ if (filled($threadPolls)) {+ $metadata['thread_polls'] = $threadPolls;+ }++ if (blank($metadata)) {+ return null;+ }++ return $metadata;+ }+protected function account(AnalyticsPublication $publication): SocialAccount{$account = $publication->socialAccount;@@ -99,7 +167,7 @@ abstract class AbstractPublicationMetricsCollector extends AbstractApiPublicatio* 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+ protected function rethrowWhenTemporary(AnalyticsCollectionException $exception): void{if (in_array($exception->category, ['rate_limited', 'transient'], true)) {throw $exception;diff --git a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.phpindex 5bdc37e57..343d7d7a5 100644--- a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php@@ -13,7 +13,6 @@ 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;/**@@ -132,28 +131,4 @@ class FacebookPublicationMetricsCollector extends AbstractMetaPublicationMetricsreturn $this->observation($date, $metrics);}-- /**- * @param array<string, string> $query- * @return array<string, mixed>- */- private function optional(SocialAccount $account, string $url, array $query): array- {- try {- return (array) $this->get($account, $url, $query)->json();- } catch (AnalyticsCollectionException $exception) {- if (! in_array($exception->category, ['permission', 'malformed'], true)) {- throw $exception;- }-- $this->recordRefusal($exception);- Log::info('analytics.facebook_read_refused', [- 'path' => parse_url($url, PHP_URL_PATH),- 'category' => $exception->category,- 'reason' => $exception->getMessage(),- ]);-- return [];- }- }}diff --git a/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.phpindex 6fc8f2428..061358942 100644--- a/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/MastodonPublicationMetricsCollector.php@@ -10,15 +10,60 @@ use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Services\Social\Mastodon\MastodonApi;+use App\Support\Social\MastodonPoll;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Response;+use Illuminate\Support\Collection;class MastodonPublicationMetricsCollector extends AbstractPublicationMetricsCollector{+ /**+ * Statuses asked for in one multiple read: Mastodon's default page size,+ * since the endpoint documents no maximum. A thread's 24 replies take two.+ */+ private const int STATUSES_PER_READ = 20;+public function collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation{$account = $this->account($publication);+ [$status, $threadPolls] = $this->read($account, $publication);++ return $this->observation($date, $this->withEngagements($this->present([+ $this->count(MetricKey::Reactions, $status, 'favourites_count'),+ $this->count(MetricKey::Comments, $status, 'replies_count'),+ $this->count(MetricKey::Shares, $status, 'reblogs_count'),+ ])), $this->pollMetadata(MastodonPoll::metadataFrom(data_get($status, 'poll')), $threadPolls));+ }++ /**+ * The status and its reply polls: a thread without a reply poll reads the+ * status alone; otherwise one read brings the status and its reply polls,+ * as on X. A server without that read (before Mastodon 4.3), or one that+ * leaves the status out (deleted or private), gets the status read alone,+ * which is where a deletion is confirmed.+ *+ * @return array{0: array<string, mixed>, 1: list<array<string, mixed>>}+ */+ private function read(SocialAccount $account, AnalyticsPublication $publication): array+ {+ $replyPolls = $this->replyPollIds($publication);++ if (filled($replyPolls)) {+ $thread = $this->readThread($account, $publication->remote_id, $replyPolls);++ if (filled($thread)) {+ return $thread;+ }+ }+ return [$this->readStatus($account, $publication), []];+ }++ /**+ * @return array<string, mixed>+ */+ private function readStatus(SocialAccount $account, AnalyticsPublication $publication): array+ {$response = $this->readUnlessDeleted(fn (): Response => $this->get($account,@@ -29,13 +74,57 @@ class MastodonPublicationMetricsCollector extends AbstractPublicationMetricsColl$publication->platform,);- $status = (array) $response->json();+ return (array) $response->json();+ }- return $this->observation($date, $this->withEngagements($this->present([- $this->count(MetricKey::Reactions, $status, 'favourites_count'),- $this->count(MetricKey::Comments, $status, 'replies_count'),- $this->count(MetricKey::Shares, $status, 'reblogs_count'),- ])));+ /**+ * The status and its reply polls (`GET /api/v1/statuses?id[]=`, Mastodon+ * 4.3), each reply poll's result with its reply position: one read for up+ * to `STATUSES_PER_READ` statuses, the status in the first. Null when the+ * server has no such read or left the status out; a read that failed only+ * for now is rethrown so the job retries.+ *+ * @param array<int, string> $replyPolls status ids keyed by reply position+ * @return array{0: array<string, mixed>, 1: list<array<string, mixed>>}|null+ */+ private function readThread(SocialAccount $account, string $id, array $replyPolls): ?array+ {+ $chunks = collect([$id, ...$replyPolls])->chunk(self::STATUSES_PER_READ);+ $statuses = $this->readStatuses($account, $chunks->first()->values()->all());+ $status = $statuses->get($id);++ if (! is_array($status)) {+ return null;+ }++ foreach ($chunks->skip(1) as $ids) {+ $statuses = $statuses->union($this->readStatuses($account, $ids->values()->all()));+ }++ return [$status, $this->threadPolls($replyPolls, fn (string $replyId): mixed => data_get($statuses->get($replyId), 'poll'), MastodonPoll::class)];+ }++ /**+ * Statuses by id, from one multiple read; none when the server refuses it.+ *+ * @param list<string> $ids+ * @return Collection<string, mixed>+ */+ private function readStatuses(SocialAccount $account, array $ids): Collection+ {+ try {+ $response = $this->get(+ $account,+ MastodonApi::url($account->mastodon_instance, 'statuses', ['id[]' => $ids]),+ authenticated: $account->canReadMastodonStatuses(),+ );+ } catch (AnalyticsCollectionException $exception) {+ $this->rethrowWhenTemporary($exception);++ return collect();+ }++ return $response->collect()->keyBy('id');}/**diff --git a/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.phpindex b7223a6b1..f4650ea4d 100644--- a/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/ThreadsPublicationMetricsCollector.php@@ -6,8 +6,12 @@ namespace App\Services\Analytics\Collectors\Metrics;use App\Dto\Analytics\PublicationMetricObservation;use App\Enums\Analytics\MetricKey;+use App\Enums\Analytics\PollVotingStatus;+use App\Enums\Analytics\PublicationContentType;use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\AnalyticsPublication;+use App\Models\SocialAccount;+use App\Support\Social\ThreadsPoll;use Carbon\CarbonImmutable;class ThreadsPublicationMetricsCollector extends AbstractMetaPublicationMetricsCollector@@ -39,6 +43,38 @@ class ThreadsPublicationMetricsCollector extends AbstractMetaPublicationMetricsC$this->count(MetricKey::Comments, $values, 'replies'),$this->count(MetricKey::Shares, $values, 'reposts'),$this->count(MetricKey::Quotes, $values, 'quotes'),- ])));+ ])), $this->readPoll($account, $publication));+ }++ /**+ * A poll's result, read on each metrics read like X's: the insights edge+ * carries no poll, so a poll is read once more for its `poll_attachment`.+ * Only a poll not yet stored closed makes that read (a closed one's result+ * is final), and one the token cannot read keeps the metrics measured.+ *+ * @return array{poll: array<string, mixed>}|null+ */+ private function readPoll(SocialAccount $account, AnalyticsPublication $publication): ?array+ {+ if (! $this->pollMayChange($publication)) {+ return null;+ }++ $post = $this->optional($account, "{$account->platform->graphApiUrl()}/{$publication->remote_id}", ['fields' => ThreadsPoll::LOOKUP_FIELDS]);++ return $this->pollMetadata(ThreadsPoll::metadataFrom(data_get($post, 'poll_attachment')));+ }++ /**+ * A poll whose stored result can still change: until a read after its end+ * stores it closed (`ThreadsPoll::result()`), so the final tally is read.+ */+ private function pollMayChange(AnalyticsPublication $publication): bool+ {+ if ($publication->content_type !== PublicationContentType::Poll) {+ return false;+ }++ return data_get($publication->provider_metadata, 'poll.voting_status') !== PollVotingStatus::Closed->value;}}diff --git a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.phpindex 8fc7dfe90..c8f0dd26d 100644--- a/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/XPublicationMetricsCollector.php@@ -11,7 +11,6 @@ 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;@@ -45,10 +44,7 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector$this->count(MetricKey::Quotes, $public, 'quote_count'),$this->count(MetricKey::Bookmarks, $public, 'bookmark_count'),$this->count(MetricKey::LinkClicks, $private, 'url_link_clicks'),- ])), Arr::whereNotNull([- 'poll' => transform($poll, XPoll::result(...)),- 'thread_polls' => filled($threadPolls) ? $threadPolls : null,- ]) ?: null);+ ])), $this->pollMetadata(XPoll::metadataFrom($poll), $threadPolls));}/**@@ -60,7 +56,7 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector*/private function read(SocialAccount $account, AnalyticsPublication $publication, array $fields): array{- $replyPolls = $this->replyPollTweetIds($publication);+ $replyPolls = $this->replyPollIds($publication);if (blank($replyPolls)) {return $this->readPost($account, $publication->remote_id, $fields);@@ -99,14 +95,7 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector$tweets = $response->collect('data')->keyBy('id');$polls = $response->collect('includes.polls')->keyBy('id');$pollOf = fn (mixed $tweet): mixed => $polls->get((string) data_get($tweet, 'attachments.poll_ids.0'));- $threadPolls = collect($replyPolls)- ->map(fn (string $replyId, int $reply): ?array => transform(- $pollOf($tweets->get($replyId)),- fn (array $poll): array => ['reply' => $reply, ...XPoll::result($poll)],- ))- ->filter()- ->values()- ->all();+ $threadPolls = $this->threadPolls($replyPolls, fn (string $replyId): mixed => $pollOf($tweets->get($replyId)), XPoll::class);$tweet = $this->postTweet($response, $id, $tweets->get($id));@@ -150,25 +139,4 @@ class XPublicationMetricsCollector extends AbstractPublicationMetricsCollector'poll.fields' => XPoll::LOOKUP_FIELDS,];}-- /**- * The tweet ids of the thread replies TryPost published with a poll, keyed by- * reply position, so their votes come in the same lookup as the post's.- *- * @return array<int, string>- */- private function replyPollTweetIds(AnalyticsPublication $publication): array- {- if (blank($publication->post_id)) {- return [];- }-- $post = $publication->post()->first(['id', 'meta', 'thread_reply_ids']);- $replyIds = (array) $post?->thread_reply_ids;-- return collect(ThreadReplies::of($post?->meta))- ->filter(fn (array $reply, int $index): bool => ThreadReplies::hasPoll($reply) && is_string(data_get($replyIds, $index)))- ->map(fn (array $reply, int $index): string => (string) data_get($replyIds, $index))- ->all();- }}diff --git a/app/Services/Analytics/Collectors/Publications/AbstractApiPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/AbstractApiPublicationCollector.phpindex 4709710fa..c5026b79b 100644--- a/app/Services/Analytics/Collectors/Publications/AbstractApiPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/AbstractApiPublicationCollector.php@@ -11,6 +11,7 @@ use App\Support\Analytics\InvalidPublicationCursor;use Carbon\CarbonImmutable;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response;+use Illuminate\Support\Arr;use Illuminate\Support\Facades\Http;use Throwable;@@ -23,8 +24,7 @@ abstract class AbstractApiPublicationCollectorarray $query = [],bool $authenticated = true,): Response {- $response = $this->client($account, $authenticated)- ->get($url, array_filter($query, fn (mixed $value): bool => $value !== null && $value !== ''));+ $response = $this->client($account, $authenticated)->get($url, self::queryParameters($query));if ((filled(data_get($query, 'pageToken'))|| filled(data_get($query, 'pagination_token'))@@ -36,6 +36,24 @@ abstract class AbstractApiPublicationCollectorreturn $this->successfulResponse($response);}+ /**+ * The query's filled parameters, or null without any: an empty query would+ * replace the query a URL already carries (`MastodonApi::url()`).+ *+ * @param array<string, mixed> $query+ * @return array<string, mixed>|null+ */+ protected static function queryParameters(array $query): ?array+ {+ $parameters = Arr::where($query, fn (mixed $value): bool => filled($value));++ if (blank($parameters)) {+ return null;+ }++ return $parameters;+ }+/** @param array<string, mixed> $payload */protected function post(SocialAccount $account, string $url, array $payload, bool $hasCursor = false): Response{diff --git a/app/Services/Analytics/Collectors/Publications/AbstractMetaPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/AbstractMetaPublicationCollector.phpindex d62485ae7..c08eb0d01 100644--- a/app/Services/Analytics/Collectors/Publications/AbstractMetaPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/AbstractMetaPublicationCollector.php@@ -26,7 +26,7 @@ abstract class AbstractMetaPublicationCollector extends AbstractPublicationHisto$response = Http::acceptJson()->withToken(AnalyticsAccessToken::for($account))->timeout(120)- ->get($url, array_filter($query, fn (mixed $value): bool => $value !== null && $value !== ''));+ ->get($url, self::queryParameters($query));if (filled(data_get($query, 'after')) && InvalidPublicationCursor::matches($response)) {throw new AnalyticsCollectionException('invalid_cursor', 'publication history cursor expired');diff --git a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.phpindex b8290cb75..48041f689 100644--- a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php@@ -9,6 +9,7 @@ use App\Dto\Analytics\PublicationPage;use App\Enums\Analytics\PublicationContentType;use App\Models\SocialAccount;use App\Services\Social\Mastodon\MastodonApi;+use App\Support\Social\MastodonPoll;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Response;@@ -72,6 +73,7 @@ class MastodonPublicationCollector extends AbstractPublicationHistoryCollector'replies_count' => (int) data_get($row, 'replies_count', 0),'history_visibility' => $hasPrivateHistoryScope ? 'authorized' : 'public_only','reconnect_required' => ! $hasPrivateHistoryScope,+ ...MastodonPoll::metadataFrom(data_get($row, 'poll')),],);}diff --git a/app/Services/Analytics/Collectors/Publications/ThreadsPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/ThreadsPublicationCollector.phpindex 6ea923831..36cc720ce 100644--- a/app/Services/Analytics/Collectors/Publications/ThreadsPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/ThreadsPublicationCollector.php@@ -8,13 +8,14 @@ use App\Dto\Analytics\DiscoveredPublication;use App\Dto\Analytics\PublicationPage;use App\Enums\Analytics\PublicationContentType;use App\Models\SocialAccount;+use App\Support\Social\ThreadsPoll;use Carbon\CarbonImmutable;class ThreadsPublicationCollector extends AbstractMetaPublicationCollector{private const PAGE_SIZE = 50;- private const FIELDS = 'id,media_product_type,media_type,media_url,permalink,text,timestamp,thumbnail_url,is_quote_post';+ private const FIELDS = 'id,media_product_type,media_type,media_url,permalink,text,timestamp,thumbnail_url,is_quote_post,'.ThreadsPoll::LOOKUP_FIELDS;public function page(SocialAccount $account,@@ -57,7 +58,10 @@ class ThreadsPublicationCollector extends AbstractMetaPublicationCollectorpermalink: data_get($row, 'permalink'),excerpt: data_get($row, 'text'),previewMetadata: $this->preview(data_get($row, 'thumbnail_url') ?: data_get($row, 'media_url')),- providerMetadata: ['is_quote_post' => (bool) data_get($row, 'is_quote_post', false)],+ providerMetadata: [+ 'is_quote_post' => (bool) data_get($row, 'is_quote_post', false),+ ...ThreadsPoll::metadataFrom(data_get($row, 'poll_attachment')),+ ],);}@@ -67,6 +71,10 @@ class ThreadsPublicationCollector extends AbstractMetaPublicationCollector/** @param array<string, mixed> $row */private function contentType(array $row): PublicationContentType{+ if (filled(data_get($row, 'poll_attachment'))) {+ return PublicationContentType::Poll;+ }+return match (strtoupper((string) data_get($row, 'media_type'))) {'VIDEO' => PublicationContentType::Video,'IMAGE' => PublicationContentType::Image,diff --git a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.phpindex b3d4c898a..4f9abaf91 100644--- a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php@@ -75,7 +75,7 @@ class XPublicationCollector extends AbstractPublicationHistoryCollectorfn (array $item): bool => filled(data_get($item, 'preview_image_url')) || filled(data_get($item, 'url')),);- $poll = transform($polls->get((string) data_get($row, 'attachments.poll_ids.0')), XPoll::result(...));+ $poll = XPoll::resultOf($polls->get((string) data_get($row, 'attachments.poll_ids.0')));$publications[] = new DiscoveredPublication(providerPostId: $postId,diff --git a/app/Services/Post/PostPreviewer.php b/app/Services/Post/PostPreviewer.phpindex 4f57bdc87..e6a50e4b1 100644--- a/app/Services/Post/PostPreviewer.php+++ b/app/Services/Post/PostPreviewer.php@@ -8,7 +8,7 @@ use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Models\Post;use App\Services\Social\ContentSanitizer;-use App\Support\Social\XPoll;+use App\Support\Social\Poll;use App\Support\ThreadReplies;use App\Support\YouTubeDescription;use App\Support\YouTubeMetadata;@@ -86,18 +86,38 @@ class PostPreviewer$replies = ThreadReplies::supports($platform) ? ThreadReplies::of($post->meta) : [];- if ($post->content_type === ContentType::XPoll) {- $preview['poll'] = XPoll::payload($post->meta);+ $poll = $post->content_type?->poll();++ if (filled($poll)) {+ $preview['poll'] = $poll::preview($post->meta);}if ($replies !== []) {+ $replyPoll = ThreadReplies::replyPoll($platform);+$preview['thread_replies'] = array_map(fn (array $reply): array => ['text' => $this->sanitizer->sanitize($reply['text'], $platform),'media' => $reply['media'],- ...(ThreadReplies::hasPoll($reply) ? ['poll' => XPoll::payload($reply)] : []),+ ...self::replyPollPreview($replyPoll, $reply),], $replies);}return $preview;}++ /**+ * A reply's poll as the preview shows it, on a network whose replies can be polls.+ *+ * @param class-string<Poll>|null $poll+ * @param array<string, mixed> $reply+ * @return array{poll?: array<string, mixed>}+ */+ private static function replyPollPreview(?string $poll, array $reply): array+ {+ if (blank($poll) || ! ThreadReplies::hasPoll($reply)) {+ return [];+ }++ return ['poll' => $poll::preview($reply)];+ }}diff --git a/app/Services/Social/Concerns/HasSocialHttpClient.php b/app/Services/Social/Concerns/HasSocialHttpClient.phpindex a933f8dbf..46d6f6909 100644--- a/app/Services/Social/Concerns/HasSocialHttpClient.php+++ b/app/Services/Social/Concerns/HasSocialHttpClient.php@@ -11,6 +11,7 @@ use App\Services\Social\ContentSanitizer;use App\Services\Social\TokenRedactor;use App\Support\ThreadReplies;use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Arr;use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;@@ -41,6 +42,12 @@ trait HasSocialHttpClientthrow new ContentLimitException($post->platform, $threadViolation[1]);}+ $replyPollMediaError = Arr::first(ThreadReplies::pollMediaErrors($post->platform, $post->meta));++ if (filled($replyPollMediaError)) {+ throw new ContentLimitException($post->platform, $replyPollMediaError);+ }+$maxLength = ContentType::maxContentLengthFor($post->socialAccount, $post->platform, $post->content_type);$contentLength = Str::length($content) + $post->platform->reservedLength($post->meta);diff --git a/app/Services/Social/Concerns/PublishesThreads.php b/app/Services/Social/Concerns/PublishesThreads.phpindex c2d3d70da..328bc272f 100644--- a/app/Services/Social/Concerns/PublishesThreads.php+++ b/app/Services/Social/Concerns/PublishesThreads.php@@ -21,7 +21,7 @@ trait PublishesThreads* part (ThreadProgress::failureMessage()).** @param callable(): array{id: string, url?: ?string, uri?: string, cid?: string} $postRoot- * @param callable(string, Collection<int, MediaItem>, array<string, mixed>, array<string, mixed>, ?array<string, mixed>): array{id: string, url?: ?string, uri?: string, cid?: string} $postReply the last argument is the reply's poll (X only)+ * @param callable(string, Collection<int, MediaItem>, array<string, mixed>, array<string, mixed>, ?array<string, mixed>): array{id: string, url?: ?string, uri?: string, cid?: string} $postReply the last argument is the reply's poll (X and Mastodon)* @param (callable(array<string, mixed>): void)|null $afterThread* @return array{id: string, url: ?string, thread_reply_ids?: list<string>}*/diff --git a/app/Services/Social/Mastodon/MastodonApi.php b/app/Services/Social/Mastodon/MastodonApi.phpindex bba8b4e63..aac7295cc 100644--- a/app/Services/Social/Mastodon/MastodonApi.php+++ b/app/Services/Social/Mastodon/MastodonApi.php@@ -4,6 +4,8 @@ declare(strict_types=1);namespace App\Services\Social\Mastodon;+use GuzzleHttp\Psr7\Query;+/*** Builds Mastodon REST API URLs on an account's instance, so the `/api/v1`* prefix lives in one place.@@ -11,10 +13,21 @@ namespace App\Services\Social\Mastodon;class MastodonApi{/**- * Endpoint for an API path, e.g. `https://mastodon.social/api/v1/statuses`.+ * Endpoint for an API path, e.g. `https://mastodon.social/api/v1/statuses`,+ * with its query when it has one. A list repeats its key the way Mastodon+ * reads it (`['id[]' => [1, 2]]` is `id[]=1&id[]=2`), which an array query+ * of the HTTP client cannot send (it writes `id[0]=1`).+ *+ * @param array<string, mixed> $query*/- public static function url(string $instance, string $path): string+ public static function url(string $instance, string $path, array $query = []): string{- return "{$instance}/api/v1/{$path}";+ $url = "{$instance}/api/v1/{$path}";++ if (blank($query)) {+ return $url;+ }++ return "{$url}?".Query::build($query);}}diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.phpindex 95e053117..cf0e05944 100644--- a/app/Services/Social/MastodonPublisher.php+++ b/app/Services/Social/MastodonPublisher.php@@ -6,6 +6,7 @@ namespace App\Services\Social;use App\Dto\MediaItem;use App\Enums\Media\Type as MediaType;+use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Exceptions\PlatformUnavailableException;use App\Exceptions\Social\ErrorCategory;@@ -16,6 +17,7 @@ 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\MastodonPoll;use App\Support\Social\ThreadProgress;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;@@ -39,20 +41,21 @@ class MastodonPublisher$account = $post->socialAccount;$instance = $account->mastodon_instance;- $rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());+ $isPoll = $post->content_type === ContentType::MastodonPoll;+ $rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all(), $this->rootPoll($post, $isPoll));return $this->publishThread($post,$rootHash,- fn (): array => $this->publishRoot($post, $account, $instance, $content, "{$post->id}:{$rootHash}"),- fn (string $text, Collection $media, array $parent): array => $this->createStatus(+ fn (): array => $this->publishRoot($post, $account, $instance, $content, $isPoll, "{$post->id}:{$rootHash}"),+ fn (string $text, Collection $media, array $parent, array $root, ?array $poll): array => $this->createStatus($account,$instance,[...$this->replyPayload($post, $text, (string) $parent['id']),- ...$this->mediaPayload($account, $instance, $media),+ ...$this->attachments($account, $instance, $text, $media, filled($poll), ['poll' => $poll]),],- "{$post->id}:{$parent['id']}:".ThreadProgress::hash($text, $media->map(fn (MediaItem $item): string => $item->id)->all()),+ "{$post->id}:{$parent['id']}:".ThreadProgress::hash($text, $media->map(fn (MediaItem $item): string => $item->id)->all(), $poll),),);}@@ -60,17 +63,58 @@ class MastodonPublisher/*** @return array{id: string, url: ?string}*/- private function publishRoot(Post $post, SocialAccount $account, string $instance, ?string $content, string $idempotencyKey): array+ private function publishRoot(Post $post, SocialAccount $account, string $instance, ?string $content, bool $isPoll, string $idempotencyKey): array{$payload = ['status' => $content ?? '','visibility' => 'public',- ...$this->mediaPayload($account, $instance, $post->mediaItems),+ ...$this->attachments($account, $instance, $content, $post->mediaItems, $isPoll, $post->meta),];return $this->createStatus($account, $instance, [...$payload, ...$this->contentWarning($post)], $idempotencyKey);}+ /**+ * The post's own poll, part of the root's identity: it is the+ * Idempotency-Key, so a poll changed before a retry is a new status, never+ * the one Mastodon kept from the attempt before. Null off a poll, which+ * keeps the hash every other status had.+ *+ * @return array<string, mixed>|null+ */+ private function rootPoll(Post $post, bool $isPoll): ?array+ {+ if (! $isPoll) {+ return null;+ }++ return MastodonPoll::payload($post->meta);+ }++ /**+ * What a status of the thread attaches: its poll, or its media. A poll+ * needs its question (that status's text), distinct choices and a length,+ * and cannot carry media. `$meta` holds the poll under `poll`: the post's+ * meta, or the reply itself.+ *+ * @param Collection<int, MediaItem> $media+ * @return array<string, mixed>+ */+ private function attachments(SocialAccount $account, string $instance, ?string $text, Collection $media, bool $isPoll, ?array $meta): array+ {+ if (! $isPoll) {+ return $this->mediaPayload($account, $instance, $media);+ }++ $violation = MastodonPoll::publishViolation($text, $media->isNotEmpty(), $meta);++ if (filled($violation)) {+ throw new MastodonPublishException(userMessage: $violation, category: ErrorCategory::ContentPolicy);+ }++ return ['poll' => MastodonPoll::payload($meta)];+ }+/*** Uploads up to four media and returns the status's `media_ids`, empty* when the post has none.diff --git a/app/Services/Social/ThreadsPublisher.php b/app/Services/Social/ThreadsPublisher.phpindex 70a41c990..379689e14 100644--- a/app/Services/Social/ThreadsPublisher.php+++ b/app/Services/Social/ThreadsPublisher.php@@ -13,6 +13,7 @@ use App\Exceptions\Social\ThreadsPublishException;use App\Models\Post;use App\Services\Social\Concerns\HasSocialHttpClient;use App\Support\PostPlatformMetaRules;+use App\Support\Social\ThreadsPoll;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Log;@@ -33,7 +34,7 @@ class ThreadsPublisher/*** Extra parameters for the post's own container (never carousel children).*- * @var array<string, string>+ * @var array<string, mixed>*/private array $containerOptions = [];@@ -66,9 +67,7 @@ class ThreadsPublisher);}- $this->containerOptions = $post->content_type === ContentType::ThreadsGhostPost- ? ['is_ghost_post' => 'true']- : $this->postOptions($post);+ $this->containerOptions = $this->containerOptions($post, $content);// Text only postif ($media->isEmpty()) {@@ -386,6 +385,41 @@ class ThreadsPublisher);}+ /**+ * What the container takes besides the text and media: a ghost post is+ * marked as one, a poll carries its choices, and a post its topic.+ *+ * @return array<string, mixed>+ */+ private function containerOptions(Post $post, ?string $content): array+ {+ if ($post->content_type === ContentType::ThreadsGhostPost) {+ return ['is_ghost_post' => 'true'];+ }++ if ($post->content_type === ContentType::ThreadsPoll) {+ return [...$this->postOptions($post), 'poll_attachment' => $this->pollAttachment($post, $content)];+ }++ return $this->postOptions($post);+ }++ /**+ * A poll goes on a text post only, with its question and choices, sent as+ * a JSON string as the Threads docs show it (like Instagram's nested+ * parameters).+ */+ private function pollAttachment(Post $post, ?string $content): string+ {+ $violation = ThreadsPoll::publishViolation($content, $post->mediaItems->isNotEmpty(), $post->meta);++ if (filled($violation)) {+ throw new ThreadsPublishException(userMessage: $violation, category: ErrorCategory::ContentPolicy);+ }++ return (string) json_encode(ThreadsPoll::payload($post->meta));+ }+/*** @return array<string, string>*/diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.phpindex 11381cd5f..d9317d44d 100644--- a/app/Services/Social/XPublisher.php+++ b/app/Services/Social/XPublisher.php@@ -145,7 +145,7 @@ class XPublisher* @param Collection<int, MediaItem> $media* @return array<string, mixed>*/- private function attachments(?string $text, Collection $media, bool $isPoll, mixed $meta): array+ private function attachments(?string $text, Collection $media, bool $isPoll, ?array $meta): array{if ($isPoll) {return ['poll' => $this->pollPayload($text, $media, $meta)];@@ -162,9 +162,9 @@ class XPublisher* @param Collection<int, MediaItem> $media* @return array{options: list<string>, duration_minutes: int}*/- private function pollPayload(?string $question, Collection $media, mixed $meta): array+ private function pollPayload(?string $question, Collection $media, ?array $meta): array{- $violation = $this->pollViolation($question, $media, $meta);+ $violation = XPoll::publishViolation($question, $media->isNotEmpty(), $meta);if (filled($violation)) {throw new XPublishException(userMessage: $violation, category: ErrorCategory::ContentPolicy);@@ -173,29 +173,6 @@ class XPublisherreturn XPoll::payload($meta);}- /**- * Why X would refuse the poll: no question, media on it, or choices and a- * length that break X's rules. Null when the poll can go.- *- * @param Collection<int, MediaItem> $media- */- private function pollViolation(?string $question, Collection $media, mixed $meta): ?string- {- $questionViolation = XPoll::questionViolation($question);-- if (filled($questionViolation)) {- return $questionViolation;- }-- if ($media->isNotEmpty()) {- return trans('posts.errors.media_not_accepted');- }-- $pollViolation = XPoll::violation($meta) ?? XPoll::requiredViolation($meta);-- return data_get($pollViolation, 1);- }-/*** Uploads the media and returns the tweet's `media` field, empty when* nothing uploaded.diff --git a/app/Support/Analytics/SyncCadence.php b/app/Support/Analytics/SyncCadence.phpindex 90fe5bf5f..09bc7e1e1 100644--- a/app/Support/Analytics/SyncCadence.php+++ b/app/Support/Analytics/SyncCadence.php@@ -22,6 +22,13 @@ class SyncCadence*/public const array X_METRICS_DAYS = [2, 3, 7, 14, 28];+ /**+ * A Mastodon poll may run 30 days (`MastodonPoll::MAX_DURATION`), so a+ * Mastodon post is read one day longer: the daily read after the poll ends+ * stores its final result (and the votes a poll hid until then).+ */+ public const int MASTODON_METRICS_WINDOW_DAYS = 31;+/*** A post just published has nothing to measure yet, so its first read waits this long.*/@@ -29,7 +36,15 @@ class SyncCadencepublic static function metricsWindowDays(Platform $platform): int{- return $platform === Platform::X ? max(self::X_METRICS_DAYS) : self::METRICS_WINDOW_DAYS;+ if ($platform === Platform::X) {+ return max(self::X_METRICS_DAYS);+ }++ if ($platform === Platform::Mastodon) {+ return self::MASTODON_METRICS_WINDOW_DAYS;+ }++ return self::METRICS_WINDOW_DAYS;}/**diff --git a/app/Support/PostCompositionValidator.php b/app/Support/PostCompositionValidator.phpindex a03cac22e..de2bfa74f 100644--- a/app/Support/PostCompositionValidator.php+++ b/app/Support/PostCompositionValidator.php@@ -15,7 +15,6 @@ use App\Models\Workspace;use App\Rules\ContentFitsPlatformLimits;use App\Rules\ContentTypeCompatibleWithMedia;use App\Rules\PostContentFitsMaxLength;-use App\Support\Social\XPoll;use Illuminate\Support\Arr;use Illuminate\Support\Facades\Validator;use Illuminate\Support\Str;@@ -199,13 +198,11 @@ class PostCompositionValidator}}- $formatViolation = PostPlatformMetaRules::formatViolation($account->platform, data_get($destination, 'meta', []), $contentType);- if ($formatViolation !== null) {- [$field, $message] = $formatViolation;+ foreach (PostPlatformMetaRules::formatErrors($account->platform, data_get($destination, 'meta', []), $contentType) as $field => $message) {$validator->errors()->add("{$key}.meta.{$field}", $message);}- $pollWithMedia = $contentType === ContentType::XPoll && filled(data_get($destination, 'media'));+ $pollWithMedia = $contentType?->isPoll() === true && filled(data_get($destination, 'media'));if ($pollWithMedia) {$validator->errors()->add("{$key}.media", trans('posts.errors.media_not_accepted'));@@ -227,16 +224,16 @@ class PostCompositionValidator$validator->errors()->add("{$key}.content", $contentValidator->errors()->first('content'));}- $questionViolation = $contentType === ContentType::XPoll ? XPoll::questionViolation(data_get($destination, 'content')) : null;+ $questionViolation = transform($contentType?->poll(), fn (string $poll): ?string => $poll::questionViolation(data_get($destination, 'content')));if (filled($questionViolation)) {$validator->errors()->add("{$key}.content", $questionViolation);} elseif (blank(data_get($destination, 'content')) && blank(data_get($destination, 'media'))) {$validator->errors()->add("{$key}.content", trans('posts.edit.compliance.requires_content_or_media'));}- $metaViolation = PostPlatformMetaRules::requiredMetaViolation($account, $destination['meta'] ?? [], $destination['content_type'] ?? null)+ $metaViolation = PostPlatformMetaRules::requiredMetaViolation($account, $destination['meta'] ?? [], $contentType)?? PostPlatformMetaRules::contentMetaViolation($account->platform, $destination['meta'] ?? [], (string) $destination['content']);- if ($metaViolation !== null && $metaViolation !== $formatViolation) {+ if (filled($metaViolation) && ! $validator->errors()->has("{$key}.meta.{$metaViolation[0]}")) {[$field, $message] = $metaViolation;$validator->errors()->add("{$key}.meta.{$field}", $message);}diff --git a/app/Support/PostMeta.php b/app/Support/PostMeta.phpindex d911488a7..a300b0bfd 100644--- a/app/Support/PostMeta.php+++ b/app/Support/PostMeta.php@@ -8,6 +8,7 @@ use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Models\SocialAccount;use App\Services\Social\Discord\DiscordClient;+use App\Support\Social\Poll;use Illuminate\Support\Arr;/**@@ -34,13 +35,8 @@ class PostMeta...Arr::only($stored, PostPlatformMetaRules::SYSTEM_KEYS),];- if (ContentType::resolve($contentType) !== ContentType::XPoll) {- $meta = Arr::except($meta, 'poll');- }-- if ($account->platform !== Platform::X) {- $meta = ThreadReplies::withoutPolls($meta);- }+ $meta = self::withPoll($meta, ContentType::resolve($contentType));+ $meta = ThreadReplies::forNetwork($account->platform, $meta);return match ($account->platform) {Platform::Discord => self::withDiscordChannelName($account, $meta),@@ -48,6 +44,28 @@ class PostMeta};}+ /**+ * A poll type keeps its poll with only what its network takes; any other+ * type drops it.+ *+ * @param array<string, mixed> $meta+ * @return array<string, mixed>+ */+ private static function withPoll(array $meta, ?ContentType $contentType): array+ {+ $poll = $contentType?->poll();++ if (blank($poll)) {+ return Arr::except($meta, 'poll');+ }++ if (is_array(data_get($meta, 'poll'))) {+ $meta['poll'] = $poll::forNetwork(data_get($meta, 'poll'));+ }++ return $meta;+ }+/*** The meta an update starts from: the stored meta with the sent keys on top.* A sent poll is merged into the stored one key by key, so sending only itsdiff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.phpindex f8569de36..c6a6638e1 100644--- a/app/Support/PostPlatformMetaRules.php+++ b/app/Support/PostPlatformMetaRules.php@@ -17,6 +17,9 @@ use App\Models\Post;use App\Models\SocialAccount;use App\Rules\ValidYouTubeDescription;use App\Services\Social\ContentSanitizer;+use App\Support\Social\MastodonPoll;+use App\Support\Social\Poll;+use App\Support\Social\ThreadsPoll;use App\Support\Social\XPoll;use Closure;use Illuminate\Support\Arr;@@ -50,7 +53,7 @@ class PostPlatformMetaRules* clients by every tool that schedules or publishes, so a new rule is* written here once.*/- public const SCHEDULING_REQUIREMENTS = 'Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text), an X poll (content_type x_poll) meta.poll with at least 2 options and duration_minutes plus text as its question (a reply poll in meta.thread_replies needs the same, its text being the question); list-content-types-tool lists the TikTok, Pinterest and Discord ones per platform as required_meta. A scheduled or published post also needs text or media; an X poll needs text and takes no media.';+ public const SCHEDULING_REQUIREMENTS = 'Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text), a poll (content_type x_poll, mastodon_poll or threads_poll) meta.poll with at least 2 options plus text as its question, and on X and Mastodon duration_minutes (a reply poll in meta.thread_replies on X or Mastodon needs the same, its text being the question); list-content-types-tool lists the TikTok, Pinterest and Discord ones per platform as required_meta. A scheduled or published post also needs text or media; a poll needs text and takes no media.';/** An Instagram username, with or without its leading @. */public const INSTAGRAM_USERNAME_PATTERN = '/^@?[A-Za-z0-9._]{1,30}$/';@@ -82,8 +85,10 @@ class PostPlatformMetaRules"{$prefix}.poll" => ['sometimes', 'nullable', 'array'],"{$prefix}.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],- "{$prefix}.poll.options.*" => ['nullable', 'string', self::pollChoiceLength(...)],- "{$prefix}.poll.duration_minutes" => ['sometimes', 'nullable', 'integer', 'between:'.XPoll::MIN_DURATION.','.XPoll::MAX_DURATION],+ "{$prefix}.poll.options.*" => ['nullable', 'string'],+ "{$prefix}.poll.duration_minutes" => ['sometimes', 'nullable', 'integer'],+ "{$prefix}.poll.multiple" => ['sometimes', 'nullable', 'boolean'],+ "{$prefix}.poll.hide_totals" => ['sometimes', 'nullable', 'boolean'],"{$prefix}.spoiler_text" => ['sometimes', 'nullable', 'string', 'max:500'],@@ -105,8 +110,10 @@ class PostPlatformMetaRules"{$prefix}.thread_replies.*.media.*.url" => ['sometimes', 'nullable', 'string'],"{$prefix}.thread_replies.*.poll" => ['sometimes', 'nullable', 'array'],"{$prefix}.thread_replies.*.poll.options" => ['sometimes', 'nullable', 'array', self::pollOptionsCount(...)],- "{$prefix}.thread_replies.*.poll.options.*" => ['nullable', 'string', self::pollChoiceLength(...)],- "{$prefix}.thread_replies.*.poll.duration_minutes" => ['sometimes', 'nullable', 'integer', 'between:'.XPoll::MIN_DURATION.','.XPoll::MAX_DURATION],+ "{$prefix}.thread_replies.*.poll.options.*" => ['nullable', 'string'],+ "{$prefix}.thread_replies.*.poll.duration_minutes" => ['sometimes', 'nullable', 'integer'],+ "{$prefix}.thread_replies.*.poll.multiple" => ['sometimes', 'nullable', 'boolean'],+ "{$prefix}.thread_replies.*.poll.hide_totals" => ['sometimes', 'nullable', 'boolean'],"{$prefix}.document_title" => ['sometimes', 'nullable', 'string', 'max:300'],@@ -202,33 +209,25 @@ class PostPlatformMetaRules"{$prefix}.collaborators.*.regex" => __('posts.form.instagram.collaborators.invalid'),"{$prefix}.event.end_date.after_or_equal" => __('posts.form.google_business.event_end_date_before_start'),"{$prefix}.event.title.max" => __('posts.form.google_business.title_max'),- "{$prefix}.poll.array" => __('posts.form.x.poll.poll_object'),- "{$prefix}.poll.options.array" => __('posts.form.x.poll.options_list'),- "{$prefix}.poll.options.*.string" => __('posts.form.x.poll.choice_text'),- "{$prefix}.poll.duration_minutes.integer" => XPoll::durationRangeMessage(),- "{$prefix}.poll.duration_minutes.between" => XPoll::durationRangeMessage(),- "{$prefix}.thread_replies.*.poll.array" => __('posts.form.x.poll.poll_object'),- "{$prefix}.thread_replies.*.poll.options.array" => __('posts.form.x.poll.options_list'),- "{$prefix}.thread_replies.*.poll.options.*.string" => __('posts.form.x.poll.choice_text'),- "{$prefix}.thread_replies.*.poll.duration_minutes.integer" => XPoll::durationRangeMessage(),- "{$prefix}.thread_replies.*.poll.duration_minutes.between" => XPoll::durationRangeMessage(),+ "{$prefix}.poll.array" => __('posts.form.poll.poll_object'),+ "{$prefix}.poll.options.array" => __('posts.form.poll.options_list'),+ "{$prefix}.poll.options.*.string" => __('posts.form.poll.choice_text'),+ "{$prefix}.poll.duration_minutes.integer" => __('posts.form.poll.duration_whole'),+ "{$prefix}.thread_replies.*.poll.array" => __('posts.form.poll.poll_object'),+ "{$prefix}.thread_replies.*.poll.options.array" => __('posts.form.poll.options_list'),+ "{$prefix}.thread_replies.*.poll.options.*.string" => __('posts.form.poll.choice_text'),+ "{$prefix}.thread_replies.*.poll.duration_minutes.integer" => __('posts.form.poll.duration_whole'),];}/**- * A poll's choices, checked by `XPoll` (the post's poll and each reply's).+ * A poll's choices (the post's poll and each reply's): four at most on+ * every network. The length of each choice and of the poll depends on the+ * network, so `formatErrors()` checks them once the channel is known.*/private static function pollOptionsCount(string $attribute, mixed $value, Closure $fail): void{- transform(XPoll::optionsCountViolation($value), $fail);- }-- /**- * One poll choice, checked by `XPoll`.- */- private static function pollChoiceLength(string $attribute, mixed $value, Closure $fail): void- {- transform(XPoll::choiceLengthViolation($value), $fail);+ transform(Poll::optionsCountViolation($value), $fail);}/**@@ -261,13 +260,15 @@ class PostPlatformMetaRules'Discord: channel_id (required to publish — call list-discord-channels-tool first), mentions ([{token,label}], e.g. {token: "@everyone"} or {token: "<@&roleId>"}), embeds (up to 10 [{title ≤256, description ≤4096, url, image (URL), color (#RRGGBB)}]).','YouTube Shorts: title (≤100, no < or >; omitted, it is derived from the first non-empty line of the content with < and > removed, cut to 100 characters), description (plain text, at most 5000 bytes; omit or null to use the content), category_id (YouTube category id: '.collect(Category::cases())->map(fn (Category $category): string => "{$category->value}=".__($category->labelKey(), [], 'en'))->implode(', ').'; default '.Category::DEFAULT->value.'), privacy_status (public|unlisted|private, default public), license (youtube|creativeCommon), notify_subscribers (default true), embeddable (default true), made_for_kids (default false), is_ai_generated (discloses altered or synthetic content). A cover image is the media item meta.cover, set as the thumbnail once YouTube processes the video.','Instagram: is_ai_generated (feed, reels, stories, carousels), share_to_feed (instagram_reel only, default true), collaborators (up to '.self::INSTAGRAM_MAX_COLLABORATORS.' Instagram usernames invited as co-authors; feed, reels and carousels, not stories; the post shows on a collaborator\'s profile only after they accept the invite in the Instagram app, and a username that does not exist is only refused when the post publishes, so confirm the usernames first), trial_graduation (instagram_reel only: MANUAL|SS_PERFORMANCE publishes a trial reel shown only to non-followers, graduated by hand in the app or by Instagram when it performs well; not with collaborators, and only on accounts where Instagram offers trial reels), audio (instagram_reel only, Instagram connected through Facebook, platform instagram-facebook: {id} of an Instagram audio track from search-instagram-audio-tool, with optional title, artist, cover_url and preview_url copied from that result so the app can show the track, and audio_volume and video_volume from 0 to 100, default 100). An instagram_feed post with a single video publishes as a Reel. People tags are the media item meta.user_tags, a video cover frame is meta.cover_offset_ms and an instagram_reel may take an uploaded image as its cover in the media item meta.cover with cover_source image (it then wins over the frame).',- 'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post). poll (content_type x_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies, up to '.XPoll::QUESTION_MAX_LENGTH.' characters): {options (list of '.XPoll::MIN_OPTIONS.' to '.XPoll::MAX_OPTIONS.' choices of 1 to '.XPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.XPoll::MIN_DURATION.' to '.XPoll::MAX_DURATION.', how long voting stays open)}, both required to schedule or publish.',+ 'X: is_ai_generated (sent as made_with_ai, discloses AI-generated media on the post). poll (content_type x_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies, up to '.XPoll::QUESTION_MAX_LENGTH.' characters): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.XPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.XPoll::MIN_DURATION.' to '.XPoll::MAX_DURATION.', how long voting stays open)}, both required to schedule or publish.',+ 'Mastodon poll (content_type mastodon_poll only, no media; the post content is the question; a reply of the thread can be a poll too, see thread_replies): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.MastodonPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped), duration_minutes ('.MastodonPoll::MIN_DURATION.' to '.MastodonPoll::MAX_DURATION.', how long voting stays open), multiple (default false: voters may pick several choices), hide_totals (default false: votes stay hidden until the poll ends)}, options and duration_minutes required to schedule or publish.',+ 'Threads poll (content_type threads_poll only, a text post without media; the post content is the question): {options (list of '.Poll::MIN_OPTIONS.' to '.Poll::MAX_OPTIONS.' choices of 1 to '.ThreadsPoll::OPTION_MAX_LENGTH.' characters, no two the same; blank ones are dropped)}, required to schedule or publish; Threads sets how long it stays open.','Threads: topic_tag (1-50 characters after a leading # is dropped, no . or &). Use content_type threads_ghost_post for a text-only post archived after 24 hours (no media, no topic).','Facebook, Bluesky, LinkedIn: link_preview (default true; false publishes a text post with a link without its preview card).','LinkedIn (profile and page): document_title (≤300, the title shown on a PDF document post; defaults to the file name).','Google Business Profile: topic_type STANDARD (default)|EVENT|OFFER; call_to_action {action_type: '.implode('|', array_column(CtaAction::cases(), 'value')).', url} (not on OFFER; url required unless NONE or CALL); event {title ≤'.TopicType::TITLE_MAX_LENGTH.', start_date, end_date (YYYY-MM-DD), start_time, end_time (HH:MM)} (required on EVENT and OFFER, the title being the offer title); offer {coupon_code, redeem_online_url, terms_conditions ≤5000} (OFFER only).','Telegram, Facebook reels and stories: no settings. Stories (Instagram and Facebook) publish no text.',- 'Threads of posts: thread_replies (list of up to '.ThreadReplies::MAX_REPLIES.' replies published under the post as a thread, each {text, media} where media is a list of up to 4 media items ({url}, {id} or {upload_token}, with optional meta.alt_text) for that reply alone; a plain string is a text-only reply) on Bluesky, Mastodon and X; on LinkedIn (profile and page) a post takes one reply, published as a comment from the same profile or page, text only, up to 3000 characters; each reply needs text or media, its media follows the rules of a post on that network, and its text must fit the account limit (Bluesky 300, Mastodon 500 including the content warning, which every reply repeats, X 280 or 25000 for accounts with long posts). On X a reply may instead be a poll: {text, poll} with poll {options, duration_minutes} under the same rules as meta.poll, no media, and the reply text as its question (required, up to '.XPoll::QUESTION_MAX_LENGTH.' characters).',+ 'Threads of posts: thread_replies (list of up to '.ThreadReplies::MAX_REPLIES.' replies published under the post as a thread, each {text, media} where media is a list of up to 4 media items ({url}, {id} or {upload_token}, with optional meta.alt_text) for that reply alone; a plain string is a text-only reply) on Bluesky, Mastodon and X; on LinkedIn (profile and page) a post takes one reply, published as a comment from the same profile or page, text only, up to 3000 characters; each reply needs text or media, its media follows the rules of a post on that network, and its text must fit the account limit (Bluesky 300, Mastodon 500 including the content warning, which every reply repeats, X 280 or 25000 for accounts with long posts). On X and Mastodon a reply may instead be a poll: {text, poll} with poll under the same rules as that network\'s meta.poll, no media, and the reply text as its question (required; on X up to '.XPoll::QUESTION_MAX_LENGTH.' characters).',]);}@@ -275,7 +276,7 @@ class PostPlatformMetaRules* Adds the validation error for meta that becomes mandatory once a post is* published or scheduled (TikTok privacy, Pinterest board, Discord channel).*/- public static function addRequiredOnPublishErrors(Validator $validator, Platform|SocialAccount|null $target, mixed $meta, string $prefix = 'meta', mixed $contentType = null): void+ public static function addRequiredOnPublishErrors(Validator $validator, Platform|SocialAccount|null $target, mixed $meta, string $prefix = 'meta', ?ContentType $contentType = null): void{$violation = self::requiredMetaViolation($target, $meta, $contentType);@@ -314,7 +315,7 @@ class PostPlatformMetaRulesthrow ValidationException::withMessages(["meta.{$field}" => $message]);}- $question = $post->content_type === ContentType::XPoll ? XPoll::questionViolation($post->content) : null;+ $question = transform($post->content_type?->poll(), fn (string $poll): ?string => $poll::questionViolation($post->content));if (filled($question)) {throw ValidationException::withMessages(['content' => $question]);@@ -344,7 +345,7 @@ class PostPlatformMetaRules}if (is_array(data_get($meta, 'poll'))) {- $meta['poll'] = XPoll::normalize($meta['poll']);+ $meta['poll'] = Poll::normalize($meta['poll']);}if (is_array(data_get($meta, 'collaborators'))) {@@ -393,19 +394,22 @@ class PostPlatformMetaRules}/**- * A meta value no post may store, even as a draft: a YouTube title with- * < or >.+ * Every meta value no post may store, even as a draft, keyed by field: a+ * YouTube title with < or >, and on a poll (the post's or a reply's)+ * repeated choices, a choice or a length beyond what the network takes.*- * @return array{0: string, 1: string}|null [field, message]+ * @return array<string, string>*/- public static function formatViolation(?Platform $platform, mixed $meta, ContentType|string|null $contentType = null): ?array+ public static function formatErrors(?Platform $platform, ?array $meta, ?ContentType $contentType = null): array{if ($platform === Platform::YouTube) {- return YouTubeMetadata::violation($meta);+ return transform(YouTubeMetadata::violation($meta), fn (array $violation): array => [$violation[0] => $violation[1]], []);}- return (ContentType::resolve($contentType) === ContentType::XPoll ? XPoll::violation($meta) : null)- ?? ($platform === Platform::X ? ThreadReplies::pollFormatViolation($meta) : null);+ return [+ ...transform($contentType?->poll(), fn (string $poll): array => $poll::formatErrors($meta), []),+ ...ThreadReplies::pollFormatErrors($platform, $meta),+ ];}/**@@ -416,10 +420,9 @@ class PostPlatformMetaRules** @return array{0: string, 1: string}|null [field, message]*/- public static function requiredMetaViolation(Platform|SocialAccount|null $target, mixed $meta, mixed $contentType = null): ?array+ public static function requiredMetaViolation(Platform|SocialAccount|null $target, mixed $meta, ?ContentType $type = null): ?array{$platform = $target instanceof SocialAccount ? $target->platform : $target;- $type = ContentType::resolve($contentType);$threadViolation = ThreadReplies::violation($target, $meta);if ($threadViolation !== null) {@@ -431,10 +434,10 @@ class PostPlatformMetaRules$needsGoogleBusinessEvent = $platform === Platform::GoogleBusiness && $topicType->requiresEvent();return match (true) {- $platform === Platform::YouTube => self::youtubeDescriptionViolation($meta) ?? self::formatViolation($platform, $meta),+ $platform === Platform::YouTube => self::youtubeDescriptionViolation($meta) ?? YouTubeMetadata::violation($meta),$platform === Platform::TikTok => self::tiktokPrivacyViolation($meta),$type === ContentType::InstagramReel => self::instagramReelViolation($platform, $meta),- $type === ContentType::XPoll => XPoll::violation($meta) ?? XPoll::requiredViolation($meta),+ $type?->isPoll() === true => $type->poll()::firstViolation($meta),$platform === Platform::Pinterest && blank(data_get($meta, 'board_id')) => ['board_id', trans('posts.form.pinterest.board_required')],$platform === Platform::Discord && blank(data_get($meta, 'channel_id')) => ['channel_id', trans('posts.form.discord.channel_required')],$needsGoogleBusinessEventdiff --git a/app/Support/Repurpose/DestinationMetaRules.php b/app/Support/Repurpose/DestinationMetaRules.phpindex 7418897ae..1d824d5f7 100644--- a/app/Support/Repurpose/DestinationMetaRules.php+++ b/app/Support/Repurpose/DestinationMetaRules.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Support\Repurpose;+use App\Enums\PostPlatform\ContentType;use App\Enums\Repurpose\Status;use App\Models\Repurpose;use App\Models\SocialAccount;@@ -63,7 +64,7 @@ class DestinationMetaRules$violation = PostPlatformMetaRules::requiredMetaViolation($platforms->get(data_get($destination, 'social_account_id')),data_get($destination, 'meta'),- data_get($destination, 'content_type'),+ ContentType::resolve(data_get($destination, 'content_type')),);if ($violation !== null) {diff --git a/app/Support/Requests/Post/PostRequestRules.php b/app/Support/Requests/Post/PostRequestRules.phpindex 07d9c0d48..564394944 100644--- a/app/Support/Requests/Post/PostRequestRules.php+++ b/app/Support/Requests/Post/PostRequestRules.php@@ -170,7 +170,7 @@ class PostRequestRulesself::addMediaCompatibilityErrors($validator, $post, $input);if (array_key_exists('meta', $input)) {- PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, self::effectiveMeta($post, $input), contentType: data_get($input, 'content_type') ?? $post->content_type);+ PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, self::effectiveMeta($post, $input), contentType: ContentType::resolve(data_get($input, 'content_type')) ?? $post->content_type);}}diff --git a/app/Support/Social/MastodonPoll.php b/app/Support/Social/MastodonPoll.phpnew file mode 100644index 000000000..a1545ba06--- /dev/null+++ b/app/Support/Social/MastodonPoll.php@@ -0,0 +1,136 @@+<?php++declare(strict_types=1);++namespace App\Support\Social;++use App\Enums\Analytics\PollVotingStatus;+use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Models\AnalyticsPublication;+use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;+use Illuminate\Support\Collection;+use Illuminate\Support\Number;++/**+ * The poll a Mastodon status may carry (`meta.poll`, content type+ * `mastodon_poll`), or any reply of its thread: two to four choices of up to+ * 50 characters, open from 5 minutes to 30 days, with a single or multiple+ * choice and totals shown or hidden until it ends. These are the limits of+ * mastodon.social; an instance may set others, which are not read. Its+ * `mixed` helpers read values of Mastodon's JSON as returned.+ *+ * @see https://docs.joinmastodon.org/methods/statuses/#create+ */+final class MastodonPoll extends Poll+{+ public const int OPTION_MAX_LENGTH = 50;++ public const ?int MIN_DURATION = 5;++ public const ?int MAX_DURATION = 43200;++ public const ?int DEFAULT_DURATION = 1440;++ public const bool MULTIPLE_CHOICE = true;++ public const bool HIDE_TOTALS = true;++ public static function platform(): Platform+ {+ return Platform::Mastodon;+ }++ public static function contentType(): ContentType+ {+ return ContentType::MastodonPoll;+ }++ /**+ * The `poll` field of the create-status request (`expires_in` is in seconds).+ *+ * @return array{options: list<string>, expires_in: int, multiple: bool, hide_totals: bool}+ */+ public static function payload(?array $meta): array+ {+ $poll = self::preview($meta);++ return [+ 'options' => data_get($poll, 'options'),+ 'expires_in' => data_get($poll, 'duration_minutes') * CarbonInterface::SECONDS_PER_MINUTE,+ 'multiple' => data_get($poll, 'multiple'),+ 'hide_totals' => data_get($poll, 'hide_totals'),+ ];+ }++ /**+ * A status's `poll` reduced to what is stored. A multiple choice poll+ * keeps how many people voted (`voters`), which its shares are worked out+ * of, as Mastodon does; a poll whose totals Mastodon hides until it ends+ * is marked `totals_hidden`, its votes reading as none.+ *+ * @param array<string, mixed> $poll+ * @return array{options: list<array{label: string, votes: int}>, voting_status: ?string, end_datetime: ?string, duration_minutes: null, multiple: bool, voters: ?int, totals_hidden: bool}+ */+ public static function result(array $poll): array+ {+ $expired = data_get($poll, 'expired');++ return [+ 'options' => Collection::wrap(data_get($poll, 'options'))+ ->map(fn (mixed $option): array => [+ 'label' => (string) data_get($option, 'title', ''),+ 'votes' => (int) data_get($option, 'votes_count', 0),+ ])+ ->values()+ ->all(),+ 'voting_status' => self::votingStatus($expired)?->value,+ 'end_datetime' => data_get($poll, 'expires_at'),+ 'duration_minutes' => null,+ 'multiple' => data_get($poll, 'multiple') === true,+ 'voters' => transform(data_get($poll, 'voters_count'), fn (mixed $voters): int => (int) $voters),+ 'totals_hidden' => collect(data_get($poll, 'options'))->contains(fn (mixed $option): bool => blank(data_get($option, 'votes_count'))),+ ];+ }++ /**+ * Its length is the time from publishing to its end, within Mastodon's range.+ *+ * @return array{options: list<string>, duration_minutes: int, multiple: bool}+ */+ public static function fromPublication(AnalyticsPublication $publication): array+ {+ $poll = data_get($publication->provider_metadata, 'poll');++ return [+ ...parent::fromPublication($publication),+ 'duration_minutes' => self::durationFrom($publication->provider_published_at, data_get($poll, 'end_datetime')),+ 'multiple' => data_get($poll, 'multiple') === true,+ ];+ }++ private static function votingStatus(mixed $expired): ?PollVotingStatus+ {+ if ($expired === true) {+ return PollVotingStatus::Closed;+ }++ if ($expired === false) {+ return PollVotingStatus::Open;+ }++ return null;+ }++ private static function durationFrom(?CarbonInterface $publishedAt, mixed $endsAt): int+ {+ if (blank($publishedAt) || ! is_string($endsAt)) {+ return self::DEFAULT_DURATION;+ }++ $minutes = (int) round($publishedAt->diffInMinutes(CarbonImmutable::parse($endsAt)));++ return (int) Number::clamp($minutes, self::MIN_DURATION, self::MAX_DURATION);+ }+}diff --git a/app/Support/Social/Poll.php b/app/Support/Social/Poll.phpnew file mode 100644index 000000000..405a0f8fe--- /dev/null+++ b/app/Support/Social/Poll.php@@ -0,0 +1,468 @@+<?php++declare(strict_types=1);++namespace App\Support\Social;++use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Models\AnalyticsPublication;+use App\Services\Social\ContentSanitizer;+use Carbon\CarbonInterface;+use Illuminate\Support\Arr;+use Illuminate\Support\Collection;+use Illuminate\Support\Str;++/**+ * The poll a post may carry (`meta.poll`, on a poll content type) or a thread+ * reply may carry (`{text, media, poll}`): two to four short choices, and on+ * the networks that let the author pick them, how long voting stays open,+ * whether a voter may pick several choices and whether the totals stay hidden+ * until it ends. Each network's rules live in its subclass (`XPoll`,+ * `MastodonPoll`, `ThreadsPoll`), which `for()` and `ContentType::poll()` pick;+ * the post text is always the question. Blank choices are dropped when the+ * meta is normalized, so the rules below read the cleaned list.+ *+ * A `mixed` parameter here is a value as it came in, whose shape its source+ * does not guarantee: a choice or a switch as sent, before validation, or a+ * poll as the network's JSON returned it. Everything else takes one type.+ */+abstract class Poll+{+ public const int MIN_OPTIONS = 2;++ public const int MAX_OPTIONS = 4;++ /** The longest choice the network takes, counted by `choiceLength()`. */+ public const int OPTION_MAX_LENGTH = 25;++ /** The shortest and longest a poll runs, in minutes; null on a network that sets it itself. */+ public const ?int MIN_DURATION = null;++ public const ?int MAX_DURATION = null;++ public const ?int DEFAULT_DURATION = null;++ /** A cap on the question below the account's text limit, or null for none. */+ public const ?int QUESTION_MAX_LENGTH = null;++ /** Whether the author may let a voter pick several choices (`poll.multiple`). */+ public const bool MULTIPLE_CHOICE = false;++ /** Whether the author may hide the totals until voting ends (`poll.hide_totals`). */+ public const bool HIDE_TOTALS = false;++ /** The network the poll publishes on. */+ abstract public static function platform(): Platform;++ /** The content type of a post that is this network's poll. */+ abstract public static function contentType(): ContentType;++ /**+ * The poll as the network's create request takes it.+ *+ * @return array<string, mixed>+ */+ abstract public static function payload(?array $meta): array;++ /**+ * One poll as the network returns it, reduced to what is stored as its+ * result (`provider_metadata.poll`).+ *+ * @param array<string, mixed> $poll+ * @return array<string, mixed>+ */+ abstract public static function result(array $poll): array;++ /**+ * The poll meta of a poll found on the network, read from its stored+ * result: its choices, and its length (else the default) where the+ * author picks one.+ *+ * @return array<string, mixed>+ */+ public static function fromPublication(AnalyticsPublication $publication): array+ {+ $poll = data_get($publication->provider_metadata, 'poll');+ $meta = ['options' => Collection::wrap(data_get($poll, 'options'))->pluck('label')->all()];++ if (static::hasDuration()) {+ $meta['duration_minutes'] = self::minutes(data_get($poll, 'duration_minutes'), static::DEFAULT_DURATION);+ }++ return $meta;+ }++ /**+ * A poll the network returned, reduced to its stored result; null when the+ * post carries no poll.+ *+ * @return array<string, mixed>|null+ */+ public static function resultOf(mixed $poll): ?array+ {+ if (! is_array($poll)) {+ return null;+ }++ return static::result($poll);+ }++ /**+ * A poll the network returned, as `provider_metadata` keeps it; nothing+ * when the post carries no poll.+ *+ * @return array{poll?: array<string, mixed>}+ */+ public static function metadataFrom(mixed $poll): array+ {+ $result = static::resultOf($poll);++ if (blank($result)) {+ return [];+ }++ return ['poll' => $result];+ }++ /**+ * The poll rules of a network, or null when it has no polls.+ *+ * @return class-string<self>|null+ */+ public static function for(?Platform $platform): ?string+ {+ return match ($platform) {+ Platform::X => XPoll::class,+ Platform::Mastodon => MastodonPoll::class,+ Platform::Threads => ThreadsPoll::class,+ Platform::LinkedIn, Platform::LinkedInPage, Platform::TikTok, Platform::YouTube,+ Platform::Facebook, Platform::Instagram, Platform::InstagramFacebook, Platform::Pinterest,+ Platform::Bluesky, Platform::Telegram, Platform::Discord, Platform::GoogleBusiness, null => null,+ };+ }++ /**+ * The limits the composer reads from `Platform::publishConfig()`, so they are never copied into TypeScript.+ *+ * @return array{minOptions: int, maxOptions: int, optionMaxLength: int, minDuration: ?int, maxDuration: ?int, defaultDuration: ?int, questionMaxLength: ?int, multipleChoice: bool, hideTotals: bool}+ */+ public static function limits(): array+ {+ return [+ 'minOptions' => static::MIN_OPTIONS,+ 'maxOptions' => static::MAX_OPTIONS,+ 'optionMaxLength' => static::OPTION_MAX_LENGTH,+ 'minDuration' => static::MIN_DURATION,+ 'maxDuration' => static::MAX_DURATION,+ 'defaultDuration' => static::DEFAULT_DURATION,+ 'questionMaxLength' => static::QUESTION_MAX_LENGTH,+ 'multipleChoice' => static::MULTIPLE_CHOICE,+ 'hideTotals' => static::HIDE_TOTALS,+ ];+ }++ /** Whether the author picks how long voting stays open. */+ protected static function hasDuration(): bool+ {+ return filled(static::MAX_DURATION);+ }++ /**+ * The poll's choices, trimmed, without blanks.+ *+ * @return list<string>+ */+ protected static function options(?array $meta): array+ {+ return self::choices(data_get($meta, 'poll.options'));+ }++ /**+ * A list of choices, trimmed, without blanks.+ *+ * @return list<string>+ */+ protected static function choices(mixed $options): array+ {+ return Collection::wrap($options)+ ->filter(fn (mixed $option): bool => is_string($option))+ ->map(fn (string $option): string => Str::trim($option))+ ->filter(fn (string $option): bool => filled($option))+ ->values()+ ->all();+ }++ /**+ * A poll in the shape every network's poll has, before the network is+ * known. Each choice keeps its position, blank ones included, so an error+ * on a choice is reported on the field that was sent; `forNetwork()` drops+ * the blanks and keeps what the network takes when the poll is stored.+ *+ * @param array<string, mixed> $poll+ * @return array{options: list<string>, duration_minutes?: int, multiple?: bool, hide_totals?: bool}+ */+ public static function normalize(array $poll): array+ {+ return Arr::whereNotNull([+ 'options' => Collection::wrap(data_get($poll, 'options'))->map(self::submittedChoice(...))->values()->all(),+ 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes')),+ 'multiple' => self::flag(data_get($poll, 'multiple')),+ 'hide_totals' => self::flag(data_get($poll, 'hide_totals')),+ ]);+ }++ /**+ * A poll with only what this network takes: its length where the author+ * picks one, and the multiple choice and hidden totals switches where the+ * network has them.+ *+ * @param array<string, mixed> $poll+ * @return array<string, mixed>+ */+ public static function forNetwork(array $poll): array+ {+ $normalized = [...self::normalize($poll), 'options' => self::choices(data_get($poll, 'options'))];++ if (! static::hasDuration()) {+ unset($normalized['duration_minutes']);+ }++ if (! static::MULTIPLE_CHOICE) {+ unset($normalized['multiple']);+ }++ if (! static::HIDE_TOTALS) {+ unset($normalized['hide_totals']);+ }++ return $normalized;+ }++ /**+ * The poll as the API and MCP preview show it: its choices, and its+ * length and switches on the networks that have them, with the defaults+ * the network publishes with.+ *+ * @return array{options: list<string>, duration_minutes?: int, multiple?: bool, hide_totals?: bool}+ */+ public static function preview(?array $meta): array+ {+ $preview = ['options' => self::options($meta)];++ if (static::hasDuration()) {+ $preview['duration_minutes'] = self::minutes(data_get($meta, 'poll.duration_minutes'), static::DEFAULT_DURATION);+ }++ if (static::MULTIPLE_CHOICE) {+ $preview['multiple'] = data_get($meta, 'poll.multiple') === true;+ }++ if (static::HIDE_TOTALS) {+ $preview['hide_totals'] = data_get($meta, 'poll.hide_totals') === true;+ }++ return $preview;+ }++ /**+ * A choice's length without the spaces around it, in UTF-16 units, so an+ * emoji outside the basic plane (🐧) counts two. X counts that way (it+ * refused a 25-character choice holding one); counting the same on every+ * network keeps each choice within the strictest reading.+ */+ protected static function choiceLength(string $choice): int+ {+ return intdiv(strlen(mb_convert_encoding(Str::trim($choice), 'UTF-16LE', 'UTF-8')), 2);+ }++ /**+ * Repeated choices, refused at every save.+ */+ protected static function duplicatesViolation(?array $meta): ?string+ {+ $duplicates = collect(self::options($meta))->map(fn (string $option): string => Str::lower($option))->duplicatesStrict();++ return when($duplicates->isNotEmpty(), fn (): string => trans('posts.form.poll.options_distinct'));+ }++ /**+ * Too many choices once blanks are dropped, refused at every save. Every+ * network takes four at most.+ */+ public static function optionsCountViolation(mixed $options): ?string+ {+ return when(+ count(self::choices($options)) > self::MAX_OPTIONS,+ fn (): string => trans('posts.form.poll.options_max', ['max' => self::MAX_OPTIONS]),+ );+ }++ /**+ * A choice longer than the network allows once trimmed, refused at every save.+ */+ protected static function choiceLengthViolation(mixed $choice): ?string+ {+ $tooLong = is_string($choice) && self::choiceLength($choice) > static::OPTION_MAX_LENGTH;++ return when($tooLong, fn (): string => trans('posts.form.poll.choice_max', ['max' => static::OPTION_MAX_LENGTH]));+ }++ /**+ * A length outside the network's range, refused at every save. A network+ * that sets the length itself ignores it (`forNetwork()` drops it).+ */+ protected static function durationViolation(?array $meta): ?string+ {+ $minutes = data_get($meta, 'poll.duration_minutes');++ if (! static::hasDuration() || ! is_numeric($minutes)) {+ return null;+ }++ $minutes = (int) $minutes;+ $outOfRange = $minutes < static::MIN_DURATION || $minutes > static::MAX_DURATION;++ return when($outOfRange, fn (): string => static::durationRangeMessage());+ }++ /**+ * What no poll of this network may store, even as a draft, keyed by its+ * field under `$prefix` (`thread_replies.0.` for a reply): repeated+ * choices, a choice too long and a length out of range.+ *+ * @return array<string, string>+ */+ public static function formatErrors(?array $meta, string $prefix = ''): array+ {+ $errors = [];+ $duplicates = self::duplicatesViolation($meta);++ if (filled($duplicates)) {+ $errors["{$prefix}poll.options"] = $duplicates;+ }++ foreach (Collection::wrap(data_get($meta, 'poll.options')) as $index => $choice) {+ $tooLong = static::choiceLengthViolation($choice);++ if (filled($tooLong)) {+ $errors["{$prefix}poll.options.{$index}"] = $tooLong;+ }+ }++ $duration = static::durationViolation($meta);++ if (filled($duration)) {+ $errors["{$prefix}poll.duration_minutes"] = $duration;+ }++ return $errors;+ }++ /**+ * "Add at least 2 choices", with the minimum every network shares.+ */+ public static function optionsRequiredMessage(): string+ {+ return trans('posts.form.poll.options_required', ['min' => self::MIN_OPTIONS]);+ }++ /**+ * "From 5 minutes to 7 days", with the range of this network.+ */+ public static function durationRangeMessage(): string+ {+ $maxDays = intdiv((int) static::MAX_DURATION, CarbonInterface::MINUTES_PER_HOUR * CarbonInterface::HOURS_PER_DAY);++ return trans('posts.form.poll.duration_range', ['min' => static::MIN_DURATION, 'max' => $maxDays]);+ }++ /**+ * What a poll needs before its post is scheduled or published.+ *+ * @return array{0: string, 1: string}|null [field, message]+ */+ protected static function requiredViolation(?array $meta): ?array+ {+ if (count(self::options($meta)) < self::MIN_OPTIONS) {+ return ['poll.options', self::optionsRequiredMessage()];+ }++ if (static::hasDuration() && blank(data_get($meta, 'poll.duration_minutes'))) {+ return ['poll.duration_minutes', trans('posts.form.poll.duration_required')];+ }++ return null;+ }++ /**+ * Why the poll cannot go yet: the first thing no save may store, else+ * what scheduling needs.+ *+ * @return array{0: string, 1: string}|null [field, message]+ */+ public static function firstViolation(?array $meta): ?array+ {+ $errors = collect(static::formatErrors($meta));++ if ($errors->isNotEmpty()) {+ return [$errors->keys()->first(), $errors->first()];+ }++ return static::requiredViolation($meta);+ }++ /**+ * A poll's question is the post text: it cannot be scheduled or published+ * without one. It is measured as the network receives it, so editor markup+ * with no words (`<p></p>`) counts as no question.+ */+ public static function questionViolation(?string $content): ?string+ {+ $question = app(ContentSanitizer::class)->displayText((string) $content, static::platform());++ return when(blank($question), fn (): string => trans('posts.form.poll.question_required'));+ }++ /**+ * Why the network would refuse the poll at publish: no question, media on+ * it, or choices and a length that break its rules. Null when it can go.+ * `$meta` holds the poll under `poll`: the post's meta, or a reply itself.+ */+ public static function publishViolation(?string $question, bool $hasMedia, ?array $meta): ?string+ {+ $questionViolation = static::questionViolation($question);++ if (filled($questionViolation)) {+ return $questionViolation;+ }++ if ($hasMedia) {+ return trans('posts.errors.media_not_accepted');+ }++ return data_get(static::firstViolation($meta), 1);+ }++ protected static function minutes(mixed $value, ?int $default = null): ?int+ {+ return transform($value, fn (mixed $minutes): int => (int) $minutes, $default);+ }++ /**+ * A choice as sent, trimmed; anything that is not text counts as blank.+ */+ private static function submittedChoice(mixed $option): string+ {+ if (! is_string($option)) {+ return '';+ }++ return Str::trim($option);+ }++ private static function flag(mixed $value): ?bool+ {+ return transform($value, fn (mixed $flag): bool => filter_var($flag, FILTER_VALIDATE_BOOLEAN));+ }+}diff --git a/app/Support/Social/ThreadsPoll.php b/app/Support/Social/ThreadsPoll.phpnew file mode 100644index 000000000..814b08174--- /dev/null+++ b/app/Support/Social/ThreadsPoll.php@@ -0,0 +1,92 @@+<?php++declare(strict_types=1);++namespace App\Support\Social;++use App\Enums\Analytics\PollVotingStatus;+use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use Carbon\CarbonImmutable;++/**+ * The poll a Threads text post may carry (`meta.poll`, content type+ * `threads_poll`): two to four choices of up to 25 characters. Threads sets+ * how long it stays open, so there is no length to pick, and it is sent as+ * `poll_attachment` (`option_a` to `option_d`) on a text post only.+ *+ * @see https://developers.facebook.com/documentation/threads/create-posts/polls+ */+final class ThreadsPoll extends Poll+{+ public const int OPTION_MAX_LENGTH = 25;++ /** The keys Threads names the choices by, in order. */+ private const array OPTION_KEYS = ['option_a', 'option_b', 'option_c', 'option_d'];++ /**+ * The `poll_attachment` fields a post read asks Threads for.+ */+ public const string LOOKUP_FIELDS = 'poll_attachment{option_a,option_b,option_c,option_d,option_a_votes_percentage,option_b_votes_percentage,option_c_votes_percentage,option_d_votes_percentage,total_votes,expiration_timestamp}';++ public static function platform(): Platform+ {+ return Platform::Threads;+ }++ public static function contentType(): ContentType+ {+ return ContentType::ThreadsPoll;+ }++ /**+ * The `poll_attachment` field of the text post container.+ *+ * @return array<string, string>+ */+ public static function payload(?array $meta): array+ {+ return collect(self::options($meta))+ ->take(self::MAX_OPTIONS)+ ->mapWithKeys(fn (string $option, int $index): array => [self::OPTION_KEYS[$index] => $option])+ ->all();+ }++ /**+ * A post's `poll_attachment` reduced to what is stored. Threads gives each+ * choice its share of `total_votes` as a decimal (`0.10` for 10%), so the+ * votes are worked out from it; a poll is closed once its+ * `expiration_timestamp` has passed.+ *+ * @param array<string, mixed> $poll+ * @return array{options: list<array{label: string, votes: int}>, voting_status: ?string, end_datetime: ?string, duration_minutes: null}+ */+ public static function result(array $poll): array+ {+ $total = (int) data_get($poll, 'total_votes', 0);+ $choices = collect(self::OPTION_KEYS)->filter(fn (string $key): bool => filled(data_get($poll, $key)));+ $endsAt = transform(data_get($poll, 'expiration_timestamp'), fn (mixed $at): CarbonImmutable => CarbonImmutable::parse((string) $at)->utc());++ return [+ 'options' => $choices+ ->map(fn (string $key): array => [+ 'label' => (string) data_get($poll, $key),+ 'votes' => (int) round((float) data_get($poll, "{$key}_votes_percentage", 0) * $total),+ ])+ ->values()+ ->all(),+ 'voting_status' => transform($endsAt, fn (CarbonImmutable $at): string => self::votingStatus($at)->value),+ 'end_datetime' => $endsAt?->toIso8601ZuluString(),+ 'duration_minutes' => null,+ ];+ }++ private static function votingStatus(CarbonImmutable $endsAt): PollVotingStatus+ {+ if ($endsAt->isPast()) {+ return PollVotingStatus::Closed;+ }++ return PollVotingStatus::Open;+ }+}diff --git a/app/Support/Social/XPoll.php b/app/Support/Social/XPoll.phpindex d142653c5..acc88263a 100644--- a/app/Support/Social/XPoll.php+++ b/app/Support/Social/XPoll.php@@ -4,188 +4,42 @@ declare(strict_types=1);namespace App\Support\Social;+use App\Enums\Analytics\PollVotingStatus;+use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;-use App\Enums\X\PollVotingStatus;-use App\Models\AnalyticsPublication;-use App\Services\Social\ContentSanitizer;-use Carbon\CarbonInterface;-use Illuminate\Support\Arr;use Illuminate\Support\Collection;-use Illuminate\Support\Str;/**- * The poll an X post may carry (`meta.poll`, content type `x_poll`): two to- * four short choices and how long voting stays open. Blank choices are dropped- * when the meta is normalized, so the rules below read the cleaned list.+ * The poll an X post may carry (`meta.poll`, content type `x_poll`), or any+ * reply of its thread: two to four choices of up to 25 characters and how+ * long voting stays open, with the question capped at 280 characters even on+ * an account with long posts.*/-final class XPoll+final class XPoll extends Poll{- public const int MIN_OPTIONS = 2;-- public const int MAX_OPTIONS = 4;-public const int OPTION_MAX_LENGTH = 25;- public const int MIN_DURATION = 5;+ public const ?int MIN_DURATION = 5;- public const int MAX_DURATION = 10080;+ public const ?int MAX_DURATION = 10080;- public const int DEFAULT_DURATION = 1440;+ public const ?int DEFAULT_DURATION = 1440;- public const int QUESTION_MAX_LENGTH = 280;+ public const ?int QUESTION_MAX_LENGTH = 280;/*** The `poll.fields` every tweet lookup asks X for.*/public const string LOOKUP_FIELDS = 'options,duration_minutes,end_datetime,voting_status';- /**- * The limits the composer reads from `Platform::publishConfig()`, so they are never copied into TypeScript.- *- * @return array{minOptions: int, maxOptions: int, optionMaxLength: int, minDuration: int, maxDuration: int, defaultDuration: int, questionMaxLength: int}- */- public static function limits(): array- {- return [- 'minOptions' => self::MIN_OPTIONS,- 'maxOptions' => self::MAX_OPTIONS,- 'optionMaxLength' => self::OPTION_MAX_LENGTH,- 'minDuration' => self::MIN_DURATION,- 'maxDuration' => self::MAX_DURATION,- 'defaultDuration' => self::DEFAULT_DURATION,- 'questionMaxLength' => self::QUESTION_MAX_LENGTH,- ];- }-- /**- * The poll's choices, trimmed, without blanks.- *- * @return list<string>- */- public static function options(mixed $meta): array- {- return self::choices(data_get($meta, 'poll.options'));- }-- /**- * A list of choices, trimmed, without blanks.- *- * @return list<string>- */- public static function choices(mixed $options): array- {- return Collection::wrap($options)- ->filter(fn (mixed $option): bool => is_string($option))- ->map(fn (string $option): string => Str::trim($option))- ->filter(fn (string $option): bool => filled($option))- ->values()- ->all();- }-- /**- * @param array<string, mixed> $poll- * @return array{options: list<string>, duration_minutes?: int}- */- public static function normalize(array $poll): array- {- return Arr::whereNotNull([- 'options' => self::choices(data_get($poll, 'options')),- 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes')),- ]);- }-- /**- * @return array{0: string, 1: string}|null [field, message]- */- public static function violation(mixed $meta): ?array- {- $duplicates = collect(self::options($meta))->map(fn (string $option): string => Str::lower($option))->duplicatesStrict();-- if ($duplicates->isNotEmpty()) {- return ['poll.options', trans('posts.form.x.poll.options_distinct')];- }-- return null;- }-- /**- * Too many choices once blanks are dropped, refused at every save.- */- public static function optionsCountViolation(mixed $options): ?string- {- return when(- count(self::choices($options)) > self::MAX_OPTIONS,- fn (): string => trans('posts.form.x.poll.options_max', ['max' => self::MAX_OPTIONS]),- );- }-- /**- * A choice's length as X counts it, without the spaces around it: in- * UTF-16 units, so an emoji outside the basic plane (🐧) counts two. X- * refused a 25-character choice holding one with "is not 1 to 25- * characters long".- */- public static function choiceLength(string $choice): int- {- return intdiv(strlen(mb_convert_encoding(Str::trim($choice), 'UTF-16LE', 'UTF-8')), 2);- }-- /**- * A choice longer than X allows once trimmed, refused at every save.- */- public static function choiceLengthViolation(mixed $choice): ?string- {- $tooLong = is_string($choice) && self::choiceLength($choice) > self::OPTION_MAX_LENGTH;-- return when($tooLong, fn (): string => trans('posts.form.x.poll.choice_max', ['max' => self::OPTION_MAX_LENGTH]));- }-- /**- * "Add at least 2 choices", with the minimum from X's rules.- */- public static function optionsRequiredMessage(): string- {- return trans('posts.form.x.poll.options_required', ['min' => self::MIN_OPTIONS]);- }-- /**- * "From 5 minutes to 7 days", with the range from X's rules.- */- public static function durationRangeMessage(): string+ public static function platform(): Platform{- $maxDays = intdiv(self::MAX_DURATION, CarbonInterface::MINUTES_PER_HOUR * CarbonInterface::HOURS_PER_DAY);-- return trans('posts.form.x.poll.duration_range', ['min' => self::MIN_DURATION, 'max' => $maxDays]);+ return Platform::X;}- /**- * What a poll needs before its post is scheduled or published.- *- * @return array{0: string, 1: string}|null [field, message]- */- public static function requiredViolation(mixed $meta): ?array+ public static function contentType(): ContentType{- if (count(self::options($meta)) < self::MIN_OPTIONS) {- return ['poll.options', self::optionsRequiredMessage()];- }-- if (blank(data_get($meta, 'poll.duration_minutes'))) {- return ['poll.duration_minutes', trans('posts.form.x.poll.duration_required')];- }-- return null;- }-- /**- * A poll's question is the post text: it cannot be scheduled or published- * without one. It is measured as X receives it, so editor markup with no- * words (`<p></p>`) counts as no question.- */- public static function questionViolation(?string $content): ?string- {- $question = app(ContentSanitizer::class)->displayText((string) $content, Platform::X);-- return when(blank($question), fn (): string => trans('posts.form.x.poll.question_required'));+ return ContentType::XPoll;}/**@@ -212,35 +66,13 @@ final class XPoll}/**- * The poll meta of an X poll found on the network, read from what discovery stored.+ * The `poll` field of the create-post request: the poll as it is+ * previewed, its choices and its length.** @return array{options: list<string>, duration_minutes: int}*/- public static function fromPublication(AnalyticsPublication $publication): array- {- $poll = data_get($publication->provider_metadata, 'poll');-- return [- 'options' => Collection::wrap(data_get($poll, 'options'))->pluck('label')->all(),- 'duration_minutes' => self::minutes(data_get($poll, 'duration_minutes'), self::DEFAULT_DURATION),- ];- }-- /**- * The `poll` field of the create-post request.- *- * @return array{options: list<string>, duration_minutes: int}- */- public static function payload(mixed $meta): array- {- return [- 'options' => self::options($meta),- 'duration_minutes' => self::minutes(data_get($meta, 'poll.duration_minutes'), self::DEFAULT_DURATION),- ];- }-- private static function minutes(mixed $value, ?int $default = null): ?int+ public static function payload(?array $meta): array{- return transform($value, fn (mixed $minutes): int => (int) $minutes, $default);+ return self::preview($meta);}}diff --git a/app/Support/ThreadReplies.php b/app/Support/ThreadReplies.phpindex 99231a4f1..b65c13be8 100644--- a/app/Support/ThreadReplies.php+++ b/app/Support/ThreadReplies.php@@ -12,7 +12,7 @@ use App\Models\SocialAccount;use App\Models\Workspace;use App\Rules\ContentTypeCompatibleWithMedia;use App\Services\Social\ContentSanitizer;-use App\Support\Social\XPoll;+use App\Support\Social\Poll;use Illuminate\Support\Arr;use Illuminate\Support\Collection;use Illuminate\Support\Str;@@ -22,9 +22,9 @@ use Illuminate\Support\Str;* networks that let an app reply to its own post with the scopes we hold.* Each reply is `{text, media}`; its media belongs to that reply and follows* the rules of the network's reply content type. A reply stored as a bare- * string is a text-only reply. On X a reply may carry a poll instead of media- * (`{text, media, poll}`), following `XPoll`'s rules with the reply text as- * its question.+ * string is a text-only reply. On X and Mastodon a reply may carry a poll+ * instead of media (`{text, media, poll}`), following that network's `Poll`+ * rules with the reply text as its question.*/class ThreadReplies{@@ -88,14 +88,29 @@ class ThreadReplies];if (is_array($poll) && filled($poll)) {- $normalized['poll'] = XPoll::normalize($poll);+ $normalized['poll'] = Poll::normalize($poll);}return $normalized;}/**- * Whether a reply is a poll (an X reply only; `of()` drops an empty one).+ * The poll rules a reply of this network follows, or null when its+ * replies cannot be polls (a network without polls, or without threads).+ *+ * @return class-string<Poll>|null+ */+ public static function replyPoll(?Platform $platform): ?string+ {+ if (! self::supports($platform)) {+ return null;+ }++ return Poll::for($platform);+ }++ /**+ * Whether a reply is a poll (`of()` drops an empty one).** @param array<string, mixed> $reply*/@@ -105,49 +120,67 @@ class ThreadReplies}/**- * Replies without their polls, for a network other than X.+ * The replies as the network keeps them: each poll with only what that+ * network's polls take, or no polls on a network whose replies cannot be+ * polls.** @param array<string, mixed> $meta* @return array<string, mixed>*/- public static function withoutPolls(array $meta): array+ public static function forNetwork(?Platform $platform, array $meta): array{if (blank(data_get($meta, 'thread_replies'))) {return $meta;}- $meta['thread_replies'] = collect(self::of($meta))->map(fn (array $reply): array => Arr::except($reply, 'poll'))->all();+ $poll = self::replyPoll($platform);++ $meta['thread_replies'] = collect(self::of($meta))+ ->map(function (array $reply) use ($poll): array {+ if (! self::hasPoll($reply)) {+ return $reply;+ }++ if (blank($poll)) {+ return Arr::except($reply, 'poll');+ }++ return [...$reply, 'poll' => $poll::forNetwork(data_get($reply, 'poll'))];+ })+ ->all();return $meta;}/**- * A reply poll no post may store, even as a draft: repeated choices.+ * What no reply poll may store, even as a draft (repeated choices, a+ * choice or a length beyond what the network takes), keyed by field.*- * @return array{0: string, 1: string}|null [field, message]+ * @return array<string, string>*/- public static function pollFormatViolation(mixed $meta): ?array+ public static function pollFormatErrors(?Platform $platform, ?array $meta): array{- foreach (self::of($meta) as $index => $reply) {- $violation = self::hasPoll($reply) ? XPoll::violation($reply) : null;+ $poll = self::replyPoll($platform);- if (filled($violation)) {- return ["thread_replies.{$index}.{$violation[0]}", $violation[1]];- }+ if (blank($poll)) {+ return [];}- return null;+ return collect(self::of($meta))+ ->filter(self::hasPoll(...))+ ->flatMap(fn (array $reply, int $index): array => $poll::formatErrors($reply, "thread_replies.{$index}."))+ ->all();}/**- * A reply poll carries no media, drafts included. Only X has reply polls;- * any other network drops them on save.+ * A reply poll carries no media, drafts included. A network whose replies+ * cannot be polls drops them on save.** @return array<string, string>*/- public static function pollMediaErrors(?Platform $platform, mixed $meta): array+ public static function pollMediaErrors(?Platform $platform, ?array $meta): array{- if ($platform !== Platform::X) {+ if (blank(self::replyPoll($platform))) {return [];}@@ -230,8 +263,10 @@ class ThreadReplies*/private static function replyViolation(array $reply, Platform $platform, ?SocialAccount $account, int $reserved): ?array{- if ($platform === Platform::X && self::hasPoll($reply)) {- return self::pollReplyViolation($reply, $account, $reserved);+ $poll = self::replyPoll($platform);++ if (filled($poll) && self::hasPoll($reply)) {+ return self::pollReplyViolation($poll, $reply, $account, $reserved);}if (filled(Str::trim($reply['text']))) {@@ -251,22 +286,22 @@ class ThreadReplies/*** A reply poll needs its question (the reply's text) within the poll's cap,- * and choices and a length X accepts.+ * and choices and a length the network accepts.*+ * @param class-string<Poll> $poll* @param array{text: string, media: list<array<string, mixed>>, poll?: array<string, mixed>} $reply* @return array{0: string|null, 1: string}|null*/- private static function pollReplyViolation(array $reply, ?SocialAccount $account, int $reserved): ?array+ private static function pollReplyViolation(string $poll, array $reply, ?SocialAccount $account, int $reserved): ?array{- $questionViolation = XPoll::questionViolation($reply['text']);+ $questionViolation = $poll::questionViolation($reply['text']);if (filled($questionViolation)) {return [null, $questionViolation];}- return self::lengthViolation($reply['text'], Platform::X, $account, ContentType::XPoll, $reserved)- ?? XPoll::violation($reply)- ?? XPoll::requiredViolation($reply);+ return self::lengthViolation($reply['text'], $poll::platform(), $account, $poll::contentType(), $reserved)+ ?? $poll::firstViolation($reply);}/**@@ -294,7 +329,8 @@ class ThreadReplies/*** Each reply's media against the reply content type, keyed- * `thread_replies.{n}.media`.+ * `thread_replies.{n}.media`. A reply poll takes no media at all, which+ * `pollMediaErrors()` reports, so it is left out here.** @return array<string, string>*/@@ -307,9 +343,14 @@ class ThreadReplies}$errors = [];+ $pollsTakeReplies = filled(self::replyPoll($platform));foreach (self::of($meta) as $index => $reply) {$key = "thread_replies.{$index}.media";++ if ($pollsTakeReplies && self::hasPoll($reply)) {+ continue;+ }$count = count($reply['media']);if ($count > $contentType->maxMediaCount()) {diff --git a/lang/ar/posts.php b/lang/ar/posts.phpindex 1fbfd0fac..5a9e674aa 100644--- a/lang/ar/posts.php+++ b/lang/ar/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'يجب أن يتكون الموضوع من 1 إلى 50 حرفًا، بدون . أو &.','ghost_post_attachments' => 'لا تدعم المنشورات الشبحية المرفقات',],- 'x' => [- 'poll' => [- 'options_required' => 'أضف خيارين على الأقل إلى استطلاعك.',- 'options_distinct' => 'يجب أن يكون كل خيار في الاستطلاع مختلفًا. غيّر الخيار المكرر.',- 'duration_required' => 'اختر المدة التي يبقى فيها استطلاعك مفتوحًا.',- 'question_required' => 'اكتب سؤال الاستطلاع في نص المنشور.',- 'options_max' => 'يمكن أن يحتوي الاستطلاع على :max خيارات كحد أقصى. احذف الخيارات الزائدة.',- 'poll_object' => 'أرسل الاستطلاع مع خياراته (options) ومدته (duration_minutes).',- 'options_list' => 'أرسل خيارات الاستطلاع كقائمة من النصوص.',- 'choice_text' => 'يجب أن يكون كل خيار في الاستطلاع نصًا.',- 'choice_max' => 'يمكن أن يحتوي كل خيار في الاستطلاع على :max حرفًا كحد أقصى. اختصر الخيار الأطول.',- 'duration_range' => 'يمكن أن يبقى الاستطلاع مفتوحًا من :min دقائق إلى :max أيام. اختر مدة ضمن هذا النطاق.',- 'choices' => 'الخيارات',- 'choice' => 'الخيار :number',- 'choice_optional' => 'الخيار :number (اختياري)',- 'add_choice' => 'إضافة خيار',- 'remove_choice' => 'إزالة الخيار :number',- 'length' => 'المدة',- 'days' => 'الأيام',- 'hours' => 'الساعات',- 'minutes' => 'الدقائق',- 'remove' => 'إزالة الاستطلاع',- 'attachments' => 'الاستطلاعات لا تدعم الوسائط',- 'add' => 'إضافة استطلاع',- ],+ 'poll' => [+ 'options_required' => 'أضف خيارين على الأقل إلى استطلاعك.',+ 'options_distinct' => 'يجب أن يكون كل خيار في الاستطلاع مختلفًا. غيّر الخيار المكرر.',+ 'duration_required' => 'اختر المدة التي يبقى فيها استطلاعك مفتوحًا.',+ 'question_required' => 'اكتب سؤال الاستطلاع في نص المنشور.',+ 'options_max' => 'يمكن أن يحتوي الاستطلاع على :max خيارات كحد أقصى. احذف الخيارات الزائدة.',+ 'poll_object' => 'أرسل الاستطلاع مع خياراته (options)، ومع مدته (duration_minutes) على X وMastodon.',+ 'options_list' => 'أرسل خيارات الاستطلاع كقائمة من النصوص.',+ 'choice_text' => 'يجب أن يكون كل خيار في الاستطلاع نصًا.',+ 'choice_max' => 'يمكن أن يحتوي كل خيار في الاستطلاع على :max حرفًا كحد أقصى. اختصر الخيار الأطول.',+ 'duration_range' => 'يمكن أن يبقى الاستطلاع مفتوحًا من :min دقائق إلى :max أيام. اختر مدة ضمن هذا النطاق.',+ 'choices' => 'الخيارات',+ 'choice' => 'الخيار :number',+ 'choice_optional' => 'الخيار :number (اختياري)',+ 'add_choice' => 'إضافة خيار',+ 'remove_choice' => 'إزالة الخيار :number',+ 'length' => 'المدة',+ 'days' => 'الأيام',+ 'hours' => 'الساعات',+ 'minutes' => 'الدقائق',+ 'remove' => 'إزالة الاستطلاع',+ 'attachments' => 'الاستطلاعات لا تدعم الوسائط',+ 'add' => 'إضافة استطلاع',+ 'duration_whole' => 'أرسل مدة الاستطلاع بعدد صحيح من الدقائق.',+ 'multiple' => 'السماح باختيارات متعددة',+ 'hide_totals' => 'إخفاء الأصوات حتى النهاية',],'linkedin' => ['document_title' => 'عنوان المستند',@@ -858,6 +859,14 @@ return ['label' => 'استطلاع','description' => 'سؤال بـ :min إلى :max خيارات',],+ 'mastodon_poll' => [+ 'label' => 'استطلاع',+ 'description' => 'سؤال بـ :min إلى :max خيارات',+ ],+ 'threads_poll' => [+ 'label' => 'استطلاع',+ 'description' => 'سؤال بـ :min إلى :max خيارات',+ ],'threads_post' => ['label' => 'سلسلة','description' => 'منشور نصي مع وسائط اختيارية',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count صوت|[0,*] :count أصوات',+ 'voters' => '{1} شخص واحد|[0,*] :count أشخاص','final' => 'النتائج النهائية','ended' => 'انتهى التصويت','ends' => 'تنتهي :time','thread_post' => 'المنشور :number في السلسلة',+ 'hidden' => 'الأصوات مخفية حتى انتهاء الاستطلاع',],'publish' => [diff --git a/lang/de/posts.php b/lang/de/posts.phpindex ef6fe1934..14df5425b 100644--- a/lang/de/posts.php+++ b/lang/de/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Das Thema muss 1 bis 50 Zeichen ohne . oder & haben.','ghost_post_attachments' => 'Ghost-Posts unterstützen keine Anhänge',],- 'x' => [- 'poll' => [- 'options_required' => 'Füge deiner Umfrage mindestens :min Antworten hinzu.',- 'options_distinct' => 'Jede Antwort muss anders sein. Ändere die doppelte.',- 'duration_required' => 'Wähle, wie lange deine Umfrage läuft.',- 'question_required' => 'Schreib die Frage deiner Umfrage in den Text des Beitrags.',- 'options_max' => 'Eine Umfrage kann bis zu :max Antworten haben. Entferne die übrigen.',- 'poll_object' => 'Sende die Umfrage mit ihren Antworten (options) und ihrer Dauer (duration_minutes).',- 'options_list' => 'Sende die Antworten der Umfrage als Liste von Texten.',- 'choice_text' => 'Jede Antwort der Umfrage muss Text sein.',- 'choice_max' => 'Jede Antwort kann bis zu :max Zeichen haben. Kürze die längere.',- 'duration_range' => 'Eine Umfrage kann :min Minuten bis :max Tage laufen. Wähle eine Dauer in diesem Bereich.',- 'choices' => 'Antworten',- 'choice' => 'Antwort :number',- 'choice_optional' => 'Antwort :number (optional)',- 'add_choice' => 'Antwort hinzufügen',- 'remove_choice' => 'Antwort :number entfernen',- 'length' => 'Dauer',- 'days' => 'Tage',- 'hours' => 'Stunden',- 'minutes' => 'Minuten',- 'remove' => 'Umfrage entfernen',- 'attachments' => 'Umfragen können keine Medien enthalten',- 'add' => 'Umfrage hinzufügen',- ],+ 'poll' => [+ 'options_required' => 'Füge deiner Umfrage mindestens :min Antworten hinzu.',+ 'options_distinct' => 'Jede Antwort muss anders sein. Ändere die doppelte.',+ 'duration_required' => 'Wähle, wie lange deine Umfrage läuft.',+ 'question_required' => 'Schreib die Frage deiner Umfrage in den Text des Beitrags.',+ 'options_max' => 'Eine Umfrage kann bis zu :max Antworten haben. Entferne die übrigen.',+ 'poll_object' => 'Sende die Umfrage mit ihren Antworten (options) und, auf X und Mastodon, ihrer Dauer (duration_minutes).',+ 'options_list' => 'Sende die Antworten der Umfrage als Liste von Texten.',+ 'choice_text' => 'Jede Antwort der Umfrage muss Text sein.',+ 'choice_max' => 'Jede Antwort kann bis zu :max Zeichen haben. Kürze die längere.',+ 'duration_range' => 'Eine Umfrage kann :min Minuten bis :max Tage laufen. Wähle eine Dauer in diesem Bereich.',+ 'choices' => 'Antworten',+ 'choice' => 'Antwort :number',+ 'choice_optional' => 'Antwort :number (optional)',+ 'add_choice' => 'Antwort hinzufügen',+ 'remove_choice' => 'Antwort :number entfernen',+ 'length' => 'Dauer',+ 'days' => 'Tage',+ 'hours' => 'Stunden',+ 'minutes' => 'Minuten',+ 'remove' => 'Umfrage entfernen',+ 'attachments' => 'Umfragen können keine Medien enthalten',+ 'add' => 'Umfrage hinzufügen',+ 'duration_whole' => 'Gib die Laufzeit der Umfrage in ganzen Minuten an.',+ 'multiple' => 'Mehrfachauswahl erlauben',+ 'hide_totals' => 'Stimmen bis zum Ende verbergen',],'linkedin' => ['document_title' => 'Dokumenttitel',@@ -858,6 +859,14 @@ return ['label' => 'Umfrage','description' => 'Frage mit :min bis :max Antworten',],+ 'mastodon_poll' => [+ 'label' => 'Umfrage',+ 'description' => 'Frage mit :min bis :max Antworten',+ ],+ 'threads_poll' => [+ 'label' => 'Umfrage',+ 'description' => 'Frage mit :min bis :max Antworten',+ ],'threads_post' => ['label' => 'Thread','description' => 'Textbeitrag mit optionalen Medien',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count Stimme|[0,*] :count Stimmen',+ 'voters' => '{1} :count Person|[0,*] :count Personen','final' => 'Endergebnis','ended' => 'Abstimmung beendet','ends' => 'Endet :time','thread_post' => 'Beitrag :number im Thread',+ 'hidden' => 'Stimmen bis zum Ende der Umfrage verborgen',],'publish' => [diff --git a/lang/el/posts.php b/lang/el/posts.phpindex cb02a972c..196a295c4 100644--- a/lang/el/posts.php+++ b/lang/el/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Το θέμα πρέπει να έχει από 1 έως 50 χαρακτήρες, χωρίς . ή &.','ghost_post_attachments' => 'Οι αναρτήσεις-φαντάσματα δεν υποστηρίζουν συνημμένα',],- 'x' => [- 'poll' => [- 'options_required' => 'Πρόσθεσε τουλάχιστον :min επιλογές στη δημοσκόπησή σου.',- 'options_distinct' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι διαφορετική. Άλλαξε την επαναλαμβανόμενη.',- 'duration_required' => 'Διάλεξε για πόσο θα μένει ανοιχτή η δημοσκόπησή σου.',- 'question_required' => 'Γράψε την ερώτηση της δημοσκόπησης στο κείμενο της ανάρτησης.',- 'options_max' => 'Μια δημοσκόπηση μπορεί να έχει έως :max επιλογές. Αφαίρεσε όσες περισσεύουν.',- 'poll_object' => 'Στείλε τη δημοσκόπηση με τις επιλογές της (options) και τη διάρκειά της (duration_minutes).',- 'options_list' => 'Στείλε τις επιλογές της δημοσκόπησης ως λίστα κειμένων.',- 'choice_text' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι κείμενο.',- 'choice_max' => 'Κάθε επιλογή της δημοσκόπησης μπορεί να έχει έως :max χαρακτήρες. Συντόμευσε τη μεγαλύτερη.',- 'duration_range' => 'Μια δημοσκόπηση μπορεί να μένει ανοιχτή από :min λεπτά έως :max ημέρες. Διάλεξε διάρκεια μέσα σε αυτό το εύρος.',- 'choices' => 'Επιλογές',- 'choice' => 'Επιλογή :number',- 'choice_optional' => 'Επιλογή :number (προαιρετική)',- 'add_choice' => 'Προσθήκη επιλογής',- 'remove_choice' => 'Αφαίρεση επιλογής :number',- 'length' => 'Διάρκεια',- 'days' => 'Ημέρες',- 'hours' => 'Ώρες',- 'minutes' => 'Λεπτά',- 'remove' => 'Αφαίρεση δημοσκόπησης',- 'attachments' => 'Οι δημοσκοπήσεις δεν υποστηρίζουν πολυμέσα',- 'add' => 'Προσθήκη δημοσκόπησης',- ],+ 'poll' => [+ 'options_required' => 'Πρόσθεσε τουλάχιστον :min επιλογές στη δημοσκόπησή σου.',+ 'options_distinct' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι διαφορετική. Άλλαξε την επαναλαμβανόμενη.',+ 'duration_required' => 'Διάλεξε για πόσο θα μένει ανοιχτή η δημοσκόπησή σου.',+ 'question_required' => 'Γράψε την ερώτηση της δημοσκόπησης στο κείμενο της ανάρτησης.',+ 'options_max' => 'Μια δημοσκόπηση μπορεί να έχει έως :max επιλογές. Αφαίρεσε όσες περισσεύουν.',+ 'poll_object' => 'Στείλε τη δημοσκόπηση με τις επιλογές της (options) και, στο X και στο Mastodon, τη διάρκειά της (duration_minutes).',+ 'options_list' => 'Στείλε τις επιλογές της δημοσκόπησης ως λίστα κειμένων.',+ 'choice_text' => 'Κάθε επιλογή της δημοσκόπησης πρέπει να είναι κείμενο.',+ 'choice_max' => 'Κάθε επιλογή της δημοσκόπησης μπορεί να έχει έως :max χαρακτήρες. Συντόμευσε τη μεγαλύτερη.',+ 'duration_range' => 'Μια δημοσκόπηση μπορεί να μένει ανοιχτή από :min λεπτά έως :max ημέρες. Διάλεξε διάρκεια μέσα σε αυτό το εύρος.',+ 'choices' => 'Επιλογές',+ 'choice' => 'Επιλογή :number',+ 'choice_optional' => 'Επιλογή :number (προαιρετική)',+ 'add_choice' => 'Προσθήκη επιλογής',+ 'remove_choice' => 'Αφαίρεση επιλογής :number',+ 'length' => 'Διάρκεια',+ 'days' => 'Ημέρες',+ 'hours' => 'Ώρες',+ 'minutes' => 'Λεπτά',+ 'remove' => 'Αφαίρεση δημοσκόπησης',+ 'attachments' => 'Οι δημοσκοπήσεις δεν υποστηρίζουν πολυμέσα',+ 'add' => 'Προσθήκη δημοσκόπησης',+ 'duration_whole' => 'Στείλε τη διάρκεια της δημοσκόπησης σε ακέραια λεπτά.',+ 'multiple' => 'Πολλαπλές επιλογές',+ 'hide_totals' => 'Απόκρυψη ψήφων ως το τέλος',],'linkedin' => ['document_title' => 'Τίτλος εγγράφου',@@ -858,6 +859,14 @@ return ['label' => 'Δημοσκόπηση','description' => 'Ερώτηση με :min έως :max επιλογές',],+ 'mastodon_poll' => [+ 'label' => 'Δημοσκόπηση',+ 'description' => 'Ερώτηση με :min έως :max επιλογές',+ ],+ 'threads_poll' => [+ 'label' => 'Δημοσκόπηση',+ 'description' => 'Ερώτηση με :min έως :max επιλογές',+ ],'threads_post' => ['label' => 'Νήμα','description' => 'Δημοσίευση κειμένου με προαιρετικά πολυμέσα',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count ψήφος|[0,*] :count ψήφοι',+ 'voters' => '{1} :count άτομο|[0,*] :count άτομα','final' => 'Τελικά αποτελέσματα','ended' => 'Η ψηφοφορία έληξε','ends' => 'Λήγει :time','thread_post' => 'Ανάρτηση :number του νήματος',+ 'hidden' => 'Οι ψήφοι κρύβονται ως το τέλος της δημοσκόπησης',],'publish' => [diff --git a/lang/en/posts.php b/lang/en/posts.phpindex c2e3675e4..c05b9c034 100644--- a/lang/en/posts.php+++ b/lang/en/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'The topic must have 1 to 50 characters, without . or &.','ghost_post_attachments' => 'Ghost Posts don\'t support attachments',],- 'x' => [- 'poll' => [- 'options_required' => 'Add at least :min choices to your poll.',- 'options_distinct' => 'Each poll choice must be different. Change the repeated one.',- 'duration_required' => 'Choose how long your poll stays open.',- 'question_required' => 'Write your poll question in the post text.',- 'options_max' => 'A poll can have up to :max choices. Remove the extra ones.',- 'poll_object' => 'Send the poll with its choices (options) and length (duration_minutes).',- 'options_list' => 'Send the poll choices as a list of text.',- 'choice_text' => 'Each poll choice must be text.',- 'choice_max' => 'Each poll choice can have up to :max characters. Shorten the longer one.',- 'duration_range' => 'A poll can stay open from :min minutes to :max days. Choose a length in that range.',- 'choices' => 'Choices',- 'choice' => 'Choice :number',- 'choice_optional' => 'Choice :number (optional)',- 'add_choice' => 'Add a choice',- 'remove_choice' => 'Remove choice :number',- 'length' => 'Length',- 'days' => 'Days',- 'hours' => 'Hours',- 'minutes' => 'Minutes',- 'remove' => 'Remove poll',- 'attachments' => 'Polls can\'t have media',- 'add' => 'Add a poll',- ],+ 'poll' => [+ 'options_required' => 'Add at least :min choices to your poll.',+ 'options_distinct' => 'Each poll choice must be different. Change the repeated one.',+ 'duration_required' => 'Choose how long your poll stays open.',+ 'question_required' => 'Write your poll question in the post text.',+ 'options_max' => 'A poll can have up to :max choices. Remove the extra ones.',+ 'poll_object' => 'Send the poll with its choices (options) and, on X and Mastodon, its length (duration_minutes).',+ 'options_list' => 'Send the poll choices as a list of text.',+ 'choice_text' => 'Each poll choice must be text.',+ 'choice_max' => 'Each poll choice can have up to :max characters. Shorten the longer one.',+ 'duration_range' => 'A poll can stay open from :min minutes to :max days. Choose a length in that range.',+ 'choices' => 'Choices',+ 'choice' => 'Choice :number',+ 'choice_optional' => 'Choice :number (optional)',+ 'add_choice' => 'Add a choice',+ 'remove_choice' => 'Remove choice :number',+ 'length' => 'Length',+ 'days' => 'Days',+ 'hours' => 'Hours',+ 'minutes' => 'Minutes',+ 'remove' => 'Remove poll',+ 'attachments' => 'Polls can\'t have media',+ 'add' => 'Add a poll',+ 'duration_whole' => 'Send the poll length as a whole number of minutes.',+ 'multiple' => 'Allow multiple choices',+ 'hide_totals' => 'Hide votes until it ends',],'linkedin' => ['document_title' => 'Document title',@@ -858,6 +859,14 @@ return ['label' => 'Poll','description' => 'Question with :min to :max choices',],+ 'mastodon_poll' => [+ 'label' => 'Poll',+ 'description' => 'Question with :min to :max choices',+ ],+ 'threads_poll' => [+ 'label' => 'Poll',+ 'description' => 'Question with :min to :max choices',+ ],'threads_post' => ['label' => 'Thread','description' => 'Text post with optional media',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count vote|[0,*] :count votes',+ 'voters' => '{1} :count person|[0,*] :count people','final' => 'Final results','ended' => 'Voting ended','ends' => 'Ends :time','thread_post' => 'Post :number of the thread',+ 'hidden' => 'Votes hidden until the poll ends',],'publish' => [diff --git a/lang/es/posts.php b/lang/es/posts.phpindex ae1c98480..c19572117 100644--- a/lang/es/posts.php+++ b/lang/es/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'El tema debe tener entre 1 y 50 caracteres, sin . ni &.','ghost_post_attachments' => 'Los posts fantasma no admiten adjuntos',],- 'x' => [- 'poll' => [- 'options_required' => 'Añade al menos :min opciones a tu encuesta.',- 'options_distinct' => 'Cada opción de la encuesta debe ser distinta. Cambia la repetida.',- 'duration_required' => 'Elige cuánto tiempo estará abierta tu encuesta.',- 'question_required' => 'Escribe la pregunta de tu encuesta en el texto de la publicación.',- 'options_max' => 'Una encuesta puede tener hasta :max opciones. Quita las que sobran.',- 'poll_object' => 'Envía la encuesta con sus opciones (options) y su duración (duration_minutes).',- 'options_list' => 'Envía las opciones de la encuesta como una lista de textos.',- 'choice_text' => 'Cada opción de la encuesta debe ser texto.',- 'choice_max' => 'Cada opción de la encuesta puede tener hasta :max caracteres. Acorta la más larga.',- 'duration_range' => 'Una encuesta puede estar abierta de :min minutos a :max días. Elige una duración dentro de ese rango.',- 'choices' => 'Opciones',- 'choice' => 'Opción :number',- 'choice_optional' => 'Opción :number (opcional)',- 'add_choice' => 'Añadir opción',- 'remove_choice' => 'Quitar opción :number',- 'length' => 'Duración',- 'days' => 'Días',- 'hours' => 'Horas',- 'minutes' => 'Minutos',- 'remove' => 'Quitar encuesta',- 'attachments' => 'Las encuestas no admiten contenido multimedia',- 'add' => 'Añadir encuesta',- ],+ 'poll' => [+ 'options_required' => 'Añade al menos :min opciones a tu encuesta.',+ 'options_distinct' => 'Cada opción de la encuesta debe ser distinta. Cambia la repetida.',+ 'duration_required' => 'Elige cuánto tiempo estará abierta tu encuesta.',+ 'question_required' => 'Escribe la pregunta de tu encuesta en el texto de la publicación.',+ 'options_max' => 'Una encuesta puede tener hasta :max opciones. Quita las que sobran.',+ 'poll_object' => 'Envía la encuesta con sus opciones (options) y, en X y Mastodon, su duración (duration_minutes).',+ 'options_list' => 'Envía las opciones de la encuesta como una lista de textos.',+ 'choice_text' => 'Cada opción de la encuesta debe ser texto.',+ 'choice_max' => 'Cada opción de la encuesta puede tener hasta :max caracteres. Acorta la más larga.',+ 'duration_range' => 'Una encuesta puede estar abierta de :min minutos a :max días. Elige una duración dentro de ese rango.',+ 'choices' => 'Opciones',+ 'choice' => 'Opción :number',+ 'choice_optional' => 'Opción :number (opcional)',+ 'add_choice' => 'Añadir opción',+ 'remove_choice' => 'Quitar opción :number',+ 'length' => 'Duración',+ 'days' => 'Días',+ 'hours' => 'Horas',+ 'minutes' => 'Minutos',+ 'remove' => 'Quitar encuesta',+ 'attachments' => 'Las encuestas no admiten contenido multimedia',+ 'add' => 'Añadir encuesta',+ 'duration_whole' => 'Indica la duración de la encuesta en minutos enteros.',+ 'multiple' => 'Permitir varias opciones',+ 'hide_totals' => 'Ocultar votos hasta el final',],'linkedin' => ['document_title' => 'Título del documento',@@ -858,6 +859,14 @@ return ['label' => 'Encuesta','description' => 'Pregunta con :min a :max opciones',],+ 'mastodon_poll' => [+ 'label' => 'Encuesta',+ 'description' => 'Pregunta con :min a :max opciones',+ ],+ 'threads_poll' => [+ 'label' => 'Encuesta',+ 'description' => 'Pregunta con :min a :max opciones',+ ],'threads_post' => ['label' => 'Hilo','description' => 'Post de texto con multimedia opcional',@@ -998,10 +1007,12 @@ return [],'poll_results' => ['votes' => '{1} :count voto|[0,*] :count votos',+ 'voters' => '{1} :count persona|[0,*] :count personas','final' => 'Resultados finales','ended' => 'Votación cerrada','ends' => 'Termina :time','thread_post' => 'Publicación :number del hilo',+ 'hidden' => 'Votos ocultos hasta que termine la encuesta',],'publish' => [diff --git a/lang/fr/posts.php b/lang/fr/posts.phpindex dcf99de2d..9d6d38dcf 100644--- a/lang/fr/posts.php+++ b/lang/fr/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Le sujet doit contenir de 1 à 50 caractères, sans . ni &.','ghost_post_attachments' => 'Les posts fantômes n\'acceptent pas les pièces jointes',],- 'x' => [- 'poll' => [- 'options_required' => 'Ajoutez au moins :min choix à votre sondage.',- 'options_distinct' => 'Chaque choix du sondage doit être différent. Modifiez celui qui se répète.',- 'duration_required' => 'Choisissez la durée de votre sondage.',- 'question_required' => 'Écrivez la question de votre sondage dans le texte du post.',- 'options_max' => 'Un sondage peut avoir jusqu\'à :max choix. Retirez ceux en trop.',- 'poll_object' => 'Envoyez le sondage avec ses choix (options) et sa durée (duration_minutes).',- 'options_list' => 'Envoyez les choix du sondage sous forme de liste de textes.',- 'choice_text' => 'Chaque choix du sondage doit être du texte.',- 'choice_max' => 'Chaque choix du sondage peut contenir jusqu\'à :max caractères. Raccourcissez le plus long.',- 'duration_range' => 'Un sondage peut rester ouvert de :min minutes à :max jours. Choisissez une durée dans cet intervalle.',- 'choices' => 'Choix',- 'choice' => 'Choix :number',- 'choice_optional' => 'Choix :number (facultatif)',- 'add_choice' => 'Ajouter un choix',- 'remove_choice' => 'Retirer le choix :number',- 'length' => 'Durée',- 'days' => 'Jours',- 'hours' => 'Heures',- 'minutes' => 'Minutes',- 'remove' => 'Retirer le sondage',- 'attachments' => 'Un sondage n\'accepte pas de médias',- 'add' => 'Ajouter un sondage',- ],+ 'poll' => [+ 'options_required' => 'Ajoutez au moins :min choix à votre sondage.',+ 'options_distinct' => 'Chaque choix du sondage doit être différent. Modifiez celui qui se répète.',+ 'duration_required' => 'Choisissez la durée de votre sondage.',+ 'question_required' => 'Écrivez la question de votre sondage dans le texte du post.',+ 'options_max' => 'Un sondage peut avoir jusqu\'à :max choix. Retirez ceux en trop.',+ 'poll_object' => 'Envoyez le sondage avec ses choix (options) et, sur X et Mastodon, sa durée (duration_minutes).',+ 'options_list' => 'Envoyez les choix du sondage sous forme de liste de textes.',+ 'choice_text' => 'Chaque choix du sondage doit être du texte.',+ 'choice_max' => 'Chaque choix du sondage peut contenir jusqu\'à :max caractères. Raccourcissez le plus long.',+ 'duration_range' => 'Un sondage peut rester ouvert de :min minutes à :max jours. Choisissez une durée dans cet intervalle.',+ 'choices' => 'Choix',+ 'choice' => 'Choix :number',+ 'choice_optional' => 'Choix :number (facultatif)',+ 'add_choice' => 'Ajouter un choix',+ 'remove_choice' => 'Retirer le choix :number',+ 'length' => 'Durée',+ 'days' => 'Jours',+ 'hours' => 'Heures',+ 'minutes' => 'Minutes',+ 'remove' => 'Retirer le sondage',+ 'attachments' => 'Un sondage n\'accepte pas de médias',+ 'add' => 'Ajouter un sondage',+ 'duration_whole' => 'Indiquez la durée du sondage en minutes entières.',+ 'multiple' => 'Autoriser plusieurs choix',+ 'hide_totals' => 'Masquer les votes jusqu’à la fin',],'linkedin' => ['document_title' => 'Titre du document',@@ -858,6 +859,14 @@ return ['label' => 'Sondage','description' => 'Question avec :min à :max choix',],+ 'mastodon_poll' => [+ 'label' => 'Sondage',+ 'description' => 'Question avec :min à :max choix',+ ],+ 'threads_poll' => [+ 'label' => 'Sondage',+ 'description' => 'Question avec :min à :max choix',+ ],'threads_post' => ['label' => 'Fil','description' => 'Publication texte avec média facultatif',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count vote|[0,*] :count votes',+ 'voters' => '{1} :count personne|[0,*] :count personnes','final' => 'Résultats finaux','ended' => 'Vote terminé','ends' => 'Se termine :time','thread_post' => 'Publication :number du fil',+ 'hidden' => 'Votes masqués jusqu’à la fin du sondage',],'publish' => [diff --git a/lang/id/posts.php b/lang/id/posts.phpindex 7c11e7643..d43911f57 100644--- a/lang/id/posts.php+++ b/lang/id/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Topik harus 1 sampai 50 karakter, tanpa . atau &.','ghost_post_attachments' => 'Ghost post tidak mendukung lampiran',],- 'x' => [- 'poll' => [- 'options_required' => 'Tambahkan minimal :min pilihan ke polling kamu.',- 'options_distinct' => 'Setiap pilihan polling harus berbeda. Ubah yang berulang.',- 'duration_required' => 'Pilih berapa lama polling kamu tetap terbuka.',- 'question_required' => 'Tulis pertanyaan polling di teks postingan.',- 'options_max' => 'Polling bisa punya maksimal :max pilihan. Hapus yang berlebih.',- 'poll_object' => 'Kirim polling beserta pilihannya (options) dan durasinya (duration_minutes).',- 'options_list' => 'Kirim pilihan polling sebagai daftar teks.',- 'choice_text' => 'Setiap pilihan polling harus berupa teks.',- 'choice_max' => 'Setiap pilihan polling maksimal :max karakter. Persingkat yang lebih panjang.',- 'duration_range' => 'Polling bisa terbuka dari :min menit sampai :max hari. Pilih durasi dalam rentang itu.',- 'choices' => 'Pilihan',- 'choice' => 'Pilihan :number',- 'choice_optional' => 'Pilihan :number (opsional)',- 'add_choice' => 'Tambahkan pilihan',- 'remove_choice' => 'Hapus pilihan :number',- 'length' => 'Durasi',- 'days' => 'Hari',- 'hours' => 'Jam',- 'minutes' => 'Menit',- 'remove' => 'Hapus polling',- 'attachments' => 'Polling tidak bisa memuat media',- 'add' => 'Tambahkan polling',- ],+ 'poll' => [+ 'options_required' => 'Tambahkan minimal :min pilihan ke polling kamu.',+ 'options_distinct' => 'Setiap pilihan polling harus berbeda. Ubah yang berulang.',+ 'duration_required' => 'Pilih berapa lama polling kamu tetap terbuka.',+ 'question_required' => 'Tulis pertanyaan polling di teks postingan.',+ 'options_max' => 'Polling bisa punya maksimal :max pilihan. Hapus yang berlebih.',+ 'poll_object' => 'Kirim polling beserta pilihannya (options) dan, di X dan Mastodon, durasinya (duration_minutes).',+ 'options_list' => 'Kirim pilihan polling sebagai daftar teks.',+ 'choice_text' => 'Setiap pilihan polling harus berupa teks.',+ 'choice_max' => 'Setiap pilihan polling maksimal :max karakter. Persingkat yang lebih panjang.',+ 'duration_range' => 'Polling bisa terbuka dari :min menit sampai :max hari. Pilih durasi dalam rentang itu.',+ 'choices' => 'Pilihan',+ 'choice' => 'Pilihan :number',+ 'choice_optional' => 'Pilihan :number (opsional)',+ 'add_choice' => 'Tambahkan pilihan',+ 'remove_choice' => 'Hapus pilihan :number',+ 'length' => 'Durasi',+ 'days' => 'Hari',+ 'hours' => 'Jam',+ 'minutes' => 'Menit',+ 'remove' => 'Hapus polling',+ 'attachments' => 'Polling tidak bisa memuat media',+ 'add' => 'Tambahkan polling',+ 'duration_whole' => 'Kirim durasi polling dalam menit bulat.',+ 'multiple' => 'Izinkan beberapa pilihan',+ 'hide_totals' => 'Sembunyikan suara sampai selesai',],'linkedin' => ['document_title' => 'Judul dokumen',@@ -858,6 +859,14 @@ return ['label' => 'Polling','description' => 'Pertanyaan dengan :min sampai :max pilihan',],+ 'mastodon_poll' => [+ 'label' => 'Polling',+ 'description' => 'Pertanyaan dengan :min sampai :max pilihan',+ ],+ 'threads_poll' => [+ 'label' => 'Polling',+ 'description' => 'Pertanyaan dengan :min sampai :max pilihan',+ ],'threads_post' => ['label' => 'Thread','description' => 'Postingan teks dengan media opsional',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count suara|[0,*] :count suara',+ 'voters' => '{1} :count orang|[0,*] :count orang','final' => 'Hasil akhir','ended' => 'Voting berakhir','ends' => 'Berakhir :time','thread_post' => 'Postingan ke-:number di thread',+ 'hidden' => 'Suara disembunyikan hingga polling berakhir',],'publish' => [diff --git a/lang/it/posts.php b/lang/it/posts.phpindex 4f2367bf6..e384bec59 100644--- a/lang/it/posts.php+++ b/lang/it/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'L\'argomento deve avere da 1 a 50 caratteri, senza . o &.','ghost_post_attachments' => 'I post fantasma non supportano allegati',],- 'x' => [- 'poll' => [- 'options_required' => 'Aggiungi almeno :min opzioni al sondaggio.',- 'options_distinct' => 'Ogni opzione del sondaggio deve essere diversa. Modifica quella ripetuta.',- 'duration_required' => 'Scegli per quanto tempo resta aperto il sondaggio.',- 'question_required' => 'Scrivi la domanda del sondaggio nel testo del post.',- 'options_max' => 'Un sondaggio può avere fino a :max opzioni. Rimuovi quelle in più.',- 'poll_object' => 'Invia il sondaggio con le sue opzioni (options) e la sua durata (duration_minutes).',- 'options_list' => 'Invia le opzioni del sondaggio come elenco di testi.',- 'choice_text' => 'Ogni opzione del sondaggio deve essere un testo.',- 'choice_max' => 'Ogni opzione del sondaggio può avere fino a :max caratteri. Accorcia quella più lunga.',- 'duration_range' => 'Un sondaggio può restare aperto da :min minuti a :max giorni. Scegli una durata in questo intervallo.',- 'choices' => 'Opzioni',- 'choice' => 'Opzione :number',- 'choice_optional' => 'Opzione :number (facoltativa)',- 'add_choice' => 'Aggiungi opzione',- 'remove_choice' => 'Rimuovi opzione :number',- 'length' => 'Durata',- 'days' => 'Giorni',- 'hours' => 'Ore',- 'minutes' => 'Minuti',- 'remove' => 'Rimuovi sondaggio',- 'attachments' => 'I sondaggi non supportano i media',- 'add' => 'Aggiungi sondaggio',- ],+ 'poll' => [+ 'options_required' => 'Aggiungi almeno :min opzioni al sondaggio.',+ 'options_distinct' => 'Ogni opzione del sondaggio deve essere diversa. Modifica quella ripetuta.',+ 'duration_required' => 'Scegli per quanto tempo resta aperto il sondaggio.',+ 'question_required' => 'Scrivi la domanda del sondaggio nel testo del post.',+ 'options_max' => 'Un sondaggio può avere fino a :max opzioni. Rimuovi quelle in più.',+ 'poll_object' => 'Invia il sondaggio con le sue opzioni (options) e, su X e Mastodon, la sua durata (duration_minutes).',+ 'options_list' => 'Invia le opzioni del sondaggio come elenco di testi.',+ 'choice_text' => 'Ogni opzione del sondaggio deve essere un testo.',+ 'choice_max' => 'Ogni opzione del sondaggio può avere fino a :max caratteri. Accorcia quella più lunga.',+ 'duration_range' => 'Un sondaggio può restare aperto da :min minuti a :max giorni. Scegli una durata in questo intervallo.',+ 'choices' => 'Opzioni',+ 'choice' => 'Opzione :number',+ 'choice_optional' => 'Opzione :number (facoltativa)',+ 'add_choice' => 'Aggiungi opzione',+ 'remove_choice' => 'Rimuovi opzione :number',+ 'length' => 'Durata',+ 'days' => 'Giorni',+ 'hours' => 'Ore',+ 'minutes' => 'Minuti',+ 'remove' => 'Rimuovi sondaggio',+ 'attachments' => 'I sondaggi non supportano i media',+ 'add' => 'Aggiungi sondaggio',+ 'duration_whole' => 'Indica la durata del sondaggio in minuti interi.',+ 'multiple' => 'Consenti più scelte',+ 'hide_totals' => 'Nascondi i voti fino alla fine',],'linkedin' => ['document_title' => 'Titolo del documento',@@ -858,6 +859,14 @@ return ['label' => 'Sondaggio','description' => 'Domanda con :min-:max opzioni',],+ 'mastodon_poll' => [+ 'label' => 'Sondaggio',+ 'description' => 'Domanda con :min-:max opzioni',+ ],+ 'threads_poll' => [+ 'label' => 'Sondaggio',+ 'description' => 'Domanda con :min-:max opzioni',+ ],'threads_post' => ['label' => 'Thread','description' => 'Post di testo con media facoltativi',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count voto|[0,*] :count voti',+ 'voters' => '{1} :count persona|[0,*] :count persone','final' => 'Risultati finali','ended' => 'Votazione chiusa','ends' => 'Termina :time','thread_post' => 'Post :number del thread',+ 'hidden' => 'Voti nascosti fino alla fine del sondaggio',],'publish' => [diff --git a/lang/ja/posts.php b/lang/ja/posts.phpindex c99f1f245..befa5a262 100644--- a/lang/ja/posts.php+++ b/lang/ja/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'トピックは . と & を含まない1〜50文字にしてください。','ghost_post_attachments' => 'ゴースト投稿は添付ファイルに対応していません',],- 'x' => [- 'poll' => [- 'options_required' => '投票に選択肢を:minつ以上追加してください。',- 'options_distinct' => '投票の選択肢はそれぞれ異なる内容にしてください。重複しているものを変更してください。',- 'duration_required' => '投票を受け付ける期間を選んでください。',- 'question_required' => '投稿のテキストに投票の質問を書いてください。',- 'options_max' => '投票の選択肢は最大:max個までです。余分な選択肢を削除してください。',- 'poll_object' => '投票は選択肢(options)と期間(duration_minutes)を含めて送信してください。',- 'options_list' => '投票の選択肢はテキストのリストで送信してください。',- 'choice_text' => '投票の選択肢はテキストで入力してください。',- 'choice_max' => '投票の選択肢はそれぞれ最大:max文字までです。長い選択肢を短くしてください。',- 'duration_range' => '投票の期間は:min分から:max日までです。この範囲で期間を選んでください。',- 'choices' => '選択肢',- 'choice' => '選択肢:number',- 'choice_optional' => '選択肢:number(任意)',- 'add_choice' => '選択肢を追加',- 'remove_choice' => '選択肢:numberを削除',- 'length' => '期間',- 'days' => '日',- 'hours' => '時間',- 'minutes' => '分',- 'remove' => '投票を削除',- 'attachments' => '投票はメディアに対応していません',- 'add' => '投票を追加',- ],+ 'poll' => [+ 'options_required' => '投票に選択肢を:minつ以上追加してください。',+ 'options_distinct' => '投票の選択肢はそれぞれ異なる内容にしてください。重複しているものを変更してください。',+ 'duration_required' => '投票を受け付ける期間を選んでください。',+ 'question_required' => '投稿のテキストに投票の質問を書いてください。',+ 'options_max' => '投票の選択肢は最大:max個までです。余分な選択肢を削除してください。',+ 'poll_object' => '投票は選択肢(options)と、X と Mastodon では期間(duration_minutes)も含めて送信してください。',+ 'options_list' => '投票の選択肢はテキストのリストで送信してください。',+ 'choice_text' => '投票の選択肢はテキストで入力してください。',+ 'choice_max' => '投票の選択肢はそれぞれ最大:max文字までです。長い選択肢を短くしてください。',+ 'duration_range' => '投票の期間は:min分から:max日までです。この範囲で期間を選んでください。',+ 'choices' => '選択肢',+ 'choice' => '選択肢:number',+ 'choice_optional' => '選択肢:number(任意)',+ 'add_choice' => '選択肢を追加',+ 'remove_choice' => '選択肢:numberを削除',+ 'length' => '期間',+ 'days' => '日',+ 'hours' => '時間',+ 'minutes' => '分',+ 'remove' => '投票を削除',+ 'attachments' => '投票はメディアに対応していません',+ 'add' => '投票を追加',+ 'duration_whole' => '投票期間は分単位の整数で送ってください。',+ 'multiple' => '複数選択を許可',+ 'hide_totals' => '投票が終わるまで結果を非表示',],'linkedin' => ['document_title' => 'ドキュメントタイトル',@@ -858,6 +859,14 @@ return ['label' => '投票','description' => ':min〜:max個の選択肢がある質問',],+ 'mastodon_poll' => [+ 'label' => '投票',+ 'description' => ':min〜:max個の選択肢がある質問',+ ],+ 'threads_poll' => [+ 'label' => '投票',+ 'description' => ':min〜:max個の選択肢がある質問',+ ],'threads_post' => ['label' => 'スレッド','description' => 'メディア(任意)付きのテキスト投稿',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count票|[0,*] :count票',+ 'voters' => '{1} :count 人|[0,*] :count 人','final' => '最終結果','ended' => '投票は終了しました','ends' => '終了:time','thread_post' => 'スレッドの投稿 :number',+ 'hidden' => '投票が終わるまで結果は非表示',],'publish' => [diff --git a/lang/ko/posts.php b/lang/ko/posts.phpindex 60b93bf71..0e2898f3e 100644--- a/lang/ko/posts.php+++ b/lang/ko/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => '주제는 . 또는 & 없이 1~50자여야 합니다.','ghost_post_attachments' => '고스트 게시물은 첨부 파일을 지원하지 않습니다',],- 'x' => [- 'poll' => [- 'options_required' => '투표에 선택지를 :min개 이상 추가하세요.',- 'options_distinct' => '투표 선택지는 서로 달라야 합니다. 중복된 선택지를 바꿔 주세요.',- 'duration_required' => '투표를 얼마나 열어 둘지 선택하세요.',- 'question_required' => '게시물 텍스트에 투표 질문을 작성해 주세요.',- 'options_max' => '투표 선택지는 최대 :max개까지 추가할 수 있습니다. 남는 선택지를 삭제하세요.',- 'poll_object' => '투표를 선택지(options)와 기간(duration_minutes)과 함께 보내 주세요.',- 'options_list' => '투표 선택지를 텍스트 목록으로 보내 주세요.',- 'choice_text' => '투표 선택지는 텍스트여야 합니다.',- 'choice_max' => '투표 선택지는 각각 최대 :max자까지 입력할 수 있습니다. 긴 선택지를 줄여 주세요.',- 'duration_range' => '투표는 :min분에서 :max일까지 열어 둘 수 있습니다. 이 범위 안에서 기간을 선택하세요.',- 'choices' => '선택지',- 'choice' => '선택지 :number',- 'choice_optional' => '선택지 :number (선택 사항)',- 'add_choice' => '선택지 추가',- 'remove_choice' => '선택지 :number 삭제',- 'length' => '기간',- 'days' => '일',- 'hours' => '시간',- 'minutes' => '분',- 'remove' => '투표 삭제',- 'attachments' => '투표는 미디어를 지원하지 않습니다',- 'add' => '투표 추가',- ],+ 'poll' => [+ 'options_required' => '투표에 선택지를 :min개 이상 추가하세요.',+ 'options_distinct' => '투표 선택지는 서로 달라야 합니다. 중복된 선택지를 바꿔 주세요.',+ 'duration_required' => '투표를 얼마나 열어 둘지 선택하세요.',+ 'question_required' => '게시물 텍스트에 투표 질문을 작성해 주세요.',+ 'options_max' => '투표 선택지는 최대 :max개까지 추가할 수 있습니다. 남는 선택지를 삭제하세요.',+ 'poll_object' => '투표를 선택지(options)와 함께 보내고, X와 Mastodon에서는 기간(duration_minutes)도 함께 보내 주세요.',+ 'options_list' => '투표 선택지를 텍스트 목록으로 보내 주세요.',+ 'choice_text' => '투표 선택지는 텍스트여야 합니다.',+ 'choice_max' => '투표 선택지는 각각 최대 :max자까지 입력할 수 있습니다. 긴 선택지를 줄여 주세요.',+ 'duration_range' => '투표는 :min분에서 :max일까지 열어 둘 수 있습니다. 이 범위 안에서 기간을 선택하세요.',+ 'choices' => '선택지',+ 'choice' => '선택지 :number',+ 'choice_optional' => '선택지 :number (선택 사항)',+ 'add_choice' => '선택지 추가',+ 'remove_choice' => '선택지 :number 삭제',+ 'length' => '기간',+ 'days' => '일',+ 'hours' => '시간',+ 'minutes' => '분',+ 'remove' => '투표 삭제',+ 'attachments' => '투표는 미디어를 지원하지 않습니다',+ 'add' => '투표 추가',+ 'duration_whole' => '투표 기간은 분 단위 정수로 보내세요.',+ 'multiple' => '복수 선택 허용',+ 'hide_totals' => '투표가 끝날 때까지 결과 숨기기',],'linkedin' => ['document_title' => '문서 제목',@@ -858,6 +859,14 @@ return ['label' => '투표','description' => '선택지 :min~:max개가 있는 질문',],+ 'mastodon_poll' => [+ 'label' => '투표',+ 'description' => '선택지 :min~:max개가 있는 질문',+ ],+ 'threads_poll' => [+ 'label' => '투표',+ 'description' => '선택지 :min~:max개가 있는 질문',+ ],'threads_post' => ['label' => '스레드','description' => '선택적 미디어가 있는 텍스트 게시물',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count표|[0,*] :count표',+ 'voters' => '{1} :count명|[0,*] :count명','final' => '최종 결과','ended' => '투표 종료','ends' => '종료 :time','thread_post' => '스레드의 게시물 :number',+ 'hidden' => '투표가 끝날 때까지 결과는 숨겨져요',],'publish' => [diff --git a/lang/nl/posts.php b/lang/nl/posts.phpindex 007444e1d..f3c9152a2 100644--- a/lang/nl/posts.php+++ b/lang/nl/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Het onderwerp moet 1 tot 50 tekens hebben, zonder . of &.','ghost_post_attachments' => 'Ghost-posts ondersteunen geen bijlagen',],- 'x' => [- 'poll' => [- 'options_required' => 'Voeg minstens :min keuzes toe aan je poll.',- 'options_distinct' => 'Elke keuze in de poll moet anders zijn. Pas de dubbele aan.',- 'duration_required' => 'Kies hoe lang je poll openstaat.',- 'question_required' => 'Schrijf de vraag van je poll in de tekst van het bericht.',- 'options_max' => 'Een poll kan maximaal :max keuzes hebben. Verwijder de overige.',- 'poll_object' => 'Stuur de poll met de keuzes (options) en de duur (duration_minutes).',- 'options_list' => 'Stuur de keuzes van de poll als een lijst met tekst.',- 'choice_text' => 'Elke keuze in de poll moet tekst zijn.',- 'choice_max' => 'Elke keuze in de poll mag maximaal :max tekens hebben. Maak de langere korter.',- 'duration_range' => 'Een poll kan van :min minuten tot :max dagen openstaan. Kies een duur binnen dat bereik.',- 'choices' => 'Keuzes',- 'choice' => 'Keuze :number',- 'choice_optional' => 'Keuze :number (optioneel)',- 'add_choice' => 'Keuze toevoegen',- 'remove_choice' => 'Keuze :number verwijderen',- 'length' => 'Duur',- 'days' => 'Dagen',- 'hours' => 'Uren',- 'minutes' => 'Minuten',- 'remove' => 'Poll verwijderen',- 'attachments' => 'Een poll ondersteunt geen media',- 'add' => 'Poll toevoegen',- ],+ 'poll' => [+ 'options_required' => 'Voeg minstens :min keuzes toe aan je poll.',+ 'options_distinct' => 'Elke keuze in de poll moet anders zijn. Pas de dubbele aan.',+ 'duration_required' => 'Kies hoe lang je poll openstaat.',+ 'question_required' => 'Schrijf de vraag van je poll in de tekst van het bericht.',+ 'options_max' => 'Een poll kan maximaal :max keuzes hebben. Verwijder de overige.',+ 'poll_object' => 'Stuur de poll met de keuzes (options) en, op X en Mastodon, de duur (duration_minutes).',+ 'options_list' => 'Stuur de keuzes van de poll als een lijst met tekst.',+ 'choice_text' => 'Elke keuze in de poll moet tekst zijn.',+ 'choice_max' => 'Elke keuze in de poll mag maximaal :max tekens hebben. Maak de langere korter.',+ 'duration_range' => 'Een poll kan van :min minuten tot :max dagen openstaan. Kies een duur binnen dat bereik.',+ 'choices' => 'Keuzes',+ 'choice' => 'Keuze :number',+ 'choice_optional' => 'Keuze :number (optioneel)',+ 'add_choice' => 'Keuze toevoegen',+ 'remove_choice' => 'Keuze :number verwijderen',+ 'length' => 'Duur',+ 'days' => 'Dagen',+ 'hours' => 'Uren',+ 'minutes' => 'Minuten',+ 'remove' => 'Poll verwijderen',+ 'attachments' => 'Een poll ondersteunt geen media',+ 'add' => 'Poll toevoegen',+ 'duration_whole' => 'Geef de duur van de poll op in hele minuten.',+ 'multiple' => 'Meerdere keuzes toestaan',+ 'hide_totals' => 'Stemmen verbergen tot het einde',],'linkedin' => ['document_title' => 'Documenttitel',@@ -858,6 +859,14 @@ return ['label' => 'Poll','description' => 'Vraag met :min tot :max keuzes',],+ 'mastodon_poll' => [+ 'label' => 'Poll',+ 'description' => 'Vraag met :min tot :max keuzes',+ ],+ 'threads_poll' => [+ 'label' => 'Poll',+ 'description' => 'Vraag met :min tot :max keuzes',+ ],'threads_post' => ['label' => 'Thread','description' => 'Tekstpost met optionele media',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count stem|[0,*] :count stemmen',+ 'voters' => '{1} :count persoon|[0,*] :count personen','final' => 'Eindresultaat','ended' => 'Stemmen gesloten','ends' => 'Eindigt :time','thread_post' => 'Bericht :number van de thread',+ 'hidden' => 'Stemmen verborgen tot de poll afloopt',],'publish' => [diff --git a/lang/pl/posts.php b/lang/pl/posts.phpindex cc6f70f8a..91d73aef7 100644--- a/lang/pl/posts.php+++ b/lang/pl/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Temat musi mieć od 1 do 50 znaków, bez . i &.','ghost_post_attachments' => 'Posty-duchy nie obsługują załączników',],- 'x' => [- 'poll' => [- 'options_required' => 'Dodaj do ankiety co najmniej :min opcje.',- 'options_distinct' => 'Każda opcja ankiety musi być inna. Zmień powtórzoną.',- 'duration_required' => 'Wybierz, jak długo ankieta ma być otwarta.',- 'question_required' => 'Wpisz pytanie ankiety w treści posta.',- 'options_max' => 'Ankieta może mieć maksymalnie :max opcje. Usuń nadmiarowe.',- 'poll_object' => 'Wyślij ankietę z opcjami (options) i czasem trwania (duration_minutes).',- 'options_list' => 'Wyślij opcje ankiety jako listę tekstów.',- 'choice_text' => 'Każda opcja ankiety musi być tekstem.',- 'choice_max' => 'Każda opcja ankiety może mieć maksymalnie :max znaków. Skróć dłuższą.',- 'duration_range' => 'Ankieta może być otwarta od :min minut do :max dni. Wybierz czas trwania w tym zakresie.',- 'choices' => 'Opcje',- 'choice' => 'Opcja :number',- 'choice_optional' => 'Opcja :number (opcjonalna)',- 'add_choice' => 'Dodaj opcję',- 'remove_choice' => 'Usuń opcję :number',- 'length' => 'Czas trwania',- 'days' => 'Dni',- 'hours' => 'Godziny',- 'minutes' => 'Minuty',- 'remove' => 'Usuń ankietę',- 'attachments' => 'Ankieta nie obsługuje multimediów',- 'add' => 'Dodaj ankietę',- ],+ 'poll' => [+ 'options_required' => 'Dodaj do ankiety co najmniej :min opcje.',+ 'options_distinct' => 'Każda opcja ankiety musi być inna. Zmień powtórzoną.',+ 'duration_required' => 'Wybierz, jak długo ankieta ma być otwarta.',+ 'question_required' => 'Wpisz pytanie ankiety w treści posta.',+ 'options_max' => 'Ankieta może mieć maksymalnie :max opcje. Usuń nadmiarowe.',+ 'poll_object' => 'Wyślij ankietę z opcjami (options), a na X i Mastodonie także z czasem trwania (duration_minutes).',+ 'options_list' => 'Wyślij opcje ankiety jako listę tekstów.',+ 'choice_text' => 'Każda opcja ankiety musi być tekstem.',+ 'choice_max' => 'Każda opcja ankiety może mieć maksymalnie :max znaków. Skróć dłuższą.',+ 'duration_range' => 'Ankieta może być otwarta od :min minut do :max dni. Wybierz czas trwania w tym zakresie.',+ 'choices' => 'Opcje',+ 'choice' => 'Opcja :number',+ 'choice_optional' => 'Opcja :number (opcjonalna)',+ 'add_choice' => 'Dodaj opcję',+ 'remove_choice' => 'Usuń opcję :number',+ 'length' => 'Czas trwania',+ 'days' => 'Dni',+ 'hours' => 'Godziny',+ 'minutes' => 'Minuty',+ 'remove' => 'Usuń ankietę',+ 'attachments' => 'Ankieta nie obsługuje multimediów',+ 'add' => 'Dodaj ankietę',+ 'duration_whole' => 'Podaj czas trwania ankiety w pełnych minutach.',+ 'multiple' => 'Zezwól na wiele odpowiedzi',+ 'hide_totals' => 'Ukryj głosy do końca ankiety',],'linkedin' => ['document_title' => 'Tytuł dokumentu',@@ -858,6 +859,14 @@ return ['label' => 'Ankieta','description' => 'Pytanie z :min do :max opcjami',],+ 'mastodon_poll' => [+ 'label' => 'Ankieta',+ 'description' => 'Pytanie z :min do :max opcjami',+ ],+ 'threads_poll' => [+ 'label' => 'Ankieta',+ 'description' => 'Pytanie z :min do :max opcjami',+ ],'threads_post' => ['label' => 'Wątek','description' => 'Post tekstowy z opcjonalnymi multimediami',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count głos|[0,*] Głosów: :count',+ 'voters' => '{1} :count osoba|[2,4] :count osoby|[0,*] :count osób','final' => 'Wyniki końcowe','ended' => 'Głosowanie zakończone','ends' => 'Kończy się :time','thread_post' => 'Post :number w wątku',+ 'hidden' => 'Głosy ukryte do końca ankiety',],'publish' => [diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.phpindex 031c852eb..91e6e4220 100644--- a/lang/pt-BR/posts.php+++ b/lang/pt-BR/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'O tópico deve ter de 1 a 50 caracteres, sem . ou &.','ghost_post_attachments' => 'Posts temporários não aceitam anexos',],- 'x' => [- 'poll' => [- 'options_required' => 'Adicione pelo menos :min opções à sua enquete.',- 'options_distinct' => 'Cada opção da enquete precisa ser diferente. Altere a repetida.',- 'duration_required' => 'Escolha por quanto tempo sua enquete fica aberta.',- 'question_required' => 'Escreva a pergunta da sua enquete no texto do post.',- 'options_max' => 'Uma enquete pode ter até :max opções. Remova as que sobram.',- 'poll_object' => 'Envie a enquete com as opções (options) e a duração (duration_minutes).',- 'options_list' => 'Envie as opções da enquete como uma lista de textos.',- 'choice_text' => 'Cada opção da enquete precisa ser um texto.',- 'choice_max' => 'Cada opção da enquete pode ter até :max caracteres. Encurte a mais longa.',- 'duration_range' => 'Uma enquete pode ficar aberta de :min minutos a :max dias. Escolha uma duração nesse intervalo.',- 'choices' => 'Opções',- 'choice' => 'Opção :number',- 'choice_optional' => 'Opção :number (opcional)',- 'add_choice' => 'Adicionar opção',- 'remove_choice' => 'Remover opção :number',- 'length' => 'Duração',- 'days' => 'Dias',- 'hours' => 'Horas',- 'minutes' => 'Minutos',- 'remove' => 'Remover enquete',- 'attachments' => 'Enquetes não aceitam mídia',- 'add' => 'Adicionar enquete',- ],+ 'poll' => [+ 'options_required' => 'Adicione pelo menos :min opções à sua enquete.',+ 'options_distinct' => 'Cada opção da enquete precisa ser diferente. Altere a repetida.',+ 'duration_required' => 'Escolha por quanto tempo sua enquete fica aberta.',+ 'question_required' => 'Escreva a pergunta da sua enquete no texto do post.',+ 'options_max' => 'Uma enquete pode ter até :max opções. Remova as que sobram.',+ 'poll_object' => 'Envie a enquete com as opções (options) e, no X e no Mastodon, a duração (duration_minutes).',+ 'options_list' => 'Envie as opções da enquete como uma lista de textos.',+ 'choice_text' => 'Cada opção da enquete precisa ser um texto.',+ 'choice_max' => 'Cada opção da enquete pode ter até :max caracteres. Encurte a mais longa.',+ 'duration_range' => 'Uma enquete pode ficar aberta de :min minutos a :max dias. Escolha uma duração nesse intervalo.',+ 'choices' => 'Opções',+ 'choice' => 'Opção :number',+ 'choice_optional' => 'Opção :number (opcional)',+ 'add_choice' => 'Adicionar opção',+ 'remove_choice' => 'Remover opção :number',+ 'length' => 'Duração',+ 'days' => 'Dias',+ 'hours' => 'Horas',+ 'minutes' => 'Minutos',+ 'remove' => 'Remover enquete',+ 'attachments' => 'Enquetes não aceitam mídia',+ 'add' => 'Adicionar enquete',+ 'duration_whole' => 'Informe a duração da enquete em minutos inteiros.',+ 'multiple' => 'Permitir várias escolhas',+ 'hide_totals' => 'Ocultar votos até o fim',],'linkedin' => ['document_title' => 'Título do documento',@@ -858,6 +859,14 @@ return ['label' => 'Enquete','description' => 'Pergunta com :min a :max opções',],+ 'mastodon_poll' => [+ 'label' => 'Enquete',+ 'description' => 'Pergunta com :min a :max opções',+ ],+ 'threads_poll' => [+ 'label' => 'Enquete',+ 'description' => 'Pergunta com :min a :max opções',+ ],'threads_post' => ['label' => 'Thread','description' => 'Post de texto com mídia opcional',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count voto|[0,*] :count votos',+ 'voters' => '{1} :count pessoa|[0,*] :count pessoas','final' => 'Resultado final','ended' => 'Votação encerrada','ends' => 'Termina :time','thread_post' => 'Post :number da sequência',+ 'hidden' => 'Votos ocultos até a enquete terminar',],'publish' => [diff --git a/lang/ru/posts.php b/lang/ru/posts.phpindex fd1826e5a..1f4ea9c7a 100644--- a/lang/ru/posts.php+++ b/lang/ru/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Тема должна содержать от 1 до 50 символов, без . и &.','ghost_post_attachments' => 'Посты-призраки не поддерживают вложения',],- 'x' => [- 'poll' => [- 'options_required' => 'Добавьте в опрос хотя бы :min варианта.',- 'options_distinct' => 'Варианты ответа должны отличаться. Измените повторяющийся.',- 'duration_required' => 'Выберите, как долго опрос будет открыт.',- 'question_required' => 'Напишите вопрос опроса в тексте поста.',- 'options_max' => 'В опросе может быть не больше :max вариантов. Удалите лишние.',- 'poll_object' => 'Отправьте опрос с вариантами (options) и длительностью (duration_minutes).',- 'options_list' => 'Отправьте варианты опроса списком текстов.',- 'choice_text' => 'Каждый вариант опроса должен быть текстом.',- 'choice_max' => 'Каждый вариант опроса может содержать не больше :max символов. Сократите длинный.',- 'duration_range' => 'Опрос может быть открыт от :min минут до :max дней. Выберите длительность в этом диапазоне.',- 'choices' => 'Варианты',- 'choice' => 'Вариант :number',- 'choice_optional' => 'Вариант :number (необязательно)',- 'add_choice' => 'Добавить вариант',- 'remove_choice' => 'Удалить вариант :number',- 'length' => 'Длительность',- 'days' => 'Дни',- 'hours' => 'Часы',- 'minutes' => 'Минуты',- 'remove' => 'Удалить опрос',- 'attachments' => 'Опрос не поддерживает медиа',- 'add' => 'Добавить опрос',- ],+ 'poll' => [+ 'options_required' => 'Добавьте в опрос хотя бы :min варианта.',+ 'options_distinct' => 'Варианты ответа должны отличаться. Измените повторяющийся.',+ 'duration_required' => 'Выберите, как долго опрос будет открыт.',+ 'question_required' => 'Напишите вопрос опроса в тексте поста.',+ 'options_max' => 'В опросе может быть не больше :max вариантов. Удалите лишние.',+ 'poll_object' => 'Отправьте опрос с вариантами (options), а в X и Mastodon — с длительностью (duration_minutes).',+ 'options_list' => 'Отправьте варианты опроса списком текстов.',+ 'choice_text' => 'Каждый вариант опроса должен быть текстом.',+ 'choice_max' => 'Каждый вариант опроса может содержать не больше :max символов. Сократите длинный.',+ 'duration_range' => 'Опрос может быть открыт от :min минут до :max дней. Выберите длительность в этом диапазоне.',+ 'choices' => 'Варианты',+ 'choice' => 'Вариант :number',+ 'choice_optional' => 'Вариант :number (необязательно)',+ 'add_choice' => 'Добавить вариант',+ 'remove_choice' => 'Удалить вариант :number',+ 'length' => 'Длительность',+ 'days' => 'Дни',+ 'hours' => 'Часы',+ 'minutes' => 'Минуты',+ 'remove' => 'Удалить опрос',+ 'attachments' => 'Опрос не поддерживает медиа',+ 'add' => 'Добавить опрос',+ 'duration_whole' => 'Укажите длительность опроса в целых минутах.',+ 'multiple' => 'Разрешить несколько вариантов',+ 'hide_totals' => 'Скрыть голоса до конца',],'linkedin' => ['document_title' => 'Название документа',@@ -858,6 +859,14 @@ return ['label' => 'Опрос','description' => 'Вопрос с :min–:max вариантами',],+ 'mastodon_poll' => [+ 'label' => 'Опрос',+ 'description' => 'Вопрос с :min–:max вариантами',+ ],+ 'threads_poll' => [+ 'label' => 'Опрос',+ 'description' => 'Вопрос с :min–:max вариантами',+ ],'threads_post' => ['label' => 'Тред','description' => 'Текстовый пост с опциональным медиа',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count голос|[0,*] Голосов: :count',+ 'voters' => '{1} :count человек|[2,4] :count человека|[0,*] :count человек','final' => 'Итоговые результаты','ended' => 'Голосование завершено','ends' => 'Завершится :time','thread_post' => 'Пост :number в цепочке',+ 'hidden' => 'Голоса скрыты до окончания опроса',],'publish' => [diff --git a/lang/tr/posts.php b/lang/tr/posts.phpindex 7326729b3..ad189188e 100644--- a/lang/tr/posts.php+++ b/lang/tr/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Konu . veya & içermeden 1 ile 50 karakter arasında olmalıdır.','ghost_post_attachments' => 'Hayalet gönderiler ek desteklemez',],- 'x' => [- 'poll' => [- 'options_required' => 'Anketine en az :min seçenek ekle.',- 'options_distinct' => 'Anket seçeneklerinin her biri farklı olmalı. Tekrar eden seçeneği değiştir.',- 'duration_required' => 'Anketinin ne kadar açık kalacağını seç.',- 'question_required' => 'Anket sorunu gönderi metnine yaz.',- 'options_max' => 'Bir ankette en fazla :max seçenek olabilir. Fazla olanları kaldır.',- 'poll_object' => 'Anketi seçenekleri (options) ve süresiyle (duration_minutes) birlikte gönder.',- 'options_list' => 'Anket seçeneklerini metin listesi olarak gönder.',- 'choice_text' => 'Her anket seçeneği metin olmalı.',- 'choice_max' => 'Her anket seçeneği en fazla :max karakter olabilir. Uzun olanı kısalt.',- 'duration_range' => 'Bir anket :min dakikadan :max güne kadar açık kalabilir. Bu aralıkta bir süre seç.',- 'choices' => 'Seçenekler',- 'choice' => 'Seçenek :number',- 'choice_optional' => 'Seçenek :number (isteğe bağlı)',- 'add_choice' => 'Seçenek ekle',- 'remove_choice' => ':number. seçeneği kaldır',- 'length' => 'Süre',- 'days' => 'Gün',- 'hours' => 'Saat',- 'minutes' => 'Dakika',- 'remove' => 'Anketi kaldır',- 'attachments' => 'Anketler medya desteklemiyor',- 'add' => 'Anket ekle',- ],+ 'poll' => [+ 'options_required' => 'Anketine en az :min seçenek ekle.',+ 'options_distinct' => 'Anket seçeneklerinin her biri farklı olmalı. Tekrar eden seçeneği değiştir.',+ 'duration_required' => 'Anketinin ne kadar açık kalacağını seç.',+ 'question_required' => 'Anket sorunu gönderi metnine yaz.',+ 'options_max' => 'Bir ankette en fazla :max seçenek olabilir. Fazla olanları kaldır.',+ 'poll_object' => 'Anketi seçenekleriyle (options), X ve Mastodon\'da süresiyle (duration_minutes) birlikte gönder.',+ 'options_list' => 'Anket seçeneklerini metin listesi olarak gönder.',+ 'choice_text' => 'Her anket seçeneği metin olmalı.',+ 'choice_max' => 'Her anket seçeneği en fazla :max karakter olabilir. Uzun olanı kısalt.',+ 'duration_range' => 'Bir anket :min dakikadan :max güne kadar açık kalabilir. Bu aralıkta bir süre seç.',+ 'choices' => 'Seçenekler',+ 'choice' => 'Seçenek :number',+ 'choice_optional' => 'Seçenek :number (isteğe bağlı)',+ 'add_choice' => 'Seçenek ekle',+ 'remove_choice' => ':number. seçeneği kaldır',+ 'length' => 'Süre',+ 'days' => 'Gün',+ 'hours' => 'Saat',+ 'minutes' => 'Dakika',+ 'remove' => 'Anketi kaldır',+ 'attachments' => 'Anketler medya desteklemiyor',+ 'add' => 'Anket ekle',+ 'duration_whole' => 'Anket süresini tam dakika olarak gönder.',+ 'multiple' => 'Birden fazla seçime izin ver',+ 'hide_totals' => 'Oyları sona kadar gizle',],'linkedin' => ['document_title' => 'Belge başlığı',@@ -858,6 +859,14 @@ return ['label' => 'Anket','description' => ':min ila :max seçenekli soru',],+ 'mastodon_poll' => [+ 'label' => 'Anket',+ 'description' => ':min ila :max seçenekli soru',+ ],+ 'threads_poll' => [+ 'label' => 'Anket',+ 'description' => ':min ila :max seçenekli soru',+ ],'threads_post' => ['label' => 'Flood','description' => 'İsteğe bağlı medya içeren metin gönderisi',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count oy|[0,*] :count oy',+ 'voters' => '{1} :count kişi|[0,*] :count kişi','final' => 'Nihai sonuçlar','ended' => 'Oylama sona erdi','ends' => 'Bitiş: :time','thread_post' => 'Zincirin :number. gönderisi',+ 'hidden' => 'Oylar anket bitene kadar gizli',],'publish' => [diff --git a/lang/uk/posts.php b/lang/uk/posts.phpindex c657b470e..bd280e963 100644--- a/lang/uk/posts.php+++ b/lang/uk/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => 'Тема має містити від 1 до 50 символів, без . і &.','ghost_post_attachments' => 'Пости-привиди не підтримують вкладення',],- 'x' => [- 'poll' => [- 'options_required' => 'Додайте в опитування щонайменше :min варіанти.',- 'options_distinct' => 'Варіанти відповіді мають відрізнятися. Змініть той, що повторюється.',- 'duration_required' => 'Виберіть, як довго опитування буде відкритим.',- 'question_required' => 'Напишіть питання опитування в тексті допису.',- 'options_max' => 'В опитуванні може бути не більше :max варіантів. Видаліть зайві.',- 'poll_object' => 'Надішліть опитування з варіантами (options) і тривалістю (duration_minutes).',- 'options_list' => 'Надішліть варіанти опитування списком текстів.',- 'choice_text' => 'Кожен варіант опитування має бути текстом.',- 'choice_max' => 'Кожен варіант опитування може містити не більше :max символів. Скоротіть довший.',- 'duration_range' => 'Опитування може бути відкритим від :min хвилин до :max днів. Виберіть тривалість у цьому діапазоні.',- 'choices' => 'Варіанти',- 'choice' => 'Варіант :number',- 'choice_optional' => 'Варіант :number (необов’язково)',- 'add_choice' => 'Додати варіант',- 'remove_choice' => 'Видалити варіант :number',- 'length' => 'Тривалість',- 'days' => 'Дні',- 'hours' => 'Години',- 'minutes' => 'Хвилини',- 'remove' => 'Видалити опитування',- 'attachments' => 'Опитування не підтримує медіа',- 'add' => 'Додати опитування',- ],+ 'poll' => [+ 'options_required' => 'Додайте в опитування щонайменше :min варіанти.',+ 'options_distinct' => 'Варіанти відповіді мають відрізнятися. Змініть той, що повторюється.',+ 'duration_required' => 'Виберіть, як довго опитування буде відкритим.',+ 'question_required' => 'Напишіть питання опитування в тексті допису.',+ 'options_max' => 'В опитуванні може бути не більше :max варіантів. Видаліть зайві.',+ 'poll_object' => 'Надішліть опитування з варіантами (options), а в X і Mastodon — з тривалістю (duration_minutes).',+ 'options_list' => 'Надішліть варіанти опитування списком текстів.',+ 'choice_text' => 'Кожен варіант опитування має бути текстом.',+ 'choice_max' => 'Кожен варіант опитування може містити не більше :max символів. Скоротіть довший.',+ 'duration_range' => 'Опитування може бути відкритим від :min хвилин до :max днів. Виберіть тривалість у цьому діапазоні.',+ 'choices' => 'Варіанти',+ 'choice' => 'Варіант :number',+ 'choice_optional' => 'Варіант :number (необов’язково)',+ 'add_choice' => 'Додати варіант',+ 'remove_choice' => 'Видалити варіант :number',+ 'length' => 'Тривалість',+ 'days' => 'Дні',+ 'hours' => 'Години',+ 'minutes' => 'Хвилини',+ 'remove' => 'Видалити опитування',+ 'attachments' => 'Опитування не підтримує медіа',+ 'add' => 'Додати опитування',+ 'duration_whole' => 'Вкажіть тривалість опитування в цілих хвилинах.',+ 'multiple' => 'Дозволити кілька варіантів',+ 'hide_totals' => 'Приховати голоси до кінця',],'linkedin' => ['document_title' => 'Назва документа',@@ -858,6 +859,14 @@ return ['label' => 'Опитування','description' => 'Питання з :min–:max варіантами',],+ 'mastodon_poll' => [+ 'label' => 'Опитування',+ 'description' => 'Питання з :min–:max варіантами',+ ],+ 'threads_poll' => [+ 'label' => 'Опитування',+ 'description' => 'Питання з :min–:max варіантами',+ ],'threads_post' => ['label' => 'Тред','description' => 'Текстовий пост із необов’язковим медіа',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count голос|[0,*] Голосів: :count',+ 'voters' => '{1} :count людина|[2,4] :count людини|[0,*] :count людей','final' => 'Остаточні результати','ended' => 'Голосування завершено','ends' => 'Завершиться :time','thread_post' => 'Допис :number у ланцюжку',+ 'hidden' => 'Голоси приховано до завершення опитування',],'publish' => [diff --git a/lang/zh/posts.php b/lang/zh/posts.phpindex ac27c3b9a..e25ed0174 100644--- a/lang/zh/posts.php+++ b/lang/zh/posts.php@@ -439,31 +439,32 @@ return ['topic_invalid' => '话题须为 1 到 50 个字符,且不含 . 或 &。','ghost_post_attachments' => '幽灵帖子不支持附件',],- 'x' => [- 'poll' => [- 'options_required' => '请为投票至少添加 :min 个选项。',- 'options_distinct' => '每个投票选项必须不同,请修改重复的选项。',- 'duration_required' => '请选择投票的开放时长。',- 'question_required' => '请在帖子正文中写下投票问题。',- 'options_max' => '投票最多可以有 :max 个选项。请删除多余的选项。',- 'poll_object' => '请发送包含选项(options)和时长(duration_minutes)的投票。',- 'options_list' => '请以文本列表的形式发送投票选项。',- 'choice_text' => '每个投票选项都必须是文本。',- 'choice_max' => '每个投票选项最多 :max 个字符。请缩短较长的选项。',- 'duration_range' => '投票可开放 :min 分钟到 :max 天。请在此范围内选择时长。',- 'choices' => '选项',- 'choice' => '选项 :number',- 'choice_optional' => '选项 :number(可选)',- 'add_choice' => '添加选项',- 'remove_choice' => '删除选项 :number',- 'length' => '时长',- 'days' => '天',- 'hours' => '小时',- 'minutes' => '分钟',- 'remove' => '删除投票',- 'attachments' => '投票不支持媒体',- 'add' => '添加投票',- ],+ 'poll' => [+ 'options_required' => '请为投票至少添加 :min 个选项。',+ 'options_distinct' => '每个投票选项必须不同,请修改重复的选项。',+ 'duration_required' => '请选择投票的开放时长。',+ 'question_required' => '请在帖子正文中写下投票问题。',+ 'options_max' => '投票最多可以有 :max 个选项。请删除多余的选项。',+ 'poll_object' => '请发送包含选项(options)的投票;在 X 和 Mastodon 上还需包含时长(duration_minutes)。',+ 'options_list' => '请以文本列表的形式发送投票选项。',+ 'choice_text' => '每个投票选项都必须是文本。',+ 'choice_max' => '每个投票选项最多 :max 个字符。请缩短较长的选项。',+ 'duration_range' => '投票可开放 :min 分钟到 :max 天。请在此范围内选择时长。',+ 'choices' => '选项',+ 'choice' => '选项 :number',+ 'choice_optional' => '选项 :number(可选)',+ 'add_choice' => '添加选项',+ 'remove_choice' => '删除选项 :number',+ 'length' => '时长',+ 'days' => '天',+ 'hours' => '小时',+ 'minutes' => '分钟',+ 'remove' => '删除投票',+ 'attachments' => '投票不支持媒体',+ 'add' => '添加投票',+ 'duration_whole' => '请以整数分钟发送投票时长。',+ 'multiple' => '允许多选',+ 'hide_totals' => '投票结束前隐藏结果',],'linkedin' => ['document_title' => '文档标题',@@ -858,6 +859,14 @@ return ['label' => '投票','description' => '带 :min 到 :max 个选项的问题',],+ 'mastodon_poll' => [+ 'label' => '投票',+ 'description' => '带 :min 到 :max 个选项的问题',+ ],+ 'threads_poll' => [+ 'label' => '投票',+ 'description' => '带 :min 到 :max 个选项的问题',+ ],'threads_post' => ['label' => '串文','description' => '可附带媒体的文字帖子',@@ -997,10 +1006,12 @@ return [],'poll_results' => ['votes' => '{1} :count 票|[0,*] :count 票',+ 'voters' => '{1} :count 人|[0,*] :count 人','final' => '最终结果','ended' => '投票已结束','ends' => ':time结束','thread_post' => '帖子串中的第 :number 条',+ 'hidden' => '投票结束前结果隐藏',],'publish' => [diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vueindex 519f269df..5349c6c6a 100644--- a/resources/js/components/ChannelConfigurator.vue+++ b/resources/js/components/ChannelConfigurator.vue@@ -18,7 +18,7 @@ import {getPlatformLabel,} from '@/composables/usePlatformLogo';import type { Channel } from '@/types/channel';-import { ContentType } from '@/types/content-type';+import { POLL_CONTENT_TYPES } from '@/types/content-type';import type { MediaItem } from '@/types/media';import { Platform } from '@/types/platform';@@ -62,10 +62,10 @@ const hasDocument = computed(() =>props.media.some((item) => isDocumentMedia(item)),);-/** A repurpose publishes the source's media, so it never offers an X poll, which takes none. */+/** A repurpose publishes the source's media, so it never offers a poll, which takes none. */const repurposeContentTypes = (platform: string): ContentTypeOption[] =>getContentTypeOptions(platform).filter(- (option) => option.value !== ContentType.XPoll,+ (option) => !POLL_CONTENT_TYPES.has(option.value),);const offersContentTypeChoice = (channel: Channel): boolean =>diff --git a/resources/js/components/posts/composer/ComposerEditorToolbar.vue b/resources/js/components/posts/composer/ComposerEditorToolbar.vueindex 4d5e787fd..05896bc9b 100644--- a/resources/js/components/posts/composer/ComposerEditorToolbar.vue+++ b/resources/js/components/posts/composer/ComposerEditorToolbar.vue@@ -111,7 +111,7 @@ const selectEmoji = (emoji: string): void => {<buttontype="button":data-testid="`${testIdPrefix}-poll`"- :aria-label="$t('posts.form.x.poll.add')"+ :aria-label="$t('posts.form.poll.add')"class="flex size-8 items-center justify-center rounded-lg text-foreground transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"@click="addPoll">@@ -119,7 +119,7 @@ const selectEmoji = (emoji: string): void => {</button></TooltipTrigger><TooltipContent :data-testid="`${testIdPrefix}-poll-tooltip`">- {{ $t('posts.form.x.poll.add') }}+ {{ $t('posts.form.poll.add') }}</TooltipContent></Tooltip></template>diff --git a/resources/js/components/posts/composer/ComposerNetworkCard.vue b/resources/js/components/posts/composer/ComposerNetworkCard.vueindex ed91c628b..e3bba1668 100644--- a/resources/js/components/posts/composer/ComposerNetworkCard.vue+++ b/resources/js/components/posts/composer/ComposerNetworkCard.vue@@ -8,6 +8,8 @@ import { autosizeTextarea } from '@/lib/autosizeTextarea';import { isShiftEnter } from '@/lib/keyboard';import {CAPTIONLESS_CONTENT_TYPES,+ type ContentTypeValue,+ isContentType,MEDIALESS_CONTENT_TYPES,} from '@/types/content-type';@@ -46,7 +48,7 @@ const props = withDefaults(const emit = defineEmits<{'update:content': [value: string];- 'update:contentType': [value: string];+ 'update:contentType': [value: ContentTypeValue];paste: [event: ClipboardEvent];drop: [event: DragEvent];'open-templates': [];@@ -55,6 +57,13 @@ const emit = defineEmits<{'next-post': [];}>();+/** A picked post type, read from the radio as text. */+const selectContentType = (value: string): void => {+ if (isContentType(value)) {+ emit('update:contentType', value);+ }+};+const caption = ref<HTMLTextAreaElement | null>(null);watch(@@ -165,7 +174,7 @@ const showsHeader = computed(:model-value="contentType":test-id-prefix="typeTestIdPrefix":disabled="disabled"- @update:model-value="emit('update:contentType', $event)"+ @update:model-value="selectContentType"/><slot name="header" /></div>diff --git a/resources/js/components/posts/composer/PostComposerDialog.vue b/resources/js/components/posts/composer/PostComposerDialog.vueindex c458cdf4f..c06c7a6f7 100644--- a/resources/js/components/posts/composer/PostComposerDialog.vue+++ b/resources/js/components/posts/composer/PostComposerDialog.vue@@ -70,8 +70,8 @@ import MediaEditorDialog, {import ResumeUnfinishedPostDialog from '@/components/posts/composer/ResumeUnfinishedPostDialog.vue';import ChannelMediaWarnings from '@/components/posts/editor/ChannelMediaWarnings.vue';import GoogleBusinessTopicTypeRadios from '@/components/posts/editor/GoogleBusinessTopicTypeRadios.vue';+import PollField from '@/components/posts/editor/PollField.vue';import ThreadRepliesField from '@/components/posts/editor/ThreadRepliesField.vue';-import XPollField from '@/components/posts/editor/XPollField.vue';import PlatformPreview from '@/components/posts/previews/PlatformPreview.vue';import PreviewPanelTitle from '@/components/posts/previews/PreviewPanelTitle.vue';import PublishEmptyIllustration from '@/components/publish/PublishEmptyIllustration.vue';@@ -173,6 +173,7 @@ import {import { isGooglePickerOpen } from '@/lib/mediaSources/googleDrive';import { acceptAttribute, mediaKey } from '@/lib/mediaType';import { evaluatePlatformMeta } from '@/lib/platformMeta';+import { pollLimitsOf } from '@/lib/poll';import {newThreadReply,repliesAreComments,@@ -184,9 +185,9 @@ import {type ThreadReply,threadRepliesOf,threadReplyContentType,+ threadReplyPostType,} from '@/lib/threadReplies';import { htmlToPlainText } from '@/lib/utils';-import { pollLimitsOf } from '@/lib/xPoll';import { userTimezone } from '@/preferences';import { settings as channelSettings } from '@/routes/app/channels';import { linkPreviewMedia } from '@/routes/app/posts';@@ -198,15 +199,14 @@ import type {} from '@/types';import {CAPTIONLESS_CONTENT_TYPES,- ContentType,MEDIALESS_CONTENT_TYPE_REASONS,+ POLL_CONTENT_TYPES,} from '@/types/content-type';import type { MediaItem } from '@/types/media';import {- THREAD_PLATFORMS,- THREAD_REPLY_CONTENT_TYPES,+ isThreadPlatform,} from '@/types/network-options';-import { Platform } from '@/types/platform';+import { Platform, type PlatformValue } from '@/types/platform';import {PostStatus,ScheduleMode,@@ -485,7 +485,6 @@ const {setGroupPoll,setGroupContentType,removeGroupPoll,- forgetGroupPoll,forgetPolls,replyPollLimit,replyTextLimit,@@ -506,27 +505,23 @@ const {},);/**- * Step 1 shows no post type, so an X poll, which takes no media, would quietly+ * Step 1 shows no post type, so a poll, which takes no media, would quietly* refuse the shared media there. Entering it (a second network added) puts- * the poll card back on X's first type and forgets its poll, as going back to- * step 1 does.+ * the poll card back on its network's first type and forgets its poll, as+ * going back to step 1 does.*/watch(sharedStep, (shared) => {if (!shared) return;networkGroups.value- .filter(- (group) =>- groupDestination(group).content_type === ContentType.XPoll,+ .filter((group) =>+ POLL_CONTENT_TYPES.has(groupDestination(group).content_type),)- .forEach((group) => {- const [firstType] = getPickableContentTypeOptions(group.platform);- if (!firstType) return;-- setGroupContentType(group, firstType.value);- forgetGroupPoll(group);- });+ .forEach(removeGroupPoll);});+/** The test ids of a card's poll: `x-poll`, `mastodon-poll`, `threads-poll`. */+const pollTestIdPrefix = (group: NetworkGroup): string =>+ `${group.platform}-poll`;/** Why the media button is off: a type that takes no media says so, and so does a reply poll. */const groupMediaDisabledReasonKey = (group: NetworkGroup): string => {const contentType = transform(@@ -1152,7 +1147,7 @@ const threadReplies = (group: NetworkGroup): ThreadReply[] =>const activeReply = (group: NetworkGroup): ThreadReply | undefined =>threadReplies(group)[threadActive.value];const supportsThread = (group: NetworkGroup): boolean =>- THREAD_PLATFORMS.includes(group.platform);+ isThreadPlatform(group.platform);const replyLimit = (account: ComposerAccount): number | null => {const limit = props.platformConfigs[account.id]?.maxContentLength;@@ -1363,9 +1358,15 @@ const onMediaFilesSelected = (event: Event): void => {mediaFileTarget.value.add(files);}};-const replyAcceptsMedia = (platform: string): boolean =>- getMediaRulesForContentType(THREAD_REPLY_CONTENT_TYPES[platform]).maxFiles >- 0;+const replyAcceptsMedia = (platform: PlatformValue): boolean => {+ const replyType = threadReplyPostType(platform);++ if (!filled(replyType)) {+ return false;+ }++ return getMediaRulesForContentType(replyType).maxFiles > 0;+};const groupAcceptsMedia = (group: NetworkGroup): boolean => {const reply = activeReply(group);@@ -1504,7 +1505,7 @@ const destinationIssues = (account: ComposerAccount): DestinationIssue[] => {contentType,});}- const replyContentType = THREAD_REPLY_CONTENT_TYPES[account.platform];+ const replyContentType = threadReplyPostType(account.platform);if (replyContentType) {const limit = replyLimit(account);for (const reply of threadRepliesOf(destination.meta)) {@@ -1767,7 +1768,7 @@ const editorContentTypes = (): string[] => {const group = findGroup(groupKey);if (group && replyKey !== null) {- const replyContentType = THREAD_REPLY_CONTENT_TYPES[group.platform];+ const replyContentType = threadReplyPostType(group.platform);return replyContentType ? [replyContentType] : [];}@@ -2937,12 +2938,13 @@ const onDialogOpenChange = (value: boolean): void => {"#attachment>- <XPollField+ <PollField:model-value="groupPoll(group)":limits="groupPollLimits(group)!":platform-index="selectedAccounts.indexOf(group.anchor)"+ :test-id-prefix="pollTestIdPrefix(group)":disabled="cropUploading"@update:model-value="setGroupPoll(group, $event)@@ -3005,7 +3007,7 @@ const onDialogOpenChange = (value: boolean): void => {@paste="onReplyMediaPasted($event, group)"><template #media="{ reply, index }">- <XPollField+ <PollFieldv-if="filled(reply.poll) &&threadActive === index &&@@ -3040,9 +3042,9 @@ const onDialogOpenChange = (value: boolean): void => {<ChannelMediaWarnings:platform="group.platform":content-type="- THREAD_REPLY_CONTENT_TYPES[- group.platform- ]+ threadReplyPostType(+ group.platform,+ )!":media="reply.media":media-editing="true"diff --git a/resources/js/components/posts/editor/XPollField.vue b/resources/js/components/posts/editor/PollField.vuesimilarity index 63%rename from resources/js/components/posts/editor/XPollField.vuerename to resources/js/components/posts/editor/PollField.vueindex 9e98db0c6..03fe9f21a 100644--- a/resources/js/components/posts/editor/XPollField.vue+++ b/resources/js/components/posts/editor/PollField.vue@@ -7,6 +7,7 @@ import InputError from '@/components/InputError.vue';import SettingsRow from '@/components/posts/editor/SettingsRow.vue';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';import {Select,SelectContent,@@ -14,24 +15,28 @@ import {SelectTrigger,SelectValue,} from '@/components/ui/select';+import { Switch } from '@/components/ui/switch';import { useMetaErrors } from '@/composables/useMetaErrors';+import { filled } from '@/lib/helpers';import {editablePollOptions,fitPollChoice,pollChoiceLength,+ pollDurationOf,+ pollHasDuration,HOURS_PER_DAY,joinPollDuration,MINUTES_PER_HOUR,pollMaxDays,splitPollDuration,-} from '@/lib/xPoll';-import type { XPoll, XPollDuration, XPollLimits } from '@/types/x';+} from '@/lib/poll';+import type { Poll, PollDuration, PollLimits } from '@/types/poll';const props = withDefaults(defineProps<{- modelValue: Partial<XPoll>;+ modelValue: Partial<Poll>;/** The account's poll limits, from its `publishConfig`. */- limits: XPollLimits;+ limits: PollLimits;/** This card's position in the submitted `destinations`; see useMetaErrors. */platformIndex: number;/** Where the poll sits in the meta: '' for the post, `thread_replies.{n}.` for a reply. */@@ -40,11 +45,11 @@ const props = withDefaults(testIdPrefix?: string;disabled?: boolean;}>(),- { fieldPrefix: '', testIdPrefix: 'x-poll', disabled: false },+ { fieldPrefix: '', testIdPrefix: 'poll', disabled: false },);const emit = defineEmits<{- 'update:modelValue': [value: XPoll];+ 'update:modelValue': [value: Poll];remove: [];}>();@@ -63,25 +68,52 @@ const choiceId = (index: number): string => `${id}-choice-${index}`;const options = computed((): string[] =>editablePollOptions(props.modelValue.options, props.limits.minOptions),);-const durationMinutes = computed(- (): number =>- props.modelValue.duration_minutes ?? props.limits.defaultDuration,+/** Whether the author picks the length: not on Threads, which sets it. */+const hasDuration = computed((): boolean => pollHasDuration(props.limits));+const durationMinutes = computed((): number =>+ pollDurationOf(props.modelValue, props.limits),);const duration = computed(- (): XPollDuration => splitPollDuration(durationMinutes.value),+ (): PollDuration => splitPollDuration(durationMinutes.value),);-const atLongestLength = computed(- (): boolean => durationMinutes.value >= props.limits.maxDuration,+const atLongestLength = computed((): boolean => {+ const longest = props.limits.maxDuration;++ if (!filled(longest)) {+ return false;+ }++ return durationMinutes.value >= longest;+});+/** A length select is off at the longest length, where only the days count. */+const lengthPartDisabled = (part: keyof PollDuration): boolean => {+ if (props.disabled) {+ return true;+ }++ return atLongestLength.value && part !== 'days';+};+/** Mastodon lets the author pick multiple choice and hidden totals. */+const hasSwitches = computed((): boolean => {+ if (props.limits.multipleChoice) {+ return true;+ }++ return props.limits.hideTotals;+});+const multiple = computed((): boolean => props.modelValue.multiple === true);+const hideTotals = computed(+ (): boolean => props.modelValue.hide_totals === true,);const lengthParts: {- part: keyof XPollDuration;+ part: keyof PollDuration;labelKey: string;values: number[];}[] = [{part: 'days',- labelKey: 'posts.form.x.poll.days',+ labelKey: 'posts.form.poll.days',values: Array.from({ length: pollMaxDays(props.limits) + 1 },(_, value) => value,@@ -89,35 +121,83 @@ const lengthParts: {},{part: 'hours',- labelKey: 'posts.form.x.poll.hours',+ labelKey: 'posts.form.poll.hours',values: Array.from({ length: HOURS_PER_DAY }, (_, value) => value),},{part: 'minutes',- labelKey: 'posts.form.x.poll.minutes',+ labelKey: 'posts.form.poll.minutes',values: Array.from({ length: MINUTES_PER_HOUR }, (_, value) => value),},];-const update = (patch: Partial<XPoll>): void => {- emit('update:modelValue', {- options: options.value,- duration_minutes: durationMinutes.value,- ...patch,- });+/**+ * The poll with the editor's choices and length. Every other key stays as it+ * came, in its order (MySQL reorders a stored poll's keys), and a switch is+ * only added once it is used, so a stored poll edited back to what it was is+ * no unsaved change.+ */+const currentPoll = (): Poll => {+ const poll: Poll = { ...props.modelValue, options: options.value };++ if (hasDuration.value) {+ poll.duration_minutes = durationMinutes.value;+ }++ return poll;+};++const update = (patch: Partial<Poll>): void => {+ emit('update:modelValue', { ...currentPoll(), ...patch });+};++const setMultiple = (value: boolean): void => {+ update({ multiple: value });};-/** A choice's length as the server measures it, without the spaces around it. */+const setHideTotals = (value: boolean): void => {+ update({ hide_totals: value });+};/** The `:number` a choice's labels show, counted from one. */const choiceNumber = (index: number): { number: string } => ({number: String(index + 1),});-const choiceLabelKey = (index: number): string =>- index < props.limits.minOptions- ? 'posts.form.x.poll.choice'- : 'posts.form.x.poll.choice_optional';+const choiceLabelKey = (index: number): string => {+ if (index < props.limits.minOptions) {+ return 'posts.form.poll.choice';+ }++ return 'posts.form.poll.choice_optional';+};++/** A choice past the ones every poll needs can be removed. */+const isOptionalChoice = (index: number): boolean =>+ index >= props.limits.minOptions;++/** Another choice fits until the network's most. */+const canAddChoice = computed(+ (): boolean => options.value.length < props.limits.maxOptions,+);++/** A choice the server refused is marked invalid for assistive tech; none otherwise. */+const choiceInvalid = (index: number): true | undefined => {+ if (!filled(choiceErrors[index]?.value)) {+ return undefined;+ }++ return true;+};++/** A choice's counter turns red once it runs over the network's limit. */+const choiceCountClass = (option: string): string => {+ if (pollChoiceLength(option) > props.limits.optionMaxLength) {+ return 'text-destructive-text';+ }++ return 'text-muted-foreground';+};const writeChoice = (index: number, choice: string): void => {update({@@ -148,7 +228,9 @@ const setChoice = async (};const addChoice = async (): Promise<void> => {- if (options.value.length >= props.limits.maxOptions) return;+ if (!canAddChoice.value) {+ return;+ }const added = options.value.length;update({ options: [...options.value, ''] });@@ -163,7 +245,7 @@ const removeChoice = (index: number): void => {};const setLengthPart = (- part: keyof XPollDuration,+ part: keyof PollDuration,value: AcceptableValue,): void => {update({@@ -184,7 +266,7 @@ const removePoll = (): void => {<SettingsRow align-top><template #label><span data-single-line>{{- $t('posts.form.x.poll.choices')+ $t('posts.form.poll.choices')}}</span></template><template v-for="(option, index) in options" :key="index">@@ -199,33 +281,27 @@ const removePoll = (): void => {:placeholder="$t(choiceLabelKey(index), choiceNumber(index))"- :aria-invalid="- choiceErrors[index]?.value ? true : undefined- "+ :aria-invalid="choiceInvalid(index)":disabled="disabled":data-testid="`${testIdPrefix}-choice-${index}`"@update:model-value="setChoice(index, $event)"/><spanclass="w-11 shrink-0 text-end text-xs tabular-nums"- :class="- pollChoiceLength(option) > limits.optionMaxLength- ? 'text-destructive-text'- : 'text-muted-foreground'- "+ :class="choiceCountClass(option)":data-testid="`${testIdPrefix}-choice-${index}-count`">{{ pollChoiceLength(option) }} /{{ limits.optionMaxLength }}</span><Button- v-if="index >= limits.minOptions"+ v-if="isOptionalChoice(index)"type="button"variant="ghost"size="icon-sm"class="text-muted-foreground":aria-label="$t(- 'posts.form.x.poll.remove_choice',+ 'posts.form.poll.remove_choice',choiceNumber(index),)"@@ -247,7 +323,7 @@ const removePoll = (): void => {:data-testid="`${testIdPrefix}-options-error`"/><Button- v-if="options.length < limits.maxOptions"+ v-if="canAddChoice"type="button"variant="outline"size="sm"@@ -257,14 +333,14 @@ const removePoll = (): void => {><IconPlus class="size-4" /><span data-single-line>{{- $t('posts.form.x.poll.add_choice')+ $t('posts.form.poll.add_choice')}}</span></Button></SettingsRow>- <SettingsRow>+ <SettingsRow v-if="hasDuration"><template #label><span data-single-line>{{- $t('posts.form.x.poll.length')+ $t('posts.form.poll.length')}}</span></template><div class="flex flex-wrap items-center gap-x-4 gap-y-2">@@ -275,10 +351,7 @@ const removePoll = (): void => {><Select:model-value="String(duration[lengthPart.part])"- :disabled="- disabled ||- (atLongestLength && lengthPart.part !== 'days')- "+ :disabled="lengthPartDisabled(lengthPart.part)"@update:model-value="setLengthPart(lengthPart.part, $event)"@@ -315,6 +388,37 @@ const removePoll = (): void => {:data-testid="`${testIdPrefix}-duration-error`"/></SettingsRow>+ <SettingsRow v-if="hasSwitches">+ <div class="flex flex-col gap-3">+ <div+ v-if="limits.multipleChoice"+ class="flex items-center gap-2"+ >+ <Switch+ :id="`${id}-multiple`"+ :model-value="multiple"+ :disabled="disabled"+ :data-testid="`${testIdPrefix}-multiple`"+ @update:model-value="setMultiple"+ />+ <Label :for="`${id}-multiple`" class="font-normal">{{+ $t('posts.form.poll.multiple')+ }}</Label>+ </div>+ <div v-if="limits.hideTotals" class="flex items-center gap-2">+ <Switch+ :id="`${id}-hide-totals`"+ :model-value="hideTotals"+ :disabled="disabled"+ :data-testid="`${testIdPrefix}-hide-totals`"+ @update:model-value="setHideTotals"+ />+ <Label :for="`${id}-hide-totals`" class="font-normal">{{+ $t('posts.form.poll.hide_totals')+ }}</Label>+ </div>+ </div>+ </SettingsRow><SettingsRow><div><Button@@ -328,7 +432,7 @@ const removePoll = (): void => {><IconTrash class="size-4" /><span data-single-line>{{- $t('posts.form.x.poll.remove')+ $t('posts.form.poll.remove')}}</span></Button></div>diff --git a/resources/js/components/posts/previews/MastodonPreview.vue b/resources/js/components/posts/previews/MastodonPreview.vueindex 18d97158f..51180979b 100644--- a/resources/js/components/posts/previews/MastodonPreview.vue+++ b/resources/js/components/posts/previews/MastodonPreview.vue@@ -9,9 +9,12 @@ import {} from '@tabler/icons-vue';import { computed } from 'vue';+import MastodonPreviewPoll from '@/components/posts/previews/MastodonPreviewPoll.vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';import type { PreviewProps } from '@/components/posts/previews/types';import date from '@/date';+import { blank, filled } from '@/lib/helpers';+import { type PreviewPoll, previewPollOf } from '@/lib/poll';const props = defineProps<PreviewProps>();@@ -19,6 +22,22 @@ const props = defineProps<PreviewProps>();const contentWarning = computed((): string =>String(props.meta?.spoiler_text ?? '').trim(),);++const previewPoll = computed((): PreviewPoll | null =>+ previewPollOf(props.contentType, props.meta, props.publishConfig),+);++/** A poll shows no link card. */+const showsLinkCard = computed((): boolean => blank(previewPoll.value));++/** The poll stays behind a content warning, like the rest of the status. */+const shownPoll = computed((): PreviewPoll | null => {+ if (filled(contentWarning.value)) {+ return null;+ }++ return previewPoll.value;+});</script><template>@@ -35,7 +54,7 @@ const contentWarning = computed((): string =>link-tone="info"host-onlytags="muted"- link-card+ :link-card="showsLinkCard":link-card-options="{ band: true, titleFirst: true }":actions="[{ icon: IconArrowBackUp },@@ -60,6 +79,9 @@ const contentWarning = computed((): string =></p></div></template>+ <template v-if="shownPoll" #default>+ <MastodonPreviewPoll :poll="shownPoll.poll" :limits="shownPoll.limits" />+ </template><template #aside><spanclass="flex shrink-0 items-center gap-1 self-start pt-1 text-muted-foreground"diff --git a/resources/js/components/posts/previews/MastodonPreviewPoll.vue b/resources/js/components/posts/previews/MastodonPreviewPoll.vuenew file mode 100644index 000000000..0d050f7dd--- /dev/null+++ b/resources/js/components/posts/previews/MastodonPreviewPoll.vue@@ -0,0 +1,52 @@+<script setup lang="ts">+import { computed } from 'vue';++import {+ editablePollOptions,+ formatPollLength,+ pollDurationOf,+} from '@/lib/poll';+import type { Poll, PollLimits } from '@/types/poll';++const props = defineProps<{+ poll: Partial<Poll>;+ /** The account's poll limits, from its `publishConfig`. */+ limits: PollLimits;+}>();++const options = computed((): string[] =>+ editablePollOptions(props.poll.options, props.limits.minOptions),+);++const length = computed((): string =>+ formatPollLength(pollDurationOf(props.poll, props.limits)),+);++/** A multiple choice poll shows square boxes, a single choice round ones. */+const markerClass = computed((): string => {+ if (props.poll.multiple === true) {+ return 'rounded-sm';+ }++ return 'rounded-full';+});+</script>++<template>+ <div class="space-y-2.5" data-testid="mastodon-preview-poll">+ <div+ v-for="(option, index) in options"+ :key="index"+ class="flex min-h-6 items-center gap-2.5"+ >+ <span+ class="size-[18px] shrink-0 border border-border-strong"+ :class="markerClass"+ />+ <span class="truncate">{{ option }}</span>+ </div>+ <p class="text-muted-foreground">+ {{ $t('posts.composer.preview.poll_summary', { time: length }) }}+ </p>+ </div>+</template>diff --git a/resources/js/components/posts/previews/PlatformPreview.vue b/resources/js/components/posts/previews/PlatformPreview.vueindex 16b4769f7..8de7d06d8 100644--- a/resources/js/components/posts/previews/PlatformPreview.vue+++ b/resources/js/components/posts/previews/PlatformPreview.vue@@ -27,16 +27,17 @@ import {threadReplyContentType,} from '@/lib/threadReplies';import { withCoversFor } from '@/lib/videoFrame';+import type { ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';-import { THREAD_PLATFORMS } from '@/types/network-options';-import type { PublishConfig } from '@/types/platform';+import { isThreadPlatform } from '@/types/network-options';+import type { PlatformValue, PublishConfig } from '@/types/platform';interface Props {- platform: string;+ platform: PlatformValue;socialAccount: PreviewAccount | null | undefined;content: string;media: MediaItem[];- contentType?: string;+ contentType?: ContentTypeValue;meta?: Record<string, any>;/** Local scheduled datetime (datetime-local); falls back to now in previews. */postedAt?: string | null;@@ -68,18 +69,25 @@ const takesCoverImage = computed((): boolean => {const previewMedia = computed((): MediaItem[] => withCoversFor(props.media, takesCoverImage.value));-const shownReplies = computed((): { reply: ThreadReply; index: number }[] =>- THREAD_PLATFORMS.includes(props.platform) && !repliesAreComments(props.platform)- ? threadRepliesOf(props.meta)- .map((reply, index) => ({ reply, index }))- .filter(- ({ reply }) =>- filled(reply.text) ||- filled(reply.media) ||- filled(reply.poll),- )- : [],-);+const shownReplies = computed((): { reply: ThreadReply; index: number }[] => {+ if (!isThreadPlatform(props.platform) || repliesAreComments(props.platform)) {+ return [];+ }++ return threadRepliesOf(props.meta)+ .map((reply, index) => ({ reply, index }))+ .filter(({ reply }) => hasContent(reply));+});++/** A reply shows once it holds text, media or a poll. */+const hasContent = (reply: ThreadReply): boolean => {+ if (filled(reply.text) || filled(reply.media)) {+ return true;+ }++ return filled(reply.poll);+};+const threadReplies = computed((): ThreadReply[] =>shownReplies.value.map(({ reply }) => reply),);diff --git a/resources/js/components/posts/previews/PreviewTextPost.vue b/resources/js/components/posts/previews/PreviewTextPost.vueindex bb9800ca9..481c711a3 100644--- a/resources/js/components/posts/previews/PreviewTextPost.vue+++ b/resources/js/components/posts/previews/PreviewTextPost.vue@@ -12,7 +12,7 @@ import type {PreviewMediaLayout,} from '@/components/posts/previews/types';import VerifiedBadge from '@/components/VerifiedBadge.vue';-import { useLinkCard } from '@/composables/useLinkCard';+import { firstHttpUrl, useLinkCard } from '@/composables/useLinkCard';import type { MediaItem } from '@/types/media';@@ -80,10 +80,23 @@ const props = withDefaults(},);+/** The link whose card the preview draws: none when it shows no card, so nothing is fetched. */+const cardUrl = (text: string): string | null => {+ if (!props.linkCard) {+ return null;+ }++ if (props.linkUrl !== undefined) {+ return props.linkUrl(text);+ }++ return firstHttpUrl(text);+};+const { card, loading } = useLinkCard(toRef(props, 'content'),toRef(props, 'media'),- props.linkUrl,+ cardUrl,);const isStacked = computed((): boolean => props.variant === 'stacked');diff --git a/resources/js/components/posts/previews/ThreadsPreview.vue b/resources/js/components/posts/previews/ThreadsPreview.vueindex 7ee24dad6..3b0217236 100644--- a/resources/js/components/posts/previews/ThreadsPreview.vue+++ b/resources/js/components/posts/previews/ThreadsPreview.vue@@ -12,7 +12,10 @@ import {import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';+import ThreadsPreviewPoll from '@/components/posts/previews/ThreadsPreviewPoll.vue';import type { PreviewProps } from '@/components/posts/previews/types';+import { blank } from '@/lib/helpers';+import { type PreviewPoll, previewPollOf } from '@/lib/poll';import { ContentType } from '@/types/content-type';@@ -21,6 +24,19 @@ const props = defineProps<PreviewProps>();const isGhost = computed((): boolean => props.contentType === ContentType.ThreadsGhostPost,);++const previewPoll = computed((): PreviewPoll | null =>+ previewPollOf(props.contentType, props.meta, props.publishConfig),+);++/** A ghost post and a poll show no link card. */+const showsLinkCard = computed((): boolean => {+ if (isGhost.value) {+ return false;+ }++ return blank(previewPoll.value);+});</script><template>@@ -35,7 +51,7 @@ const isGhost = computed(tags="bare"media-layout="peek"mute-badge- :link-card="!isGhost"+ :link-card="showsLinkCard":content-testid="isGhost ? 'threads-ghost-bubble' : undefined":text-class="isGhost@@ -64,6 +80,11 @@ const isGhost = computed(<template v-if="isGhost" #aside><IconDots class="ml-auto size-4 shrink-0 self-center" /></template>+ <ThreadsPreviewPoll+ v-if="previewPoll"+ :poll="previewPoll.poll"+ :limits="previewPoll.limits"+ /><divv-if="isGhost"class="flex items-center gap-6 pt-1 text-muted-foreground"diff --git a/resources/js/components/posts/previews/ThreadsPreviewPoll.vue b/resources/js/components/posts/previews/ThreadsPreviewPoll.vuenew file mode 100644index 000000000..345f18837--- /dev/null+++ b/resources/js/components/posts/previews/ThreadsPreviewPoll.vue@@ -0,0 +1,28 @@+<script setup lang="ts">+import { computed } from 'vue';++import { editablePollOptions } from '@/lib/poll';+import type { Poll, PollLimits } from '@/types/poll';++const props = defineProps<{+ poll: Partial<Poll>;+ /** The account's poll limits, from its `publishConfig`. */+ limits: PollLimits;+}>();++const options = computed((): string[] =>+ editablePollOptions(props.poll.options, props.limits.minOptions),+);+</script>++<template>+ <div class="space-y-2 pt-1" data-testid="threads-preview-poll">+ <div+ v-for="(option, index) in options"+ :key="index"+ class="min-h-9 truncate rounded-xl border border-border-strong px-3 py-2 font-medium"+ >+ {{ option }}+ </div>+ </div>+</template>diff --git a/resources/js/components/posts/previews/XPreview.vue b/resources/js/components/posts/previews/XPreview.vueindex 42b2f347e..a046d2d20 100644--- a/resources/js/components/posts/previews/XPreview.vue+++ b/resources/js/components/posts/previews/XPreview.vue@@ -12,22 +12,17 @@ import { computed } from 'vue';import PreviewTextPost from '@/components/posts/previews/PreviewTextPost.vue';import type { PreviewProps } from '@/components/posts/previews/types';import XPreviewPoll from '@/components/posts/previews/XPreviewPoll.vue';-import { pollLimitsOf } from '@/lib/xPoll';-import { ContentType } from '@/types/content-type';-import type { XPoll } from '@/types/x';+import { blank } from '@/lib/helpers';+import { type PreviewPoll, previewPollOf } from '@/lib/poll';const props = defineProps<PreviewProps>();-/** The poll the post shows: only a Poll post has one, whatever its meta still holds. */-const poll = computed((): Partial<XPoll> | undefined => {- if (props.contentType !== ContentType.XPoll) {- return undefined;- }+const previewPoll = computed((): PreviewPoll | null =>+ previewPollOf(props.contentType, props.meta, props.publishConfig),+);- return props.meta?.poll;-});--const pollLimits = computed(() => pollLimitsOf(props.publishConfig));+/** A poll shows no link card. */+const showsLinkCard = computed((): boolean => blank(previewPoll.value));</script><template>@@ -39,7 +34,7 @@ const pollLimits = computed(() => pollLimitsOf(props.publishConfig));:handle="`@${socialAccount.username || socialAccount.handle_label}`"content-testid="x-preview-content"media-layout="grid"- :link-card="!poll"+ :link-card="showsLinkCard":actions="[{ icon: IconMessageCircle },{ icon: IconRepeat },@@ -48,8 +43,8 @@ const pollLimits = computed(() => pollLimitsOf(props.publishConfig));]":trailing-actions="[{ icon: IconBookmark }, { icon: IconUpload }]">- <template v-if="poll && pollLimits" #default>- <XPreviewPoll :poll="poll" :limits="pollLimits" />+ <template v-if="previewPoll" #default>+ <XPreviewPoll :poll="previewPoll.poll" :limits="previewPoll.limits" /></template></PreviewTextPost></template>diff --git a/resources/js/components/posts/previews/XPreviewPoll.vue b/resources/js/components/posts/previews/XPreviewPoll.vueindex a150a95f9..f7fea9666 100644--- a/resources/js/components/posts/previews/XPreviewPoll.vue+++ b/resources/js/components/posts/previews/XPreviewPoll.vue@@ -1,13 +1,17 @@<script setup lang="ts">import { computed } from 'vue';-import { editablePollOptions, formatPollLength } from '@/lib/xPoll';-import type { XPoll, XPollLimits } from '@/types/x';+import {+ editablePollOptions,+ formatPollLength,+ pollDurationOf,+} from '@/lib/poll';+import type { Poll, PollLimits } from '@/types/poll';const props = defineProps<{- poll: Partial<XPoll>;+ poll: Partial<Poll>;/** The account's poll limits, from its `publishConfig`. */- limits: XPollLimits;+ limits: PollLimits;}>();const options = computed((): string[] =>@@ -15,7 +19,7 @@ const options = computed((): string[] =>);const length = computed((): string =>- formatPollLength(props.poll.duration_minutes ?? props.limits.defaultDuration),+ formatPollLength(pollDurationOf(props.poll, props.limits)),);</script>diff --git a/resources/js/components/posts/previews/types.ts b/resources/js/components/posts/previews/types.tsindex 04844257e..1dcde55c8 100644--- a/resources/js/components/posts/previews/types.ts+++ b/resources/js/components/posts/previews/types.ts@@ -1,5 +1,6 @@import type { Component } from 'vue';+import type { ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';import type { PublishConfig } from '@/types/platform';import type { VerifiedBadge } from '@/types/social-account';@@ -19,7 +20,7 @@ export interface PreviewProps {socialAccount: PreviewAccount;content: string;media: MediaItem[];- contentType?: string;+ contentType?: ContentTypeValue;meta?: Record<string, any>;postedAt?: string | null;/** The account's `publishConfig` (`Platform::publishConfig()`), e.g. X's poll limits. */diff --git a/resources/js/components/publish/PostDetailsDialog.vue b/resources/js/components/publish/PostDetailsDialog.vueindex 6196e6f51..2b8d9a875 100644--- a/resources/js/components/publish/PostDetailsDialog.vue+++ b/resources/js/components/publish/PostDetailsDialog.vue@@ -47,11 +47,11 @@ import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';import date from '@/date';import dayjs from '@/dayjs';import { filled } from '@/lib/helpers';+import { postPollResults } from '@/lib/poll';import { isDeletedOnNetwork, postPermalink } from '@/lib/postNetwork';import { postThreadOf } from '@/lib/postThread';import { compactPublicationMetrics } from '@/lib/publicationMetrics';import { isRecurring } from '@/lib/recurrence';-import { postPollResults } from '@/lib/xPoll';import type { MediaItem } from '@/types/media';import { Platform } from '@/types/platform';import { PostOrigin, PostStatus } from '@/types/post';diff --git a/resources/js/components/publish/PostPollResults.vue b/resources/js/components/publish/PostPollResults.vueindex 00da9a917..168f291d6 100644--- a/resources/js/components/publish/PostPollResults.vue+++ b/resources/js/components/publish/PostPollResults.vue@@ -2,7 +2,7 @@import { computed } from 'vue';import date from '@/date';-import { transform } from '@/lib/helpers';+import { filled, transform } from '@/lib/helpers';import { formatFullNumber, formatPercent } from '@/lib/utils';import type { PublicationPoll } from '@/types/analytics';@@ -30,13 +30,40 @@ const topVotes = computed((): number => Math.max(...votes.value));const hasVotes = computed((): boolean => totalVotes.value > 0);+/** Whether the network hides the votes until the poll ends (Mastodon). */+const totalsHidden = computed((): boolean => props.poll.totals_hidden === true);++/**+ * What each share is of: the people who voted on a multiple choice poll+ * (Mastodon counts each voter once, whatever they picked), else the votes.+ */+const shareBase = computed((): number => {+ if (filled(props.poll.voters)) {+ return props.poll.voters;+ }++ return totalVotes.value;+});++/**+ * The total under the choices, counted like the shares: the people who voted+ * on a multiple choice poll ("3 people"), else the votes.+ */+const summary = computed((): { key: string; count: number } => {+ if (filled(props.poll.voters)) {+ return { key: 'posts.poll_results.voters', count: props.poll.voters };+ }++ return { key: 'posts.poll_results.votes', count: totalVotes.value };+});+/** A choice's percentage of the votes; none before the first vote. */const percentOf = (count: number): number => {- if (!hasVotes.value) {+ if (!hasVotes.value || shareBase.value === 0) {return 0;}- return (count / totalVotes.value) * 100;+ return (count / shareBase.value) * 100;};/** The choice with the most votes leads, ties included; none before the first vote. */@@ -102,6 +129,7 @@ const status = computed((): PollStatus | null => {/><span class="relative min-w-0 truncate">{{ row.label }}</span><span+ v-if="!totalsHidden"class="relative shrink-0 tabular-nums":data-testid="`${testId}-option-${index}-votes`">@@ -119,13 +147,16 @@ const status = computed((): PollStatus | null => {class="text-xs text-muted-foreground":data-testid="`${testId}-summary`">- {{- $tChoice('posts.poll_results.votes', totalVotes, {- count: formatFullNumber(totalVotes),+ <template v-if="totalsHidden">{{+ $t('posts.poll_results.hidden')+ }}</template>+ <template v-else>{{+ $tChoice(summary.key, summary.count, {+ count: formatFullNumber(summary.count),})- }}- <template v-if="status"- >· {{ $t(status.key, status.replacements) }}</template+ }}</template>+ <template v-if="status">+ · {{ $t(status.key, status.replacements) }}</template></p></div>diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vueindex 7bfc60499..addc46e60 100644--- a/resources/js/components/publish/PostTimelineCard.vue+++ b/resources/js/components/publish/PostTimelineCard.vue@@ -64,12 +64,12 @@ import date from '@/date';import dayjs from '@/dayjs';import { blank, filled } from '@/lib/helpers';import { isImage, isVideo } from '@/lib/mediaType';+import { postPollResults } from '@/lib/poll';import { postAttemptAt, postNoTimeKey } from '@/lib/postCard';import { isDeletedOnNetwork, postPermalink } from '@/lib/postNetwork';import { postThreadOf } from '@/lib/postThread';import { compactPublicationMetrics } from '@/lib/publicationMetrics';import { recurrenceRuleOf } from '@/lib/recurrence';-import { postPollResults } from '@/lib/xPoll';import { Platform } from '@/types/platform';import {PostOrigin,@@ -277,6 +277,8 @@ const CONTENT_TYPE_ICONS: Record<string, Component> = {facebook_reel: IconCirclePlay,threads_ghost_post: IconGhost2,x_poll: IconListDetails,+ mastodon_poll: IconListDetails,+ threads_poll: IconListDetails,};const contentTypeIcon = computed(() =>diff --git a/resources/js/composables/composer/useComposerPoll.ts b/resources/js/composables/composer/useComposerPoll.tsindex 2b0d97eba..d19362346 100644--- a/resources/js/composables/composer/useComposerPoll.ts+++ b/resources/js/composables/composer/useComposerPoll.ts@@ -1,16 +1,23 @@import type {ComposerAccount,+ DestinationDraft,NetworkGroup,usePostComposition,} from '@/composables/usePostComposition';import { blank, filled, transform } from '@/lib/helpers';+import { newPoll } from '@/lib/poll';import { type ThreadReply, withReplyPoll } from '@/lib/threadReplies';-import { newPoll } from '@/lib/xPoll';import {- ContentType,+ type ContentTypeValue,MEDIALESS_CONTENT_TYPE_REASONS,+ POLL_CONTENT_TYPES,+ POLL_POST_CONTENT_TYPES,} from '@/types/content-type';-import type { XPoll, XPollLimits } from '@/types/x';+import {+ isReplyPollPlatform,+ THREAD_REPLY_POLL_CONTENT_TYPES,+} from '@/types/network-options';+import type { Poll, PollLimits } from '@/types/poll';/** What the composer gives the card polls: each card's destination and the override that changes it. */type ComposerCards = Pick<@@ -18,6 +25,9 @@ type ComposerCards = Pick<'resolvedDestination' | 'setGroupOverride'>;+/** A card's meta as the composer keeps it: what the post sends as `meta`. */+type CardMeta = Record<string, any>;+/** What the composer's thread gives the reply polls: the reply being edited, the replies, a reply's text limit, and whether a reply's file is still uploading. */export interface ComposerThread {activeReply: (group: NetworkGroup) => ThreadReply | undefined;@@ -28,20 +38,21 @@ export interface ComposerThread {}/**- * The X polls of each composer card: the post's (picking Poll starts one,- * editing writes it into the card's meta, and any other type drops it, as the- * server does) and each thread reply's (the toolbar's poll button).+ * The polls of each composer card (X, Mastodon and Threads): the post's+ * (picking Poll starts one, editing writes it into the card's meta, and any+ * other type drops it, as the server does) and each thread reply's (the+ * toolbar's poll button).*/export const useComposerPoll = (composition: ComposerCards,- pollLimits: (account: ComposerAccount) => XPollLimits | null,+ pollLimits: (account: ComposerAccount) => PollLimits | null,thread: ComposerThread,) => {- const destination = (group: NetworkGroup) =>+ const destination = (group: NetworkGroup): DestinationDraft =>composition.resolvedDestination(group.anchor);/** The card's poll limits, or null on a network without polls. */- const groupPollLimits = (group: NetworkGroup): XPollLimits | null =>+ const groupPollLimits = (group: NetworkGroup): PollLimits | null =>pollLimits(group.anchor);/** An account's text limit for its post type: a poll's question keeps the poll's cap, even with long posts. */@@ -50,9 +61,9 @@ export const useComposerPoll = (limit: number | undefined,): number | undefined => {const questionCap = pollLimits(account)?.questionMaxLength;- const isPoll =- composition.resolvedDestination(account).content_type ===- ContentType.XPoll;+ const isPoll = POLL_CONTENT_TYPES.has(+ composition.resolvedDestination(account).content_type,+ );if (isPoll && filled(limit) && filled(questionCap)) {return Math.min(limit, questionCap);@@ -67,22 +78,30 @@ export const useComposerPoll = (* arrives as `[]` (PHP's empty array), and putting back `{}` instead would* count as an unsaved change.*/- const metaBeforePoll = new Map<string, Record<string, any>>();+ const metaBeforePoll = new Map<string, CardMeta>();/*** Each card's meta, poll included, from before another type was picked:* picking Poll again brings the poll back, and the very same object when* nothing else changed, so its keys keep their order and the switch counts* as no change.*/- const metaBeforeOtherType = new Map<string, Record<string, any>>();+ const metaBeforeOtherType = new Map<string, CardMeta>();const isPollGroup = (group: NetworkGroup): boolean =>- destination(group).content_type === ContentType.XPoll;+ POLL_CONTENT_TYPES.has(destination(group).content_type);++ /** The card's poll, or an empty one before Poll is picked. */+ const groupPoll = (group: NetworkGroup): Partial<Poll> => {+ const poll = destination(group).meta?.poll;- const groupPoll = (group: NetworkGroup): Partial<XPoll> =>- destination(group).meta?.poll ?? {};+ if (!filled(poll)) {+ return {};+ }++ return poll;+ };- const setGroupPoll = (group: NetworkGroup, poll: XPoll): void => {+ const setGroupPoll = (group: NetworkGroup, poll: Poll): void => {composition.setGroupOverride(group.key, 'meta', {...destination(group).meta,poll,@@ -94,15 +113,15 @@ export const useComposerPoll = (* stored empty arrives as `[]` (PHP's empty array) and counts as `{}`.*/const sameMeta = (- first: Record<string, any>,- second: Record<string, any>,+ first: CardMeta,+ second: CardMeta,): boolean => JSON.stringify({ ...first }) === JSON.stringify({ ...second });/** Takes a card's saved meta out of `saved`, so it is used once. */const takeSaved = (- saved: Map<string, Record<string, any>>,+ saved: Map<string, CardMeta>,group: NetworkGroup,- ): Record<string, any> | undefined => {+ ): CardMeta | undefined => {const meta = saved.get(group.key);saved.delete(group.key);@@ -111,9 +130,9 @@ export const useComposerPoll = (/** The card's last poll back on its meta: the very same object when nothing else changed. */const restorePoll = (- previous: Record<string, any>,- current: Record<string, any>,- ): Record<string, any> => {+ previous: CardMeta,+ current: CardMeta,+ ): CardMeta => {const { poll, ...previousMeta } = previous;if (sameMeta(previousMeta, current)) {@@ -126,8 +145,8 @@ export const useComposerPoll = (/** Picking Poll: the card's last poll comes back, else a new one starts. */const metaWithPoll = (group: NetworkGroup,- current: Record<string, any>,- ): Record<string, any> => {+ current: CardMeta,+ ): CardMeta => {metaBeforePoll.set(group.key, current);const previous = takeSaved(metaBeforeOtherType, group);@@ -141,9 +160,9 @@ export const useComposerPoll = (/** Picking another type: the poll goes, and the meta from before it comes back when nothing else changed. */const metaWithoutPoll = (group: NetworkGroup,- current: Record<string, any>,- meta: Record<string, any>,- ): Record<string, any> => {+ current: CardMeta,+ meta: CardMeta,+ ): CardMeta => {metaBeforeOtherType.set(group.key, current);const before = takeSaved(metaBeforePoll, group);@@ -160,12 +179,12 @@ export const useComposerPoll = (*/const pollMetaForContentType = (group: NetworkGroup,- contentType: string,- ): Record<string, any> | null => {+ contentType: ContentTypeValue,+ ): CardMeta | null => {const current = destination(group).meta ?? {};const { poll, ...meta } = current;const hasPoll = poll !== undefined;- const picksPoll = contentType === ContentType.XPoll;+ const picksPoll = POLL_CONTENT_TYPES.has(contentType);if (picksPoll && !hasPoll) {return metaWithPoll(group, current);@@ -186,7 +205,7 @@ export const useComposerPoll = (/** Picks the card's post type, adding or dropping its poll with it. */const setGroupContentType = (group: NetworkGroup,- contentType: string,+ contentType: ContentTypeValue,): void => {const meta = pollMetaForContentType(group, contentType);composition.setGroupOverride(group.key, 'content_type', contentType);@@ -196,9 +215,15 @@ export const useComposerPoll = (}};- /** The card's Remove poll: back to a plain post, and picking Poll again starts a new one. */+ /** The card's Remove poll: back to the network's plain post, and picking Poll again starts a new one. */const removeGroupPoll = (group: NetworkGroup): void => {- setGroupContentType(group, ContentType.XPost);+ const postType =+ POLL_POST_CONTENT_TYPES[destination(group).content_type];++ if (filled(postType)) {+ setGroupContentType(group, postType);+ }+forgetGroupPoll(group);};@@ -208,9 +233,16 @@ export const useComposerPoll = (metaBeforeOtherType.clear();};- /** A reply poll's question keeps the poll's cap, even on an account with long posts. */- const replyPollLimit = (group: NetworkGroup): number =>- groupPollLimits(group)?.questionMaxLength ?? Infinity;+ /** A reply poll's question keeps the poll's cap (X), even on an account with long posts; no cap elsewhere. */+ const replyPollLimit = (group: NetworkGroup): number => {+ const cap = groupPollLimits(group)?.questionMaxLength;++ if (!filled(cap)) {+ return Infinity;+ }++ return cap;+ };/** A reply's text limit: a poll's question keeps the poll's cap, even on an account with long posts. */const replyTextLimit = (@@ -229,7 +261,7 @@ export const useComposerPoll = (const setReplyPoll = (group: NetworkGroup,replyKey: string,- poll: XPoll | undefined,+ poll: Poll | undefined,): void => {const replies = thread.replies(group).map((reply) => {if (reply.key !== replyKey) {@@ -242,27 +274,43 @@ export const useComposerPoll = (thread.setReplies(group, replies);};- /** The poll button shows on an X reply that is not a poll yet. */+ /** The poll button shows on a reply that is not a poll yet, on a network whose replies can be polls. */const replyPollAvailable = (group: NetworkGroup): boolean => {const reply = thread.activeReply(group);- return (- filled(reply) && blank(reply.poll) && filled(groupPollLimits(group))- );+ if (!filled(reply) || filled(reply.poll)) {+ return false;+ }++ if (!isReplyPollPlatform(group.platform)) {+ return false;+ }++ return filled(groupPollLimits(group));};/** Media in the reply (or on its way) keeps the poll button off, saying why. */const replyPollDisabledReasonKey = (group: NetworkGroup): string | null => {const reply = thread.activeReply(group);- const carriesMedia =- filled(reply) &&- (filled(reply.media) || thread.uploading(group, reply));- if (carriesMedia) {- return MEDIALESS_CONTENT_TYPE_REASONS[ContentType.XPoll];+ if (!filled(reply) || !isReplyPollPlatform(group.platform)) {+ return null;}- return null;+ if (blank(reply.media) && !thread.uploading(group, reply)) {+ return null;+ }++ const reason =+ MEDIALESS_CONTENT_TYPE_REASONS[+ THREAD_REPLY_POLL_CONTENT_TYPES[group.platform]+ ];++ if (!filled(reason)) {+ return null;+ }++ return reason;};const addReplyPoll = (group: NetworkGroup): void => {@@ -282,7 +330,6 @@ export const useComposerPoll = (setGroupPoll,setGroupContentType,removeGroupPoll,- forgetGroupPoll,forgetPolls,replyPollLimit,replyTextLimit,diff --git a/resources/js/composables/usePlatformLogo.ts b/resources/js/composables/usePlatformLogo.tsindex 846bd8377..3c4b8dff7 100644--- a/resources/js/composables/usePlatformLogo.ts+++ b/resources/js/composables/usePlatformLogo.ts@@ -1,79 +1,83 @@import { derivesContentType } from '@/lib/derivedContentType';+import { filled } from '@/lib/helpers';+import { ContentType, type ContentTypeValue } from '@/types/content-type';+import { Platform } from '@/types/platform';const PLATFORM_LOGOS: Record<string, string> = {- linkedin: '/images/accounts/linkedin.png',- 'linkedin-page': '/images/accounts/linkedin.png',- x: '/images/accounts/x.png',- tiktok: '/images/accounts/tiktok.png',- instagram: '/images/accounts/instagram.png',- 'instagram-facebook': '/images/accounts/instagram.png',- facebook: '/images/accounts/facebook.png',- youtube: '/images/accounts/youtube.png',- threads: '/images/accounts/threads.png',- bluesky: '/images/accounts/bluesky.png',- pinterest: '/images/accounts/pinterest.png',- mastodon: '/images/accounts/mastodon.png',- telegram: '/images/accounts/telegram.png',- discord: '/images/accounts/discord.png',- google_business: '/images/accounts/google_business.png',+ [Platform.LinkedIn]: '/images/accounts/linkedin.png',+ [Platform.LinkedInPage]: '/images/accounts/linkedin.png',+ [Platform.X]: '/images/accounts/x.png',+ [Platform.TikTok]: '/images/accounts/tiktok.png',+ [Platform.Instagram]: '/images/accounts/instagram.png',+ [Platform.InstagramFacebook]: '/images/accounts/instagram.png',+ [Platform.Facebook]: '/images/accounts/facebook.png',+ [Platform.YouTube]: '/images/accounts/youtube.png',+ [Platform.Threads]: '/images/accounts/threads.png',+ [Platform.Bluesky]: '/images/accounts/bluesky.png',+ [Platform.Pinterest]: '/images/accounts/pinterest.png',+ [Platform.Mastodon]: '/images/accounts/mastodon.png',+ [Platform.Telegram]: '/images/accounts/telegram.png',+ [Platform.Discord]: '/images/accounts/discord.png',+ [Platform.GoogleBusiness]: '/images/accounts/google_business.png',};const PLATFORM_LABELS: Record<string, string> = {- linkedin: 'LinkedIn',- 'linkedin-page': 'LinkedIn Page',- x: 'X',- tiktok: 'TikTok',- instagram: 'Instagram',- 'instagram-facebook': 'Instagram',- facebook: 'Facebook',- youtube: 'YouTube',- threads: 'Threads',- bluesky: 'Bluesky',- pinterest: 'Pinterest',- mastodon: 'Mastodon',- telegram: 'Telegram',- discord: 'Discord',- google_business: 'Google Business Profile',+ [Platform.LinkedIn]: 'LinkedIn',+ [Platform.LinkedInPage]: 'LinkedIn Page',+ [Platform.X]: 'X',+ [Platform.TikTok]: 'TikTok',+ [Platform.Instagram]: 'Instagram',+ [Platform.InstagramFacebook]: 'Instagram',+ [Platform.Facebook]: 'Facebook',+ [Platform.YouTube]: 'YouTube',+ [Platform.Threads]: 'Threads',+ [Platform.Bluesky]: 'Bluesky',+ [Platform.Pinterest]: 'Pinterest',+ [Platform.Mastodon]: 'Mastodon',+ [Platform.Telegram]: 'Telegram',+ [Platform.Discord]: 'Discord',+ [Platform.GoogleBusiness]: 'Google Business Profile',};-const PLATFORM_CONTENT_TYPES: Record<string, string[]> = {- instagram: ['instagram_feed', 'instagram_reel', 'instagram_story'],- 'instagram-facebook': [- 'instagram_feed',- 'instagram_reel',- 'instagram_story',+const PLATFORM_CONTENT_TYPES: Readonly<Record<string, ContentTypeValue[]>> = {+ [Platform.Instagram]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory],+ [Platform.InstagramFacebook]: [+ ContentType.InstagramFeed,+ ContentType.InstagramReel,+ ContentType.InstagramStory,],- linkedin: ['linkedin_post'],- 'linkedin-page': ['linkedin_page_post'],- facebook: ['facebook_post', 'facebook_reel', 'facebook_story'],- tiktok: ['tiktok_video', 'tiktok_photo'],- youtube: ['youtube_short'],- x: ['x_post', 'x_poll'],- threads: ['threads_post', 'threads_ghost_post'],- pinterest: ['pinterest_pin', 'pinterest_video_pin', 'pinterest_carousel'],- bluesky: ['bluesky_post'],- mastodon: ['mastodon_post'],- telegram: ['telegram_post'],- discord: ['discord_message'],- google_business: ['google_business_post'],+ [Platform.LinkedIn]: [ContentType.LinkedInPost],+ [Platform.LinkedInPage]: [ContentType.LinkedInPagePost],+ [Platform.Facebook]: [ContentType.FacebookPost, ContentType.FacebookReel, ContentType.FacebookStory],+ [Platform.TikTok]: [ContentType.TikTokVideo, ContentType.TikTokPhoto],+ [Platform.YouTube]: [ContentType.YouTubeShort],+ [Platform.X]: [ContentType.XPost, ContentType.XPoll],+ [Platform.Threads]: [ContentType.ThreadsPost, ContentType.ThreadsGhostPost, ContentType.ThreadsPoll],+ [Platform.Pinterest]: [ContentType.PinterestPin, ContentType.PinterestVideoPin, ContentType.PinterestCarousel],+ [Platform.Bluesky]: [ContentType.BlueskyPost],+ [Platform.Mastodon]: [ContentType.MastodonPost, ContentType.MastodonPoll],+ [Platform.Telegram]: [ContentType.TelegramPost],+ [Platform.Discord]: [ContentType.DiscordMessage],+ [Platform.GoogleBusiness]: [ContentType.GoogleBusinessPost],};-const PLATFORM_CONTENT_TYPE_BADGES: Record<string, string[]> = {- instagram: ['instagram_reel', 'instagram_story'],- 'instagram-facebook': ['instagram_reel', 'instagram_story'],- facebook: ['facebook_reel', 'facebook_story'],- threads: ['threads_ghost_post'],- x: ['x_poll'],+const PLATFORM_CONTENT_TYPE_BADGES: Readonly<Record<string, ContentTypeValue[]>> = {+ [Platform.Instagram]: [ContentType.InstagramReel, ContentType.InstagramStory],+ [Platform.InstagramFacebook]: [ContentType.InstagramReel, ContentType.InstagramStory],+ [Platform.Facebook]: [ContentType.FacebookReel, ContentType.FacebookStory],+ [Platform.Threads]: [ContentType.ThreadsGhostPost, ContentType.ThreadsPoll],+ [Platform.X]: [ContentType.XPoll],+ [Platform.Mastodon]: [ContentType.MastodonPoll],};export interface ContentTypeOption {- value: string;+ value: ContentTypeValue;labelKey: string;disabledReasonKey?: string;}export const getPlatformLogo = (platform: string): string =>- PLATFORM_LOGOS[platform] ?? PLATFORM_LOGOS.linkedin;+ PLATFORM_LOGOS[platform] ?? PLATFORM_LOGOS[Platform.LinkedIn];export const getPlatformLabel = (platform: string): string =>PLATFORM_LABELS[platform] ?? platform;@@ -112,8 +116,15 @@ export const hasMultipleContentTypes = (platform: string): boolean =>/** Translation key for a format explicitly shown as a badge on post cards. */export const getContentTypeBadgeKey = (platform: string,- contentType: string | null,-): string | null =>- contentType && PLATFORM_CONTENT_TYPE_BADGES[platform]?.includes(contentType)- ? translationKeyFor(contentType)- : null;+ contentType: ContentTypeValue | null,+): string | null => {+ if (!filled(contentType)) {+ return null;+ }++ if (!PLATFORM_CONTENT_TYPE_BADGES[platform]?.includes(contentType)) {+ return null;+ }++ return translationKeyFor(contentType);+};diff --git a/resources/js/composables/usePostComposition.ts b/resources/js/composables/usePostComposition.tsindex 50b3b0e65..9d27f37fe 100644--- a/resources/js/composables/usePostComposition.ts+++ b/resources/js/composables/usePostComposition.ts@@ -2,8 +2,9 @@ import { computed, ref } from 'vue';import { getContentTypeOptions } from '@/composables/usePlatformLogo';import { derivedContentTypeFor } from '@/lib/derivedContentType';+import type { ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';-import { Platform } from '@/types/platform';+import { Platform, type PlatformValue } from '@/types/platform';import {PostStatus,type QueuePositionValue,@@ -15,7 +16,7 @@ import type { SocialAccountStatusValue } from '@/types/social-account-status';export interface ComposerAccount {id: string;- platform: string;+ platform: PlatformValue;display_name: string;username: string;display_label: string;@@ -30,7 +31,7 @@ export interface ComposerAccount {export interface DestinationDraft {social_account_id: string;- content_type: string;+ content_type: ContentTypeValue;meta: Record<string, any>;content?: string;media?: MediaItem[];@@ -58,7 +59,7 @@ export interface ComposerInitialPost {schedule_mode?: ScheduleModeValue | null;queue_position?: QueuePositionValue | null;social_account_id: string;- content_type: string;+ content_type?: ContentTypeValue;meta: Record<string, any>;label_ids: string[];}@@ -78,7 +79,7 @@ type Override = DestinationOverride;export interface NetworkGroup {key: string;- platform: string;+ platform: PlatformValue;accounts: ComposerAccount[];anchor: ComposerAccount;}@@ -149,7 +150,7 @@ export const usePostComposition = (};const networkGroups = computed<NetworkGroup[]>(() => {- const members = new Map<string, ComposerAccount[]>();+ const members = new Map<PlatformValue, ComposerAccount[]>();const ordered = accounts().filter((account) =>selectedAccountIds.value.includes(account.id),);diff --git a/resources/js/lib/derivedContentType.ts b/resources/js/lib/derivedContentType.tsindex 756161e86..1694534ee 100644--- a/resources/js/lib/derivedContentType.ts+++ b/resources/js/lib/derivedContentType.ts@@ -1,13 +1,13 @@import { isVideo } from '@/lib/mediaType';-import { ContentType } from '@/types/content-type';+import { ContentType, type ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';-import { Platform } from '@/types/platform';+import { Platform, type PlatformValue } from '@/types/platform';/*** Networks that offer no post-type choice: the attached media decides it, so the* composer shows no type radios for them.*/-const DERIVED_CONTENT_TYPES: Partial<Record<string, (media: MediaItem[]) => string>> = {+const DERIVED_CONTENT_TYPES: Partial<Record<PlatformValue, (media: MediaItem[]) => ContentTypeValue>> = {[Platform.Pinterest]: (media) => {if (media.some((item) => isVideo(item))) {return ContentType.PinterestVideoPin;@@ -25,5 +25,5 @@ export const derivesContentType = (platform: string): boolean =>platform in DERIVED_CONTENT_TYPES;/** The content type the media decides on this network, or null when the user picks it. */-export const derivedContentTypeFor = (platform: string, media: MediaItem[]): string | null =>+export const derivedContentTypeFor = (platform: PlatformValue, media: MediaItem[]): ContentTypeValue | null =>DERIVED_CONTENT_TYPES[platform]?.(media) ?? null;diff --git a/resources/js/lib/linkPreview.ts b/resources/js/lib/linkPreview.tsindex 078b81526..1133d4a7d 100644--- a/resources/js/lib/linkPreview.ts+++ b/resources/js/lib/linkPreview.ts@@ -1,6 +1,10 @@import { firstHttpUrl } from '@/composables/useLinkCard';import { facebookLinkPreviewUrl } from '@/lib/facebookLinkPreview';-import { ContentType } from '@/types/content-type';+import {+ ContentType,+ type ContentTypeValue,+ POLL_CONTENT_TYPES,+} from '@/types/content-type';import { Platform } from '@/types/platform';/** Networks whose editor shows the link preview card under the text. */@@ -16,22 +20,34 @@ export const LINK_PREVIEW_PLATFORMS: ReadonlySet<string> = new Set([export const linkPreviewDroppable = (platform: string): boolean =>LINK_PREVIEW_PLATFORMS.has(platform) && platform !== Platform.Threads;+/** Post types that draw no link card: a Threads ghost post and every poll. */+const NO_LINK_CARD_CONTENT_TYPES: ReadonlySet<ContentTypeValue> = new Set([+ ContentType.ThreadsGhostPost,+ ...POLL_CONTENT_TYPES,+]);+/** URL whose card the editor shows, or null when the network has no card or the user dropped it. */export const linkPreviewUrl = (platform: string,- contentType: string,+ contentType: ContentTypeValue,meta: Record<string, any> | undefined,text: string,): string | null => {- if (- !LINK_PREVIEW_PLATFORMS.has(platform) ||- contentType === ContentType.ThreadsGhostPost ||- meta?.link_preview === false- ) {+ if (!LINK_PREVIEW_PLATFORMS.has(platform)) {+ return null;+ }++ if (NO_LINK_CARD_CONTENT_TYPES.has(contentType)) {return null;}- return platform === Platform.Facebook- ? facebookLinkPreviewUrl(text)- : firstHttpUrl(text);+ if (meta?.link_preview === false) {+ return null;+ }++ if (platform === Platform.Facebook) {+ return facebookLinkPreviewUrl(text);+ }++ return firstHttpUrl(text);};diff --git a/resources/js/lib/poll.ts b/resources/js/lib/poll.tsnew file mode 100644index 000000000..f65707efb--- /dev/null+++ b/resources/js/lib/poll.ts@@ -0,0 +1,304 @@+import dayjs from '@/dayjs';+import { activeLocale } from '@/language';+import { clamp, filled, transform } from '@/lib/helpers';+import { threadRepliesOf } from '@/lib/threadReplies';+import type {+ PublicationPoll,+ PublicationThreadPoll,+} from '@/types/analytics';+import { type ContentTypeValue, POLL_CONTENT_TYPES } from '@/types/content-type';+import type { PublishConfig } from '@/types/platform';+import type { Poll, PollDuration, PollLimits } from '@/types/poll';+import type { PostCard } from '@/types/publish';++export const MINUTES_PER_HOUR = 60;+export const HOURS_PER_DAY = 24;+const MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR;++/** The poll limits in an account's `publishConfig`, or null on a network without polls. */+export const pollLimitsOf = (+ publishConfig: PublishConfig | null | undefined,+): PollLimits | null => {+ const limits = publishConfig?.poll;++ if (!filled(limits)) {+ return null;+ }++ return limits;+};++/** Whether the author picks how long the poll runs (not on Threads, which sets it). */+export const pollHasDuration = (limits: PollLimits): boolean =>+ filled(limits.maxDuration);++/** The longest a poll runs, in whole days. */+export const pollMaxDays = (limits: PollLimits): number => {+ const longest = limits.maxDuration;++ if (!filled(longest)) {+ return 0;+ }++ return Math.floor(longest / MINUTES_PER_DAY);+};++export const splitPollDuration = (minutes: number): PollDuration => ({+ days: Math.floor(minutes / MINUTES_PER_DAY),+ hours: Math.floor((minutes % MINUTES_PER_DAY) / MINUTES_PER_HOUR),+ minutes: minutes % MINUTES_PER_HOUR,+});++/** Minutes for the picked parts, within the poll's shortest and longest length; the longest takes no hours or minutes. */+export const joinPollDuration = (+ parts: PollDuration,+ limits: PollLimits,+): number => {+ const { minDuration, maxDuration } = limits;++ if (!filled(minDuration) || !filled(maxDuration)) {+ return 0;+ }++ if (parts.days >= pollMaxDays(limits)) {+ return maxDuration;+ }++ const total =+ parts.days * MINUTES_PER_DAY ++ parts.hours * MINUTES_PER_HOUR ++ parts.minutes;++ return clamp(total, minDuration, maxDuration);+};++/** A poll's length: the stored one, else the network's default (0 where the network sets it). */+export const pollDurationOf = (+ poll: Partial<Poll>,+ limits: PollLimits,+): number => {+ if (filled(poll.duration_minutes)) {+ return poll.duration_minutes;+ }++ if (filled(limits.defaultDuration)) {+ return limits.defaultDuration;+ }++ return 0;+};++/** A new poll: empty choices, and the network's default length where the author picks one. */+export const newPoll = (limits: PollLimits): Poll => {+ const options = Array.from({ length: limits.minOptions }, () => '');++ if (!filled(limits.defaultDuration)) {+ return { options };+ }++ return { options, duration_minutes: limits.defaultDuration };+};++/**+ * A choice's length without the spaces around it, in UTF-16 units (a string's+ * `length`), so an emoji like 🐧 counts two: X counts that way, and the server+ * counts every network's choices the same (`Poll::choiceLength()`).+ */+export const pollChoiceLength = (choice: string): number => choice.trim().length;++/**+ * A choice cut to the longest the network accepts, counted by+ * `pollChoiceLength`: the last character goes until it fits, so a character+ * is never split and the spaces before the choice stay.+ */+export const fitPollChoice = (choice: string, maxLength: number): string => {+ let characters = Array.from(choice);++ while (pollChoiceLength(characters.join('')) > maxLength) {+ characters = characters.slice(0, -1);+ }++ return characters.join('');+};++/** The stored choices as text, none when the poll has no list yet. */+const storedPollOptions = (options: string[] | undefined): string[] => {+ if (!Array.isArray(options)) {+ return [];+ }++ return options.map(String);+};++/** The choices the editor shows: the stored ones, padded to the number a poll starts with. */+export const editablePollOptions = (+ options: string[] | undefined,+ minOptions: number,+): string[] => {+ const stored = storedPollOptions(options);++ return Array.from(+ { length: Math.max(minOptions, stored.length) },+ (_, index) => stored[index] ?? '',+ );+};++/** The units a poll's length is shown in, largest first, with their minutes. */+const POLL_LENGTH_UNITS = [+ ['day', MINUTES_PER_DAY],+ ['hour', MINUTES_PER_HOUR],+ ['minute', 1],+] as const;++/** The largest unit the length fills at least once; minutes below a minute. */+const pollLengthUnit = (+ minutes: number,+): (typeof POLL_LENGTH_UNITS)[number] => {+ const unit = POLL_LENGTH_UNITS.find(([, size]) => minutes >= size);++ if (!filled(unit)) {+ return POLL_LENGTH_UNITS[POLL_LENGTH_UNITS.length - 1];+ }++ return unit;+};++/** The poll's length in its largest whole unit ("1 day", "23 hours", "5 minutes"). */+export const formatPollLength = (minutes: number): string => {+ const [unit, size] = pollLengthUnit(minutes);++ return new Intl.NumberFormat(activeLocale.value, {+ style: 'unit',+ unit,+ unitDisplay: 'long',+ }).format(Math.floor(minutes / size));+};++/**+ * When a published poll ends: its length from publishing. Unknown before it+ * is published, and on a network that sets the length itself (Threads).+ */+const pollEndsAt = (+ poll: Partial<Poll>,+ publishedAt: string | null,+): string | null => {+ if (!filled(publishedAt) || !filled(poll.duration_minutes)) {+ return null;+ }++ return dayjs.utc(publishedAt).add(poll.duration_minutes, 'minute').toISOString();+};++/**+ * A poll before its network has been read for it: its choices with no votes.+ * Once its post is published it is open; before that, voting has not started.+ * Votes hidden until the end (Mastodon) show as hidden from the start.+ */+const unreadPollResult = (+ poll: Partial<Poll>,+ publishedAt: string | null,+): PublicationPoll => ({+ options: storedPollOptions(poll.options).map((label) => ({ label, votes: 0 })),+ voting_status: transform(publishedAt, (): 'open' => 'open'),+ end_datetime: pollEndsAt(poll, publishedAt),+ duration_minutes: poll.duration_minutes ?? null,+ totals_hidden: poll.hide_totals === true,+});++/** A post's own poll: only a poll type has one, whatever its meta still holds. */+export const pollOf = (+ contentType: ContentTypeValue | null | undefined,+ meta: Record<string, any> | null | undefined,+): Partial<Poll> | undefined => {+ if (!filled(contentType) || !POLL_CONTENT_TYPES.has(contentType)) {+ return undefined;+ }++ return meta?.poll;+};++/** What a network's preview draws for a poll: the post's poll and the account's poll limits. */+export interface PreviewPoll {+ poll: Partial<Poll>;+ limits: PollLimits;+}++/** The poll a preview draws, or null for a post that is no poll or an account without poll limits. */+export const previewPollOf = (+ contentType: ContentTypeValue | undefined,+ meta: Record<string, any> | undefined,+ publishConfig: PublishConfig | null | undefined,+): PreviewPoll | null => {+ const poll = pollOf(contentType, meta);+ const limits = pollLimitsOf(publishConfig);++ if (!filled(poll) || !filled(limits)) {+ return null;+ }++ return { poll, limits };+};++/** A post's own polls (the post's and its replies') with no votes yet. */+const unreadPollsOf = (+ post: PostCard,+): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => ({+ poll: transform(pollOf(post.content_type, post.meta), (poll) =>+ unreadPollResult(poll, post.published_at),+ ),+ threadPolls: threadRepliesOf(post.meta).flatMap((reply, index) => {+ if (filled(reply.poll)) {+ return [+ {+ reply: index,+ ...unreadPollResult(reply.poll, post.published_at),+ },+ ];+ }++ return [];+ }),+});++/** The polls the network returned at the last read, none before the first one. */+const readPollsOf = (+ post: PostCard,+): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => {+ const metrics = post.metrics;++ if (!filled(metrics) || !metrics.available) {+ return { poll: null, threadPolls: [] };+ }++ return {+ poll: metrics.publication.poll,+ threadPolls: metrics.publication.thread_polls,+ };+};++/**+ * The polls a post shows, in every tab: each one as its network returned it+ * at the last read, or, until it has been read (about an hour after+ * publishing, and never for a post still in the queue, a draft or a request),+ * with its choices and no votes.+ */+export const postPollResults = (+ post: PostCard,+): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => {+ const read = readPollsOf(post);+ const unread = unreadPollsOf(post);+ const unreadReplies = unread.threadPolls.filter(+ (unreadReply) =>+ !read.threadPolls.some((readReply) => readReply.reply === unreadReply.reply),+ );++ const threadPolls = [...read.threadPolls, ...unreadReplies].sort(+ (first, second) => first.reply - second.reply,+ );++ if (filled(read.poll)) {+ return { poll: read.poll, threadPolls };+ }++ return { poll: unread.poll, threadPolls };+};diff --git a/resources/js/lib/postThread.ts b/resources/js/lib/postThread.tsindex 65adee6ae..6281fad14 100644--- a/resources/js/lib/postThread.ts+++ b/resources/js/lib/postThread.ts@@ -1,16 +1,16 @@-import { blank } from '@/lib/helpers';+import { blank, filled } from '@/lib/helpers';+import { postPollResults } from '@/lib/poll';import {isBlankThreadReply,type ThreadReply,threadRepliesOf,} from '@/lib/threadReplies';-import { postPollResults } from '@/lib/xPoll';import type {PublicationPoll,PublicationThreadPoll,} from '@/types/analytics';import type { MediaItem } from '@/types/media';-import { THREAD_PLATFORMS } from '@/types/network-options';+import { isThreadPlatform } from '@/types/network-options';import type { PostCard } from '@/types/publish';/** One post of a thread as the post card and its details show it, with its own poll. */@@ -39,7 +39,7 @@ const replyPostOf = (* when the post has no reply to show.*/export const postThreadOf = (post: PostCard): ThreadPost[] => {- if (!THREAD_PLATFORMS.includes(post.platform ?? '')) {+ if (!filled(post.platform) || !isThreadPlatform(post.platform)) {return [];}diff --git a/resources/js/lib/threadReplies.ts b/resources/js/lib/threadReplies.tsindex bd784ba2f..d46544904 100644--- a/resources/js/lib/threadReplies.ts+++ b/resources/js/lib/threadReplies.ts@@ -1,24 +1,28 @@import { blank, filled, isEmpty } from '@/lib/helpers';import { uuid } from '@/lib/uuid';-import { ContentType } from '@/types/content-type';+import { ContentType, type ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';import {+ isReplyPollPlatform,+ isThreadPlatform,THREAD_MAX_REPLIES,THREAD_REPLY_CONTENT_TYPES,+ THREAD_REPLY_POLL_CONTENT_TYPES,} from '@/types/network-options';-import type { XPoll } from '@/types/x';+import type { PlatformValue } from '@/types/platform';+import type { Poll } from '@/types/poll';/*** One post of a thread after the first. `key` only lives in the composer: it* keeps an upload attached to its reply while replies are added or removed- * above it, and the server drops it. On X a reply may carry a poll instead of- * media, its text being the question.+ * above it, and the server drops it. On X and Mastodon a reply may carry a+ * poll instead of media, its text being the question.*/export type ThreadReply = {key: string;text: string;media: MediaItem[];- poll?: Partial<XPoll>;+ poll?: Partial<Poll>;};export const newThreadReply = (): ThreadReply => ({@@ -58,7 +62,7 @@ export const threadRepliesOf = (/** The reply as a poll, which carries no media, or as a plain post without one. */export const withReplyPoll = ({ key, text, media }: ThreadReply,- poll: Partial<XPoll> | undefined,+ poll: Partial<Poll> | undefined,): ThreadReply => {if (blank(poll)) {return { key, text, media };@@ -82,25 +86,45 @@ export const replyErrorOf = (errors[`${prefix}.${index}.text`] ??errors[`${prefix}.${index}.media`];+/** The post type a reply that is no poll publishes as, on a network that chains replies. */+export const threadReplyPostType = (+ platform: PlatformValue,+): ContentTypeValue | undefined => {+ if (!isThreadPlatform(platform)) {+ return undefined;+ }++ return THREAD_REPLY_CONTENT_TYPES[platform];+};+/** The post type a reply publishes as: a poll, or its network's reply type. */export const threadReplyContentType = (- platform: string,+ platform: PlatformValue,reply: ThreadReply,-): string | undefined => {- if (filled(reply.poll)) {- return ContentType.XPoll;+): ContentTypeValue | undefined => {+ if (!filled(reply.poll)) {+ return threadReplyPostType(platform);}- return THREAD_REPLY_CONTENT_TYPES[platform];+ if (!isReplyPollPlatform(platform)) {+ return undefined;+ }++ return THREAD_REPLY_POLL_CONTENT_TYPES[platform];};-export const threadMaxReplies = (platform: string): number =>- THREAD_MAX_REPLIES[platform] ?? 0;+export const threadMaxReplies = (platform: PlatformValue): number => {+ if (!isThreadPlatform(platform)) {+ return 0;+ }++ return THREAD_MAX_REPLIES[platform];+};-export const repliesAreComments = (platform: string): boolean =>- THREAD_REPLY_CONTENT_TYPES[platform] === ContentType.LinkedInComment;+export const repliesAreComments = (platform: PlatformValue): boolean =>+ threadReplyPostType(platform) === ContentType.LinkedInComment;-export const replyTooLongKey = (platform: string): string => {+export const replyTooLongKey = (platform: PlatformValue): string => {if (repliesAreComments(platform)) {return 'posts.form.thread.comment_too_long';}@@ -108,7 +132,7 @@ export const replyTooLongKey = (platform: string): string => {return 'posts.form.thread.reply_too_long';};-export const startThreadKey = (platform: string): string => {+export const startThreadKey = (platform: PlatformValue): string => {if (repliesAreComments(platform)) {return 'posts.form.thread.add_comment';}@@ -116,7 +140,7 @@ export const startThreadKey = (platform: string): string => {return 'posts.form.thread.start';};-export const replyEmptyKey = (platform: string): string => {+export const replyEmptyKey = (platform: PlatformValue): string => {if (repliesAreComments(platform)) {return 'posts.form.thread.comment_empty';}diff --git a/resources/js/lib/xPoll.ts b/resources/js/lib/xPoll.tsdeleted file mode 100644index 56700f1a9..000000000--- a/resources/js/lib/xPoll.ts+++ /dev/null@@ -1,180 +0,0 @@-import dayjs from '@/dayjs';-import { activeLocale } from '@/language';-import { clamp, filled, transform } from '@/lib/helpers';-import { threadRepliesOf } from '@/lib/threadReplies';-import type {- PublicationPoll,- PublicationThreadPoll,-} from '@/types/analytics';-import { ContentType } from '@/types/content-type';-import type { PublishConfig } from '@/types/platform';-import type { PostCard } from '@/types/publish';-import type { XPoll, XPollDuration, XPollLimits } from '@/types/x';--export const MINUTES_PER_HOUR = 60;-export const HOURS_PER_DAY = 24;-const MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR;--/** The poll limits in an account's `publishConfig`, or null on a network without polls. */-export const pollLimitsOf = (- publishConfig: PublishConfig | null | undefined,-): XPollLimits | null => publishConfig?.poll ?? null;--/** The longest a poll runs, in whole days. */-export const pollMaxDays = (limits: XPollLimits): number =>- Math.floor(limits.maxDuration / MINUTES_PER_DAY);--export const splitPollDuration = (minutes: number): XPollDuration => ({- days: Math.floor(minutes / MINUTES_PER_DAY),- hours: Math.floor((minutes % MINUTES_PER_DAY) / MINUTES_PER_HOUR),- minutes: minutes % MINUTES_PER_HOUR,-});--/** Minutes for the picked parts, within the poll's shortest and longest length; the longest takes no hours or minutes. */-export const joinPollDuration = (- parts: XPollDuration,- limits: XPollLimits,-): number => {- if (parts.days >= pollMaxDays(limits)) return limits.maxDuration;-- const total =- parts.days * MINUTES_PER_DAY +- parts.hours * MINUTES_PER_HOUR +- parts.minutes;-- return clamp(total, limits.minDuration, limits.maxDuration);-};--export const newPoll = (limits: XPollLimits): XPoll => ({- options: Array.from({ length: limits.minOptions }, () => ''),- duration_minutes: limits.defaultDuration,-});--/**- * A choice's length as X counts it, without the spaces around it: in UTF-16- * units (a string's `length`), so an emoji like 🐧 counts two, as on the server- * (`XPoll::choiceLength()`).- */-export const pollChoiceLength = (choice: string): number => choice.trim().length;--/**- * A choice cut to the longest X accepts, counted as X counts it- * (`pollChoiceLength`): the last character goes until it fits, so a character- * is never split and the spaces before the choice stay.- */-export const fitPollChoice = (choice: string, maxLength: number): string => {- let characters = Array.from(choice);-- while (pollChoiceLength(characters.join('')) > maxLength) {- characters = characters.slice(0, -1);- }-- return characters.join('');-};--/** The choices the editor shows: the stored ones, padded to the number a poll starts with. */-export const editablePollOptions = (- options: string[] | undefined,- minOptions: number,-): string[] => {- const stored = Array.isArray(options) ? options.map(String) : [];-- return Array.from(- { length: Math.max(minOptions, stored.length) },- (_, index) => stored[index] ?? '',- );-};--/** The units a poll's length is shown in, largest first, with their minutes. */-const POLL_LENGTH_UNITS = [- ['day', MINUTES_PER_DAY],- ['hour', MINUTES_PER_HOUR],- ['minute', 1],-] as const;--/** The poll's length in its largest whole unit, as X shows it ("1 day", "23 hours", "5 minutes"). */-export const formatPollLength = (minutes: number): string => {- const [unit, size] =- POLL_LENGTH_UNITS.find(([, size]) => minutes >= size) ??- POLL_LENGTH_UNITS[POLL_LENGTH_UNITS.length - 1];-- return new Intl.NumberFormat(activeLocale.value, {- style: 'unit',- unit,- unitDisplay: 'long',- }).format(Math.floor(minutes / size));-};--/**- * A poll before X has been read for it: its choices with no votes. Once its- * post is published it is open until its length from publishing; before- * that, voting has not started and has no end.- */-const unreadPollResult = (- poll: Partial<XPoll>,- publishedAt: string | null,-): PublicationPoll => ({- options: (poll.options ?? []).map((label) => ({ label, votes: 0 })),- voting_status: transform(publishedAt, (): 'open' => 'open'),- end_datetime: transform(publishedAt, (at) =>- transform(poll.duration_minutes, (minutes) =>- dayjs.utc(at).add(minutes, 'minute').toISOString(),- ),- ),- duration_minutes: poll.duration_minutes ?? null,-});--/** A post's own poll: only an X poll has one, whatever its meta still holds. */-const ownPollOf = (post: PostCard): Partial<XPoll> | undefined => {- if (post.content_type !== ContentType.XPoll) {- return undefined;- }-- return post.meta?.poll;-};--/** A post's own polls (the post's and its replies') with no votes yet. */-const unreadPollsOf = (- post: PostCard,-): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => ({- poll: transform(ownPollOf(post), (poll) =>- unreadPollResult(poll, post.published_at),- ),- threadPolls: threadRepliesOf(post.meta).flatMap((reply, index) => {- if (filled(reply.poll)) {- return [- {- reply: index,- ...unreadPollResult(reply.poll, post.published_at),- },- ];- }-- return [];- }),-});--/**- * The polls a post shows, in every tab: each one as X returned it at the last- * read, or, until X has been read for it (about an hour after publishing, and- * never for a post still in the queue, a draft or a request), with its- * choices and no votes.- */-export const postPollResults = (- post: PostCard,-): { poll: PublicationPoll | null; threadPolls: PublicationThreadPoll[] } => {- const read = post.metrics?.available ? post.metrics.publication : null;- const readReplies = read?.thread_polls ?? [];- const unread = unreadPollsOf(post);- const unreadReplies = unread.threadPolls.filter(- (unreadReply) =>- !readReplies.some((readReply) => readReply.reply === unreadReply.reply),- );-- return {- poll: read?.poll ?? unread.poll,- threadPolls: [...readReplies, ...unreadReplies].sort(- (first, second) => first.reply - second.reply,- ),- };-};diff --git a/resources/js/pages/publish/Index.vue b/resources/js/pages/publish/Index.vueindex 6f1c40919..d21c3726c 100644--- a/resources/js/pages/publish/Index.vue+++ b/resources/js/pages/publish/Index.vue@@ -649,7 +649,7 @@ const initialPost = computed<ComposerInitialPost | null>(() => {schedule_mode: post.schedule_mode ?? null,queue_position: post.approval_queue_position ?? null,social_account_id: post.social_account_id,- content_type: post.content_type ?? '',+ content_type: post.content_type ?? undefined,meta: post.meta ?? {},label_ids: post.labels?.map((label) => label.id) ?? [],};diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.tsindex 1ccdcd038..957348205 100644--- a/resources/js/types/analytics.ts+++ b/resources/js/types/analytics.ts@@ -282,6 +282,10 @@ export interface PublicationPoll {voting_status: 'open' | 'closed' | null;end_datetime: string | null;duration_minutes: number | null;+ /** Mastodon, multiple choice: how many people voted, which each share is of. */+ voters?: number | null;+ /** Mastodon: the votes stay hidden until the poll ends. */+ totals_hidden?: boolean;}/** The poll of one thread reply; `reply` is its position among the replies, from 0. */diff --git a/resources/js/types/channel.ts b/resources/js/types/channel.tsindex ff797b97d..64830581b 100644--- a/resources/js/types/channel.ts+++ b/resources/js/types/channel.ts@@ -1,12 +1,12 @@import type { PinterestBoard } from '@/types';-import type { PublishConfig } from '@/types/platform';+import type { PlatformValue, PublishConfig } from '@/types/platform';import type { VerifiedBadge } from '@/types/social-account';import type { SocialAccountStatusValue } from '@/types/social-account-status';import type { TikTokPrivacyLevelValue } from '@/types/tiktok-privacy';export interface ChannelAccount {id: string;- platform: string;+ platform: PlatformValue;display_name: string;username: string;display_label: string;@@ -27,7 +27,7 @@ export interface ChannelTikTokCreatorInfo {export interface Channel {id: string;- platform: string;+ platform: PlatformValue;displayName: string;username: string | null;avatarUrl: string | null;@@ -46,7 +46,7 @@ export interface Channel {export interface SidebarChannel {id: string;- platform: string;+ platform: PlatformValue;network: string;username: string;display_name: string | null;diff --git a/resources/js/types/content-type.ts b/resources/js/types/content-type.tsindex 34fec58d2..239f16964 100644--- a/resources/js/types/content-type.ts+++ b/resources/js/types/content-type.ts@@ -15,11 +15,13 @@ export const ContentType = {XPoll: 'x_poll',ThreadsPost: 'threads_post',ThreadsGhostPost: 'threads_ghost_post',+ ThreadsPoll: 'threads_poll',PinterestPin: 'pinterest_pin',PinterestVideoPin: 'pinterest_video_pin',PinterestCarousel: 'pinterest_carousel',BlueskyPost: 'bluesky_post',MastodonPost: 'mastodon_post',+ MastodonPoll: 'mastodon_poll',TelegramPost: 'telegram_post',DiscordMessage: 'discord_message',GoogleBusinessPost: 'google_business_post',@@ -27,6 +29,12 @@ export const ContentType = {export type ContentTypeValue = (typeof ContentType)[keyof typeof ContentType];+const CONTENT_TYPE_VALUES: ReadonlySet<string> = new Set(Object.values(ContentType));++/** Whether a value read as text (a radio, a URL) is one of the content types. */+export const isContentType = (value: string): value is ContentTypeValue =>+ CONTENT_TYPE_VALUES.has(value);+/** Content types published without a caption: the composer hides the text, it is not deleted. */export const CAPTIONLESS_CONTENT_TYPES: ReadonlySet<string> = new Set([ContentType.FacebookStory,@@ -34,12 +42,28 @@ export const CAPTIONLESS_CONTENT_TYPES: ReadonlySet<string> = new Set([]);/** Content types that carry no media, with why a card holding media cannot switch to one (`maxMediaCount()` 0 on the server). */-export const MEDIALESS_CONTENT_TYPE_REASONS: Readonly<Record<string, string>> = {+export const MEDIALESS_CONTENT_TYPE_REASONS: Readonly<Partial<Record<ContentTypeValue, string>>> = {[ContentType.ThreadsGhostPost]: 'posts.form.threads.ghost_post_attachments',- [ContentType.XPoll]: 'posts.form.x.poll.attachments',+ [ContentType.XPoll]: 'posts.form.poll.attachments',+ [ContentType.MastodonPoll]: 'posts.form.poll.attachments',+ [ContentType.ThreadsPoll]: 'posts.form.poll.attachments',[ContentType.LinkedInComment]: 'posts.form.thread.comment_attachments',};+/** Content types that are a poll (`ContentType::isPoll()` on the server): the post text is the question and there is no media. */+export const POLL_CONTENT_TYPES: ReadonlySet<ContentTypeValue> = new Set([+ ContentType.XPoll,+ ContentType.MastodonPoll,+ ContentType.ThreadsPoll,+]);++/** Each network's poll with the plain post it goes back to when its poll is removed. */+export const POLL_POST_CONTENT_TYPES: Readonly<Partial<Record<ContentTypeValue, ContentTypeValue>>> = {+ [ContentType.XPoll]: ContentType.XPost,+ [ContentType.MastodonPoll]: ContentType.MastodonPost,+ [ContentType.ThreadsPoll]: ContentType.ThreadsPost,+};+/** Content types that carry no media: the composer hides the media tray. */export const MEDIALESS_CONTENT_TYPES: ReadonlySet<string> = new Set(Object.keys(MEDIALESS_CONTENT_TYPE_REASONS),diff --git a/resources/js/types/network-options.ts b/resources/js/types/network-options.tsindex d48839cb0..70437353f 100644--- a/resources/js/types/network-options.ts+++ b/resources/js/types/network-options.ts@@ -1,4 +1,5 @@-import { ContentType } from '@/types/content-type';+import { ContentType, type ContentTypeValue } from '@/types/content-type';+import { Platform, type PlatformValue } from '@/types/platform';export const YouTubePrivacyStatus = {Public: 'public',@@ -14,22 +15,62 @@ export const YouTubeLicense = {export const YOUTUBE_TITLE_MAX = 100;export const THREADS_TOPIC_TAG_MAX = 50;-/** The content type a thread reply publishes as, per network that chains replies. */-export const THREAD_REPLY_CONTENT_TYPES: Readonly<Record<string, string>> = {- bluesky: ContentType.BlueskyPost,- mastodon: ContentType.MastodonPost,- x: ContentType.XPost,- linkedin: ContentType.LinkedInComment,- 'linkedin-page': ContentType.LinkedInComment,-};-export const THREAD_PLATFORMS: readonly string[] = Object.keys(- THREAD_REPLY_CONTENT_TYPES,+/** Networks that chain thread replies (`ThreadReplies::supports()` on the server). */+export const THREAD_PLATFORMS = [+ Platform.Bluesky,+ Platform.Mastodon,+ Platform.X,+ Platform.LinkedIn,+ Platform.LinkedInPage,+] as const;++export type ThreadPlatform = (typeof THREAD_PLATFORMS)[number];++const THREAD_PLATFORM_SET: ReadonlySet<PlatformValue> = new Set(THREAD_PLATFORMS);++/** Whether a network chains thread replies. */+export const isThreadPlatform = (+ platform: PlatformValue,+): platform is ThreadPlatform => THREAD_PLATFORM_SET.has(platform);++/** Networks whose thread replies can be polls (`ThreadReplies::replyPoll()` on the server). */+export const REPLY_POLL_PLATFORMS = [Platform.Mastodon, Platform.X] as const;++export type ReplyPollPlatform = (typeof REPLY_POLL_PLATFORMS)[number];++const REPLY_POLL_PLATFORM_SET: ReadonlySet<PlatformValue> = new Set(+ REPLY_POLL_PLATFORMS,);-export const THREAD_MAX_REPLIES: Readonly<Record<string, number>> = {- bluesky: 24,- mastodon: 24,- x: 24,- linkedin: 1,- 'linkedin-page': 1,++/** Whether a network's thread replies can be polls. */+export const isReplyPollPlatform = (+ platform: PlatformValue,+): platform is ReplyPollPlatform => REPLY_POLL_PLATFORM_SET.has(platform);++/** The content type a thread reply publishes as. */+export const THREAD_REPLY_CONTENT_TYPES: Readonly<+ Record<ThreadPlatform, ContentTypeValue>+> = {+ [Platform.Bluesky]: ContentType.BlueskyPost,+ [Platform.Mastodon]: ContentType.MastodonPost,+ [Platform.X]: ContentType.XPost,+ [Platform.LinkedIn]: ContentType.LinkedInComment,+ [Platform.LinkedInPage]: ContentType.LinkedInComment,};+/** The content type a thread reply that is a poll publishes as. */+export const THREAD_REPLY_POLL_CONTENT_TYPES: Readonly<+ Record<ReplyPollPlatform, ContentTypeValue>+> = {+ [Platform.Mastodon]: ContentType.MastodonPoll,+ [Platform.X]: ContentType.XPoll,+};++/** How many replies a thread takes: a thread, or one comment on LinkedIn (`ThreadReplies::maxReplies()`). */+export const THREAD_MAX_REPLIES: Readonly<Record<ThreadPlatform, number>> = {+ [Platform.Bluesky]: 24,+ [Platform.Mastodon]: 24,+ [Platform.X]: 24,+ [Platform.LinkedIn]: 1,+ [Platform.LinkedInPage]: 1,+};diff --git a/resources/js/types/platform.ts b/resources/js/types/platform.tsindex 9afd3cfb2..1d25aba22 100644--- a/resources/js/types/platform.ts+++ b/resources/js/types/platform.ts@@ -1,4 +1,4 @@-import type { XPollLimits } from '@/types/x';+import type { PollLimits } from '@/types/poll';export const Platform = {LinkedIn: 'linkedin',@@ -29,6 +29,6 @@ export interface PublishConfig {/** YouTube: the category list and the default category. */categoryOptions?: { value: string; labelKey: string }[];defaultCategoryId?: string;- /** X: the poll limits. */- poll?: XPollLimits;+ /** X, Mastodon and Threads: the poll limits. */+ poll?: PollLimits;}diff --git a/resources/js/types/poll.ts b/resources/js/types/poll.tsnew file mode 100644index 000000000..a89974bcb--- /dev/null+++ b/resources/js/types/poll.ts@@ -0,0 +1,34 @@+/**+ * A network's poll limits, served by `Platform::publishConfig()`+ * (`publishConfig.poll`, from the server's `Poll::limits()`). The length is+ * null on a network that sets it itself (Threads), and the question cap null+ * where the account's text limit applies.+ */+export interface PollLimits {+ minOptions: number;+ maxOptions: number;+ optionMaxLength: number;+ minDuration: number | null;+ maxDuration: number | null;+ defaultDuration: number | null;+ questionMaxLength: number | null;+ /** Mastodon: the author may let a voter pick several choices. */+ multipleChoice: boolean;+ /** Mastodon: the author may hide the votes until the poll ends. */+ hideTotals: boolean;+}++/** A poll's length split into the units the editor picks. */+export interface PollDuration {+ days: number;+ hours: number;+ minutes: number;+}++/** A poll as `meta.poll` (or a thread reply's `poll`) stores it; each network keeps only what it takes. */+export interface Poll {+ options: string[];+ duration_minutes?: number;+ multiple?: boolean;+ hide_totals?: boolean;+}diff --git a/resources/js/types/publish.ts b/resources/js/types/publish.tsindex 2c67db5a7..70db9dc75 100644--- a/resources/js/types/publish.ts+++ b/resources/js/types/publish.ts@@ -3,6 +3,7 @@ import type {MetricsUnavailableReason,PublicationAnalyticsDetail,} from '@/types/analytics';+import type { ContentTypeValue } from '@/types/content-type';import type { MediaItem } from '@/types/media';import type { PlatformValue } from '@/types/platform';import type {@@ -76,8 +77,8 @@ export interface PostCard {publish_status: PublishStatusValue;social_account_id: string | null;social_account: PublishSocialAccount | null;- platform: string | null;- content_type?: string | null;+ platform: PlatformValue | null;+ content_type?: ContentTypeValue | null;meta?: Record<string, any> | null;platform_url?: string | null;error_message?: string | null;diff --git a/resources/js/types/social-account.ts b/resources/js/types/social-account.tsindex c3e3cd569..881234a12 100644--- a/resources/js/types/social-account.ts+++ b/resources/js/types/social-account.ts@@ -1,6 +1,6 @@import { filled } from '@/lib/helpers';import type { MediaType } from '@/lib/mediaType';-import { Platform } from '@/types/platform';+import { Platform, type PlatformValue } from '@/types/platform';import type { TimezoneOption } from '@/types/posting-schedule';import {SocialAccountStatus,@@ -32,7 +32,7 @@ export interface ChannelListRow extends ConnectedAccount, PostingGoalProgress {export interface ConnectedAccount {id: string;- platform: string;+ platform: PlatformValue;network: string;username: string;display_name: string;diff --git a/resources/js/types/x.ts b/resources/js/types/x.tsdeleted file mode 100644index 3b94e761a..000000000--- a/resources/js/types/x.ts+++ /dev/null@@ -1,23 +0,0 @@-/** The poll limits X sets, served by `Platform::publishConfig()` (`publishConfig.poll`). */-export interface XPollLimits {- minOptions: number;- maxOptions: number;- optionMaxLength: number;- minDuration: number;- maxDuration: number;- defaultDuration: number;- questionMaxLength: number;-}--/** A poll's length split into the units the editor picks. */-export interface XPollDuration {- days: number;- hours: number;- minutes: number;-}--/** An X poll as `meta.poll` (or a thread reply's `poll`) stores it. */-export interface XPoll {- options: string[];- duration_minutes: number;-}diff --git a/tests/Browser/ComposerMastodonThreadsPollTest.php b/tests/Browser/ComposerMastodonThreadsPollTest.phpnew file mode 100644index 000000000..a692d7cb6--- /dev/null+++ b/tests/Browser/ComposerMastodonThreadsPollTest.php@@ -0,0 +1,422 @@+<?php++declare(strict_types=1);++use App\Dto\MediaItem;+use App\Enums\Post\Status;+use App\Enums\PostPlatform\ContentType;+use App\Models\Media;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Support\Social\MastodonPoll;+use Illuminate\Support\Str;++test('a mastodon poll schedules with its length, multiple choice and hidden votes', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);+ $id = $post->social_account_id;+ $page = openPollComposer($post);++ $page->click("@composer-type-{$id}-mastodon_poll");+ waitFor($page, '@mastodon-poll-choice-0');++ $page->assertVisible('@mastodon-poll-days')+ ->assertMissing("@composer-{$id}-media-source-menu")+ ->fill('@mastodon-poll-choice-0', 'Tabs')+ ->fill('@mastodon-poll-choice-1', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 5));+ waitForText($page, '@mastodon-poll-choice-1-count', MastodonPoll::OPTION_MAX_LENGTH.' / '.MastodonPoll::OPTION_MAX_LENGTH);+ waitForText($page, '@mastodon-preview-poll', 'Tabs');++ $page->click('@mastodon-poll-multiple')+ ->click('@mastodon-poll-hide-totals');+ waitForState($page, '@mastodon-poll-hide-totals', "element.getAttribute('aria-checked') === 'true'");+ $page->click('@composer-submit');+ waitForGone($page, '@post-composer-dialog');++ $post->refresh();+ expect($post->content_type)->toBe(ContentType::MastodonPoll)+ ->and($post->status)->toBe(Status::Scheduled)+ ->and($post->meta['poll'])->toEqual([+ 'options' => ['Tabs', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH)],+ 'duration_minutes' => MastodonPoll::DEFAULT_DURATION,+ 'multiple' => true,+ 'hide_totals' => true,+ ]);+ $page->assertNoJavaScriptErrors();+});++test('removing a mastodon poll returns to a mastodon post', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]);+ $id = $post->social_account_id;+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-choice-0');++ $page->click('@mastodon-poll-remove');+ waitForGone($page, '@mastodon-poll-choice-0');+ $page->assertAttribute("@composer-type-{$id}-mastodon_post", 'aria-checked', 'true')+ ->click('@composer-save-draft');+ waitForGone($page, '@post-composer-dialog');++ expect($post->fresh()->content_type)->toBe(ContentType::MastodonPost)+ ->and($post->fresh()->meta)->not->toHaveKey('poll');+ $page->assertNoJavaScriptErrors();+});++test('a mastodon thread reply turns into a poll and saves it on the reply', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost);+ $id = $post->social_account_id;+ $page = openPollComposer($post);++ waitFor($page, '@thread-start');+ $page->click('@thread-start');+ waitFor($page, '@thread-reply-0');+ $page->fill('@thread-reply-0', 'Which one?');+ waitFor($page, "@composer-{$id}-poll");+ $page->click("@composer-{$id}-poll");+ waitFor($page, '@thread-reply-0-poll-choice-0');++ $page->fill('@thread-reply-0-poll-choice-0', 'Yes')+ ->fill('@thread-reply-0-poll-choice-1', 'No');+ waitForText($page, '@preview-thread-reply-0 @mastodon-preview-poll', 'No');+ $page->click('@composer-save-draft');+ waitForGone($page, '@post-composer-dialog');++ expect($post->fresh()->meta['thread_replies'])->toEqual([+ ['text' => 'Which one?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::DEFAULT_DURATION]],+ ]);+ $page->assertNoJavaScriptErrors();+});++test('a threads poll has choices only, no length, and schedules', function () {+ $post = seedPollComposerPost(ContentType::ThreadsPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);+ $id = $post->social_account_id;+ $page = openPollComposer($post);++ $page->click("@composer-type-{$id}-threads_poll");+ waitFor($page, '@threads-poll-choice-0');++ $page->assertMissing('@threads-poll-days')+ ->assertMissing('@threads-poll-multiple')+ ->assertMissing('@threads-poll-hide-totals')+ ->assertMissing("@composer-{$id}-media-source-menu")+ ->fill('@threads-poll-choice-0', 'Tabs')+ ->fill('@threads-poll-choice-1', 'Spaces');+ waitForText($page, '@threads-preview-poll', 'Spaces');+ $page->click('@composer-submit');+ waitForGone($page, '@post-composer-dialog');++ $post->refresh();+ expect($post->content_type)->toBe(ContentType::ThreadsPoll)+ ->and($post->status)->toBe(Status::Scheduled)+ ->and($post->meta['poll'])->toEqual(['options' => ['Tabs', 'Spaces']]);+ $page->assertNoJavaScriptErrors();+});++test('a mastodon poll stays behind the content warning in the preview', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]);+ $page = openPollComposer($post);+ waitForText($page, '@mastodon-preview-poll', 'Spaces');++ $post->update(['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'spoiler_text' => 'Code style']]);+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-preview-content-warning');++ $page->assertMissing('@mastodon-preview-poll')+ ->assertNoJavaScriptErrors();+});++test('a reopened poll closes without an unsaved change', function (ContentType $type, array $poll, string $choice) {+ $post = seedPollComposerPost($type, ['meta' => ['poll' => $poll]]);+ $page = openPollComposer($post);+ waitFor($page, "@{$choice}");++ $page->click('@composer-close');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');++ $page->assertMissing('@unsaved-changes-dialog')+ ->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+})->with([+ 'mastodon with multiple choice and hidden votes' => [ContentType::MastodonPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true], 'mastodon-poll-choice-1'],+ 'threads' => [ContentType::ThreadsPoll, ['options' => ['Tabs', 'Spaces']], 'threads-poll-choice-1'],+]);++test('a stored poll edited back to what it was closes without an unsaved change', function (array $poll) {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => $poll]]);+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-choice-1');++ $page->click('@mastodon-poll-choice-1')+ ->fill('@mastodon-poll-choice-1', 'Spacesx');+ waitForState($page, '@mastodon-poll-choice-1', "element.value === 'Spacesx'");+ $page->fill('@mastodon-poll-choice-1', 'Spaces');+ waitForState($page, '@mastodon-poll-choice-1', "element.value === 'Spaces'");++ $page->click('@composer-close');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');++ $page->assertMissing('@unsaved-changes-dialog')+ ->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+})->with([+ 'saved without the switches (API or MCP)' => [['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],+ 'keys in the order MySQL returns them' => [['options' => ['Tabs', 'Spaces'], 'multiple' => true, 'hide_totals' => false, 'duration_minutes' => 60]],+]);++test('a saved mastodon poll switched to post and back brings the poll back with no unsaved change', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces', 'Both'], 'duration_minutes' => 4320, 'multiple' => true, 'hide_totals' => true]]]);+ $id = $post->social_account_id;+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-choice-2');++ $page->click("@composer-type-{$id}-mastodon_post");+ waitForGone($page, '@mastodon-poll-choice-0');+ $page->click("@composer-type-{$id}-mastodon_poll");+ waitFor($page, '@mastodon-poll-choice-2');++ expect(elementsMap($page, '@mastodon-poll-choice-0, @mastodon-poll-choice-1, @mastodon-poll-choice-2', 'element.value'))->toBe(['Tabs', 'Spaces', 'Both']);+ $page->assertSeeIn('@mastodon-poll-days', '3')+ ->assertAttribute('@mastodon-poll-multiple', 'aria-checked', 'true')+ ->assertAttribute('@mastodon-poll-hide-totals', 'aria-checked', 'true')+ ->click('@composer-close');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');++ $page->assertMissing('@unsaved-changes-dialog')+ ->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+});++test('a saved threads poll switched to a ghost post and back brings the poll back with no unsaved change', function () {+ $post = seedPollComposerPost(ContentType::ThreadsPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces', 'Both']]]]);+ $id = $post->social_account_id;+ $page = openPollComposer($post);+ waitFor($page, '@threads-poll-choice-2');++ $page->click("@composer-type-{$id}-threads_ghost_post");+ waitForGone($page, '@threads-poll-choice-0');+ $page->click("@composer-type-{$id}-threads_poll");+ waitFor($page, '@threads-poll-choice-2');++ expect(elementsMap($page, '@threads-poll-choice-0, @threads-poll-choice-1, @threads-poll-choice-2', 'element.value'))->toBe(['Tabs', 'Spaces', 'Both']);+ $page->click('@composer-close');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');++ $page->assertMissing('@unsaved-changes-dialog')+ ->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+});++test('a saved draft with a poll on a mastodon thread reply closes without an unsaved change', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost, ['meta' => ['thread_replies' => [+ ['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => false]],+ ]]]);+ $page = openPollComposer($post);+ waitFor($page, '@thread-reply-collapsed-0');++ $page->click('@composer-close');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@unsaved-changes-dialog');++ $page->assertMissing('@unsaved-changes-dialog')+ ->assertMissing('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+});++test('a poll picked while its network was the only one turns back into its post when another network joins, so shared media saves', function (ContentType $postType, ContentType $pollType) {+ $post = seedPollComposerPost($postType);+ $account = $post->socialAccount;+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);+ $prefix = $postType->platform()->value;+ $png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));++ $page = visit(route('app.posts.create'))->resize(1280, 900);+ waitForOpen($page, '@post-composer-dialog');+ $page->click('@composer-add-account');+ waitFor($page, "@composer-account-option-{$account->id}");+ $page->click("@composer-account-option-{$account->id}")+ ->click('@composer-header');+ waitForGone($page, "@composer-account-option-{$account->id}");+ waitFor($page, "@composer-type-{$account->id}-{$pollType->value}");+ $page->click("@composer-type-{$account->id}-{$pollType->value}");+ waitFor($page, "@{$prefix}-poll-choice-1");+ $page->fill("@{$prefix}-poll-choice-0", 'Tabs')+ ->fill("@{$prefix}-poll-choice-1", 'Spaces');++ $page->click('@composer-add-account');+ waitFor($page, "@composer-account-option-{$linkedIn->id}");+ $page->click("@composer-account-option-{$linkedIn->id}")+ ->click('@composer-header');+ waitForGone($page, "@composer-account-option-{$linkedIn->id}");+ waitForState($page, '@composer-file-input', 'true');+ $page->fill('@composer-base-content', 'Tabs or spaces?');+ $page->script(<<<JS+ (() => {+ const input = document.querySelector('[data-testid="composer-file-input"]');+ const transfer = new DataTransfer();+ transfer.items.add(new File([Uint8Array.from(atob('{$png}'), (character) => character.charCodeAt(0))], 'shared.png', { type: 'image/png' }));+ input.files = transfer.files;+ input.dispatchEvent(new Event('change', { bubbles: true }));+ })();+ JS);+ waitFor($page, '@composer-media-item');+ $page->click('@composer-save-draft');+ waitForGone($page, '@post-composer-dialog');++ $posts = Post::query()->where('workspace_id', $post->workspace_id)->whereKeyNot($post->id)->get()->keyBy('social_account_id');+ expect($posts)->toHaveCount(2)+ ->and($posts[$account->id]->content_type)->toBe($postType)+ ->and($posts[$account->id]->meta)->not->toHaveKey('poll')+ ->and($posts[$account->id]->media)->toHaveCount(1)+ ->and($posts[$linkedIn->id]->media)->toHaveCount(1);+ $page->assertNoJavaScriptErrors();+})->with([+ 'mastodon' => [ContentType::MastodonPost, ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPost, ContentType::ThreadsPoll],+]);++test('thirty days locks the hours and minutes of a mastodon poll', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1520]]]);+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-days');++ $page->assertSeeIn('@mastodon-poll-days', '1')+ ->assertSeeIn('@mastodon-poll-hours', '1')+ ->assertSeeIn('@mastodon-poll-minutes', '20')+ ->click('@mastodon-poll-days');+ waitFor($page, '@mastodon-poll-days-30');+ $page->click('@mastodon-poll-days-30');+ waitForState($page, '@mastodon-poll-hours', 'element.disabled');++ expect(elementsMap($page, '@mastodon-poll-days, @mastodon-poll-hours, @mastodon-poll-minutes', 'element.disabled'))->toBe([false, true, true]);+ $page->assertSeeIn('@mastodon-poll-hours', '0')+ ->assertSeeIn('@mastodon-poll-minutes', '0')+ ->click('@composer-save-draft');+ waitForGone($page, '@post-composer-dialog');++ expect(data_get($post->fresh()->meta, 'poll.duration_minutes'))->toBe(MastodonPoll::MAX_DURATION);+ $page->assertNoJavaScriptErrors();+});++test('the mastodon preview shows a multiple choice poll with its choices and length', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 43200, 'multiple' => true]]]);+ $page = openPollComposer($post);+ waitForText($page, '@mastodon-preview-poll', '30 days left');++ $page->assertSeeIn('@mastodon-preview-poll', 'Tabs')+ ->assertSeeIn('@mastodon-preview-poll', 'Spaces')+ ->assertNoJavaScriptErrors();+});++test('a mastodon thread reply with media cannot turn into a poll and says why', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost);+ $id = $post->social_account_id;+ $image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);+ $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]]]]]);+ $page = openPollComposer($post);++ waitFor($page, '@thread-reply-collapsed-0');+ $page->click('@thread-reply-collapsed-0');+ waitFor($page, "@composer-{$id}-poll-disabled");++ $page->assertMissing("@composer-{$id}-poll")+ ->assertAttribute("@composer-{$id}-poll-disabled", 'aria-label', __('posts.form.poll.attachments'))+ ->assertNoJavaScriptErrors();+});++test('removing a mastodon thread reply poll gives the reply its media back', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost);+ $id = $post->social_account_id;+ $page = openPollComposer($post);++ waitFor($page, '@thread-start');+ $page->click('@thread-start');+ waitFor($page, "@composer-{$id}-poll");+ $page->click("@composer-{$id}-poll");+ waitFor($page, '@thread-reply-0-poll-remove');+ $page->click('@thread-reply-0-poll-remove');+ waitFor($page, "@composer-{$id}-media-source-menu");++ $page->assertMissing('@thread-reply-0-poll')+ ->assertPresent("@composer-{$id}-poll")+ ->assertMissing("@composer-{$id}-media-source-disabled")+ ->assertNoJavaScriptErrors();+});++test('a server error on the poll shows on the mastodon card when mastodon is not the first channel', function () {+ $post = seedPollComposerPost(ContentType::MastodonPost);+ $mastodon = $post->socialAccount;+ $linkedIn = SocialAccount::factory()->linkedin()->create(['workspace_id' => $post->workspace_id]);++ $page = visit(route('app.posts.create'))->resize(1280, 900);+ waitForOpen($page, '@post-composer-dialog');+ $page->click('@composer-add-account');+ waitFor($page, "@composer-account-option-{$linkedIn->id}");+ $page->click("@composer-account-option-{$linkedIn->id}");+ waitFor($page, "@composer-account-option-{$mastodon->id}");+ $page->click("@composer-account-option-{$mastodon->id}");+ waitFor($page, '@composer-base-content');+ $page->fill('@composer-base-content', 'Tabs or spaces?')+ ->click('@composer-next');+ waitFor($page, "@composer-account-{$mastodon->id}");+ $page->click("@composer-account-{$mastodon->id}");+ waitFor($page, "@composer-type-{$mastodon->id}-mastodon_poll");+ $page->click("@composer-type-{$mastodon->id}-mastodon_poll");+ waitFor($page, '@mastodon-poll-choice-1');++ $page->fill('@mastodon-poll-choice-0', 'Yes')+ ->fill('@mastodon-poll-choice-1', 'yes')+ ->click('@composer-save-draft');+ waitForText($page, '@mastodon-poll-options-error', __('posts.form.poll.options_distinct'));++ $page->assertSeeIn('@mastodon-poll-options-error', __('posts.form.poll.options_distinct'))+ ->assertVisible('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+ expect(Post::query()->where('workspace_id', $post->workspace_id)->count())->toBe(1);+});++test('a mastodon poll choice the server refuses as too long is marked on that choice only', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => [Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1), 'Spaces'], 'duration_minutes' => 60]]]);+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-choice-1');++ $page->click('@composer-save-draft');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@mastodon-poll-choice-0-error');+ waitForText($page, '@mastodon-poll-choice-0-error', __('posts.form.poll.choice_max', ['max' => MastodonPoll::OPTION_MAX_LENGTH]));++ $page->assertAttribute('@mastodon-poll-choice-0', 'aria-invalid', 'true')+ ->assertAttributeMissing('@mastodon-poll-choice-1', 'aria-invalid')+ ->assertMissing('@mastodon-poll-choice-1-error')+ ->assertVisible('@post-composer-dialog')+ ->assertNoJavaScriptErrors();+ expect(data_get($post->fresh()->meta, 'poll.options.0'))->toBe(Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1));+});++test('a mastodon poll length the server refuses shows the range under the length', function () {+ $post = seedPollComposerPost(ContentType::MastodonPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 50000]]]);+ $page = openPollComposer($post);+ waitFor($page, '@mastodon-poll-days');++ $page->click('@composer-save-draft');+ waitForGoneOrShown($page, gone: '@post-composer-dialog', shown: '@mastodon-poll-duration-error');+ waitForText($page, '@mastodon-poll-duration-error', MastodonPoll::durationRangeMessage());++ $page->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();+ expect(data_get($post->fresh()->meta, 'poll.duration_minutes'))->toBe(50000);+});++test('a thread reply on a network without polls has no poll button', function (ContentType $type) {+ $post = seedPollComposerPost($type);+ $id = $post->social_account_id;++ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);+ waitFor($page, '@thread-start');+ $page->click('@thread-start');+ waitFor($page, '@thread-reply-0');+ $page->fill('@thread-reply-0', 'One more thing');+ waitFor($page, "@composer-{$id}-toolbar");++ $page->assertMissing("@composer-{$id}-poll")+ ->assertMissing("@composer-{$id}-poll-disabled")+ ->assertNoJavaScriptErrors();+})->with([+ 'bluesky reply' => [ContentType::BlueskyPost],+ 'linkedin comment' => [ContentType::LinkedInPost],+]);diff --git a/tests/Browser/ComposerXPollTest.php b/tests/Browser/ComposerXPollTest.phpindex 635af78c6..a33901b9e 100644--- a/tests/Browser/ComposerXPollTest.php+++ b/tests/Browser/ComposerXPollTest.php@@ -6,12 +6,9 @@ use App\Ai\Agents\PostWritingAssistant;use App\Dto\MediaItem;use App\Enums\Post\Status;use App\Enums\PostPlatform\ContentType;-use App\Enums\SocialAccount\Platform;use App\Models\Media;use App\Models\Post;use App\Models\SocialAccount;-use App\Models\User;-use App\Models\Workspace;use App\Support\Social\XPoll;use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;@@ -24,40 +21,7 @@ use Laravel\Ai\Prompts\AgentPrompt;*/function seedXPollPost(ContentType $contentType = ContentType::XPost, array $attributes = [], array $accountMeta = [], array $userAttributes = []): Post{- Http::fake(['*' => Http::response([], 200)]);-- $user = User::factory()->create($userAttributes);- $workspace = Workspace::factory()->create(['user_id' => $user->id]);- $workspace->members()->attach($user->id, membershipPivot('member'));- $user->update(['current_workspace_id' => $workspace->id]);- connectAiTo($user);-- $account = SocialAccount::factory()->create([- 'workspace_id' => $workspace->id,- 'platform' => Platform::X,- 'username' => 'trypostit',- 'access_token' => 'x-token',- 'token_expires_at' => now()->addDays(20),- 'meta' => $accountMeta,- ]);-- $post = Post::factory()->forAccount($account, $contentType)->create([- 'user_id' => $user->id,- 'content' => 'Which network brings you the most customers?',- ...$attributes,- ]);-- test()->actingAs($user);-- return $post;-}--function openXPollComposer(Post $post): mixed-{- $page = visit(route('app.posts.edit', $post))->resize(1280, 900);- waitFor($page, "@composer-type-{$post->social_account_id}-x_poll");-- return $page;+ return seedPollComposerPost($contentType, $attributes, ['access_token' => 'x-token', 'meta' => $accountMeta], $userAttributes);}function pickXPoll(mixed $page, Post $post): void@@ -69,7 +33,7 @@ function pickXPoll(mixed $page, Post $post): voidtest('picking poll shows two choices and turns media off', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);$page->assertVisible("@composer-{$id}-media-source-menu");pickXPoll($page, $post);@@ -80,14 +44,14 @@ test('picking poll shows two choices and turns media off', function () {->assertMissing("@composer-{$id}-media-source-menu")->assertVisible("@composer-{$id}-media-source-disabled")->hover("@composer-{$id}-media-source-disabled");- waitForText($page, '[data-slot="tooltip-content"]', __('posts.form.x.poll.attachments'));- $page->assertSeeIn('[data-slot="tooltip-content"]', __('posts.form.x.poll.attachments'))+ waitForText($page, '[data-slot="tooltip-content"]', __('posts.form.poll.attachments'));+ $page->assertSeeIn('[data-slot="tooltip-content"]', __('posts.form.poll.attachments'))->assertNoJavaScriptErrors();});test('adds choices up to four and removes one', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->assertMissing('@x-poll-remove-choice-0')@@ -110,7 +74,7 @@ test('adds choices up to four and removes one', function () {test('a new choice takes focus after one was removed', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->click('@x-poll-add-choice');@@ -132,22 +96,22 @@ test('a new choice takes focus after one was removed', function () {test('duplicate choices show the error under the choices', function () {$post = seedXPollPost(ContentType::XPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', 'Yes')->fill('@x-poll-choice-1', 'yes')->click('@composer-submit');- waitForText($page, '@x-poll-options-error', __('posts.form.x.poll.options_distinct'));+ waitForText($page, '@x-poll-options-error', __('posts.form.poll.options_distinct'));- $page->assertSeeIn('@x-poll-options-error', __('posts.form.x.poll.options_distinct'))+ $page->assertSeeIn('@x-poll-options-error', __('posts.form.poll.options_distinct'))->assertVisible('@post-composer-dialog')->assertNoJavaScriptErrors();});test('seven days zeroes hours and minutes', function () {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1520]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-days');$page->assertSeeIn('@x-poll-days', '1')@@ -171,7 +135,7 @@ test('seven days zeroes hours and minutes', function () {test('remove poll returns to post', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->assertMissing("@composer-{$id}-dropzone")@@ -195,20 +159,20 @@ test('poll is disabled while the card has media', function () {$id = $post->social_account_id;$image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);$post->update(['media' => [MediaItem::fromMedia($image)->toArray()]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);expect($page->script("document.querySelector('[data-testid=\"composer-type-{$id}-x_poll\"]').disabled"))->toBeTrue();$page->hover("@composer-type-{$id}-x_poll-label");waitFor($page, "@composer-type-{$id}-x_poll-reason");- $page->assertSeeIn("@composer-type-{$id}-x_poll-reason", __('posts.form.x.poll.attachments'))+ $page->assertSeeIn("@composer-type-{$id}-x_poll-reason", __('posts.form.poll.attachments'))->assertNoJavaScriptErrors();});test('the preview shows the choices and length', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', 'Yes')@@ -222,7 +186,7 @@ test('the preview shows the choices and length', function () {test('schedules a poll', function () {$post = seedXPollPost(ContentType::XPost, ['status' => Status::Scheduled, 'scheduled_at' => now()->addDay()]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', ' Yes ')@@ -239,14 +203,14 @@ test('schedules a poll', function () {test('a reopened poll draft shows two choices', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->click('@composer-save-draft');waitForGone($page, '@post-composer-dialog');expect($post->fresh()->content_type)->toBe(ContentType::XPoll);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-choice-0');$page->assertVisible('@x-poll-choice-1')@@ -256,14 +220,14 @@ test('a reopened poll draft shows two choices', function () {test('editing a choice is an unsaved change', function () {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-choice-0');$page->click('@composer-close');waitForGone($page, '@post-composer-dialog');$page->assertMissing('@unsaved-changes-dialog');- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-choice-0');$page->click('@x-poll-choice-1')->fill('@x-poll-choice-1', 'Nope')@@ -276,7 +240,7 @@ test('editing a choice is an unsaved change', function () {test('picking poll then post again leaves no unsaved change', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->click("@composer-type-{$id}-x_post");@@ -293,7 +257,7 @@ test('picking poll then post again leaves no unsaved change', function () {test('switching to post and back to poll brings the typed poll back', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', 'Yes')@@ -326,7 +290,7 @@ test('switching to post and back to poll brings the typed poll back', function (test('a saved poll switched to post and back has no unsaved change', function () {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]]);$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-choice-2');$page->click("@composer-type-{$id}-x_post");@@ -346,7 +310,7 @@ test('a saved draft with a poll on a thread reply closes without an unsaved chan$post = seedXPollPost(attributes: ['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-reply-collapsed-0');$page->click('@composer-close');@@ -361,7 +325,7 @@ test('a saved poll with other settings switched to post and back has no unsaved$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440], 'is_ai_generated' => true]]);$id = $post->social_account_id;expect(array_keys($post->fresh()->meta))->toBe(['poll', 'is_ai_generated']);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-choice-1');$page->click("@composer-type-{$id}-x_post");@@ -512,7 +476,7 @@ test('poll is disabled while a file is still uploading to the card', function ()$id = $post->social_account_id;$png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));$uploadUrl = route('app.media.store-chunked', absolute: false);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitForState($page, "@composer-{$id}-file-input", 'true');$page->script(<<<JS@@ -542,7 +506,7 @@ test('poll is disabled while a file is still uploading to the card', function ()test('a choice counter does not count the spaces around it', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', Str::repeat('a', 25).' ');@@ -554,7 +518,7 @@ test('a choice counter does not count the spaces around it', function () {test('a choice stops at 25 characters while typing, counted as x counts them (a penguin emoji is two) and leaving out the spaces before it', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', Str::repeat('a', 30));@@ -571,7 +535,7 @@ test('a choice stops at 25 characters while typing, counted as x counts them (atest('a thread reply under a poll can still take media while the poll root cannot', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);waitFor($page, '@thread-start');@@ -593,7 +557,7 @@ test('a thread reply under a poll can still take media while the poll root cannotest('in a thread the poll shows on the root and hides while a reply is edited', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);waitFor($page, '@thread-start');@@ -617,7 +581,7 @@ test('a poll question on a long post account counts against 280', function () {'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],], ['x_subscription_type' => 'Premium']);$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitForText($page, "@composer-char-count-{$id}", '-10');$page->assertSeeIn("@composer-char-count-{$id}", '-10')@@ -659,13 +623,13 @@ test('a server error on the poll shows on the x card when x is not the first cha->assertNoJavaScriptErrors();expect(Post::query()->where('workspace_id', $post->workspace_id)->count())->toBe(1);})->with([- 'repeated choices' => fn () => [['Yes', 'yes'], 'x-poll-options-error', __('posts.form.x.poll.options_distinct')],+ 'repeated choices' => fn () => [['Yes', 'yes'], 'x-poll-options-error', __('posts.form.poll.options_distinct')],]);test('the ai-generated switch survives a switch from poll to post', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);waitFor($page, '@x-ai-generated');@@ -686,7 +650,7 @@ test('the ai-generated switch survives a switch from poll to post', function ()test('removing the poll forgets it, so picking poll again starts empty', function () {$post = seedXPollPost();- $page = openXPollComposer($post);+ $page = openPollComposer($post);pickXPoll($page, $post);$page->fill('@x-poll-choice-0', 'Yes')@@ -710,7 +674,7 @@ test('removing the poll forgets it, so picking poll again starts empty', functiotest('a length of zero saves the shortest poll and seven days locks hours and minutes', function () {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-days');$page->click('@x-poll-days');@@ -751,11 +715,11 @@ test('on a phone the poll editor fits the screen', function () {test('the length selects are labelled and a choice is added with the keyboard', function () {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@x-poll-add-choice');expect($page->script("['days', 'hours', 'minutes'].map((part) => document.querySelector(`[data-testid=\"x-poll-\${part}\"]`).labels[0]?.textContent.trim())"))- ->toBe([__('posts.form.x.poll.days'), __('posts.form.x.poll.hours'), __('posts.form.x.poll.minutes')]);+ ->toBe([__('posts.form.poll.days'), __('posts.form.poll.hours'), __('posts.form.poll.minutes')]);$page->keys('@x-poll-add-choice', 'Enter');waitFor($page, '@x-poll-choice-2');@@ -767,7 +731,7 @@ test('the writing assistant writes a poll question for 280 characters on a longconfig()->set('trypost.self_hosted', true);PostWritingAssistant::fake(['Tabs or spaces?']);$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440]]], ['x_subscription_type' => 'Premium']);- $page = openXPollComposer($post);+ $page = openPollComposer($post);$page->click('@composer-ai-assistant');waitFor($page, '@writing-assistant-channel');@@ -784,7 +748,7 @@ test('the writing assistant writes a poll question for 280 characters on a longtest('a link in a poll question shows no link card in the preview', function () {Http::fake(['https://93.184.216.34/*' => Http::response('<meta property="og:title" content="Article card">')]);$post = seedXPollPost(ContentType::XPost, ['content' => 'Read https://93.184.216.34/article']);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitForText($page, '@link-card-title', 'Article card');$page->assertPresent('@link-card');@@ -798,7 +762,7 @@ test('a link in a poll question shows no link card in the preview', function ()test('the preview shows the poll length in its largest unit and the user language', function (int $minutes, string $locale, string $expected) {$post = seedXPollPost(ContentType::XPoll, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => $minutes]]], userAttributes: ['locale' => $locale]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitForText($page, '@x-preview-poll', $expected);$page->assertSeeIn('@x-preview-poll', $expected)->assertNoJavaScriptErrors();@@ -811,7 +775,7 @@ test('the preview shows the poll length in its largest unit and the user languagtest('a thread reply turns into a poll from its toolbar, turns its media off and saves the poll on the reply', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-start');$page->click('@thread-start');@@ -828,7 +792,7 @@ test('a thread reply turns into a poll from its toolbar, turns its media off and$page->assertMissing("@composer-{$id}-poll")->assertMissing('@x-poll')- ->assertAttribute("@composer-{$id}-media-source-disabled", 'aria-label', __('posts.form.x.poll.attachments'))+ ->assertAttribute("@composer-{$id}-media-source-disabled", 'aria-label', __('posts.form.poll.attachments'))->assertSeeIn('[data-testid="preview-thread-reply-0"] [data-testid="x-preview-poll"]', 'Tabs');$page->click('@composer-save-draft');@@ -843,7 +807,7 @@ test('a thread reply turns into a poll from its toolbar, turns its media off andtest('a thread reply poll shows in the preview before its question, and its choice errors only under the choices', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-start');$page->click('@thread-start');@@ -855,9 +819,9 @@ test('a thread reply poll shows in the preview before its question, and its choiwaitForText($page, '@preview-thread-reply-0 @x-preview-poll', 'Tabs');$page->assertVisible('[data-testid="preview-thread-reply-0"] [data-testid="x-preview-poll"]')->click('@composer-save-draft');- waitForText($page, '@thread-reply-0-poll-options-error', __('posts.form.x.poll.options_distinct'));+ waitForText($page, '@thread-reply-0-poll-options-error', __('posts.form.poll.options_distinct'));- $page->assertSeeIn('@thread-reply-0-poll-options-error', __('posts.form.x.poll.options_distinct'))+ $page->assertSeeIn('@thread-reply-0-poll-options-error', __('posts.form.poll.options_distinct'))->assertMissing('@thread-reply-error-0')->assertAttributeMissing('@thread-reply-0', 'aria-invalid')->assertVisible('@post-composer-dialog')@@ -867,7 +831,7 @@ test('a thread reply poll shows in the preview before its question, and its choitest('removing a thread reply poll gives the reply its media back', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-start');$page->click('@thread-start');@@ -888,14 +852,14 @@ test('a thread reply with media cannot turn into a poll and says why', function$id = $post->social_account_id;$image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);$post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]]]]]);- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-reply-collapsed-0');$page->click('@thread-reply-collapsed-0');waitFor($page, "@composer-{$id}-poll-disabled");$page->assertMissing("@composer-{$id}-poll")- ->assertAttribute("@composer-{$id}-poll-disabled", 'aria-label', __('posts.form.x.poll.attachments'))+ ->assertAttribute("@composer-{$id}-poll-disabled", 'aria-label', __('posts.form.poll.attachments'))->assertNoJavaScriptErrors();});@@ -904,7 +868,7 @@ test('a thread reply poll question on a long post account counts against 280', f['text' => Str::repeat('a', 290), 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],]]], accountMeta: ['x_subscription_type' => 'Premium']);$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-reply-collapsed-0');$page->click('@thread-reply-collapsed-0');@@ -919,7 +883,7 @@ test('pasting an image into a thread reply poll adds no media to it', function ($post = seedXPollPost();$id = $post->social_account_id;$png = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));- $page = openXPollComposer($post);+ $page = openPollComposer($post);waitFor($page, '@thread-start');$page->click('@thread-start');@@ -946,7 +910,7 @@ test('pasting an image into a thread reply poll adds no media to it', function (test('every toolbar button names itself in a tooltip and the ai-generated hint opens above its icon', function () {$post = seedXPollPost();$id = $post->social_account_id;- $page = openXPollComposer($post);+ $page = openPollComposer($post);foreach (["composer-{$id}-media-source" => __('posts.edit.add_media'),@@ -967,7 +931,7 @@ test('every toolbar button names itself in a tooltip and the ai-generated hint owaitFor($page, "@composer-{$id}-poll");$page->hover("@composer-{$id}-poll");waitFor($page, "@composer-{$id}-poll-tooltip");- $page->assertSeeIn("@composer-{$id}-poll-tooltip", __('posts.form.x.poll.add'))+ $page->assertSeeIn("@composer-{$id}-poll-tooltip", __('posts.form.poll.add'))->hover('@composer-header');waitForGone($page, "@composer-{$id}-poll-tooltip");diff --git a/tests/Browser/LinkCardPreviewTest.php b/tests/Browser/LinkCardPreviewTest.phpindex ad5b1a5ff..e94446f4a 100644--- a/tests/Browser/LinkCardPreviewTest.php+++ b/tests/Browser/LinkCardPreviewTest.php@@ -255,6 +255,30 @@ test('the threads link card cannot be dropped because threads always shows it',->assertNoJavaScriptErrors();});+test('a threads poll fetches no link card for a link in its question', function () {+ $url = 'https://93.184.216.34/article';+ Http::fake([$url => Http::response('<meta property="og:title" content="Article card">')]);+ [$post, $account] = seedLinkCardPreviewPost(Platform::Threads, "Best tool? {$url}");+ $post->forceFill(['content_type' => ContentType::ThreadsPoll, 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces']]]])->save();+ $previewRequests = 0;+ Event::listen(RequestHandled::class, function (RequestHandled $event) use (&$previewRequests): void {+ if ($event->request->routeIs('app.posts.link-preview')) {+ $previewRequests++;+ }+ });++ $page = visit(route('app.posts.edit', $post));+ waitForOpen($page, '@post-composer-dialog');+ waitFor($page, '@threads-poll-choice-0');+ letPageRun($page, 1500);++ $page->assertMissing("@composer-link-card-{$account->id}")+ ->assertNoJavaScriptErrors();++ expect($previewRequests)->toBe(0);+ Http::assertNothingSent();+});+test('replacing the link card with media attaches the card image', function () {$url = 'https://93.184.216.34/article';$fake = UploadedFile::fake()->image('card.jpg', 1200, 630);diff --git a/tests/Browser/PostPollResultsTest.php b/tests/Browser/PostPollResultsTest.phpindex 94e0a6d66..fdb7a5f3a 100644--- a/tests/Browser/PostPollResultsTest.php+++ b/tests/Browser/PostPollResultsTest.php@@ -12,12 +12,14 @@ use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;use Database\Factories\AnalyticsPublicationFactory;+use Illuminate\Support\Str;/**- * @param array<string, mixed>|null $poll- * @return array{0: User, 1: SocialAccount, 2: Post}+ * A subscribed admin in a workspace of their own, and a channel of `$network` there.+ *+ * @return array{0: User, 1: SocialAccount}*/-function pollResultsSetup(?array $poll, bool $withMetrics = true, string $theme = 'light'): array+function pollResultsAccount(string $network, string $theme = 'light'): array{$user = User::factory()->create(['timezone' => 'UTC', 'theme' => $theme]);$workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);@@ -26,19 +28,28 @@ function pollResultsSetup(?array $poll, bool $withMetrics = true, string $themesubscribeAccount($user->account);connectAiTo($user);- $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);- $post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([+ return [$user, SocialAccount::factory()->{$network}()->create(['workspace_id' => $workspace->id])];+}++/**+ * @param array<string, mixed>|null $poll+ * @return array{0: User, 1: SocialAccount, 2: Post}+ */+function pollResultsSetup(?array $poll, bool $withMetrics = true, string $theme = 'light', ContentType $type = ContentType::XPoll): array+{+ [$user, $account] = pollResultsAccount($type->platform()->value, $theme);+ $post = Post::factory()->forAccount($account, $type)->published()->create(['user_id' => $user->id,'scheduled_at' => now()->subHour(),'published_at' => now()->subHour(),]);$publication = AnalyticsPublication::factory()->when(filled($poll), fn (AnalyticsPublicationFactory $factory): AnalyticsPublicationFactory => $factory->withPoll($poll))->create([- 'workspace_id' => $workspace->id,+ 'workspace_id' => $account->workspace_id,'social_account_id' => $account->id,'social_account_key' => $account->id,'post_id' => $post->id,- 'platform' => Platform::X,- 'network' => Platform::X->network(),+ 'platform' => $account->platform,+ 'network' => $account->platform->network(),'remote_id' => $post->platform_post_id,]);AnalyticsPublicationDailySnapshot::factory()->create([@@ -121,13 +132,7 @@ test('where voting stands is read from the instant, whatever zone the browser is]);test('a poll whose publication x has not read yet shows its choices with no votes and when it ends', function () {- $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()->x()->create(['workspace_id' => $workspace->id]);+ [$user, $account] = pollResultsAccount('x');$post = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create(['user_id' => $user->id,'scheduled_at' => now()->subMinutes(5),@@ -138,7 +143,7 @@ test('a poll whose publication x has not read yet shows its choices with no vote],]);$publication = AnalyticsPublication::factory()->create([- 'workspace_id' => $workspace->id,+ 'workspace_id' => $account->workspace_id,'social_account_id' => $account->id,'social_account_key' => $account->id,'post_id' => $post->id,@@ -166,13 +171,7 @@ test('a poll whose publication x has not read yet shows its choices with no vote});test('a poll still in the queue shows its choices with no votes and no end yet', function () {- $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()->x()->create(['workspace_id' => $workspace->id]);+ [$user, $account] = pollResultsAccount('x');$post = Post::factory()->forAccount($account, ContentType::XPoll)->create(['user_id' => $user->id,'status' => Status::Scheduled,@@ -348,3 +347,202 @@ test('the polls of thread replies show under the post on the sent card and in th->assertSeeIn('@post-details-poll-reply-1', '25%')->assertNoJavaScriptErrors();});++test('a mastodon or threads poll still in the queue shows its choices with no votes, like an x poll', function (string $network, ContentType $type, array $poll) {+ [$user, $account] = pollResultsAccount($network);+ $post = Post::factory()->forAccount($account, $type)->create([+ 'user_id' => $user->id,+ 'status' => Status::Scheduled,+ 'scheduled_at' => now()->addDay(),+ 'meta' => ['poll' => $poll],+ ]);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', $account));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')+ ->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '0 votes')+ ->assertSeeIn("@post-poll-{$post->id}-option-1", 'Linux')+ ->assertDontSeeIn("@post-poll-{$post->id}-summary", 'Ends')+ ->assertNoJavaScriptErrors();+})->with([+ 'mastodon' => ['mastodon', ContentType::MastodonPoll, ['options' => ['Mac', 'Linux'], 'duration_minutes' => 1440]],+ 'threads' => ['threads', ContentType::ThreadsPoll, ['options' => ['Mac', 'Linux']]],+]);++test('a sent mastodon or threads poll shows the votes its network returned, like an x poll', function (ContentType $type) {+ [$user, $account, $post] = pollResultsSetup(refundPoll(), type: $type);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-option-0", '1 vote')+ ->assertSeeIn("@post-poll-{$post->id}-option-1", '2 votes')+ ->assertSeeIn("@post-poll-{$post->id}-summary", '3 votes')+ ->assertNoJavaScriptErrors();+})->with([+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);++test('a sent mastodon multiple choice poll shows each share of the people who voted', function () {+ [$user, $account, $post] = pollResultsSetup([+ 'options' => [['label' => 'Mac', 'votes' => 8], ['label' => 'Linux', 'votes' => 6], ['label' => 'Windows', 'votes' => 6]],+ 'voting_status' => 'closed',+ 'end_datetime' => now()->subHour()->toIso8601String(),+ 'duration_minutes' => null,+ 'multiple' => true,+ 'voters' => 10,+ 'totals_hidden' => false,+ ], type: ContentType::MastodonPoll);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '80%')+ ->assertSeeIn("@post-poll-{$post->id}-option-1-votes", '60%')+ ->assertSeeIn("@post-poll-{$post->id}-option-2-votes", '60%')+ ->assertSeeIn("@post-poll-{$post->id}-summary", trans_choice('posts.poll_results.voters', 10, ['count' => 10]))+ ->assertDontSeeIn("@post-poll-{$post->id}-summary", '20 votes')+ ->assertNoJavaScriptErrors();+});++test('a sent mastodon poll that hides its votes says so and shows no votes per choice', function () {+ [$user, $account, $post] = pollResultsSetup([+ 'options' => [['label' => 'Mac', 'votes' => 0], ['label' => 'Linux', 'votes' => 0]],+ 'voting_status' => 'open',+ 'end_datetime' => now()->addHours(5)->toIso8601String(),+ 'duration_minutes' => null,+ 'multiple' => false,+ 'voters' => null,+ 'totals_hidden' => true,+ ], type: ContentType::MastodonPoll);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-summary", __('posts.poll_results.hidden'))+ ->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')+ ->assertMissing("@post-poll-{$post->id}-option-0-votes")+ ->assertMissing("@post-poll-{$post->id}-option-1-votes")+ ->assertNoJavaScriptErrors();+});++test('a sent mastodon poll that hides its votes still says where voting stands', function (Closure $overrides, string $shown, array $hidden) {+ [$user, $account, $post] = pollResultsSetup([+ 'options' => [['label' => 'Mac', 'votes' => 0], ['label' => 'Linux', 'votes' => 0]],+ 'duration_minutes' => null,+ 'multiple' => false,+ 'voters' => null,+ 'totals_hidden' => true,+ ...$overrides(),+ ], type: ContentType::MastodonPoll);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $summary = Str::squish((string) $page->text("@post-poll-{$post->id}-summary"));++ expect($summary)->toStartWith(__('posts.poll_results.hidden')." · {$shown}");++ foreach ($hidden as $text) {+ expect($summary)->not->toContain($text);+ }++ $page->assertMissing("@post-poll-{$post->id}-option-0-votes")->assertNoJavaScriptErrors();+})->with([+ 'closed: final results' => [fn (): array => ['voting_status' => 'closed', 'end_datetime' => now()->subHour()->toIso8601String()], 'Final results', ['Voting ended']],+ 'open, end ahead: when it ends' => [fn (): array => ['voting_status' => 'open', 'end_datetime' => now()->addHours(5)->toIso8601String()], 'Ends ', ['Final results', 'Voting ended']],+]);++test('a published threads poll threads has not read yet shows its choices with no votes and no end', function () {+ [$user, $account] = pollResultsAccount('threads');+ $post = Post::factory()->forAccount($account, ContentType::ThreadsPoll)->published()->create([+ 'user_id' => $user->id,+ 'scheduled_at' => now()->subMinutes(5),+ 'published_at' => now()->subMinutes(5),+ 'meta' => ['poll' => ['options' => ['Mac', 'Linux']]],+ ]);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')+ ->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '0 votes')+ ->assertSeeIn("@post-poll-{$post->id}-option-1", 'Linux')+ ->assertSeeIn("@post-poll-{$post->id}-summary", '0 votes')+ ->assertDontSeeIn("@post-poll-{$post->id}-summary", 'Ends')+ ->assertNoJavaScriptErrors();+});++test('a published mastodon poll that hides its votes says so before its first read', function () {+ [$user, $account] = pollResultsAccount('mastodon');+ $post = Post::factory()->forAccount($account, ContentType::MastodonPoll)->published()->create([+ 'user_id' => $user->id,+ 'scheduled_at' => now()->subMinutes(5),+ 'published_at' => now()->subMinutes(5),+ 'meta' => ['poll' => ['options' => ['Mac', 'Linux'], 'duration_minutes' => 1440, 'hide_totals' => true]],+ ]);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-summary", __('posts.poll_results.hidden'))+ ->assertSeeIn("@post-poll-{$post->id}-option-0", 'Mac')+ ->assertMissing("@post-poll-{$post->id}-option-0-votes")+ ->assertNoJavaScriptErrors();+});++test('a mastodon reply poll the last read did not return shows its choices with no votes next to the one it did', function () {+ [$user, $account, $post] = pollResultsSetup(null, type: ContentType::MastodonPost);+ $post->update(['meta' => ['thread_replies' => [+ ['text' => 'Which one?', 'media' => [], 'poll' => ['options' => ['Mac', 'Linux'], 'duration_minutes' => 1440]],+ ['text' => 'And at work?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 1440]],+ ]]]);+ $publication = AnalyticsPublication::query()->where('post_id', $post->id)->sole();+ $publication->forceFill(['provider_metadata' => [...($publication->provider_metadata ?? []), 'thread_polls' => [+ ['reply' => 1, ...refundPoll(), 'options' => [['label' => 'Yes', 'votes' => 3], ['label' => 'No', 'votes' => 1]]],+ ]]])->save();+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}-reply-1");+ waitFor($page, "@post-poll-{$post->id}-reply-0");++ $page->assertSeeIn("@post-poll-{$post->id}-reply-0-option-0", 'Mac')+ ->assertSeeIn("@post-poll-{$post->id}-reply-0-option-0-votes", '0 votes')+ ->assertSeeIn("@post-poll-{$post->id}-reply-1-option-0", 'Yes')+ ->assertSeeIn("@post-poll-{$post->id}-reply-1-option-0-votes", '3 votes')+ ->assertSeeIn("@post-poll-{$post->id}-reply-1-option-0-votes", '75%')+ ->assertNoJavaScriptErrors();+});++test('a multiple choice poll that counts no voters but has votes shows 0% for every choice', function () {+ [$user, $account, $post] = pollResultsSetup([+ 'options' => [['label' => 'Mac', 'votes' => 2], ['label' => 'Linux', 'votes' => 1]],+ 'voting_status' => 'open',+ 'end_datetime' => now()->addHours(5)->toIso8601String(),+ 'duration_minutes' => null,+ 'multiple' => true,+ 'voters' => 0,+ 'totals_hidden' => false,+ ], type: ContentType::MastodonPoll);+ $this->actingAs($user);++ $page = visit(route('app.channels.publish', [$account, 'tab' => 'sent']));+ waitFor($page, "@post-poll-{$post->id}");++ $page->assertSeeIn("@post-poll-{$post->id}-option-0-votes", '0%')+ ->assertSeeIn("@post-poll-{$post->id}-option-1-votes", '0%')+ ->assertSeeIn("@post-poll-{$post->id}-summary", trans_choice('posts.poll_results.voters', 0, ['count' => 0]))+ ->assertDontSeeIn("@post-poll-{$post->id}", 'NaN')+ ->assertDontSeeIn("@post-poll-{$post->id}", 'Infinity')+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Browser/RepurposeTest.php b/tests/Browser/RepurposeTest.phpindex c82b7b09b..aa6f3caf3 100644--- a/tests/Browser/RepurposeTest.php+++ b/tests/Browser/RepurposeTest.php@@ -566,6 +566,34 @@ test('an x destination offers no poll, while a threads destination still offers->assertNoJavaScriptErrors();});+test('mastodon and threads destinations offer no poll', function () {+ [$user, $workspace, $source] = repurposeOwnerWithAccounts();+ $mastodon = SocialAccount::factory()->for($workspace)->mastodon()->create();+ $threads = SocialAccount::factory()->for($workspace)->threads()->create();+ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'source_social_account_id' => $source->id,+ 'destinations' => [+ ['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => []],+ ['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => []],+ ],+ ]);+ $this->actingAs($user);++ $page = visit(route('app.repurposes.show', $repurpose))->resize(1440, 1000);+ waitFor($page, "@channel-row-{$mastodon->id}");+ waitFor($page, "@channel-row-{$threads->id}");+ waitForState($page, "@channel-{$mastodon->id}", "element.getAttribute('aria-checked') === 'true'");++ $page->assertAttribute("@channel-{$threads->id}", 'aria-checked', 'true')+ ->assertMissing("@channel-type-{$mastodon->id}-mastodon_poll")+ ->assertMissing("@channel-type-{$mastodon->id}")+ ->assertPresent("@channel-type-{$threads->id}-threads_post")+ ->assertMissing("@channel-type-{$threads->id}-threads_poll")+ ->assertNoJavaScriptErrors();+});+test('on a phone the header puts the summary and the actions on their own rows', function () {[$user, $workspace, $source, $destination] = repurposeOwnerWithAccounts();diff --git a/tests/Feature/Actions/Post/DuplicatePostTest.php b/tests/Feature/Actions/Post/DuplicatePostTest.phpindex d888b4af6..68eac7630 100644--- a/tests/Feature/Actions/Post/DuplicatePostTest.php+++ b/tests/Feature/Actions/Post/DuplicatePostTest.php@@ -98,12 +98,11 @@ test('execute refuses a duplicate when the channel was removed', function () {->toThrow(ValidationException::class);});-test('execute keeps an x poll with its choices and length', function () {+test('execute keeps a poll with its choices and settings', function (string $platform, ContentType $type, array $poll) {$user = User::factory()->create();$workspace = Workspace::factory()->create(['user_id' => $user->id]);- $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);- $poll = ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 4320];- $original = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create([+ $account = SocialAccount::factory()->{$platform}()->create(['workspace_id' => $workspace->id]);+ $original = Post::factory()->forAccount($account, $type)->published()->create(['user_id' => $user->id,'content' => 'Tabs or spaces?','meta' => ['poll' => $poll],@@ -111,6 +110,10 @@ test('execute keeps an x poll with its choices and length', function () {$copy = DuplicatePost::execute($original, $user)->fresh();- expect($copy->content_type)->toBe(ContentType::XPoll)+ expect($copy->content_type)->toBe($type)->and($copy->meta['poll'])->toEqual($poll);-});+})->with([+ 'x' => ['x', ContentType::XPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],+ 'mastodon' => ['mastodon', ContentType::MastodonPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]],+ 'threads' => ['threads', ContentType::ThreadsPoll, ['options' => ['Tabs', 'Spaces', 'Both']]],+]);diff --git a/tests/Feature/Ai/PostAiAssistantTest.php b/tests/Feature/Ai/PostAiAssistantTest.phpindex 713b8995a..1adc2c394 100644--- a/tests/Feature/Ai/PostAiAssistantTest.php+++ b/tests/Feature/Ai/PostAiAssistantTest.php@@ -217,6 +217,28 @@ test('the assistant writes a poll question within 280 characters even on an accoPostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), 'Hard limit: '.XPoll::QUESTION_MAX_LENGTH.' characters'));});+test('the assistant writes a mastodon or threads poll question within the account limit, not 280', function (string $platform, ContentType $type) {+ config()->set('trypost.self_hosted', true);+ $account = SocialAccount::factory()->{$platform}()->create(['workspace_id' => $this->workspace->id]);+ PostWritingAssistant::fake(['Tabs or spaces?']);++ $this->actingAs($this->user)+ ->postJson(route('app.posts.ai.assist'), [+ 'mode' => 'generate',+ 'prompt' => 'ask our followers about tabs or spaces',+ 'platform' => $account->platform->value,+ 'social_account_id' => $account->id,+ 'content_type' => $type->value,+ ])+ ->assertOk();++ expect($account->maxContentLength())->toBe(500);+ PostWritingAssistant::assertPrompted(fn (AgentPrompt $prompt): bool => Str::contains($prompt->agent->instructions(), "Hard limit: {$account->maxContentLength()} characters"));+})->with([+ 'mastodon' => ['mastodon', ContentType::MastodonPoll],+ 'threads' => ['threads', ContentType::ThreadsPoll],+]);+test('the assistant ignores a post type of another network when picking the limit', function () {PostWritingAssistant::fake(['Big news.']);diff --git a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php b/tests/Feature/Analytics/ChannelInsightsFiltersTest.phpindex d2a03e26f..5c9760e06 100644--- a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php+++ b/tests/Feature/Analytics/ChannelInsightsFiltersTest.php@@ -236,19 +236,20 @@ test('the channel export is not available for another workspace channel', functi->assertNotFound();});-test('the poll type counts polls made on x that were never imported', function (string $type, array $expected) {- $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);- $publish = function (string $key, int $daysAgo, ?ContentType $contentType = null, PublicationContentType $publicationType = PublicationContentType::Text) use ($x): array {+test('the poll type counts polls made on the network that were never imported', function (string $platform, ContentType $postType, ContentType $pollType, string $filter, array $expected) {+ $account = SocialAccount::factory()->{$platform}()->create(['workspace_id' => $this->workspace->id]);+ $type = ['poll' => $pollType, 'post' => $postType][$filter]->value;+ $publish = function (string $key, int $daysAgo, ?ContentType $contentType = null, PublicationContentType $publicationType = PublicationContentType::Text) use ($account): array {$post = filled($contentType)- ? Post::factory()->forAccount($x, $contentType)->published()->create(['user_id' => $this->user->id])+ ? Post::factory()->forAccount($account, $contentType)->published()->create(['user_id' => $this->user->id]): null;$publication = AnalyticsPublication::factory()->create(['workspace_id' => $this->workspace->id,- 'social_account_id' => $x->id,- 'social_account_key' => $x->id,- 'network' => $x->platform->network(),- 'platform_user_id' => $x->platform_user_id,- 'platform' => Platform::X,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'network' => $account->platform->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'platform' => $account->platform,'post_id' => $post?->id,'content_type' => $publicationType,'provider_published_at' => now('UTC')->subDays($daysAgo),@@ -257,20 +258,24 @@ test('the poll type counts polls made on x that were never imported', function (return [$key => $publication->id];};$ids = [- ...$publish('post', 2, ContentType::XPost),- ...$publish('poll', 3, ContentType::XPoll),+ ...$publish('post', 2, $postType),+ ...$publish('poll', 3, $pollType),...$publish('external_post', 4),...$publish('external_poll', 5, publicationType: PublicationContentType::Poll),];$this->actingAs($this->user)- ->get(filteredInsightsUrl($x, ['types' => [$type]]))+ ->get(filteredInsightsUrl($account, ['types' => [$type]]))->assertOk()->assertInertia(fn (Assert $page) => $page->where('report.summary.posts.value', count($expected))->where('publications.data', fn ($publications): bool => collect($publications)->pluck('id')->sort()->values()->all() === collect($expected)->map(fn (string $key): string => $ids[$key])->sort()->values()->all())->etc());})->with([- 'poll' => ['x_poll', ['poll', 'external_poll']],- 'post' => ['x_post', ['post', 'external_post']],+ 'x' => ['x', ContentType::XPost, ContentType::XPoll],+ 'mastodon' => ['mastodon', ContentType::MastodonPost, ContentType::MastodonPoll],+ 'threads' => ['threads', ContentType::ThreadsPost, ContentType::ThreadsPoll],+])->with([+ 'poll' => ['poll', ['poll', 'external_poll']],+ 'post' => ['post', ['post', 'external_post']],]);diff --git a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.phpindex 62ace8eac..71502f048 100644--- a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php@@ -7,11 +7,14 @@ use App\Enums\Analytics\PublicationContentType;use App\Enums\SocialAccount\Platform;use App\Exceptions\Analytics\AnalyticsCollectionException;use App\Models\SocialAccount;+use App\Services\Analytics\Collectors\Publications\MastodonPublicationCollector;use App\Services\Analytics\Collectors\Publications\PinterestPublicationCollector;use App\Services\Analytics\Collectors\Publications\PublicationHistoryCollectorFactory;+use App\Services\Analytics\Collectors\Publications\ThreadsPublicationCollector;use App\Services\Analytics\Collectors\Publications\TikTokPublicationCollector;use App\Services\Analytics\Collectors\Publications\XPublicationCollector;use App\Services\Analytics\Collectors\Publications\YouTubePublicationCollector;+use App\Support\Social\ThreadsPoll;use App\Support\Social\XPoll;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Request;@@ -504,3 +507,92 @@ test('x discovery keeps the poll of a post made on x', function () {Http::assertSent(fn (Request $request): bool => $request['expansions'] === 'attachments.media_keys,attachments.poll_ids'&& $request['poll.fields'] === XPoll::LOOKUP_FIELDS);});++test('mastodon discovery keeps the poll of a status made on mastodon', function () {+ $createdAt = now()->subDay()->toIso8601ZuluString();+ $endsAt = now()->addDay()->toIso8601ZuluString();+ Http::fake(['*' => Http::response([+ [+ 'id' => 'status-poll',+ 'created_at' => $createdAt,+ 'content' => '<p>Tabs or spaces?</p>',+ 'media_attachments' => [],+ 'poll' => [+ 'expires_at' => $endsAt,+ 'expired' => false,+ 'multiple' => false,+ 'options' => [['title' => 'Tabs', 'votes_count' => 2], ['title' => 'Spaces', 'votes_count' => 5]],+ ],+ ],+ ['id' => 'status-plain', 'created_at' => $createdAt, 'content' => '<p>Plain</p>', 'media_attachments' => []],+ ])]);+ $account = SocialAccount::factory()->mastodon()->create();++ $page = app(MastodonPublicationCollector::class)->page($account, null, now()->subYear()->toImmutable());++ expect($page->publications[0]->contentType)->toBe(PublicationContentType::Poll)+ ->and($page->publications[0]->providerMetadata['poll'])->toEqual([+ 'options' => [['label' => 'Tabs', 'votes' => 2], ['label' => 'Spaces', 'votes' => 5]],+ 'voting_status' => 'open',+ 'end_datetime' => $endsAt,+ 'duration_minutes' => null,+ 'multiple' => false,+ 'voters' => null,+ 'totals_hidden' => false,+ ])+ ->and($page->publications[1]->contentType)->toBe(PublicationContentType::Text)+ ->and($page->publications[1]->providerMetadata)->not->toHaveKey('poll');+ Http::assertSentCount(1);+});++test('threads discovery reads the poll in the same request and works out its votes', function () {+ $endsAt = now()->addHours(12)->startOfSecond();+ Http::fake(['*' => Http::response(['data' => [+ [+ 'id' => 'thread-poll',+ 'media_type' => 'TEXT_POST',+ 'text' => 'Tabs or spaces?',+ 'timestamp' => now()->subHour()->toIso8601String(),+ 'poll_attachment' => [+ 'option_a' => 'Tabs',+ 'option_b' => 'Spaces',+ 'option_c' => 'Both',+ 'option_a_votes_percentage' => 0.25,+ 'option_b_votes_percentage' => 0.7,+ 'option_c_votes_percentage' => 0.05,+ 'total_votes' => 20,+ 'expiration_timestamp' => $endsAt->toIso8601String(),+ ],+ ],+ ['id' => 'thread-plain', 'media_type' => 'TEXT_POST', 'text' => 'Plain', 'timestamp' => now()->subHour()->toIso8601String()],+ ]])]);+ $account = SocialAccount::factory()->threads()->create();++ $page = app(ThreadsPublicationCollector::class)->page($account, null, now()->subYear()->toImmutable());++ expect($page->publications[0]->contentType)->toBe(PublicationContentType::Poll)+ ->and($page->publications[0]->providerMetadata['poll'])->toEqual([+ 'options' => [['label' => 'Tabs', 'votes' => 5], ['label' => 'Spaces', 'votes' => 14], ['label' => 'Both', 'votes' => 1]],+ 'voting_status' => 'open',+ 'end_datetime' => $endsAt->utc()->toIso8601ZuluString(),+ 'duration_minutes' => null,+ ])+ ->and($page->publications[1]->contentType)->toBe(PublicationContentType::Text)+ ->and($page->publications[1]->providerMetadata)->toBe(['is_quote_post' => false]);+ Http::assertSentCount(1);+ Http::assertSent(fn (Request $request): bool => str_contains((string) $request['fields'], ThreadsPoll::LOOKUP_FIELDS));+});++test('a threads poll whose end has passed is closed', function () {+ $result = ThreadsPoll::result([+ 'option_a' => 'Tabs',+ 'option_b' => 'Spaces',+ 'option_a_votes_percentage' => 0.4,+ 'option_b_votes_percentage' => 0.6,+ 'total_votes' => 10,+ 'expiration_timestamp' => now()->subMinute()->toIso8601String(),+ ]);++ expect($result['voting_status'])->toBe('closed')+ ->and($result['options'])->toBe([['label' => 'Tabs', 'votes' => 4], ['label' => 'Spaces', 'votes' => 6]]);+});diff --git a/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.phpindex c6879d85f..0ca3f226f 100644--- a/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php@@ -5,11 +5,13 @@ declare(strict_types=1);use App\Enums\Analytics\PublicationContentType;use App\Enums\SocialAccount\Platform;use App\Models\SocialAccount;+use App\Services\Analytics\Collectors\Publications\AbstractApiPublicationCollector;use App\Services\Analytics\Collectors\Publications\BlueskyPublicationCollector;use App\Services\Analytics\Collectors\Publications\MastodonPublicationCollector;use App\Services\Analytics\Collectors\Publications\PublicationHistoryCollectorFactory;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Request;+use Illuminate\Http\Client\Response;use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Http;@@ -313,3 +315,42 @@ test('bluesky stops at the cutoff even when the older records are replies', func->and($page->nextCursor)->toBeNull()->and($page->providerExhausted)->toBeTrue();});++/**+ * A collector that sends one GET, as every API collector does.+ */+function plainApiCollector(): AbstractApiPublicationCollector+{+ return new class extends AbstractApiPublicationCollector+ {+ /** @param array<string, mixed> $query */+ public function read(string $url, array $query): Response+ {+ return $this->get(SocialAccount::factory()->mastodon()->make(), $url, $query, authenticated: false);+ }+ };+}++test('a collector read sends only the filled query parameters, keeping zero and false', function () {+ Http::fake(['https://api.example/*' => Http::response([])]);++ plainApiCollector()->read('https://api.example/items', [+ 'space' => ' ',+ 'list' => [],+ 'none' => null,+ 'empty' => '',+ 'zero' => 0,+ 'off' => false,+ 'limit' => 20,+ ]);++ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.example/items?zero=0&off=0&limit=20');+});++test('a collector read without a filled query parameter keeps the query its url carries', function () {+ Http::fake(['https://api.example/*' => Http::response([])]);++ plainApiCollector()->read('https://api.example/items?id%5B%5D=1&id%5B%5D=2', ['none' => null, 'empty' => '']);++ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://api.example/items?id%5B%5D=1&id%5B%5D=2');+});diff --git a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.phpindex 5304553ab..e39af888c 100644--- a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php@@ -25,6 +25,7 @@ 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\ThreadsPoll;use App\Support\Social\XPoll;use Carbon\CarbonImmutable;use Illuminate\Http\Client\Request;@@ -637,6 +638,67 @@ test('mastodon reads a public status without a token that lacks read scope', fun'token with read:statuses' => [['read:accounts', 'read:statuses', 'write:statuses', 'write:media'], true],]);+test('mastodon keeps the poll result from the status it already reads', function (bool $expired, ?int $hiddenVotes, int $storedVotes, string $status) {+ $endsAt = now()->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses/*' => Http::response([+ 'id' => '117304063461175259',+ 'replies_count' => 1,+ 'reblogs_count' => 0,+ 'favourites_count' => 0,+ 'poll' => [+ 'expires_at' => $endsAt,+ 'expired' => $expired,+ 'multiple' => true,+ 'options' => [['title' => 'Tabs', 'votes_count' => 3], ['title' => 'Spaces', 'votes_count' => $hiddenVotes]],+ ],+ ])]);+ $account = SocialAccount::factory()->mastodon()->create();+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::Mastodon,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => '117304063461175259',+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toEqual(['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 3], ['label' => 'Spaces', 'votes' => $storedVotes]],+ 'voting_status' => $status,+ 'end_datetime' => $endsAt,+ 'duration_minutes' => null,+ 'multiple' => true,+ 'voters' => null,+ 'totals_hidden' => blank($hiddenVotes),+ ]]);+ Http::assertSentCount(1);+})->with([+ 'open' => [false, 1, 1, 'open'],+ 'ended, a total still hidden reading as no votes' => [true, null, 0, 'closed'],+]);++test('mastodon stores no poll for a status without one', function () {+ Http::fake(['https://mastodon.social/api/v1/statuses/*' => Http::response([+ 'id' => '117304063461175259',+ 'replies_count' => 1,+ 'reblogs_count' => 0,+ 'favourites_count' => 0,+ ])]);+ $account = SocialAccount::factory()->mastodon()->create();+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::Mastodon,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => '117304063461175259',+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toBeNull();+});+test('facebook keeps public post counts when Page insights are not available', function () {$graph = config('trypost.platforms.facebook.graph_api');$account = SocialAccount::factory()->facebook()->create();@@ -1672,3 +1734,415 @@ test('the x collector leaves out a reply poll whose tweet is gone and still read$metrics = collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value]);expect($metrics->all())->toMatchArray(['impressions' => 200]);});++/**+ * A published Mastodon poll whose second reply is a poll too, with its publication.+ */+function mastodonThreadPollPublication(): AnalyticsPublication+{+ $account = SocialAccount::factory()->mastodon()->create();+ $post = Post::factory()->forAccount($account, ContentType::MastodonPoll)->published()->create([+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440], 'thread_replies' => [+ ['text' => 'Why?', 'media' => []],+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],+ ]],+ ]);+ $post->forceFill(['thread_reply_ids' => ['200', '201']])->save();++ return AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'post_id' => $post->id,+ 'platform' => Platform::Mastodon,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => '100',+ ]);+}++/**+ * @param array<int, int> $votes+ * @return array<string, mixed>+ */+function mastodonPollStatus(string $id, array $labels, array $votes, string $endsAt): array+{+ return [+ 'id' => $id,+ 'replies_count' => 1,+ 'reblogs_count' => 2,+ 'favourites_count' => 3,+ 'poll' => [+ 'expires_at' => $endsAt,+ 'expired' => false,+ 'multiple' => false,+ 'options' => collect($labels)->map(fn (string $label, int $index): array => ['title' => $label, 'votes_count' => $votes[$index]])->all(),+ ],+ ];+}++test('the mastodon collector reads the polls of the thread replies in the same request as the status', function () {+ $publication = mastodonThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response([+ mastodonPollStatus('201', ['Yes', 'No'], [5, 3], $endsAt),+ mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt),+ ])]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(1);+ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://mastodon.social/api/v1/statuses?id%5B%5D=100&id%5B%5D=201');+ expect($observation->providerMetadata['poll']['options'])->toEqual([['label' => 'Tabs', 'votes' => 1], ['label' => 'Spaces', 'votes' => 2]])+ ->and($observation->providerMetadata['thread_polls'])->toEqual([[+ 'reply' => 1,+ 'options' => [['label' => 'Yes', 'votes' => 5], ['label' => 'No', 'votes' => 3]],+ 'voting_status' => 'open',+ 'end_datetime' => $endsAt,+ 'duration_minutes' => null,+ 'multiple' => false,+ 'voters' => null,+ 'totals_hidden' => false,+ ]]);+ expect(collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value])->all())+ ->toMatchArray(['reactions' => 3, 'comments' => 1, 'shares' => 2]);+});++test('the mastodon collector reads the status alone when the server has no multiple read or leaves the status out', function (int $status, array $body) {+ $publication = mastodonThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake([+ 'https://mastodon.social/api/v1/statuses?*' => Http::response($body, $status),+ 'https://mastodon.social/api/v1/statuses/100' => Http::response(mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt)),+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(2);+ expect($observation->providerMetadata)->toHaveKey('poll')->not->toHaveKey('thread_polls');+})->with([+ 'a server before mastodon 4.3' => [404, ['error' => 'Record not found']],+ 'the status left out' => [200, []],+]);++test('the mastodon collector reads a thread without a reply poll as before, one status alone', function () {+ $publication = mastodonThreadPollPublication();+ $publication->post->forceFill(['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440], 'thread_replies' => [['text' => 'Why?', 'media' => []]]]])->save();+ Http::fake(['https://mastodon.social/api/v1/statuses/100' => Http::response(mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], now('UTC')->addDay()->toIso8601ZuluString()))]);++ app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(1);+ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://mastodon.social/api/v1/statuses/100');+});++test('the mastodon collector retries later when the multiple read is only rate limited', function () {+ $publication = mastodonThreadPollPublication();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response(['error' => 'Too many requests'], 429)]);++ expect(fn () => app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))+ ->toThrow(AnalyticsCollectionException::class);+ Http::assertSentCount(1);+});++function threadsPollPublication(PublicationContentType $type = PublicationContentType::Poll): AnalyticsPublication+{+ $account = SocialAccount::factory()->threads()->create();++ return AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'platform' => Platform::Threads,+ 'platform_user_id' => $account->platform_user_id,+ 'remote_id' => 'thread-1',+ 'content_type' => $type,+ ]);+}++function fakeThreadsInsights(mixed $postRead): void+{+ $graph = config('trypost.platforms.threads.graph_api');++ Http::fake([+ "{$graph}/thread-1/insights*" => Http::response(['data' => [['name' => 'views', 'total_value' => ['value' => 40]]]]),+ "{$graph}/thread-1?*" => $postRead,+ ]);+}++test('the threads collector reads a poll result on each metrics read, like x', function () {+ $endsAt = now('UTC')->addHours(12)->startOfSecond();+ fakeThreadsInsights(Http::response(['id' => 'thread-1', 'poll_attachment' => [+ 'option_a' => 'Tabs',+ 'option_b' => 'Spaces',+ 'option_a_votes_percentage' => 0.25,+ 'option_b_votes_percentage' => 0.75,+ 'total_votes' => 8,+ 'expiration_timestamp' => $endsAt->toIso8601String(),+ ]]));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(), CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toEqual(['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 2], ['label' => 'Spaces', 'votes' => 6]],+ 'voting_status' => 'open',+ 'end_datetime' => $endsAt->toIso8601ZuluString(),+ 'duration_minutes' => null,+ ]]);+ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/thread-1?') && $request['fields'] === ThreadsPoll::LOOKUP_FIELDS);+});++test('the threads collector makes no poll read for a post that is not a poll', function () {+ fakeThreadsInsights(Http::response([], 500));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(PublicationContentType::Text), CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toBeNull();+ Http::assertSentCount(1);+});++test('the threads collector keeps the metrics when the poll read is refused', function () {+ fakeThreadsInsights(Http::response(['error' => ['message' => 'Missing permission', 'type' => 'OAuthException', 'code' => 10]], 403));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(), CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toBeNull()+ ->and(collect($observation->metrics)->mapWithKeys(fn ($metric) => [$metric->key->value => $metric->value])->all())->toMatchArray(['views' => 40]);+});++test('the threads collector stops reading a poll once its stored result is closed', function () {+ $publication = threadsPollPublication();+ $publication->update(['provider_metadata' => ['poll' => ['options' => [], 'voting_status' => 'closed']]]);+ fakeThreadsInsights(Http::response([], 500));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toBeNull();+ Http::assertSentCount(1);+});++test('the mastodon collector skips a reply poll the multiple read leaves out and keeps the others', function () {+ $publication = mastodonThreadPollPublication();+ $publication->post->forceFill(['meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440], 'thread_replies' => [+ ['text' => 'Why?', 'media' => [], 'poll' => ['options' => ['Fast', 'Slow'], 'duration_minutes' => 60]],+ ['text' => 'And next time?', 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],+ ]]])->save();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response([+ mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt),+ mastodonPollStatus('201', ['Yes', 'No'], [5, 3], $endsAt),+ ])]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(1);+ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://mastodon.social/api/v1/statuses?id%5B%5D=100&id%5B%5D=200&id%5B%5D=201');+ expect(collect($observation->providerMetadata['thread_polls'])->pluck('reply')->all())->toBe([1])+ ->and($observation->providerMetadata['thread_polls'][0]['options'])->toEqual([['label' => 'Yes', 'votes' => 5], ['label' => 'No', 'votes' => 3]]);+});++test('the mastodon collector reads the status alone when the multiple read is refused', function (int $status) {+ $publication = mastodonThreadPollPublication();+ Http::fake([+ 'https://mastodon.social/api/v1/statuses?*' => Http::response(['error' => 'This action is not allowed'], $status),+ 'https://mastodon.social/api/v1/statuses/100' => Http::response(mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], now('UTC')->addDay()->toIso8601ZuluString())),+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(2);+ Http::assertSent(fn (Request $request): bool => $request->url() === 'https://mastodon.social/api/v1/statuses/100');+ expect($observation->providerMetadata)->toHaveKey('poll')->not->toHaveKey('thread_polls');+})->with([401, 403]);++test('the mastodon collector marks a reply poll whose totals mastodon hides', function () {+ $publication = mastodonThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ $reply = mastodonPollStatus('201', ['Yes', 'No'], [5, 3], $endsAt);+ data_set($reply, 'poll.options', [['title' => 'Yes', 'votes_count' => null], ['title' => 'No', 'votes_count' => null]]);+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response([mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt), $reply])]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata['thread_polls'][0])->toMatchArray([+ 'reply' => 1,+ 'options' => [['label' => 'Yes', 'votes' => 0], ['label' => 'No', 'votes' => 0]],+ 'totals_hidden' => true,+ ])+ ->and($observation->providerMetadata['poll']['totals_hidden'])->toBeFalse();+});++test('the mastodon collector keeps how many people voted on a multiple choice poll', function () {+ $publication = mastodonThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ $status = mastodonPollStatus('100', ['Tabs', 'Spaces'], [4, 3], $endsAt);+ data_set($status, 'poll.multiple', true);+ data_set($status, 'poll.voters_count', 5);+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response([$status, mastodonPollStatus('201', ['Yes', 'No'], [5, 3], $endsAt)])]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata['poll'])->toMatchArray(['multiple' => true, 'voters' => 5])+ ->and($observation->providerMetadata['thread_polls'][0])->toMatchArray(['multiple' => false, 'voters' => null]);+});++test('the threads collector retries later when the poll read fails for now', function (int $status) {+ fakeThreadsInsights(Http::response(['error' => ['message' => 'Please retry', 'type' => 'OAuthException', 'code' => 2]], $status));++ expect(fn () => app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(), CarbonImmutable::today('UTC')))+ ->toThrow(AnalyticsCollectionException::class);+})->with([500, 429]);++test('the threads collector stores no poll when the poll read has no poll', function () {+ fakeThreadsInsights(Http::response(['id' => 'thread-1']));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(), CarbonImmutable::today('UTC'));++ expect($observation->providerMetadata)->toBeNull();+ Http::assertSentCount(2);+});++test('the threads collector reads a poll once more after its stored end, so the final tally is stored closed', function () {+ $endedAt = now('UTC')->subHour()->startOfSecond();+ $publication = threadsPollPublication();+ $publication->update(['provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 1], ['label' => 'Spaces', 'votes' => 1]],+ 'voting_status' => 'open',+ 'end_datetime' => $endedAt->toIso8601ZuluString(),+ ]]]);+ fakeThreadsInsights(Http::response(['id' => 'thread-1', 'poll_attachment' => [+ 'option_a' => 'Tabs',+ 'option_b' => 'Spaces',+ 'option_a_votes_percentage' => 0.25,+ 'option_b_votes_percentage' => 0.75,+ 'total_votes' => 8,+ 'expiration_timestamp' => $endedAt->toIso8601String(),+ ]]));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect(data_get($observation->providerMetadata, 'poll.voting_status'))->toBe('closed')+ ->and(data_get($observation->providerMetadata, 'poll.options'))->toBe([['label' => 'Tabs', 'votes' => 2], ['label' => 'Spaces', 'votes' => 6]]);+ Http::assertSentCount(2);+});++test('the threads collector keeps reading a poll whose stored end is still ahead', function () {+ $publication = threadsPollPublication();+ $publication->update(['provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 0], ['label' => 'Spaces', 'votes' => 0]],+ 'voting_status' => 'open',+ 'end_datetime' => now('UTC')->addHours(2)->toIso8601ZuluString(),+ ]]]);+ fakeThreadsInsights(Http::response(['id' => 'thread-1', 'poll_attachment' => [+ 'option_a' => 'Tabs',+ 'option_b' => 'Spaces',+ 'option_a_votes_percentage' => 0.5,+ 'option_b_votes_percentage' => 0.5,+ 'total_votes' => 4,+ 'expiration_timestamp' => now('UTC')->addHours(2)->toIso8601String(),+ ]]));++ $observation = app(ThreadsPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ expect(data_get($observation->providerMetadata, 'poll.voting_status'))->toBe('open');+ Http::assertSentCount(2);+});++/**+ * A published Mastodon poll whose 24 replies are all polls, reply n published as status 200 + n.+ */+function mastodonFullThreadPollPublication(): AnalyticsPublication+{+ $publication = mastodonThreadPollPublication();+ $publication->post->forceFill([+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 1440], 'thread_replies' => collect(range(0, 23))+ ->map(fn (int $reply): array => ['text' => "Reply {$reply}?", 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]])+ ->all()],+ 'thread_reply_ids' => collect(range(0, 23))->map(fn (int $reply): string => (string) (200 + $reply))->all(),+ ])->save();++ return $publication;+}++/**+ * @param list<int> $ids+ */+function mastodonStatusesUrl(array $ids): string+{+ return 'https://mastodon.social/api/v1/statuses?'.collect($ids)->map(fn (int $id): string => "id%5B%5D={$id}")->implode('&');+}++test('the mastodon collector reads a thread of 24 reply polls in reads of 20 statuses', function () {+ $publication = mastodonFullThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::sequence()+ ->push([mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt), ...collect(range(200, 218))->map(fn (int $id): array => mastodonPollStatus((string) $id, ['Yes', 'No'], [$id - 200, 1], $endsAt))->all()])+ ->push(collect(range(219, 223))->map(fn (int $id): array => mastodonPollStatus((string) $id, ['Yes', 'No'], [$id - 200, 1], $endsAt))->all()),+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(2);+ Http::assertSent(fn (Request $request): bool => $request->url() === mastodonStatusesUrl([100, ...range(200, 218)]));+ Http::assertSent(fn (Request $request): bool => $request->url() === mastodonStatusesUrl(range(219, 223)));+ expect(collect($observation->providerMetadata['thread_polls'])->pluck('reply')->all())->toBe(range(0, 23))+ ->and($observation->providerMetadata['thread_polls'][23]['options'])->toEqual([['label' => 'Yes', 'votes' => 23], ['label' => 'No', 'votes' => 1]])+ ->and($observation->providerMetadata['poll']['options'])->toEqual([['label' => 'Tabs', 'votes' => 1], ['label' => 'Spaces', 'votes' => 2]]);+});++test('the mastodon collector keeps the reply polls of the first read when a later read is refused', function () {+ $publication = mastodonFullThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::sequence()+ ->push([mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt), ...collect(range(200, 218))->map(fn (int $id): array => mastodonPollStatus((string) $id, ['Yes', 'No'], [1, 1], $endsAt))->all()])+ ->push(['error' => 'This action is not allowed'], 403),+ ]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSentCount(2);+ expect(collect($observation->providerMetadata['thread_polls'])->pluck('reply')->all())->toBe(range(0, 18))+ ->and($observation->providerMetadata)->toHaveKey('poll');+});++test('the mastodon collector retries later when a later read of the thread is only rate limited', function () {+ $publication = mastodonFullThreadPollPublication();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::sequence()+ ->push([mastodonPollStatus('100', ['Tabs', 'Spaces'], [1, 2], $endsAt), ...collect(range(200, 218))->map(fn (int $id): array => mastodonPollStatus((string) $id, ['Yes', 'No'], [1, 1], $endsAt))->all()])+ ->push(['error' => 'Too many requests'], 429),+ ]);++ expect(fn () => app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC')))+ ->toThrow(AnalyticsCollectionException::class);+ Http::assertSentCount(2);+});++test('the mastodon collector stores only the reply poll of a plain post whose first reply is a poll', function () {+ $publication = mastodonThreadPollPublication();+ $publication->post->forceFill([+ 'content_type' => ContentType::MastodonPost,+ 'meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'media' => [], 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]],+ 'thread_reply_ids' => ['200'],+ ])->save();+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();+ $status = Arr::except(mastodonPollStatus('100', [], [], $endsAt), 'poll');+ Http::fake(['https://mastodon.social/api/v1/statuses?*' => Http::response([$status, mastodonPollStatus('200', ['Tabs', 'Spaces'], [4, 1], $endsAt)])]);++ $observation = app(MastodonPublicationMetricsCollector::class)->collect($publication, CarbonImmutable::today('UTC'));++ Http::assertSent(fn (Request $request): bool => $request->url() === mastodonStatusesUrl([100, 200]));+ expect($observation->providerMetadata)->not->toHaveKey('poll')+ ->and(collect($observation->providerMetadata['thread_polls'])->pluck('reply')->all())->toBe([0])+ ->and($observation->providerMetadata['thread_polls'][0]['options'])->toEqual([['label' => 'Tabs', 'votes' => 4], ['label' => 'Spaces', 'votes' => 1]]);+});++test('the threads collector logs a refused poll read with its category, reason and path', function () {+ Log::spy();+ fakeThreadsInsights(Http::response(['error' => ['message' => 'Missing permission', 'type' => 'OAuthException', 'code' => 10]], 403));+ $path = Uri::of(config('trypost.platforms.threads.graph_api').'/thread-1')->path();++ app(ThreadsPublicationMetricsCollector::class)->collect(threadsPollPublication(), CarbonImmutable::today('UTC'));++ Log::shouldHaveReceived('info')->withArgs(fn (string $message, array $context): bool => $message === 'analytics.threads_read_refused'+ && data_get($context, 'category') === 'permission'+ && filled(data_get($context, 'reason'))+ && data_get($context, 'path') === $path)->once();+});diff --git a/tests/Feature/Analytics/PublicationMetricsJobsTest.php b/tests/Feature/Analytics/PublicationMetricsJobsTest.phpindex afb017478..0030409cd 100644--- a/tests/Feature/Analytics/PublicationMetricsJobsTest.php+++ b/tests/Feature/Analytics/PublicationMetricsJobsTest.php@@ -28,6 +28,7 @@ use App\Services\Analytics\Collectors\Metrics\MastodonPublicationMetricsCollectouse App\Services\Analytics\Collectors\Metrics\PublicationMetricsCollectorFactory;use App\Support\Analytics\SyncCadence;use App\Support\PostStatusRules;+use App\Support\Social\MastodonPoll;use Carbon\CarbonImmutable;use GuzzleHttp\Promise\PromiseInterface;use Illuminate\Support\Facades\Bus;@@ -177,8 +178,8 @@ test('regular collection respects the X and non-X refresh windows', function (Pl})->with([[Platform::X, 28, true],[Platform::X, 29, false],- [Platform::Mastodon, 30, true],- [Platform::Mastodon, 31, false],+ [Platform::Mastodon, 31, true],+ [Platform::Mastodon, 32, false],]);test('an old imported publication receives one baseline measurement only', function () {@@ -271,7 +272,7 @@ test('daily dispatcher includes old publications without a baseline and excludes}metricJobPublication(Platform::LinkedIn, $date->subDay());- $old = metricJobPublication(Platform::Mastodon, $date->subDays(31));+ $old = metricJobPublication(Platform::Mastodon, $date->subDays(32));$expiredStory = metricJobPublication(Platform::Instagram, $date->subDays(31));$expiredStory->update(['content_type' => PublicationContentType::Story]);Bus::fake([CollectPublicationMetrics::class]);@@ -476,6 +477,29 @@ test('other networks keep the daily thirty day window', function () {Bus::assertDispatchedTimes(CollectPublicationMetrics::class, 4);});+test('the daily run reads a mastodon post one day longer, after its longest poll ends', function () {+ $now = now('UTC')->startOfDay()->addHours(3);+ $this->travelTo($now);+ $published = $now->subDays(31)->setTime(23, 0);++ expect($published->addMinutes(MastodonPoll::MAX_DURATION)->lessThan($now))->toBeTrue();++ $mastodon = metricJobPublication(Platform::Mastodon, $published);+ $instagram = metricJobPublication(Platform::Instagram, $published);++ foreach ([$mastodon, $instagram] as $publication) {+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $publication->id,+ 'date' => $now->subDay()->toDateString(),+ ]);+ }++ Bus::fake([CollectPublicationMetrics::class]);+ $this->artisan('analytics:dispatch-publication-metrics')->assertSuccessful();++ expect(Bus::dispatched(CollectPublicationMetrics::class)->pluck('publicationId')->all())->toBe([$mastodon->id]);+});+test('a published post is first read an hour after publishing on every network', function (Platform $platform) {$now = CarbonImmutable::parse('2026-10-10 12:00:00', 'UTC');CarbonImmutable::setTestNow($now);@@ -848,3 +872,41 @@ test('a rediscovery keeps the poll results of the thread replies, which only theexpect($publication->refresh()->provider_metadata)->toEqual(['poll' => $poll(4), 'thread_polls' => $threadPolls]);});++test('a mastodon poll whose totals were hidden is replaced by the result read once mastodon shows them', function () {+ $date = CarbonImmutable::now('UTC');+ $publication = metricJobPublication(Platform::Mastodon, $date->subDay());+ $endsAt = $date->subHour()->toIso8601ZuluString();+ $status = fn (?int $tabs, ?int $spaces, bool $expired): array => [+ 'id' => $publication->remote_id,+ 'replies_count' => 0,+ 'reblogs_count' => 0,+ 'favourites_count' => 1,+ 'poll' => [+ 'expires_at' => $endsAt,+ 'expired' => $expired,+ 'multiple' => false,+ 'options' => [['title' => 'Tabs', 'votes_count' => $tabs], ['title' => 'Spaces', 'votes_count' => $spaces]],+ ],+ ];+ $job = new CollectPublicationMetrics($publication->id, $date->toDateString(), refreshSameDay: true);++ Http::fake(['*' => Http::sequence()+ ->push($status(null, null, false))+ ->push($status(4, 6, true))]);+ app()->call([$job, 'handle']);++ expect($publication->refresh()->provider_metadata['poll'])->toMatchArray([+ 'options' => [['label' => 'Tabs', 'votes' => 0], ['label' => 'Spaces', 'votes' => 0]],+ 'voting_status' => 'open',+ 'totals_hidden' => true,+ ]);++ app()->call([$job, 'handle']);++ expect($publication->refresh()->provider_metadata['poll'])->toMatchArray([+ 'options' => [['label' => 'Tabs', 'votes' => 4], ['label' => 'Spaces', 'votes' => 6]],+ 'voting_status' => 'closed',+ 'totals_hidden' => false,+ ]);+});diff --git a/tests/Feature/Analytics/PublicationReconciliationTest.php b/tests/Feature/Analytics/PublicationReconciliationTest.phpindex 257841789..0bdf19e4a 100644--- a/tests/Feature/Analytics/PublicationReconciliationTest.php+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php@@ -315,6 +315,8 @@ test('a network that does not report the type keeps the type TryPost published','TikTok photo' => [Platform::TikTok, ContentType::TikTokPhoto, PublicationContentType::Carousel],'YouTube Short' => [Platform::YouTube, ContentType::YouTubeShort, PublicationContentType::Short],'X poll' => [Platform::X, ContentType::XPoll, PublicationContentType::Poll],+ 'Mastodon poll' => [Platform::Mastodon, ContentType::MastodonPoll, PublicationContentType::Poll],+ 'Threads poll' => [Platform::Threads, ContentType::ThreadsPoll, PublicationContentType::Poll],]);test('a network that does not report the type stores its default on a new publication', function () {diff --git a/tests/Feature/Api/PlatformApiTest.php b/tests/Feature/Api/PlatformApiTest.phpindex 44a756dfb..9a3edf273 100644--- a/tests/Feature/Api/PlatformApiTest.php+++ b/tests/Feature/Api/PlatformApiTest.php@@ -59,15 +59,17 @@ it('lists content types per platform', function () {expect($pinterestTypes->firstWhere('value', 'pinterest_pin')['min_media_count'])->toBe(0);});-it('lists the x poll without media capabilities', function () {+it('lists each poll without media capabilities', function (string $platform, string $type) {$response = $this->withToken($this->plainToken)->getJson(route('api.content-types'))->assertOk();- $poll = collect(data_get($response->collect('platforms')->firstWhere('platform', 'x'), 'content_types'))->firstWhere('value', 'x_poll');+ $poll = collect(data_get($response->collect('platforms')->firstWhere('platform', $platform), 'content_types'))->firstWhere('value', $type);expect($poll)->toMatchArray(['max_media_count' => 0,+ 'accept_images' => false,+ 'accept_videos' => false,'accepts_gif' => false,'accepts_mov' => false,'supports_alt_text' => false,@@ -75,7 +77,11 @@ it('lists the x poll without media capabilities', function () {'max_video_bytes' => null,'max_video_duration_sec' => null,]);-});+})->with([+ 'x' => ['x', 'x_poll'],+ 'mastodon' => ['mastodon', 'mastodon_poll'],+ 'threads' => ['threads', 'threads_poll'],+]);it('rejects content-types without auth', function () {$this->getJson(route('api.content-types'))->assertUnauthorized();diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.phpindex bb223a0e4..21966e899 100644--- a/tests/Feature/Api/PostApiPlatformMetaTest.php+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php@@ -1489,7 +1489,7 @@ it('explains what is wrong with an x poll in plain words', function (mixed $poll'choice over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'meta.poll.options.0', 'Each poll choice can have up to 25 characters. Shorten the longer one.'],'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'meta.poll.options', 'A poll can have up to 4 choices. Remove the extra ones.'],'duration above 10080' => [['options' => ['a', 'b'], 'duration_minutes' => 10081], 'meta.poll.duration_minutes', 'A poll can stay open from 5 minutes to 7 days. Choose a length in that range.'],- 'poll that is not an object' => ['Yes or no', 'meta.poll', 'Send the poll with its choices (options) and length (duration_minutes).'],+ 'poll that is not an object' => ['Yes or no', 'meta.poll', 'Send the poll with its choices (options) and, on X and Mastodon, its length (duration_minutes).'],'choices sent as text' => [['options' => 'Yes, No', 'duration_minutes' => 60], 'meta.poll.options', 'Send the poll choices as a list of text.'],'a choice that is not text' => [['options' => ['Yes', ['No']], 'duration_minutes' => 60], 'meta.poll.options.1', 'Each poll choice must be text.'],]);@@ -1615,9 +1615,9 @@ it('refuses media on an x poll', function () {$this->assertDatabaseMissing(Post::class, ['social_account_id' => $x->id]);});-it('refuses to attach media to an x poll', function () {- $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);- $post = Post::factory()->forAccount($account, ContentType::XPoll)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);+it('refuses to attach media to a poll', function (ContentType $type) {+ $account = SocialAccount::factory()->{$type->platform()->value}()->create(['workspace_id' => $this->workspace->id]);+ $post = Post::factory()->forAccount($account, $type)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);$upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();$storedMedia = Media::query()->count();Http::fake();@@ -1637,7 +1637,11 @@ it('refuses to attach media to an x poll', function () {expect($post->fresh()->media)->toBeEmpty()->and(Media::query()->count())->toBe($storedMedia);Http::assertNothingSent();-});+})->with([+ 'x' => [ContentType::XPoll],+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);it('still saves a threads ghost post draft with media and attaches media to it, the poll rules being x only', function () {$threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);diff --git a/tests/Feature/Api/RepurposeApiTest.php b/tests/Feature/Api/RepurposeApiTest.phpindex 47b779130..3e893d057 100644--- a/tests/Feature/Api/RepurposeApiTest.php+++ b/tests/Feature/Api/RepurposeApiTest.php@@ -291,20 +291,24 @@ test('a content type from another network is rejected for a destination', functi->assertJsonValidationErrors('destinations.0.content_type');});-test('an x poll is refused as the format a repurposed video publishes as', function () {- $x = SocialAccount::factory()->for($this->workspace)->x()->create();+test('a poll is refused as the format a repurposed video publishes as', function (string $platform, ContentType $type) {+ $account = SocialAccount::factory()->for($this->workspace)->{$platform}()->create();$this->withHeaders(apiHeaders($this->token))->postJson(route('api.repurposes.store'), ['source_social_account_id' => $this->source->id,'destinations' => [[- 'social_account_id' => $x->id,- 'content_type' => ContentType::XPoll->value,+ 'social_account_id' => $account->id,+ 'content_type' => $type->value,]],])->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.content_type' => __('repurposes.errors.destination_needs_video')]);-});+})->with([+ 'x poll' => ['x', ContentType::XPoll],+ 'mastodon poll' => ['mastodon', ContentType::MastodonPoll],+ 'threads poll' => ['threads', ContentType::ThreadsPoll],+]);test('the api refuses a transition the interface would never offer', function () {$repurpose = Repurpose::factory()->create([diff --git a/tests/Feature/Mcp/PlatformToolTest.php b/tests/Feature/Mcp/PlatformToolTest.phpindex 550b7b922..7e0e0fcfb 100644--- a/tests/Feature/Mcp/PlatformToolTest.php+++ b/tests/Feature/Mcp/PlatformToolTest.php@@ -108,21 +108,27 @@ test('list content types exposes reel max video durations', function () {});});-test('list content types shows the x poll without media capabilities', function () {+test('list content types shows each poll without media capabilities', function (string $platform, string $type) {TryPostServer::actingAs($this->user)->tool(ListContentTypesTool::class, [])->assertOk()- ->assertStructuredContent(function (AssertableJson $json) {+ ->assertStructuredContent(function (AssertableJson $json) use ($platform, $type) {$json->etc();- $poll = collect(data_get(collect(data_get($json->toArray(), 'platforms'))->firstWhere('platform', 'x'), 'content_types'))->firstWhere('value', 'x_poll');+ $poll = collect(data_get(collect(data_get($json->toArray(), 'platforms'))->firstWhere('platform', $platform), 'content_types'))->firstWhere('value', $type);expect($poll)->toMatchArray(['max_media_count' => 0,+ 'accept_images' => false,+ 'accept_videos' => false,'accepts_gif' => false,'max_image_bytes' => null,'max_video_bytes' => null,'max_video_duration_sec' => null,]);});-});+})->with([+ 'x' => ['x', 'x_poll'],+ 'mastodon' => ['mastodon', 'mastodon_poll'],+ 'threads' => ['threads', 'threads_poll'],+]);diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.phpindex 1cba987fb..d06468390 100644--- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php+++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php@@ -1102,9 +1102,9 @@ test('an x poll with invalid choices is refused by the create tool', function (a$this->assertDatabaseMissing('posts', ['social_account_id' => $x->id]);})->with([- 'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'posts.form.x.poll.options_max', ['max' => XPoll::MAX_OPTIONS]],- 'choice over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'posts.form.x.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]],- 'repeated option' => [['options' => ['Yes', ' yes'], 'duration_minutes' => 60], 'posts.form.x.poll.options_distinct', []],+ 'five options' => [['options' => ['a', 'b', 'c', 'd', 'e'], 'duration_minutes' => 60], 'posts.form.poll.options_max', ['max' => XPoll::MAX_OPTIONS]],+ 'choice over 25 characters' => [['options' => [Str::repeat('a', 26), 'b'], 'duration_minutes' => 60], 'posts.form.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]],+ 'repeated option' => [['options' => ['Yes', ' yes'], 'duration_minutes' => 60], 'posts.form.poll.options_distinct', []],]);test('an incomplete x poll cannot be scheduled through the create tool', function (?array $poll, string $message) {@@ -1120,7 +1120,7 @@ test('an incomplete x poll cannot be scheduled through the create tool', functio])->assertHasErrors([__($message)]);})->with(['no options' => [null, fn (): string => XPoll::optionsRequiredMessage()],- 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.x.poll.duration_required'],+ 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.poll.duration_required'],]);test('publish post refuses a stored x poll without options or duration', function (array $poll, string $message) {@@ -1139,13 +1139,14 @@ test('publish post refuses a stored x poll without options or duration', functioexpect($post->fresh()->status)->toBe(PostStatus::Draft);})->with(['no options' => [[], fn (): string => XPoll::optionsRequiredMessage()],- 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.x.poll.duration_required'],+ 'no duration' => [['options' => ['Yes', 'No']], 'posts.form.poll.duration_required'],]);-test('the attach media tools refuse media on an x poll', function () {- $account = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);- $post = Post::factory()->forAccount($account, ContentType::XPoll)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);+test('the attach media tools refuse media on a poll', function (ContentType $type) {+ $account = SocialAccount::factory()->{$type->platform()->value}()->create(['workspace_id' => $this->workspace->id]);+ $post = Post::factory()->forAccount($account, $type)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft]);$upload = Media::factory()->temporaryUpload($this->workspace)->stored()->create();+ $storedMedia = Media::query()->count();Http::fake();TryPostServer::actingAs($this->user)->tool(AttachMediaFromUploadTool::class, [@@ -1158,9 +1159,14 @@ test('the attach media tools refuse media on an x poll', function () {'urls' => [['url' => 'https://example.com/photo.png']],])->assertHasErrors([__('posts.errors.media_not_accepted')]);- expect($post->fresh()->media)->toBeEmpty();+ expect($post->fresh()->media)->toBeEmpty()+ ->and(Media::query()->count())->toBe($storedMedia);Http::assertNothingSent();-});+})->with([+ 'x' => [ContentType::XPoll],+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);test('the get post tool returns the poll of an x poll', function () {$x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);diff --git a/tests/Feature/Mcp/ToolDocumentationTest.php b/tests/Feature/Mcp/ToolDocumentationTest.phpindex f50991215..f7ef7a9c1 100644--- a/tests/Feature/Mcp/ToolDocumentationTest.php+++ b/tests/Feature/Mcp/ToolDocumentationTest.php@@ -72,15 +72,15 @@ test('tools that schedule or publish list the required meta', function (string $'publish-post' => [PublishPostTool::class],]);-test('list-content-types says an x poll is refused even as a draft and what it needs', function () {+test('list-content-types says a poll is refused even as a draft and what it needs', function () {expect(mcpToolDescription(ListContentTypesTool::class))- ->toContain('The exception is an X poll')+ ->toContain('The exception is a poll')->toContain('drafts included')- ->toContain('x_poll) needs meta.poll');+ ->toContain('x_poll, mastodon_poll, threads_poll) needs meta.poll');});-test('the attach media tools say an x poll takes no media', function (string $tool) {- expect(mcpToolDescription($tool))->toContain('x_poll) takes no media');+test('the attach media tools say a poll takes no media', function (string $tool) {+ expect(mcpToolDescription($tool))->toContain('x_poll, mastodon_poll or threads_poll) takes no media');})->with(['upload' => [AttachMediaFromUploadTool::class],'url' => [AttachMediaFromUrlTool::class],diff --git a/tests/Feature/Parity/MastodonThreadsPollParityTest.php b/tests/Feature/Parity/MastodonThreadsPollParityTest.phpnew file mode 100644index 000000000..6f176fb83--- /dev/null+++ b/tests/Feature/Parity/MastodonThreadsPollParityTest.php@@ -0,0 +1,425 @@+<?php++declare(strict_types=1);++use App\Dto\MediaItem;+use App\Enums\Post\Status;+use App\Enums\PostPlatform\ContentType;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Post\CreatePostsTool;+use App\Mcp\Tools\Post\CreatePostTool;+use App\Mcp\Tools\Post\PublishPostTool;+use App\Models\Media;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Support\Social\MastodonPoll;+use App\Support\Social\Poll;+use App\Support\Social\ThreadsPoll;+use App\Support\Social\XPoll;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Str;+use Illuminate\Testing\TestResponse;+use Laravel\Mcp\Server\Testing\TestResponse as McpTestResponse;++beforeEach(function () {+ ['user' => $this->user, 'workspace' => $this->workspace, 'token' => $this->token] = parityContext();+});++function assertPollParityPassed(string $surface, TestResponse|McpTestResponse $response): void+{+ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();+}++/**+ * @param array<string, string> $errors+ */+function assertPollParityRefused(string $surface, TestResponse|McpTestResponse $response, array $errors): void+{+ $surface === 'mcp'+ ? $response->assertHasErrors(array_values($errors))+ : $response->assertUnprocessable()->assertJsonValidationErrors($errors);+}++test('a mastodon poll keeps its length, multiple choice and hidden totals on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::MastodonPoll);++ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => [+ 'options' => [' Yes ', '', 'No'],+ 'duration_minutes' => MastodonPoll::MAX_DURATION,+ 'multiple' => true,+ 'hide_totals' => true,+ ]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::MAX_DURATION, 'multiple' => true, 'hide_totals' => true]);+})->with(['web', 'api', 'mcp']);++test('a threads poll keeps only its choices on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::ThreadsPoll);++ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => [+ 'options' => ['Yes', 'No'],+ 'duration_minutes' => 60,+ 'multiple' => true,+ 'hide_totals' => true,+ ]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No']]);+})->with(['web', 'api', 'mcp']);++test('an x poll drops the switches only mastodon has on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::XPoll);++ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60]);+})->with(['web', 'api', 'mcp']);++test('each network takes the choice length it allows on the web, api and mcp', function (string $surface, ContentType $type, int $maxLength) {+ $post = pollParityPost($type);+ $message = __('posts.form.poll.choice_max', ['max' => $maxLength]);++ $refused = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', Str::repeat('a', $maxLength + 1)], 'duration_minutes' => 60]]]);++ assertPollParityRefused($surface, $refused, ['meta.poll.options.1' => $message]);++ $accepted = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', Str::repeat('a', $maxLength)], 'duration_minutes' => 60]]]);++ assertPollParityPassed($surface, $accepted);+ expect($post->fresh()->meta['poll']['options'])->toBe(['Yes', Str::repeat('a', $maxLength)]);+})->with(['web', 'api', 'mcp'])->with([+ 'x' => [ContentType::XPoll, XPoll::OPTION_MAX_LENGTH],+ 'mastodon' => [ContentType::MastodonPoll, MastodonPoll::OPTION_MAX_LENGTH],+ 'threads' => [ContentType::ThreadsPoll, ThreadsPoll::OPTION_MAX_LENGTH],+]);++test('each network takes the poll length it allows on the web, api and mcp', function (string $surface, ContentType $type, string $poll) {+ $post = pollParityPost($type);++ $refused = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => $poll::MAX_DURATION + 1]]]);++ assertPollParityRefused($surface, $refused, ['meta.poll.duration_minutes' => $poll::durationRangeMessage()]);++ $accepted = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => $poll::MAX_DURATION]]]);++ assertPollParityPassed($surface, $accepted);+ expect($post->fresh()->meta['poll']['duration_minutes'])->toBe($poll::MAX_DURATION);+})->with(['web', 'api', 'mcp'])->with([+ 'x' => [ContentType::XPoll, XPoll::class],+ 'mastodon' => [ContentType::MastodonPoll, MastodonPoll::class],+]);++test('scheduling a poll needs at least two choices on the web, api and mcp', function (string $surface, ContentType $type) {+ $post = pollParityPost($type, ['poll' => ['options' => ['Yes']]]);++ $response = pollParityUpdate($surface, $post, [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ ]);++ assertPollParityRefused($surface, $response, ['meta.poll.options' => Poll::optionsRequiredMessage()]);+ expect($post->fresh()->status)->toBe(Status::Draft);+})->with(['web', 'api', 'mcp'])->with([+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);++test('a threads poll schedules without a length on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::ThreadsPoll, ['poll' => ['options' => ['Yes', 'No']]]);++ $response = pollParityUpdate($surface, $post, [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ ]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->status)->toBe(Status::Scheduled);+})->with(['web', 'api', 'mcp']);++test('a mastodon reply can be a poll under mastodon rules on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::MastodonPost);+ $poll = ['options' => ['Yes', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH)], 'duration_minutes' => MastodonPoll::MAX_DURATION, 'multiple' => true];++ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $poll]]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['thread_replies'][0]['poll'])->toEqual($poll);+})->with(['web', 'api', 'mcp']);++test('a bluesky reply drops a poll on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::BlueskyPost);++ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', 'No']]]]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['thread_replies'][0])->not->toHaveKey('poll');+})->with(['web', 'api', 'mcp']);++test('a mastodon or threads poll refuses media even as a draft on the web, api and mcp', function (string $surface, ContentType $type) {+ $post = pollParityPost($type, ['poll' => ['options' => ['Yes', 'No']]]);+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();+ Http::fake();++ $response = pollParityUpdate($surface, $post, [+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],+ ]);++ assertPollParityRefused($surface, $response, ['media' => __('posts.errors.media_not_accepted')]);+ expect($post->fresh()->media)->toBeEmpty();+})->with(['web', 'api', 'mcp'])->with([+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);++test('a mastodon reply poll beyond mastodon limits is refused even as a draft on the web, api and mcp', function (string $surface, array $poll, string $field) {+ $post = pollParityPost(ContentType::MastodonPost);+ $messages = [+ 'meta.thread_replies.0.poll.options.1' => __('posts.form.poll.choice_max', ['max' => MastodonPoll::OPTION_MAX_LENGTH]),+ 'meta.thread_replies.0.poll.duration_minutes' => MastodonPoll::durationRangeMessage(),+ ];++ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $poll]]]]);++ assertPollParityRefused($surface, $response, [$field => $messages[$field]]);+ expect($post->fresh()->meta)->not->toHaveKey('thread_replies');+})->with(['web', 'api', 'mcp'])->with([+ 'a choice too long' => [['options' => ['Yes', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1)], 'duration_minutes' => 60], 'meta.thread_replies.0.poll.options.1'],+ 'a length too long' => [['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::MAX_DURATION + 1], 'meta.thread_replies.0.poll.duration_minutes'],+]);++test('a choice too long is reported on the field it was sent in, blank choices before it included, on the web, api and mcp', function (string $surface, string $prefix, array $meta) {+ $post = pollParityPost(ContentType::MastodonPoll, ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $message = __('posts.form.poll.choice_max', ['max' => MastodonPoll::OPTION_MAX_LENGTH]);++ $response = pollParityUpdate($surface, $post, ['meta' => $meta]);++ assertPollParityRefused($surface, $response, ["meta.{$prefix}poll.options.2" => $message]);+})->with(['web', 'api', 'mcp'])->with([+ 'the post poll' => ['', ['poll' => ['options' => ['Yes', '', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1)]]]],+ 'a reply poll' => ['thread_replies.0.', ['thread_replies' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', '', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1)], 'duration_minutes' => 60]]]]],+]);++/**+ * Creates one draft through one surface: the web composer, the REST API or+ * the MCP tool, and returns that surface's own response.+ *+ * @param array<string, mixed> $meta+ */+function pollParityCreate(string $surface, SocialAccount $account, ContentType $type, array $meta): TestResponse|McpTestResponse+{+ $destination = ['social_account_id' => $account->id, 'content_type' => $type->value, 'meta' => $meta];++ return match ($surface) {+ 'web' => test()->actingAs(test()->user)->postJson(route('app.posts.store'), [+ 'status' => Status::Draft->value,+ 'content' => 'Tabs or spaces?',+ 'media' => [],+ 'destinations' => [$destination],+ ]),+ 'api' => test()->withHeaders(parityApi(test()->token))->postJson(route('api.posts.store'), [+ 'status' => Status::Draft->value,+ 'content' => 'Tabs or spaces?',+ ...$destination,+ ]),+ 'mcp' => TryPostServer::actingAs(test()->user)->tool(CreatePostTool::class, [+ 'content' => 'Tabs or spaces?',+ ...$destination,+ ]),+ };+}++test('a new poll stores only what its network takes on the web, api and mcp', function (string $surface, ContentType $type, array $expected) {+ $account = SocialAccount::factory()->{$type->platform()->value}()->create(['workspace_id' => test()->workspace->id]);++ $response = pollParityCreate($surface, $account, $type, ['poll' => [+ 'options' => [' Yes ', '', 'No'],+ 'duration_minutes' => 60,+ 'multiple' => true,+ 'hide_totals' => true,+ ]]);++ assertPollParityPassed($surface, $response);+ expect(Post::where('social_account_id', $account->id)->sole()->meta['poll'])->toEqual($expected);+})->with(['web', 'api', 'mcp'])->with([+ 'x' => [ContentType::XPoll, ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],+ 'mastodon' => [ContentType::MastodonPoll, ['options' => ['Yes', 'No'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]],+ 'threads' => [ContentType::ThreadsPoll, ['options' => ['Yes', 'No']]],+]);++test('a new mastodon post keeps a reply poll on the web, api and mcp', function (string $surface) {+ $account = SocialAccount::factory()->mastodon()->create(['workspace_id' => test()->workspace->id]);+ $poll = ['options' => ['Yes', 'No'], 'duration_minutes' => 60, 'hide_totals' => true];++ $response = pollParityCreate($surface, $account, ContentType::MastodonPost, ['thread_replies' => [['text' => 'Which one?', 'poll' => $poll]]]);++ assertPollParityPassed($surface, $response);+ expect(Post::where('social_account_id', $account->id)->sole()->meta['thread_replies'][0]['poll'])->toEqual($poll);+})->with(['web', 'api', 'mcp']);++test('a batch reports a poll choice too long on its own destination on the api', function () {+ $mastodon = SocialAccount::factory()->mastodon()->create(['workspace_id' => test()->workspace->id]);+ $threads = SocialAccount::factory()->threads()->create(['workspace_id' => test()->workspace->id]);++ test()->withHeaders(parityApi(test()->token))->postJson(route('api.posts.batch.store'), [+ 'status' => Status::Draft->value,+ 'content' => 'Tabs or spaces?',+ 'destinations' => [+ ['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPoll->value, 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]],+ ['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPoll->value, 'meta' => ['poll' => ['options' => ['Yes', Str::repeat('a', ThreadsPoll::OPTION_MAX_LENGTH + 1)]]]],+ ],+ ])->assertUnprocessable()->assertJsonValidationErrors([+ 'destinations.1.meta.poll.options.1' => __('posts.form.poll.choice_max', ['max' => ThreadsPoll::OPTION_MAX_LENGTH]),+ ])->assertJsonMissingValidationErrors('destinations.0.meta.poll.options.1');++ expect(Post::where('workspace_id', test()->workspace->id)->exists())->toBeFalse();+});++test('a batch refuses a poll choice too long on its own destination on mcp', function () {+ $mastodon = SocialAccount::factory()->mastodon()->create(['workspace_id' => test()->workspace->id]);+ $threads = SocialAccount::factory()->threads()->create(['workspace_id' => test()->workspace->id]);++ TryPostServer::actingAs(test()->user)->tool(CreatePostsTool::class, [+ 'status' => Status::Draft->value,+ 'content' => 'Tabs or spaces?',+ 'destinations' => [+ ['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPoll->value, 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]],+ ['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPoll->value, 'meta' => ['poll' => ['options' => ['Yes', Str::repeat('a', ThreadsPoll::OPTION_MAX_LENGTH + 1)]]]],+ ],+ ])->assertHasErrors([__('posts.form.poll.choice_max', ['max' => ThreadsPoll::OPTION_MAX_LENGTH])]);++ expect(Post::where('workspace_id', test()->workspace->id)->exists())->toBeFalse();+});++test('a mastodon poll shorter than mastodon allows is refused on the post and on a reply on the web, api and mcp', function (string $surface, ContentType $type, string $prefix, array $meta) {+ $post = pollParityPost($type);++ $response = pollParityUpdate($surface, $post, ['meta' => $meta]);++ assertPollParityRefused($surface, $response, ["meta.{$prefix}poll.duration_minutes" => MastodonPoll::durationRangeMessage()]);+})->with(['web', 'api', 'mcp'])->with([+ 'the post poll' => [ContentType::MastodonPoll, '', ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::MIN_DURATION - 1]]],+ 'a reply poll' => [ContentType::MastodonPost, 'thread_replies.0.', ['thread_replies' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::MIN_DURATION - 1]]]]],+]);++test('a threads poll takes and drops a length threads does not use on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::ThreadsPoll);++ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 99999]]]);++ assertPollParityPassed($surface, $response);+ expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No']]);+})->with(['web', 'api', 'mcp']);++test('scheduling a mastodon or threads poll without a question asks for the question on the web, api and mcp', function (string $surface, ContentType $type, string $content) {+ $post = pollParityPost($type, ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);++ $response = pollParityUpdate($surface, $post, [+ 'content' => $content,+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ ]);++ assertPollParityRefused($surface, $response, ['content' => __('posts.form.poll.question_required')]);+ expect($post->fresh()->status)->toBe(Status::Draft);+})->with(['web', 'api', 'mcp'])->with([+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+])->with([+ 'no text' => [''],+ 'editor markup without words' => ['<p></p>'],+]);++test('publishing a stored mastodon or threads poll without a question is refused on mcp', function (ContentType $type) {+ $post = pollParityPost($type, ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post->update(['content' => '<p></p>']);++ TryPostServer::actingAs(test()->user)+ ->tool(PublishPostTool::class, ['post_id' => $post->id])+ ->assertHasErrors([__('posts.form.poll.question_required')]);++ expect($post->fresh()->status)->toBe(Status::Draft);+})->with([+ 'mastodon' => [ContentType::MastodonPoll],+ 'threads' => [ContentType::ThreadsPoll],+]);++test('scheduling a mastodon poll without a length is refused on the post and on a reply on the web, api and mcp', function (string $surface, ContentType $type, string $prefix, array $meta) {+ $post = pollParityPost($type);++ $response = pollParityUpdate($surface, $post, [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ 'meta' => $meta,+ ]);++ assertPollParityRefused($surface, $response, ["meta.{$prefix}poll.duration_minutes" => __('posts.form.poll.duration_required')]);+ expect($post->fresh()->status)->toBe(Status::Draft);+})->with(['web', 'api', 'mcp'])->with([+ 'the post poll' => [ContentType::MastodonPoll, '', ['poll' => ['options' => ['Yes', 'No']]]],+ 'a reply poll' => [ContentType::MastodonPost, 'thread_replies.0.', ['thread_replies' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', 'No']]]]]],+]);++test('a mastodon reply poll with media is refused even as a draft on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::MastodonPost);+ $upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();+ Http::fake();++ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [+ [+ 'text' => 'Tabs or spaces?',+ 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60],+ 'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],+ ],+ ]]]);++ assertPollParityRefused($surface, $response, ['meta.thread_replies.0.media' => __('posts.errors.media_not_accepted')]);+ expect($post->fresh()->meta)->toBe([]);+})->with(['web', 'api', 'mcp']);++test('scheduling a reply poll with too many files gives it one media error on the web and api', function (string $surface) {+ $post = pollParityPost(ContentType::MastodonPost);+ $uploads = Media::factory()->count(5)->temporaryUpload(test()->workspace)->stored()->create();+ Http::fake();++ $response = pollParityUpdate($surface, $post, [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ 'meta' => ['thread_replies' => [+ [+ 'text' => 'Tabs or spaces?',+ 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60],+ 'media' => $uploads->map(fn (Media $upload): array => $surface === 'web'+ ? MediaItem::fromMedia($upload)->toArray()+ : ['upload_token' => $upload->upload_token])->all(),+ ],+ ]],+ ]);++ expect($response->assertUnprocessable()->json('errors'))+ ->toBe(['meta.thread_replies.0.media' => [__('posts.errors.media_not_accepted')]]);+ expect($post->fresh()->status)->toBe(Status::Draft);+})->with(['web', 'api']);++test('scheduling a mastodon poll with a choice too long reports it once on the web and api', function (string $surface) {+ $post = pollParityPost(ContentType::MastodonPoll);++ $response = pollParityUpdate($surface, $post, [+ 'status' => Status::Scheduled->value,+ 'scheduled_at' => now()->addDay()->toIso8601String(),+ 'meta' => ['poll' => ['options' => ['Yes', Str::repeat('a', MastodonPoll::OPTION_MAX_LENGTH + 1)], 'duration_minutes' => 60]],+ ]);++ $response->assertUnprocessable();+ expect($response->json('errors')['meta.poll.options.1'])->toBe([__('posts.form.poll.choice_max', ['max' => MastodonPoll::OPTION_MAX_LENGTH])]);+})->with(['web', 'api']);++test('a mastodon poll switch that is not true or false is refused on the web and api', function (string $surface, string $switch) {+ $post = pollParityPost(ContentType::MastodonPoll);++ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60, $switch => 'abc']]]);++ $response->assertUnprocessable()->assertJsonValidationErrors(["meta.poll.{$switch}"]);+ expect($post->fresh()->meta)->toBe([]);+})->with(['web', 'api'])->with(['multiple', 'hide_totals']);diff --git a/tests/Feature/Parity/XPollParityTest.php b/tests/Feature/Parity/XPollParityTest.phpindex 36c485540..3f8d40f69 100644--- a/tests/Feature/Parity/XPollParityTest.php+++ b/tests/Feature/Parity/XPollParityTest.php@@ -8,68 +8,30 @@ use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Mcp\Servers\TryPostServer;use App\Mcp\Tools\Post\PublishPostTool;-use App\Mcp\Tools\Post\UpdatePostTool;use App\Models\Media;use App\Models\Post;use App\Models\SocialAccount;use App\Support\Social\XPoll;use Illuminate\Support\Facades\Http;use Illuminate\Support\Str;-use Illuminate\Testing\TestResponse;-use Laravel\Mcp\Server\Testing\TestResponse as McpTestResponse;beforeEach(function () {['user' => $this->user, 'workspace' => $this->workspace, 'token' => $this->token] = parityContext();});-function xPollParityPost(ContentType $type = ContentType::XPoll, array $meta = [], array $accountMeta = []): Post-{- $account = SocialAccount::factory()->x()->create(['workspace_id' => test()->workspace->id, 'meta' => $accountMeta]);-- return Post::factory()->forAccount($account, $type)->create([- 'user_id' => test()->user->id,- 'content' => 'Tabs or spaces?',- 'status' => Status::Draft,- 'media' => [],- 'meta' => $meta,- ]);-}--/**- * Sends the same post update through one surface: the web composer, the REST- * API or the MCP tool.- *- * @param array<string, mixed> $changes- */-function xPollParityUpdate(string $surface, Post $post, array $changes): TestResponse|McpTestResponse-{- $payload = [- 'content' => $post->content,- 'content_type' => $post->content_type->value,- 'status' => Status::Draft->value,- ...$changes,- ];-- return match ($surface) {- 'web' => test()->actingAs(test()->user)->putJson(route('app.posts.update', $post), ['media' => [], ...$payload]),- 'api' => test()->withHeaders(parityApi(test()->token))->putJson(route('api.posts.update', $post), $payload),- 'mcp' => TryPostServer::actingAs(test()->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, ...$payload]),- };-}-test('a valid x poll is stored normalized on the web, api and mcp', function (string $surface) {- $post = xPollParityPost();+ $post = pollParityPost(ContentType::XPoll);- $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [' Yes ', '', 'No'], 'duration_minutes' => 60]]]);+ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [' Yes ', '', 'No'], 'duration_minutes' => 60]]]);$surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();expect($post->fresh()->meta['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => 60]);})->with(['web', 'api', 'mcp']);test('x poll choices that repeat or number five are refused on the web, api and mcp', function (string $surface, array $options) {- $post = xPollParityPost();+ $post = pollParityPost(ContentType::XPoll);- $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => $options, 'duration_minutes' => 60]]]);+ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => $options, 'duration_minutes' => 60]]]);$surface === 'mcp'? $response->assertHasErrors()@@ -81,9 +43,9 @@ test('x poll choices that repeat or number five are refused on the web, api and]);test('scheduling an x poll without options is refused on the web, api and mcp', function (string $surface) {- $post = xPollParityPost();+ $post = pollParityPost(ContentType::XPoll);- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),]);@@ -95,18 +57,18 @@ test('scheduling an x poll without options is refused on the web, api and mcp',})->with(['web', 'api', 'mcp']);test('switching an x poll to an x post drops the poll on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);- $response = xPollParityUpdate($surface, $post, ['content_type' => ContentType::XPost->value, 'meta' => []]);+ $response = pollParityUpdate($surface, $post, ['content_type' => ContentType::XPost->value, 'meta' => []]);$surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();expect($post->fresh()->meta)->not->toHaveKey('poll');})->with(['web', 'api', 'mcp']);test('an x poll update keeps the parts it does not send on the web, api and mcp', function (string $surface, array $poll, array $expected) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);- $response = xPollParityUpdate($surface, $post, ['meta' => ['poll' => $poll]]);+ $response = pollParityUpdate($surface, $post, ['meta' => ['poll' => $poll]]);$surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();expect($post->fresh()->meta['poll'])->toEqual($expected);@@ -118,9 +80,9 @@ test('an x poll update keeps the parts it does not send on the web, api and mcp']);test('scheduling an x poll that sends only part of its poll keeps the rest on the web, api and mcp', function (string $surface, array $poll, array $expected) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No', 'Maybe'], 'duration_minutes' => 4320]]);- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),'meta' => ['poll' => $poll],@@ -136,11 +98,11 @@ test('scheduling an x poll that sends only part of its poll keeps the rest on th]);test('scheduling an x poll with media is refused on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);$upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();Http::fake();- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],@@ -153,11 +115,11 @@ test('scheduling an x poll with media is refused on the web, api and mcp', funct})->with(['web', 'api', 'mcp']);test('an x poll draft with media is refused on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);$upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();Http::fake();- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Draft->value,'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],]);@@ -169,20 +131,20 @@ test('an x poll draft with media is refused on the web, api and mcp', function (})->with(['web', 'api', 'mcp']);test('scheduling an x poll without a question asks only for the question on the web, api and mcp', function (string $surface, string $content) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['content' => $content,'status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),]);if ($surface === 'mcp') {- $response->assertHasErrors([__('posts.form.x.poll.question_required')])+ $response->assertHasErrors([__('posts.form.poll.question_required')])->assertDontSee(__('posts.edit.compliance.requires_content_or_media'));} else {$response->assertUnprocessable()- ->assertJsonValidationErrors(['content' => __('posts.form.x.poll.question_required')])+ ->assertJsonValidationErrors(['content' => __('posts.form.poll.question_required')])->assertDontSee(__('posts.edit.compliance.requires_content_or_media'));}expect($post->fresh()->status)->toBe(Status::Draft);@@ -192,9 +154,9 @@ test('scheduling an x poll without a question asks only for the question on the]);test('a poll on a thread reply is stored normalized on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(ContentType::XPost);+ $post = pollParityPost(ContentType::XPost);- $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [+ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => [' Tabs ', '', 'Spaces'], 'duration_minutes' => 60]],]]]);@@ -205,22 +167,22 @@ test('a poll on a thread reply is stored normalized on the web, api and mcp', fu})->with(['web', 'api', 'mcp']);test('repeated choices on a thread reply poll are refused on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(ContentType::XPost);+ $post = pollParityPost(ContentType::XPost);- $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [+ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes', ' yes'], 'duration_minutes' => 60]],]]]);$surface === 'mcp'- ? $response->assertHasErrors([__('posts.form.x.poll.options_distinct')])- : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0.poll.options' => __('posts.form.x.poll.options_distinct')]);+ ? $response->assertHasErrors([__('posts.form.poll.options_distinct')])+ : $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0.poll.options' => __('posts.form.poll.options_distinct')]);expect($post->fresh()->meta)->toBe([]);})->with(['web', 'api', 'mcp']);test('scheduling a thread reply poll without its question or with one choice is refused on the web, api and mcp', function (string $surface, array $reply, string $field, string $message) {- $post = xPollParityPost(ContentType::XPost);+ $post = pollParityPost(ContentType::XPost);- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),'meta' => ['thread_replies' => [$reply]],@@ -231,18 +193,18 @@ test('scheduling a thread reply poll without its question or with one choice is: $response->assertUnprocessable()->assertJsonValidationErrors([$field => __($message)]);expect($post->fresh()->status)->toBe(Status::Draft);})->with(['web', 'api', 'mcp'])->with([- 'no question' => [['text' => '', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.x.poll.question_required'],- 'a question of empty markup' => [['text' => '<p></p>', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.x.poll.question_required'],- 'no length' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes', 'No']]], 'meta.thread_replies.0.poll.duration_minutes', 'posts.form.x.poll.duration_required'],+ 'no question' => [['text' => '', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.poll.question_required'],+ 'a question of empty markup' => [['text' => '<p></p>', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'meta.thread_replies.0', 'posts.form.poll.question_required'],+ 'no length' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes', 'No']]], 'meta.thread_replies.0.poll.duration_minutes', 'posts.form.poll.duration_required'],'one choice' => [['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Yes'], 'duration_minutes' => 60]], 'meta.thread_replies.0.poll.options', fn (): string => XPoll::optionsRequiredMessage()],]);test('a thread reply poll with media is refused even as a draft on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(ContentType::XPost);+ $post = pollParityPost(ContentType::XPost);$upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();Http::fake();- $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [+ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?','poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60],@@ -257,9 +219,9 @@ test('a thread reply poll with media is refused even as a draft on the web, api})->with(['web', 'api', 'mcp']);test('a thread with polls on the post and on its replies is scheduled on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);- $response = xPollParityUpdate($surface, $post, [+ $response = pollParityUpdate($surface, $post, ['status' => Status::Scheduled->value,'scheduled_at' => now()->addDay()->toIso8601String(),'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60], 'thread_replies' => [@@ -286,7 +248,7 @@ test('a thread reply poll off x is dropped, never checked, on the web, api and m$upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();Http::fake();- $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [[+ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Tabs or spaces?','poll' => ['options' => ['Tabs'], 'duration_minutes' => 60],'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],@@ -298,11 +260,11 @@ test('a thread reply poll off x is dropped, never checked, on the web, api and m})->with(['web', 'api', 'mcp']);test('an empty poll on a thread reply is no poll on the web, api and mcp', function (string $surface) {- $post = xPollParityPost(ContentType::XPost);+ $post = pollParityPost(ContentType::XPost);$upload = Media::factory()->temporaryUpload(test()->workspace)->stored()->create();Http::fake();- $response = xPollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [[+ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [['text' => 'Just a photo','poll' => [],'media' => [$surface === 'web' ? MediaItem::fromMedia($upload)->toArray() : ['upload_token' => $upload->upload_token]],@@ -314,37 +276,37 @@ test('an empty poll on a thread reply is no poll on the web, api and mcp', funct})->with(['web', 'api', 'mcp']);test('publishing a stored x poll without a question is refused before it reaches x on mcp', function () {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]);$post->update(['content' => '<p></p>']);TryPostServer::actingAs(test()->user)->tool(PublishPostTool::class, ['post_id' => $post->id])- ->assertHasErrors([__('posts.form.x.poll.question_required')]);+ ->assertHasErrors([__('posts.form.poll.question_required')]);expect($post->fresh()->status)->toBe(Status::Draft);});test('a poll question over 280 characters is refused on a long post account on the web, api and mcp, while the same text as a post passes', function (string $surface) {- $poll = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);+ $poll = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);$schedule = ['content' => Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1), 'status' => Status::Scheduled->value, 'scheduled_at' => now()->addDay()->toIso8601String()];$message = __('posts.form.content_exceeds_platform', ['platform' => Platform::X->label(), 'limit' => XPoll::QUESTION_MAX_LENGTH, 'over' => 1]);- $response = xPollParityUpdate($surface, $poll, $schedule);+ $response = pollParityUpdate($surface, $poll, $schedule);$surface === 'mcp'? $response->assertHasErrors([$message]): expect($response->assertUnprocessable()->collect('errors')->flatten()->all())->toContain($message);expect($poll->fresh()->status)->toBe(Status::Draft);- $post = xPollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);- $passed = xPollParityUpdate($surface, $post, $schedule);+ $post = pollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);+ $passed = pollParityUpdate($surface, $post, $schedule);$surface === 'mcp' ? $passed->assertOk() : $passed->assertSessionHasNoErrors();expect($post->fresh()->status)->toBe(Status::Scheduled);})->with(['web', 'api', 'mcp']);test('an api update that sends only the text measures it against the stored poll type', function () {- $post = xPollParityPost(meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);+ $post = pollParityPost(ContentType::XPoll, meta: ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], accountMeta: ['x_subscription_type' => 'Premium']);test()->withHeaders(parityApi(test()->token))->putJson(route('api.posts.update', $post), ['content' => Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1),@@ -356,38 +318,49 @@ test('an api update that sends only the text measures it against the stored poll});test('a thread reply poll question over 280 characters is refused on a long post account on the web, api and mcp, while the same reply without a poll passes', function (string $surface) {- $post = xPollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);+ $post = pollParityPost(ContentType::XPost, accountMeta: ['x_subscription_type' => 'Premium']);$question = Str::repeat('a', XPoll::QUESTION_MAX_LENGTH + 1);$schedule = fn (array $reply): array => ['status' => Status::Scheduled->value, 'scheduled_at' => now()->addDay()->toIso8601String(), 'meta' => ['thread_replies' => [$reply]]];$message = __('posts.form.thread.reply_too_long', ['limit' => XPoll::QUESTION_MAX_LENGTH, 'over' => 1]);- $response = xPollParityUpdate($surface, $post, $schedule(['text' => $question, 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]));+ $response = pollParityUpdate($surface, $post, $schedule(['text' => $question, 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]));$surface === 'mcp'? $response->assertHasErrors([$message]): $response->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0' => $message]);expect($post->fresh()->status)->toBe(Status::Draft);- $passed = xPollParityUpdate($surface, $post, $schedule(['text' => $question]));+ $passed = pollParityUpdate($surface, $post, $schedule(['text' => $question]));$surface === 'mcp' ? $passed->assertOk() : $passed->assertSessionHasNoErrors();expect($post->fresh()->status)->toBe(Status::Scheduled);})->with(['web', 'api', 'mcp']);test('a choice is measured as x counts it, an emoji like a penguin counting two, on the web, api and mcp', function (string $surface) {- $post = xPollParityPost();+ $post = pollParityPost(ContentType::XPoll);$tooLong = '🐧 '.Str::repeat('a', 23);$fits = '🐧 '.Str::repeat('a', 22);- $message = __('posts.form.x.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]);+ $message = __('posts.form.poll.choice_max', ['max' => XPoll::OPTION_MAX_LENGTH]);- $refused = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$tooLong, 'No'], 'duration_minutes' => 60]]]);+ $refused = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$tooLong, 'No'], 'duration_minutes' => 60]]]);$surface === 'mcp'? $refused->assertHasErrors([$message]): $refused->assertUnprocessable()->assertJsonValidationErrors(['meta.poll.options.0' => $message]);- $accepted = xPollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$fits, 'No'], 'duration_minutes' => 60]]]);+ $accepted = pollParityUpdate($surface, $post, ['meta' => ['poll' => ['options' => [$fits, 'No'], 'duration_minutes' => 60]]]);$surface === 'mcp' ? $accepted->assertOk() : $accepted->assertSessionHasNoErrors();expect($post->fresh()->meta['poll']['options'])->toBe([$fits, 'No']);})->with(['web', 'api', 'mcp']);++test('an x reply poll drops the switches only mastodon has on the web, api and mcp', function (string $surface) {+ $post = pollParityPost(ContentType::XPost);++ $response = pollParityUpdate($surface, $post, ['meta' => ['thread_replies' => [+ ['text' => 'Tabs or spaces?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]],+ ]]]);++ $surface === 'mcp' ? $response->assertOk() : $response->assertSessionHasNoErrors();+ expect($post->fresh()->meta['thread_replies'][0]['poll'])->toEqual(['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]);+})->with(['web', 'api', 'mcp']);diff --git a/tests/Feature/Posts/ImportExternalPostsTest.php b/tests/Feature/Posts/ImportExternalPostsTest.phpindex 2cf974f76..c819bba42 100644--- a/tests/Feature/Posts/ImportExternalPostsTest.php+++ b/tests/Feature/Posts/ImportExternalPostsTest.php@@ -1149,11 +1149,79 @@ test('an imported x poll without a length gets the default one', function () {->toEqual(['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => XPoll::DEFAULT_DURATION]]);});-test('a poll published through trypost is linked, not imported again', function () {- $account = SocialAccount::factory()->create(['platform' => Platform::X]);- $tryPost = Post::factory()->forAccount($account, ContentType::XPoll)->published()->create(['platform_post_id' => 'x-poll-2']);+test('imports a mastodon poll with its length from publishing to its end', function () {+ $account = SocialAccount::factory()->mastodon()->create();+ $publishedAt = now()->subHours(3)->startOfMinute();+ externalPublication($account, [+ 'remote_id' => 'mastodon-poll-1',+ 'excerpt' => 'Tabs or spaces?',+ 'content_type' => PublicationContentType::Poll,+ 'provider_published_at' => $publishedAt,+ 'provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 2], ['label' => 'Spaces', 'votes' => 5]],+ 'voting_status' => 'open',+ 'end_datetime' => $publishedAt->addDays(2)->toIso8601ZuluString(),+ 'duration_minutes' => null,+ 'multiple' => true,+ ]],+ ]);++ ImportExternalPosts::execute($account);++ $poll = Post::query()->imported()->where('platform_post_id', 'mastodon-poll-1')->sole();++ expect($poll->content_type)->toBe(ContentType::MastodonPoll)+ ->and($poll->meta)->toEqual(['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 2880, 'multiple' => true]]);+});++test('a poll found before its choices were read is imported as a plain post', function (string $platform, ContentType $expected) {+ $account = SocialAccount::factory()->{$platform}()->create();+ externalPublication($account, [+ 'remote_id' => 'poll-old',+ 'excerpt' => 'Tabs or spaces?',+ 'content_type' => PublicationContentType::Poll,+ 'provider_metadata' => ['visibility' => 'public'],+ ]);++ ImportExternalPosts::execute($account);++ $post = Post::query()->imported()->where('platform_post_id', 'poll-old')->sole();++ expect($post->content_type)->toBe($expected)+ ->and($post->meta)->toBe([]);+})->with([+ 'x' => ['x', ContentType::XPost],+ 'mastodon' => ['mastodon', ContentType::MastodonPost],+ 'threads' => ['threads', ContentType::ThreadsPost],+]);++test('imports a threads poll with its choices', function () {+ $account = SocialAccount::factory()->threads()->create();+ externalPublication($account, [+ 'remote_id' => 'threads-poll-1',+ 'excerpt' => 'Tabs or spaces?',+ 'content_type' => PublicationContentType::Poll,+ 'provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tabs', 'votes' => 2], ['label' => 'Spaces', 'votes' => 5]],+ 'voting_status' => 'closed',+ 'end_datetime' => now()->subDay()->toIso8601ZuluString(),+ 'duration_minutes' => null,+ ]],+ ]);++ ImportExternalPosts::execute($account);++ $poll = Post::query()->imported()->where('platform_post_id', 'threads-poll-1')->sole();++ expect($poll->content_type)->toBe(ContentType::ThreadsPoll)+ ->and($poll->meta)->toEqual(['poll' => ['options' => ['Tabs', 'Spaces']]]);+});++test('a poll published through trypost is linked, not imported again', function (string $platform, ContentType $type) {+ $account = SocialAccount::factory()->{$platform}()->create();+ $tryPost = Post::factory()->forAccount($account, $type)->published()->create(['platform_post_id' => 'poll-2']);$publication = externalPublication($account, [- 'remote_id' => 'x-poll-2',+ 'remote_id' => 'poll-2','content_type' => PublicationContentType::Poll,'provider_metadata' => ['poll' => ['options' => [['label' => 'Yes', 'votes' => 3], ['label' => 'No', 'votes' => 1]], 'voting_status' => 'open', 'duration_minutes' => 1440]],]);@@ -1161,6 +1229,10 @@ test('a poll published through trypost is linked, not imported again', functionexpect(ImportExternalPosts::execute($account))->toBe([])->and(Post::query()->count())->toBe($count)- ->and(Post::query()->where('content_type', ContentType::XPoll)->sole()->id)->toBe($tryPost->id)+ ->and(Post::query()->where('content_type', $type)->sole()->id)->toBe($tryPost->id)->and($publication->fresh()->post_id)->toBe($tryPost->id);-});+})->with([+ 'x' => ['x', ContentType::XPoll],+ 'mastodon' => ['mastodon', ContentType::MastodonPoll],+ 'threads' => ['threads', ContentType::ThreadsPoll],+]);diff --git a/tests/Feature/Posts/PostApprovalActionsTest.php b/tests/Feature/Posts/PostApprovalActionsTest.phpindex 36de18385..0de3a783e 100644--- a/tests/Feature/Posts/PostApprovalActionsTest.php+++ b/tests/Feature/Posts/PostApprovalActionsTest.php@@ -357,27 +357,26 @@ test('approving a pending edit whose slot vanished places it in the first free s->and($edited->schedule_mode)->toBe(ScheduleMode::Queue);});-test('approving an x poll request schedules it as a poll with its choices', function (array $timing) {- $x = SocialAccount::factory()->x()->create([+test('approving a poll request schedules it as a poll with its choices', function (string $platform, ContentType $type, array $poll, array $timing) {+ $account = SocialAccount::factory()->{$platform}()->create(['workspace_id' => $this->workspace->id,'timezone' => 'America/Sao_Paulo','posting_schedule' => PostingSchedule::empty()->withTime(1, '09:00'),]);- $poll = ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60];$request = CreatePosts::execute($this->workspace, $this->requester, ['status' => 'scheduled','content' => 'Tabs or spaces?','media' => [],'destinations' => [[- 'social_account_id' => $x->id,- 'content_type' => ContentType::XPoll->value,+ 'social_account_id' => $account->id,+ 'content_type' => $type->value,'meta' => ['poll' => $poll],]],...$timing,])->sole();expect($request->status)->toBe(PostStatus::PendingApproval)- ->and($request->content_type)->toBe(ContentType::XPoll)+ ->and($request->content_type)->toBe($type)->and($request->meta['poll'])->toEqual($poll);$this->actingAs($this->owner)@@ -387,9 +386,13 @@ test('approving an x poll request schedules it as a poll with its choices', funcexpect($request->refresh())->status->toBe(PostStatus::Scheduled)->scheduled_at->not->toBeNull()- ->content_type->toBe(ContentType::XPoll)+ ->content_type->toBe($type)->meta->toEqual(['poll' => $poll]);})->with([+ 'x' => ['x', ContentType::XPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],+ 'mastodon' => ['mastodon', ContentType::MastodonPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]],+ 'threads' => ['threads', ContentType::ThreadsPoll, ['options' => ['Tabs', 'Spaces', 'Both']]],+])->with(['custom time' => [fn () => ['queue' => null, 'scheduled_at' => now()->addDays(2)->toIso8601String()]],'queue' => [['queue' => 'next']],]);diff --git a/tests/Feature/Posts/PostRecurrenceTest.php b/tests/Feature/Posts/PostRecurrenceTest.phpindex ab237c195..3cab0057a 100644--- a/tests/Feature/Posts/PostRecurrenceTest.php+++ b/tests/Feature/Posts/PostRecurrenceTest.php@@ -707,11 +707,10 @@ test('an author who left the workspace hands the next occurrence to the workspacexpect(nextOccurrence($post)->user_id)->toBe($this->user->id);});-test('the next occurrence of a recurring x poll keeps its poll', function () {- $x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id, 'timezone' => 'UTC']);- $poll = ['options' => ['Tabs', 'Spaces', 'Both'], 'duration_minutes' => 60];- $post = recurringPost($x, $this->user, [- 'content_type' => ContentType::XPoll,+test('the next occurrence of a recurring poll keeps its poll', function (string $platform, ContentType $type, array $poll) {+ $account = SocialAccount::factory()->{$platform}()->create(['workspace_id' => $this->workspace->id, 'timezone' => 'UTC']);+ $post = recurringPost($account, $this->user, [+ 'content_type' => $type,'content' => 'Tabs or spaces?','scheduled_at' => now()->subMinute(),'recurrence_interval' => 1,@@ -723,6 +722,10 @@ test('the next occurrence of a recurring x poll keeps its poll', function () {publishRecurringPost($post);expect(nextOccurrence($post))- ->content_type->toBe(ContentType::XPoll)+ ->content_type->toBe($type)->meta->toEqual(['poll' => $poll]);-});+})->with([+ 'x' => ['x', ContentType::XPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],+ 'mastodon' => ['mastodon', ContentType::MastodonPoll, ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60, 'multiple' => true, 'hide_totals' => true]],+ 'threads' => ['threads', ContentType::ThreadsPoll, ['options' => ['Tabs', 'Spaces', 'Both']]],+]);diff --git a/tests/Feature/Services/Social/MastodonPublisherTest.php b/tests/Feature/Services/Social/MastodonPublisherTest.phpindex 807f89b11..4f1d1a7f5 100644--- a/tests/Feature/Services/Social/MastodonPublisherTest.php+++ b/tests/Feature/Services/Social/MastodonPublisherTest.php@@ -729,3 +729,172 @@ test('a mastodon thread with a reply over the limit fails before posting anythinHttp::assertNothingSent();});++test('a mastodon poll sends its choices, length in seconds and switches instead of media', function () {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::MastodonPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 90, 'multiple' => true]],+ ]);+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);++ $this->publisher->publish($this->post->fresh());++ Http::assertSent(fn ($request): bool => $request->data() === [+ 'status' => 'Tabs or spaces?',+ 'visibility' => 'public',+ 'poll' => ['options' => ['Tabs', 'Spaces'], 'expires_in' => 5400, 'multiple' => true, 'hide_totals' => false],+ ]);+});++test('a mastodon poll that cannot go fails before calling mastodon', function (array $changes, string $message) {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::MastodonPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]],+ ...$changes,+ ]);+ Http::fake();++ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(MastodonPublishException::class, __($message, ['min' => 2]));+ Http::assertNothingSent();+})->with([+ 'media' => [['media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']]], 'posts.errors.media_not_accepted'],+ 'one choice' => [['meta' => ['poll' => ['options' => ['Tabs'], 'duration_minutes' => 60]]], 'posts.form.poll.options_required'],+ 'no length' => [['meta' => ['poll' => ['options' => ['Tabs', 'Spaces']]]], 'posts.form.poll.duration_required'],+ 'no question' => [['content' => ''], 'posts.form.poll.question_required'],+]);++test('a mastodon thread reply can be a poll, chained under the post before it', function () {+ $poll = ['options' => ['Yes', 'No'], 'duration_minutes' => 60, 'hide_totals' => true];+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $poll]]]]);+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()+ ->push(['id' => '1', 'url' => "{$instance}/@t/1"])+ ->push(['id' => '2', 'url' => "{$instance}/@t/2"])]);++ $result = $this->publisher->publish($this->post->fresh());++ expect($result['thread_reply_ids'])->toBe(['2']);+ Http::assertSent(fn ($request): bool => $request->data() === [+ 'status' => 'Which one?',+ 'visibility' => 'public',+ 'in_reply_to_id' => '1',+ 'poll' => ['options' => ['Yes', 'No'], 'expires_in' => 3600, 'multiple' => false, 'hide_totals' => true],+ ] && $request->header('Idempotency-Key') === ["{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $poll)]);+});++test('a mastodon poll changed before a retry gets a new idempotency key', function () {+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);+ $this->post->update(['content' => 'Tabs or spaces?', 'content_type' => ContentType::MastodonPoll, 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60]]]);++ $this->publisher->publish($this->post->fresh());+ $this->post->update(['meta' => ['poll' => ['options' => ['Tabs', 'Both'], 'duration_minutes' => 60]]]);+ $this->publisher->publish($this->post->fresh());++ $keys = collect(Http::recorded())->map(fn (array $pair): string => $pair[0]->header('Idempotency-Key')[0]);++ expect($keys->unique())->toHaveCount(2)+ ->and($keys->first())->not->toBe("{$this->post->id}:".ThreadProgress::hash('Tabs or spaces?'));+});++test('a plain mastodon post keeps the idempotency key it had before polls', function () {+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);++ $this->publisher->publish($this->post->fresh());++ Http::assertSent(fn ($request): bool => $request->header('Idempotency-Key') === ["{$this->post->id}:".ThreadProgress::hash('Hello from Mastodon!')]);+});++test('a mastodon reply poll that cannot go fails before posting anything', function (array $reply, string $message) {+ $this->post->update(['meta' => ['thread_replies' => [$reply]]]);+ Http::fake();++ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(Exception::class, __($message, ['min' => 2]));+ Http::assertNothingSent();+})->with([+ 'one choice' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes'], 'duration_minutes' => 60]], 'posts.form.poll.options_required'],+ 'repeated choices' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', ' yes'], 'duration_minutes' => 60]], 'posts.form.poll.options_distinct'],+ 'no length' => [['text' => 'Which one?', 'poll' => ['options' => ['Yes', 'No']]], 'posts.form.poll.duration_required'],+ 'no question' => [['text' => '', 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]], 'posts.form.poll.question_required'],+]);++test('a mastodon reply poll with media is refused at publish and never sent', function () {+ $this->post->update(['meta' => ['thread_replies' => [[+ 'text' => 'Which one?',+ 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60],+ 'media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']],+ ]]]]);+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(ContentLimitException::class, __('posts.errors.media_not_accepted'));+ Http::assertNothingSent();+});++test('a mastodon reply poll changed before a retry is sent again under a new idempotency key, its post resumed and a plain reply keeping its text hash', function () {+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()+ ->push(['id' => '1', 'url' => "{$instance}/@t/1"])+ ->push(['id' => '2', 'url' => "{$instance}/@t/2"])+ ->push(['id' => '3', 'url' => "{$instance}/@t/3"])+ ->push(['id' => '4', 'url' => "{$instance}/@t/4"])+ ->push(['id' => '5', 'url' => "{$instance}/@t/5"])]);+ $first = ['options' => ['Yes', 'No'], 'duration_minutes' => 60];+ $changed = ['options' => ['Yes', 'Maybe'], 'duration_minutes' => 60];+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $first], 'Thanks!']]]);++ $this->publisher->publish($this->post->fresh());+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Which one?', 'poll' => $changed], 'Thanks!']]]);+ $this->publisher->publish($this->post->fresh());++ $keys = collect(Http::recorded())->map(fn (array $pair): string => $pair[0]->header('Idempotency-Key')[0])->values();++ expect($keys->all())->toBe([+ "{$this->post->id}:".ThreadProgress::hash('Hello from Mastodon!'),+ "{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $first),+ "{$this->post->id}:2:".ThreadProgress::hash('Thanks!'),+ "{$this->post->id}:1:".ThreadProgress::hash('Which one?', [], $changed),+ "{$this->post->id}:4:".ThreadProgress::hash('Thanks!'),+ ])+ ->and($keys->get(1))->not->toBe($keys->get(3));+});++test('a mastodon poll with a content warning sends both', function () {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::MastodonPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'spoiler_text' => 'Holy war'],+ ]);+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::response(['id' => '1', 'url' => "{$instance}/@t/1"])]);++ $this->publisher->publish($this->post->fresh());++ Http::assertSent(fn ($request): bool => data_get($request->data(), 'spoiler_text') === 'Holy war'+ && data_get($request->data(), 'poll') === ['options' => ['Tabs', 'Spaces'], 'expires_in' => 3600, 'multiple' => false, 'hide_totals' => false]);+});++test('a mastodon poll followed by plain replies chains them without a poll', function () {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::MastodonPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60], 'thread_replies' => ['Two', 'Three']],+ ]);+ $instance = data_get($this->socialAccount->meta, 'instance');+ Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()+ ->push(['id' => '1', 'url' => "{$instance}/@t/1"])+ ->push(['id' => '2', 'url' => "{$instance}/@t/2"])+ ->push(['id' => '3', 'url' => "{$instance}/@t/3"])]);++ $result = $this->publisher->publish($this->post->fresh());++ expect($result['thread_reply_ids'])->toBe(['2', '3']);+ Http::assertSent(fn ($request): bool => data_get($request->data(), 'status') === 'Tabs or spaces?' && filled(data_get($request->data(), 'poll')));+ Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Two', 'visibility' => 'public', 'in_reply_to_id' => '1']);+ Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Three', 'visibility' => 'public', 'in_reply_to_id' => '2']);+});diff --git a/tests/Feature/Services/Social/ThreadsPublisherTest.php b/tests/Feature/Services/Social/ThreadsPublisherTest.phpindex 60548af8e..35572f0c4 100644--- a/tests/Feature/Services/Social/ThreadsPublisherTest.php+++ b/tests/Feature/Services/Social/ThreadsPublisherTest.php@@ -1117,3 +1117,56 @@ test('a text post waits for its container before publishing and recreates it whe->and($publicationAttempts)->toBe(2)->and(array_slice($requestOrder, 0, 3))->toBe(['create', 'status', 'publish']);});++test('a threads poll is a text container carrying its choices as option_a to option_d', function () {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::ThreadsPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces', 'Both']], 'topic_tag' => 'laravel'],+ ]);+ fakeThreadsContainerFlow();++ $this->publisher->publish($this->post->fresh());++ Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/123456789/threads')+ && data_get($request->data(), 'media_type') === 'TEXT'+ && data_get($request->data(), 'text') === 'Tabs or spaces?'+ && data_get($request->data(), 'topic_tag') === 'laravel'+ && json_decode((string) data_get($request->data(), 'poll_attachment'), true) === ['option_a' => 'Tabs', 'option_b' => 'Spaces', 'option_c' => 'Both']);+});++test('a threads poll that cannot go fails before calling threads', function (array $changes, string $message) {+ $this->post->update([+ 'content' => 'Tabs or spaces?',+ 'content_type' => ContentType::ThreadsPoll,+ 'meta' => ['poll' => ['options' => ['Tabs', 'Spaces']]],+ ...$changes,+ ]);+ Http::fake();++ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(ThreadsPublishException::class, __($message, ['min' => 2]));+ Http::assertNothingSent();+})->with([+ 'media' => [['media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']]], 'posts.errors.media_not_accepted'],+ 'one choice' => [['meta' => ['poll' => ['options' => ['Tabs']]]], 'posts.form.poll.options_required'],+ 'repeated choices' => [['meta' => ['poll' => ['options' => ['Tabs', ' tabs']]]], 'posts.form.poll.options_distinct'],+ 'no question' => [['content' => ''], 'posts.form.poll.question_required'],+]);++test('a threads poll with four choices sends option_a to option_d', function () {+ $this->post->update([+ 'content' => 'Pick a color',+ 'content_type' => ContentType::ThreadsPoll,+ 'meta' => ['poll' => ['options' => ['Red', 'Green', 'Blue', 'Gold']]],+ ]);+ fakeThreadsContainerFlow();++ $this->publisher->publish($this->post->fresh());++ Http::assertSent(fn ($request): bool => json_decode((string) data_get($request->data(), 'poll_attachment'), true) === [+ 'option_a' => 'Red',+ 'option_b' => 'Green',+ 'option_c' => 'Blue',+ 'option_d' => 'Gold',+ ]);+});diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.phpindex c70542d9e..7b81efd70 100644--- a/tests/Feature/Services/Social/XPublisherTest.php+++ b/tests/Feature/Services/Social/XPublisherTest.php@@ -2019,7 +2019,7 @@ test('x publisher asks for the question of an x poll without text', function ()Http::fake();expect(fn () => $this->publisher->publish($this->post->fresh()))- ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.x.poll.question_required'))+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.poll.question_required'))->and($exception->category)->toBe(ErrorCategory::ContentPolicy));Http::assertNothingSent();});@@ -2029,7 +2029,7 @@ test('x publisher refuses to publish an x poll without a length', function () {Http::fake();expect(fn () => $this->publisher->publish($this->post->fresh()))- ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.x.poll.duration_required'))+ ->toThrow(fn (XPublishException $exception) => expect($exception->getMessage())->toBe(__('posts.form.poll.duration_required'))->and($exception->category)->toBe(ErrorCategory::ContentPolicy));Http::assertNothingSent();});@@ -2116,7 +2116,7 @@ test('x publisher refuses a thread reply poll without its question before postinHttp::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);expect(fn () => $this->publisher->publish($this->post->fresh()))- ->toThrow(ContentLimitException::class, __('posts.form.x.poll.question_required'));+ ->toThrow(ContentLimitException::class, __('posts.form.poll.question_required'));Http::assertNothingSent();});@@ -2131,12 +2131,25 @@ test('x publisher refuses a reply poll question over 280 characters on a long poHttp::assertNothingSent();});+test('x publisher refuses a reply poll carrying media before posting anything', function () {+ $this->post->update(['content' => 'Pick one', 'meta' => ['thread_replies' => [[+ 'text' => 'Tabs or spaces?',+ 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 60],+ 'media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']],+ ]]]]);+ Http::fake();++ expect(fn () => $this->publisher->publish($this->post->fresh()))+ ->toThrow(ContentLimitException::class, __('posts.errors.media_not_accepted'));+ Http::assertNothingSent();+});+test('x publisher refuses a poll with repeated choices before calling x', function (array $meta) {$this->post->update(['content' => 'Pick one', ...$meta]);Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);expect(fn () => $this->publisher->publish($this->post->fresh()))- ->toThrow(Exception::class, __('posts.form.x.poll.options_distinct'));+ ->toThrow(Exception::class, __('posts.form.poll.options_distinct'));Http::assertNothingSent();})->with(['on the post' => [['content_type' => ContentType::XPoll, 'meta' => ['poll' => ['options' => ['Yes', 'yes'], 'duration_minutes' => 60]]]],diff --git a/tests/Feature/ThreadRepliesPreviewTest.php b/tests/Feature/ThreadRepliesPreviewTest.phpindex f5005c7c3..7fea2c8d5 100644--- a/tests/Feature/ThreadRepliesPreviewTest.php+++ b/tests/Feature/ThreadRepliesPreviewTest.php@@ -7,6 +7,7 @@ use App\Enums\SocialAccount\Platform;use App\Models\Post;use App\Services\Post\PostPreviewer;use App\Services\Social\ContentSanitizer;+use App\Support\Social\MastodonPoll;test('previews thread replies with the network sanitizer', function () {$post = Post::factory()->bluesky()->create([@@ -63,3 +64,38 @@ test('an x preview shows the poll of the post and of each reply that has one', f['text' => 'Thanks!', 'media' => []],]);});++test('a mastodon preview shows its poll with the defaults it publishes with, on the post and a reply', function () {+ $post = Post::factory()->mastodon()->create([+ 'content' => 'Pick one',+ 'content_type' => ContentType::MastodonPoll,+ 'meta' => [+ 'poll' => ['options' => ['Yes', 'No'], 'multiple' => true],+ 'thread_replies' => [['text' => 'And on Fridays?', 'poll' => ['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120, 'hide_totals' => true]]],+ ],+ ]);++ $preview = app(PostPreviewer::class)->forPost($post->fresh());++ expect($preview['poll'])->toEqual(['options' => ['Yes', 'No'], 'duration_minutes' => MastodonPoll::DEFAULT_DURATION, 'multiple' => true, 'hide_totals' => false])+ ->and($preview['thread_replies'][0]['poll'])->toEqual(['options' => ['Tabs', 'Spaces'], 'duration_minutes' => 120, 'multiple' => false, 'hide_totals' => true]);+});++test('a threads preview shows only the choices of its poll', function () {+ $post = Post::factory()->threads()->create([+ 'content' => 'Pick one',+ 'content_type' => ContentType::ThreadsPoll,+ 'meta' => ['poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]],+ ]);++ expect(app(PostPreviewer::class)->forPost($post->fresh())['poll'])->toEqual(['options' => ['Yes', 'No']]);+});++test('a bluesky reply shows no poll in the preview', function () {+ $post = Post::factory()->bluesky()->create([+ 'content' => 'Root',+ 'meta' => ['thread_replies' => [['text' => 'Two', 'poll' => ['options' => ['Yes', 'No']]]]],+ ]);++ expect(app(PostPreviewer::class)->forPost($post->fresh())['thread_replies'])->toEqual([['text' => 'Two', 'media' => []]]);+});diff --git a/tests/Pest.php b/tests/Pest.phpindex dfe1ab9e3..858e04dbd 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -3,17 +3,23 @@declare(strict_types=1);use App\Enums\Plan\Slug;+use App\Enums\Post\Status as PostStatus;+use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Post\UpdatePostTool;use App\Models\AccessToken;use App\Models\Account;use App\Models\Plan;+use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;use App\Services\Http\HostResolver;use App\Support\Social\PendingConnection;+use App\Support\Social\Poll;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Http\Client\Request as HttpClientRequest;use Illuminate\Support\Facades\Bus;@@ -22,6 +28,7 @@ use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;use Illuminate\Testing\TestResponse;+use Laravel\Mcp\Server\Testing\TestResponse as McpTestResponse;use Stripe\ApiRequestor;use Stripe\HttpClient\ClientInterface;use Tests\BrowserTestCase;@@ -687,6 +694,98 @@ function parityContext(): array];}+/**+ * A post on a channel of a poll's network (X, Mastodon or Threads), owned by a+ * signed-in member, for the composer's browser tests. Every request to a+ * network answers empty.+ *+ * @param array<string, mixed> $attributes+ * @param array<string, mixed> $accountAttributes+ * @param array<string, mixed> $userAttributes+ */+function seedPollComposerPost(ContentType $type, array $attributes = [], array $accountAttributes = [], array $userAttributes = []): Post+{+ Http::fake(['*' => Http::response([], 200)]);++ $user = User::factory()->create($userAttributes);+ $workspace = Workspace::factory()->create(['user_id' => $user->id]);+ $workspace->members()->attach($user->id, membershipPivot('member'));+ $user->update(['current_workspace_id' => $workspace->id]);+ connectAiTo($user);++ $account = SocialAccount::factory()->{$type->platform()->value}()->create([+ 'workspace_id' => $workspace->id,+ 'username' => 'trypostit',+ 'token_expires_at' => now()->addDays(20),+ ...$accountAttributes,+ ]);++ $post = Post::factory()->forAccount($account, $type)->create([+ 'user_id' => $user->id,+ 'content' => 'Which network brings you the most customers?',+ ...$attributes,+ ]);++ test()->actingAs($user);++ return $post;+}++/**+ * Opens a post in the composer, once its network's Poll type can be picked.+ */+function openPollComposer(Post $post): mixed+{+ $pollType = Poll::for($post->platform)::contentType()->value;+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);+ waitFor($page, "@composer-type-{$post->social_account_id}-{$pollType}");++ return $page;+}++/**+ * A draft of a poll's network (X, Mastodon or Threads) in the parity+ * context's workspace, asking 'Tabs or spaces?'.+ *+ * @param array<string, mixed> $meta+ * @param array<string, mixed> $accountMeta+ */+function pollParityPost(ContentType $type, array $meta = [], array $accountMeta = []): Post+{+ $account = SocialAccount::factory()->{$type->platform()->value}()->create(['workspace_id' => test()->workspace->id, 'meta' => $accountMeta]);++ return Post::factory()->forAccount($account, $type)->create([+ 'user_id' => test()->user->id,+ 'content' => 'Tabs or spaces?',+ 'status' => PostStatus::Draft,+ 'media' => [],+ 'meta' => $meta,+ ]);+}++/**+ * Sends the same post update through one surface: the web composer, the REST+ * API or the MCP tool, and returns that surface's own response, which is why+ * the return type is a union.+ *+ * @param array<string, mixed> $changes+ */+function pollParityUpdate(string $surface, Post $post, array $changes): TestResponse|McpTestResponse+{+ $payload = [+ 'content' => $post->content,+ 'content_type' => $post->content_type->value,+ 'status' => PostStatus::Draft->value,+ ...$changes,+ ];++ return match ($surface) {+ 'web' => test()->actingAs(test()->user)->putJson(route('app.posts.update', $post), ['media' => [], ...$payload]),+ 'api' => test()->withHeaders(parityApi(test()->token))->putJson(route('api.posts.update', $post), $payload),+ 'mcp' => TryPostServer::actingAs(test()->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, ...$payload]),+ };+}+/*** @return array<string, string>*/diff --git a/tests/Unit/ContentTypeParityTest.php b/tests/Unit/ContentTypeParityTest.phpnew file mode 100644index 000000000..2a6bd8bf8--- /dev/null+++ b/tests/Unit/ContentTypeParityTest.php@@ -0,0 +1,48 @@+<?php++declare(strict_types=1);++use App\Enums\PostPlatform\ContentType;+use Symfony\Component\Process\ExecutableFinder;+use Symfony\Component\Process\Process;++/**+ * @return array{values: list<string>, polls: list<string>, poll_posts: array<string, string>, medialess: list<string>}+ */+function composerContentTypes(): array+{+ $node = (new ExecutableFinder)->find('node');++ if ($node === null) {+ test()->markTestSkipped('node is unavailable');+ }++ $process = (new Process([$node, base_path('tests/fixtures/content-type-harness.ts'), resource_path('js')]))->mustRun();++ return json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR);+}++test('the composer knows every content type the server has', function () {+ expect(composerContentTypes()['values'])+ ->toEqualCanonicalizing(array_map(fn (ContentType $type): string => $type->value, ContentType::cases()));+});++test('the composer treats as polls the content types the server does', function () {+ $composer = composerContentTypes();+ $polls = collect(ContentType::cases())->filter(fn (ContentType $type): bool => $type->isPoll());++ expect($composer['polls'])+ ->toEqualCanonicalizing($polls->map(fn (ContentType $type): string => $type->value)->values()->all())+ ->and($composer['poll_posts'])+ ->toEqual($polls->mapWithKeys(fn (ContentType $type): array => [$type->value => ContentType::defaultFor($type->platform())->value])->all());+});++test('the composer takes no media on the content types the server takes none on', function () {+ $medialess = collect(ContentType::cases())+ ->filter(fn (ContentType $type): bool => $type->maxMediaCount() === 0 && ! $type->isCaptionless())+ ->map(fn (ContentType $type): string => $type->value)+ ->values()+ ->all();++ expect(composerContentTypes()['medialess'])->toEqualCanonicalizing($medialess);+});diff --git a/tests/Unit/Enums/ContentTypeTest.php b/tests/Unit/Enums/ContentTypeTest.phpindex b3d5bd5ce..209efe6e6 100644--- a/tests/Unit/Enums/ContentTypeTest.php+++ b/tests/Unit/Enums/ContentTypeTest.php@@ -5,6 +5,9 @@ declare(strict_types=1);use App\Enums\Media\Type as MediaType;use App\Enums\PostPlatform\ContentType;use App\Enums\SocialAccount\Platform;+use App\Support\Social\MastodonPoll;+use App\Support\Social\ThreadsPoll;+use App\Support\Social\XPoll;test('content type has correct labels', function () {expect(ContentType::InstagramFeed->label())->toBe('Feed Post');@@ -520,9 +523,28 @@ test('a post type that takes no media advertises no media capability', function->and($type->preferredImageDimensions())->toBe(ContentType::ThreadsGhostPost->preferredImageDimensions());})->with(['x poll' => [ContentType::XPoll],+ 'mastodon poll' => [ContentType::MastodonPoll],+ 'threads poll' => [ContentType::ThreadsPoll],'threads ghost post' => [ContentType::ThreadsGhostPost],]);+test('a poll type names its network\'s poll rules', function (ContentType $type, string $poll) {+ expect($type->poll())->toBe($poll)+ ->and($type->isPoll())->toBeTrue();+})->with([+ 'x poll' => [ContentType::XPoll, XPoll::class],+ 'mastodon poll' => [ContentType::MastodonPoll, MastodonPoll::class],+ 'threads poll' => [ContentType::ThreadsPoll, ThreadsPoll::class],+]);++test('every other type has no poll rules', function () {+ $withPoll = collect(ContentType::cases())->filter(fn (ContentType $type): bool => filled($type->poll()))->values()->all();++ expect($withPoll)->toEqualCanonicalizing([ContentType::XPoll, ContentType::MastodonPoll, ContentType::ThreadsPoll])+ ->and(ContentType::MastodonPost->isPoll())->toBeFalse()+ ->and(ContentType::ThreadsPost->isPoll())->toBeFalse();+});+test('a post type is compatible with the platforms it can go to', function () {expect(ContentType::InstagramReel->isCompatibleWith(Platform::Instagram))->toBeTrue()->and(ContentType::InstagramReel->isCompatibleWith(Platform::InstagramFacebook))->toBeTrue()diff --git a/tests/Unit/Enums/PlatformTest.php b/tests/Unit/Enums/PlatformTest.phpindex e132aec84..bbcb5e0e3 100644--- a/tests/Unit/Enums/PlatformTest.php+++ b/tests/Unit/Enums/PlatformTest.php@@ -427,6 +427,36 @@ test('x publish config serves the poll limits', function () {'maxDuration' => 10080,'defaultDuration' => 1440,'questionMaxLength' => 280,+ 'multipleChoice' => false,+ 'hideTotals' => false,+ ]]);+});++test('mastodon publish config serves the poll limits, with multiple choice and hidden totals', function () {+ expect(Platform::Mastodon->publishConfig())->toBe(['poll' => [+ 'minOptions' => 2,+ 'maxOptions' => 4,+ 'optionMaxLength' => 50,+ 'minDuration' => 5,+ 'maxDuration' => 43200,+ 'defaultDuration' => 1440,+ 'questionMaxLength' => null,+ 'multipleChoice' => true,+ 'hideTotals' => true,+ ]]);+});++test('threads publish config serves the poll limits, without a length to pick', function () {+ expect(Platform::Threads->publishConfig())->toBe(['poll' => [+ 'minOptions' => 2,+ 'maxOptions' => 4,+ 'optionMaxLength' => 25,+ 'minDuration' => null,+ 'maxDuration' => null,+ 'defaultDuration' => null,+ 'questionMaxLength' => null,+ 'multipleChoice' => false,+ 'hideTotals' => false,]]);});diff --git a/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php b/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.phpindex d6c5a55bf..9542568af 100644--- a/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php+++ b/tests/Unit/Enums/PostPlatform/ContentTypeFromPublicationTest.php@@ -23,6 +23,8 @@ function specializedPublicationTypes(): array'pinterest video' => [Platform::Pinterest, PublicationContentType::Video, ContentType::PinterestVideoPin],'pinterest carousel' => [Platform::Pinterest, PublicationContentType::Carousel, ContentType::PinterestCarousel],'x poll' => [Platform::X, PublicationContentType::Poll, ContentType::XPoll],+ 'mastodon poll' => [Platform::Mastodon, PublicationContentType::Poll, ContentType::MastodonPoll],+ 'threads poll' => [Platform::Threads, PublicationContentType::Poll, ContentType::ThreadsPoll],];}diff --git a/tests/Unit/PostPlatformMetaRulesTest.php b/tests/Unit/PostPlatformMetaRulesTest.phpindex 4bb609813..a1ec79971 100644--- a/tests/Unit/PostPlatformMetaRulesTest.php+++ b/tests/Unit/PostPlatformMetaRulesTest.php@@ -8,7 +8,6 @@ use App\Enums\SocialAccount\Platform;use App\Enums\TikTok\PrivacyLevel;use App\Rules\ContentFitsPlatformLimits;use App\Support\PostPlatformMetaRules;-use App\Support\Social\XPoll;use Illuminate\Support\Facades\Validator;test('custom meta messages cover pinterest, instagram collaborators, google business and x polls', function () {@@ -20,16 +19,14 @@ test('custom meta messages cover pinterest, instagram collaborators, google busi'meta.collaborators.*.regex' => __('posts.form.instagram.collaborators.invalid'),'meta.event.end_date.after_or_equal' => __('posts.form.google_business.event_end_date_before_start'),'meta.event.title.max' => __('posts.form.google_business.title_max'),- 'meta.poll.array' => __('posts.form.x.poll.poll_object'),- 'meta.poll.options.array' => __('posts.form.x.poll.options_list'),- 'meta.poll.options.*.string' => __('posts.form.x.poll.choice_text'),- 'meta.poll.duration_minutes.integer' => XPoll::durationRangeMessage(),- 'meta.poll.duration_minutes.between' => XPoll::durationRangeMessage(),- 'meta.thread_replies.*.poll.array' => __('posts.form.x.poll.poll_object'),- 'meta.thread_replies.*.poll.options.array' => __('posts.form.x.poll.options_list'),- 'meta.thread_replies.*.poll.options.*.string' => __('posts.form.x.poll.choice_text'),- 'meta.thread_replies.*.poll.duration_minutes.integer' => XPoll::durationRangeMessage(),- 'meta.thread_replies.*.poll.duration_minutes.between' => XPoll::durationRangeMessage(),+ 'meta.poll.array' => __('posts.form.poll.poll_object'),+ 'meta.poll.options.array' => __('posts.form.poll.options_list'),+ 'meta.poll.options.*.string' => __('posts.form.poll.choice_text'),+ 'meta.poll.duration_minutes.integer' => __('posts.form.poll.duration_whole'),+ 'meta.thread_replies.*.poll.array' => __('posts.form.poll.poll_object'),+ 'meta.thread_replies.*.poll.options.array' => __('posts.form.poll.options_list'),+ 'meta.thread_replies.*.poll.options.*.string' => __('posts.form.poll.choice_text'),+ 'meta.thread_replies.*.poll.duration_minutes.integer' => __('posts.form.poll.duration_whole'),]);});@@ -429,9 +426,9 @@ test('the meta documentation names every youtube category', function () {});test('youtube title format is checked regardless of publishing', function () {- expect(PostPlatformMetaRules::formatViolation(Platform::YouTube, ['title' => '<x>']))->toBe(['title', __('posts.form.youtube.title_invalid')])- ->and(PostPlatformMetaRules::formatViolation(Platform::Pinterest, ['title' => '<x>']))->toBeNull()- ->and(PostPlatformMetaRules::formatViolation(Platform::YouTube, ['title' => 'ok']))->toBeNull();+ expect(PostPlatformMetaRules::formatErrors(Platform::YouTube, ['title' => '<x>']))->toBe(['title' => __('posts.form.youtube.title_invalid')])+ ->and(PostPlatformMetaRules::formatErrors(Platform::Pinterest, ['title' => '<x>']))->toBe([])+ ->and(PostPlatformMetaRules::formatErrors(Platform::YouTube, ['title' => 'ok']))->toBe([]);});test('a mastodon content warning counts toward the post limit', function () {@@ -474,8 +471,8 @@ test('instagram music and trial reel rules apply only to reels', function () {$music = ['audio' => ['id' => '1234567890']];expect(PostPlatformMetaRules::requiredMetaViolation(Platform::InstagramFacebook, $trialWithCollaborators, ContentType::InstagramReel)[0] ?? null)->toBe('trial_graduation')- ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::Instagram, $music, 'instagram_reel')[0] ?? null)->toBe('audio')- ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::InstagramFacebook, ['audio' => ['title' => 'Song']], 'instagram_reel')[0] ?? null)->toBe('audio.id')+ ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::Instagram, $music, ContentType::InstagramReel)[0] ?? null)->toBe('audio')+ ->and(PostPlatformMetaRules::requiredMetaViolation(Platform::InstagramFacebook, ['audio' => ['title' => 'Song']], ContentType::InstagramReel)[0] ?? null)->toBe('audio.id')->and(PostPlatformMetaRules::requiredMetaViolation(Platform::LinkedIn, ['audio' => ['title' => 'Song']], ContentType::LinkedInPost))->toBeNull()->and(PostPlatformMetaRules::requiredMetaViolation(Platform::InstagramFacebook, $trialWithCollaborators, ContentType::InstagramFeed))->toBeNull()->and(PostPlatformMetaRules::requiredMetaViolation(Platform::Instagram, $music, ContentType::InstagramStory))->toBeNull();diff --git a/tests/Unit/Support/Social/PollTest.php b/tests/Unit/Support/Social/PollTest.phpnew file mode 100644index 000000000..eee0e5642--- /dev/null+++ b/tests/Unit/Support/Social/PollTest.php@@ -0,0 +1,209 @@+<?php++declare(strict_types=1);++use App\Enums\Analytics\PollVotingStatus;+use App\Models\AnalyticsPublication;+use App\Support\Social\MastodonPoll;+use App\Support\Social\Poll;+use App\Support\Social\ThreadsPoll;+use App\Support\Social\XPoll;++test('a mastodon poll found without a publish time takes the default length', function () {+ $publication = (new AnalyticsPublication)->forceFill([+ 'provider_published_at' => null,+ 'provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tea', 'votes' => 1], ['label' => 'Coffee', 'votes' => 2]],+ 'end_datetime' => now('UTC')->addDays(3)->toIso8601ZuluString(),+ 'multiple' => true,+ ]],+ ]);++ expect(MastodonPoll::fromPublication($publication))->toBe([+ 'options' => ['Tea', 'Coffee'],+ 'duration_minutes' => MastodonPoll::DEFAULT_DURATION,+ 'multiple' => true,+ ]);+});++test('a mastodon poll found ending further out than mastodon allows keeps the longest length', function () {+ $publishedAt = now('UTC')->subHour();++ $publication = (new AnalyticsPublication)->forceFill([+ 'provider_published_at' => $publishedAt,+ 'provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tea', 'votes' => 0], ['label' => 'Coffee', 'votes' => 0]],+ 'end_datetime' => $publishedAt->addDays(45)->toIso8601ZuluString(),+ ]],+ ]);++ expect(MastodonPoll::fromPublication($publication))->toMatchArray([+ 'duration_minutes' => MastodonPoll::MAX_DURATION,+ 'multiple' => false,+ ]);+});++test('a mastodon multiple choice poll keeps its voters and marks hidden totals', function () {+ $endsAt = now('UTC')->addDay()->toIso8601ZuluString();++ expect(MastodonPoll::result([+ 'expired' => false,+ 'expires_at' => $endsAt,+ 'multiple' => true,+ 'voters_count' => 7,+ 'options' => [['title' => 'Tea', 'votes_count' => null], ['title' => 'Coffee', 'votes_count' => null]],+ ]))->toBe([+ 'options' => [['label' => 'Tea', 'votes' => 0], ['label' => 'Coffee', 'votes' => 0]],+ 'voting_status' => PollVotingStatus::Open->value,+ 'end_datetime' => $endsAt,+ 'duration_minutes' => null,+ 'multiple' => true,+ 'voters' => 7,+ 'totals_hidden' => true,+ ]);+});++test('a mastodon single choice poll with visible totals has no voters count', function () {+ $result = MastodonPoll::result([+ 'expired' => true,+ 'multiple' => false,+ 'voters_count' => null,+ 'options' => [['title' => 'Tea', 'votes_count' => 3], ['title' => 'Coffee', 'votes_count' => 0]],+ ]);++ expect($result)->toMatchArray([+ 'options' => [['label' => 'Tea', 'votes' => 3], ['label' => 'Coffee', 'votes' => 0]],+ 'voting_status' => PollVotingStatus::Closed->value,+ 'multiple' => false,+ 'voters' => null,+ 'totals_hidden' => false,+ ]);+});++test('a threads poll with four choices is sent as option a to d', function () {+ expect(ThreadsPoll::payload(['poll' => ['options' => ['Red', ' Green ', 'Blue', 'Gold']]]))->toBe([+ 'option_a' => 'Red',+ 'option_b' => 'Green',+ 'option_c' => 'Blue',+ 'option_d' => 'Gold',+ ]);+});++test('a threads poll result with four choices works the votes out of each share', function () {+ $endsAt = now('UTC')->addDay()->startOfSecond();++ expect(ThreadsPoll::result([+ 'option_a' => 'Red',+ 'option_b' => 'Green',+ 'option_c' => 'Blue',+ 'option_d' => 'Gold',+ 'option_a_votes_percentage' => 0.1,+ 'option_b_votes_percentage' => 0.2,+ 'option_c_votes_percentage' => 0.3,+ 'option_d_votes_percentage' => 0.4,+ 'total_votes' => 20,+ 'expiration_timestamp' => $endsAt->toIso8601String(),+ ]))->toBe([+ 'options' => [+ ['label' => 'Red', 'votes' => 2],+ ['label' => 'Green', 'votes' => 4],+ ['label' => 'Blue', 'votes' => 6],+ ['label' => 'Gold', 'votes' => 8],+ ],+ 'voting_status' => PollVotingStatus::Open->value,+ 'end_datetime' => $endsAt->toIso8601ZuluString(),+ 'duration_minutes' => null,+ ]);+});++test('a threads poll result without a vote total reads no votes', function () {+ $result = ThreadsPoll::result([+ 'option_a' => 'Red',+ 'option_b' => 'Green',+ 'option_a_votes_percentage' => 0.5,+ 'option_b_votes_percentage' => 0.5,+ 'expiration_timestamp' => now('UTC')->subDay()->toIso8601String(),+ ]);++ expect(data_get($result, 'options'))->toBe([['label' => 'Red', 'votes' => 0], ['label' => 'Green', 'votes' => 0]])+ ->and(data_get($result, 'voting_status'))->toBe(PollVotingStatus::Closed->value);+});++test('normalizing a poll keeps blank choices at their position while the network keeps only filled ones', function () {+ $poll = ['options' => ['Tea', ' ', null, ' Coffee '], 'duration_minutes' => '60', 'multiple' => 'true', 'hide_totals' => '0'];++ expect(Poll::normalize($poll))->toBe([+ 'options' => ['Tea', '', '', 'Coffee'],+ 'duration_minutes' => 60,+ 'multiple' => true,+ 'hide_totals' => false,+ ])+ ->and(MastodonPoll::forNetwork($poll))->toBe([+ 'options' => ['Tea', 'Coffee'],+ 'duration_minutes' => 60,+ 'multiple' => true,+ 'hide_totals' => false,+ ])+ ->and(XPoll::forNetwork($poll))->toBe(['options' => ['Tea', 'Coffee'], 'duration_minutes' => 60])+ ->and(ThreadsPoll::forNetwork($poll))->toBe(['options' => ['Tea', 'Coffee']]);+});++test('a poll the network returned reads as its result, and anything else as none', function (mixed $poll) {+ expect(MastodonPoll::resultOf($poll))->toBeNull()+ ->and(MastodonPoll::metadataFrom($poll))->toBe([]);+})->with([+ 'no poll' => [null],+ 'a string' => ['poll'],+ 'a number' => [3],+]);++test('a poll the network returned reads as the same result its metadata keeps', function () {+ $poll = [+ 'expired' => false,+ 'expires_at' => now('UTC')->addDay()->toIso8601ZuluString(),+ 'multiple' => false,+ 'options' => [['title' => 'Tea', 'votes_count' => 2], ['title' => 'Coffee', 'votes_count' => 1]],+ ];++ expect(MastodonPoll::resultOf($poll))->toBe(MastodonPoll::result($poll))+ ->and(MastodonPoll::metadataFrom($poll))->toBe(['poll' => MastodonPoll::result($poll)]);+});++test('a mastodon poll result without an expired flag has no voting status', function () {+ $result = MastodonPoll::result([+ 'expires_at' => now('UTC')->addDay()->toIso8601ZuluString(),+ 'options' => [['title' => 'Tea', 'votes_count' => 1], ['title' => 'Coffee', 'votes_count' => 0]],+ ]);++ expect(data_get($result, 'voting_status'))->toBeNull();+});++test('a threads poll result without an end has no voting status and no end', function () {+ $result = ThreadsPoll::result([+ 'option_a' => 'Red',+ 'option_b' => 'Green',+ 'option_a_votes_percentage' => 0.5,+ 'option_b_votes_percentage' => 0.5,+ 'total_votes' => 4,+ ]);++ expect(data_get($result, 'voting_status'))->toBeNull()+ ->and(data_get($result, 'end_datetime'))->toBeNull()+ ->and(data_get($result, 'options'))->toBe([['label' => 'Red', 'votes' => 2], ['label' => 'Green', 'votes' => 2]]);+});++test('a mastodon poll found ending sooner than mastodon allows keeps the shortest length', function () {+ $publishedAt = now('UTC')->subHour();++ $publication = (new AnalyticsPublication)->forceFill([+ 'provider_published_at' => $publishedAt,+ 'provider_metadata' => ['poll' => [+ 'options' => [['label' => 'Tea', 'votes' => 0], ['label' => 'Coffee', 'votes' => 0]],+ 'end_datetime' => $publishedAt->addMinutes(2)->toIso8601ZuluString(),+ ]],+ ]);++ expect(MastodonPoll::fromPublication($publication))->toMatchArray([+ 'duration_minutes' => MastodonPoll::MIN_DURATION,+ ]);+});diff --git a/tests/Unit/ThreadRepliesParityTest.php b/tests/Unit/ThreadRepliesParityTest.phpindex fb0058779..bf7482f40 100644--- a/tests/Unit/ThreadRepliesParityTest.php+++ b/tests/Unit/ThreadRepliesParityTest.php@@ -24,6 +24,7 @@ test('the composer threads every network the way the server does', function () {return [$platform->value => ['reply_content_type' => ThreadReplies::replyContentType($platform)?->value,+ 'reply_poll_content_type' => transform(ThreadReplies::replyPoll($platform), fn (string $poll): string => $poll::contentType()->value),'max_replies' => ThreadReplies::maxReplies($platform),'empty_key' => $comments ? 'posts.form.thread.comment_empty' : 'posts.form.thread.reply_empty','too_long_key' => $comments ? 'posts.form.thread.comment_too_long' : 'posts.form.thread.reply_too_long',diff --git a/tests/Unit/ThreadRepliesTest.php b/tests/Unit/ThreadRepliesTest.phpindex a978ce864..868110844 100644--- a/tests/Unit/ThreadRepliesTest.php+++ b/tests/Unit/ThreadRepliesTest.php@@ -20,6 +20,9 @@ test('thread replies are checked per network', function (Platform $platform, arr'bluesky 300' => [Platform::Bluesky, [str_repeat('a', 301)], 'thread_replies.0'],'mastodon 500' => [Platform::Mastodon, ['ok', str_repeat('a', 501)], 'thread_replies.1'],'mastodon reply plus warning' => [Platform::Mastodon, [str_repeat('a', 495)], 'thread_replies.0', ['spoiler_text' => 'Ten chars!']],+ 'mastodon reply poll question fits' => [Platform::Mastodon, [['text' => str_repeat('a', 500), 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]], null],+ 'mastodon reply poll question 500' => [Platform::Mastodon, [['text' => str_repeat('a', 501), 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]], 'thread_replies.0'],+ 'mastodon reply poll question plus warning' => [Platform::Mastodon, [['text' => str_repeat('a', 495), 'media' => [], 'poll' => ['options' => ['Yes', 'No'], 'duration_minutes' => 60]]], 'thread_replies.0', ['spoiler_text' => 'Ten chars!']],'blank reply' => [Platform::Mastodon, [' '], 'thread_replies.0'],'blank reply object' => [Platform::X, [['text' => ' ', 'media' => []]], 'thread_replies.0'],'media-only reply' => [Platform::X, [['text' => '', 'media' => [['id' => 'image']]]], null],diff --git a/tests/fixtures/content-type-harness.ts b/tests/fixtures/content-type-harness.tsnew file mode 100644index 000000000..821348788--- /dev/null+++ b/tests/fixtures/content-type-harness.ts@@ -0,0 +1,34 @@+/**+ * Prints the composer's content types (`types/content-type.ts`): every value,+ * the polls, the post each poll goes back to and the types that carry no+ * media, so `ContentTypeParityTest.php` can compare them with `ContentType`+ * on the server.+ *+ * Node strips type annotations on import; the resolve hook maps the `@/` alias+ * and extension-less specifiers onto `resources/js/**.ts`.+ */+import { registerHooks } from 'node:module';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++const [resourcesDir] = process.argv.slice(2);++registerHooks({+ resolve: (specifier, context, nextResolve) =>+ specifier.startsWith('@/')+ ? nextResolve(pathToFileURL(path.join(path.resolve(resourcesDir), `${specifier.slice(2)}.ts`)).href, context)+ : nextResolve(specifier, context),+});++const { ContentType, MEDIALESS_CONTENT_TYPE_REASONS, POLL_CONTENT_TYPES, POLL_POST_CONTENT_TYPES } = await import(+ pathToFileURL(path.join(path.resolve(resourcesDir), 'types/content-type.ts')).href+);++console.log(+ JSON.stringify({+ values: Object.values(ContentType),+ polls: [...POLL_CONTENT_TYPES],+ poll_posts: POLL_POST_CONTENT_TYPES,+ medialess: Object.keys(MEDIALESS_CONTENT_TYPE_REASONS),+ }),+);diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.phpindex 2a16bd5ad..c1c5406d1 100644--- a/tests/fixtures/single-line-copy.php+++ b/tests/fixtures/single-line-copy.php@@ -194,15 +194,17 @@ return ['posts.form.thread.start' => 17,'posts.form.threads.topic' => 9,'posts.form.tiktok.privacy_level' => 13,- 'posts.form.x.poll.add_choice' => 18,- 'posts.form.x.poll.choice' => 10,- 'posts.form.x.poll.choice_optional' => 26,- 'posts.form.x.poll.choices' => 10,- 'posts.form.x.poll.days' => 6,- 'posts.form.x.poll.hours' => 7,- 'posts.form.x.poll.length' => 12,- 'posts.form.x.poll.minutes' => 7,- 'posts.form.x.poll.remove' => 21,+ 'posts.form.poll.add_choice' => 18,+ 'posts.form.poll.choice' => 10,+ 'posts.form.poll.choice_optional' => 26,+ 'posts.form.poll.choices' => 10,+ 'posts.form.poll.days' => 6,+ 'posts.form.poll.hide_totals' => 32,+ 'posts.form.poll.hours' => 7,+ 'posts.form.poll.length' => 12,+ 'posts.form.poll.minutes' => 7,+ 'posts.form.poll.multiple' => 29,+ 'posts.form.poll.remove' => 21,'posts.form.youtube.embeddable' => 23,'posts.form.youtube.made_for_kids' => 14,'posts.form.youtube.notify_subscribers' => 26,diff --git a/tests/fixtures/thread-replies-harness.ts b/tests/fixtures/thread-replies-harness.tsindex a0ed460c4..9c6ab1ffe 100644--- a/tests/fixtures/thread-replies-harness.ts+++ b/tests/fixtures/thread-replies-harness.ts@@ -1,6 +1,6 @@/*** Prints what the composer's thread helpers (`lib/threadReplies.ts`) answer for- * each platform given as an argument, so `ThreadRepliesParityTest.php` can+ * each platform given as an argument (a reply that is a poll included), so `ThreadRepliesParityTest.php` can* compare them with `ThreadReplies` on the server.** Node strips type annotations on import; the resolve hook maps the `@/` alias@@ -19,18 +19,27 @@ registerHooks({: nextResolve(specifier, context),});-const { replyEmptyKey, replyTooLongKey, startThreadKey, threadMaxReplies } = await import(+const {+ replyEmptyKey,+ replyTooLongKey,+ startThreadKey,+ threadMaxReplies,+ threadReplyContentType,+} = await import(pathToFileURL(path.join(path.resolve(resourcesDir), 'lib/threadReplies.ts')).href);const { THREAD_REPLY_CONTENT_TYPES } = await import(pathToFileURL(path.join(path.resolve(resourcesDir), 'types/network-options.ts')).href);+const pollReply = { text: 'Which one?', media: [], poll: { options: ['Yes', 'No'] } };+const results = Object.fromEntries(platforms.map((platform) => [platform,{reply_content_type: THREAD_REPLY_CONTENT_TYPES[platform] ?? null,+ reply_poll_content_type: threadReplyContentType(platform, pollReply) ?? null,max_replies: threadMaxReplies(platform),empty_key: replyEmptyKey(platform),too_long_key: replyTooLongKey(platform),