Skip to content

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.

24.4 KB
Raw Blame
<?php

declare(strict_types=1);

namespace App\Enums\SocialAccount;

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;

enum Platform: string
{
    case LinkedIn = 'linkedin';
    case LinkedInPage = 'linkedin-page';
    case X = 'x';
    case TikTok = 'tiktok';
    case YouTube = 'youtube';
    case Facebook = 'facebook';
    case Instagram = 'instagram';
    case InstagramFacebook = 'instagram-facebook';
    case Threads = 'threads';
    case Pinterest = 'pinterest';
    case Bluesky = 'bluesky';
    case Mastodon = 'mastodon';
    case Telegram = 'telegram';
    case Discord = 'discord';
    case GoogleBusiness = 'google_business';

    public function network(): string
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => 'linkedin',
            self::Instagram, self::InstagramFacebook => 'instagram',
            default => $this->value,
        };
    }

    /** Whether the network lays published posts out as a profile grid TryPost can approximate. */
    public function hasProfileGrid(): bool
    {
        return $this->network() === self::Instagram->network();
    }

    public function isIncludedInAnalytics(): bool
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage, self::Telegram,
            self::Discord, self::GoogleBusiness => false,
            default => true,
        };
    }

    public function reportsPublicationFollows(): bool
    {
        return match ($this) {
            self::Instagram, self::InstagramFacebook => true,
            default => false,
        };
    }

    /** @return list<string> */
    public static function analyticsValues(): array
    {
        return array_values(array_map(
            fn (self $platform): string => $platform->value,
            array_filter(self::cases(), fn (self $platform): bool => $platform->isIncludedInAnalytics()),
        ));
    }

    /**
     * @return array<int, string>
     */
    public function networkPlatformValues(): array
    {
        return array_values(array_map(
            fn (self $platform): string => $platform->value,
            array_filter(self::cases(), fn (self $platform): bool => $platform->network() === $this->network()),
        ));
    }

    public function label(): string
    {
        return match ($this) {
            self::LinkedIn => 'LinkedIn',
            self::LinkedInPage => 'LinkedIn Page',
            self::X => 'X',
            self::TikTok => 'TikTok',
            self::YouTube => 'YouTube Shorts',
            self::Facebook => 'Facebook Page',
            self::Instagram => 'Instagram',
            self::InstagramFacebook => 'Instagram (Facebook Business)',
            self::Threads => 'Threads',
            self::Pinterest => 'Pinterest',
            self::Bluesky => 'Bluesky',
            self::Mastodon => 'Mastodon',
            self::Telegram => 'Telegram',
            self::Discord => 'Discord',
            self::GoogleBusiness => 'Google Business Profile',
        };
    }

    /** What one connected identity of this platform is, as the connect confirmation page names it. */
    public function identityType(): IdentityType
    {
        return match ($this) {
            self::LinkedInPage, self::Facebook => IdentityType::Page,
            self::YouTube, self::Telegram => IdentityType::Channel,
            self::GoogleBusiness => IdentityType::Location,
            self::Discord => IdentityType::Server,
            default => IdentityType::Profile,
        };
    }

    public function color(): string
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => '#0A66C2',
            self::X => '#000000',
            self::TikTok => '#000000',
            self::YouTube => '#FF0000',
            self::Facebook => '#1877F2',
            self::Instagram => '#E4405F',
            self::InstagramFacebook => '#E4405F',
            self::Threads => '#000000',
            self::Pinterest => '#E60023',
            self::Bluesky => '#0085FF',
            self::Mastodon => '#6364FF',
            self::Telegram => '#26A5E4',
            self::Discord => '#5865F2',
            self::GoogleBusiness => '#4285F4',
        };
    }

    public function allowedMediaTypes(): array
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video, MediaType::Document],
            self::X => [MediaType::Image, MediaType::Video],
            self::TikTok => [MediaType::Image, MediaType::Video],
            self::YouTube => [MediaType::Video],
            self::Facebook => [MediaType::Image, MediaType::Video],
            self::Instagram, self::InstagramFacebook => [MediaType::Image, MediaType::Video],
            self::Threads => [MediaType::Image, MediaType::Video],
            self::Pinterest => [MediaType::Image, MediaType::Video],
            self::Bluesky => [MediaType::Image, MediaType::Video],
            self::Mastodon => [MediaType::Image, MediaType::Video],
            self::Telegram => [MediaType::Image, MediaType::Video],
            self::Discord => [MediaType::Image, MediaType::Video],
            self::GoogleBusiness => [MediaType::Image],
        };
    }

    public function maxImages(): int
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => 10,
            self::X => 4,
            self::TikTok => 0,
            self::YouTube => 0,
            self::Facebook => 10,
            self::Instagram, self::InstagramFacebook => 10,
            self::Threads => 10,
            self::Pinterest => 5,
            self::Bluesky => 4,
            self::Mastodon => 4,
            self::Telegram => 10,
            self::Discord => 10,
            self::GoogleBusiness => 1,
        };
    }

    /**
     * Character cap the platform's API accepts for image alt text (accessibility
     * description), or null when the platform has no alt-text field. X, LinkedIn,
     * Instagram, Pinterest, and Discord use documented API maxes. Facebook,
     * Threads, Mastodon, and Bluesky document no limit, so a defensive cap is
     * used instead. Single source of truth — publishers truncate to this value,
     * never a literal.
     */
    public function altTextMaxLength(): ?int
    {
        return match ($this) {
            self::Bluesky => 2000,
            self::X => 1000,
            self::Mastodon => 1500,
            self::LinkedIn, self::LinkedInPage => 4086,
            self::Facebook => 1000,
            self::Instagram, self::InstagramFacebook => 1000,
            self::Threads => 1000,
            self::Pinterest => 500,
            self::Discord => 1024,
            self::TikTok, self::YouTube, self::Telegram, self::GoogleBusiness => null,
        };
    }

    /**
     * Whether the platform's API accepts image alt text (accessibility
     * description) on published media.
     */
    public function supportsImageAltText(): bool
    {
        return $this->altTextMaxLength() !== null;
    }

    /**
     * Whether the platform's API also takes alt text on a video: Bluesky
     * (`alt` on `app.bsky.embed.video`), Mastodon (`description` on the media
     * upload), Threads (`alt_text` on a video container) and Discord
     * (`description` on the attachment).
     */
    public function supportsVideoAltText(): bool
    {
        return in_array($this, [self::Bluesky, self::Mastodon, self::Threads, self::Discord], true);
    }

    /**
     * Hard cap (in characters) the platform's API will accept. Going over this
     * means the post can't be published. Values are the documented API maxes:
     *
     *  - LinkedIn UGC: 3000 (`commentary` field)
     *  - X standard post: 280; an account with long posts gets 25000 through
     *    `SocialAccount::maxContentLength()`
     *  - TikTok caption: 2200
     *  - YouTube Shorts: content is the video description, 5000 (also capped at
     *    5000 UTF-8 bytes by `YouTubeDescription`). The title is meta.title, or
     *    `YouTubeMetadata::title()` derives it from the first line of content.
     *  - Facebook text status: 10000 (API allows 63206; we cap below
     *    that — 63k-char posts are unrealistic)
     *  - Instagram feed caption: 2200
     *  - Threads: 500
     *  - Pinterest pin description: 800 (title is 100, not modeled here)
     *  - Bluesky: 300 graphemes
     *  - Mastodon: 500 default; instances may be higher (we stay conservative)
     *  - Telegram: 4096 for a text message (media captions are capped at 1024,
     *    handled in the publisher by sending long text as its own message)
     *  - Google Business Profile Local Post `summary`: 1500
     */
    public function maxContentLength(): int
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => 3000,
            self::X => 280,
            self::TikTok => 2200,
            self::YouTube => 5000,
            self::Facebook => 10000,
            self::Instagram, self::InstagramFacebook => 2200,
            self::Threads => 500,
            self::Pinterest => 800,
            self::Bluesky => 300,
            self::Mastodon => 500,
            self::Telegram => 4096,
            self::Discord => 2000,
            self::GoogleBusiness => 1500,
        };
    }

    /**
     * Characters a network counts against the post limit besides its text:
     * Mastodon counts the content warning.
     *
     * @param  array<string, mixed>|null  $meta
     */
    public function reservedLength(?array $meta): int
    {
        $warning = data_get($meta, 'spoiler_text');

        return $this === self::Mastodon && is_string($warning) ? mb_strlen(Str::trim($warning)) : 0;
    }

    /**
     * Hashtags the network accepts per post, or null when it sets no cap we enforce.
     */
    public function maxHashtags(): ?int
    {
        return match ($this) {
            self::Instagram, self::InstagramFacebook => 5,
            default => null,
        };
    }

    public function hashtagOverflow(string $content): int
    {
        $limit = $this->maxHashtags();

        return $limit === null ? 0 : max(0, Hashtags::count($content) - $limit);
    }

    /**
     * Recommended target length (in characters) for AI-generated posts. This
     * is the engagement sweet spot — much shorter than the platform's hard
     * `maxContentLength()`. Use this to instruct the LLM at generation time;
     * use `maxContentLength()` for publish-time validation.
     */
    public function recommendedAiContentLength(): int
    {
        return match ($this) {
            // Microblogging — 70-200 char tweets perform best, leave hashtag room
            self::X, self::Bluesky => 220,
            // Threads/Mastodon — similar feel, slightly more relaxed
            self::Threads, self::Mastodon => 300,
            // LinkedIn — readable long-form sweet spot is ~1200-1500
            self::LinkedIn, self::LinkedInPage => 1200,
            // Instagram captions — most viewers expand only when interested,
            // 100-150 words performs best
            self::Instagram, self::InstagramFacebook => 600,
            // Facebook — short posts dominate the algorithm
            self::Facebook => 280,
            // Pinterest pin description — image does the work, keep it tight
            self::Pinterest => 200,
            // TikTok caption — the video carries the story
            self::TikTok => 150,
            // YouTube Shorts — the content is the description; the first lines
            // show under the video, so keep it short
            self::YouTube => 300,
            // Telegram channel posts — short announcements read best
            self::Telegram => 400,
            // Discord — conversational community posts read best when concise
            self::Discord => 280,
            // Google Business Profile — image does most of the work, keep the
            // summary tight and scannable
            self::GoogleBusiness => 300,
        };
    }

    /**
     * @return array<string>
     */
    public function requiredPublishScopes(): array
    {
        return match ($this) {
            self::Instagram => ['instagram_business_content_publish'],
            self::InstagramFacebook => ['instagram_content_publish'],
            self::Facebook => ['pages_manage_posts'],
            self::TikTok => ['video.publish'],
            self::YouTube => ['https://www.googleapis.com/auth/youtube.upload'],
            self::LinkedIn => ['w_member_social'],
            self::LinkedInPage => ['w_organization_social'],
            self::X => ['tweet.write'],
            self::Threads => ['threads_content_publish'],
            self::Pinterest => ['pins:write'],
            self::Bluesky => [],
            self::Mastodon => ['write:statuses'],
            self::Telegram => [],
            self::Discord => [],
            self::GoogleBusiness => ['https://www.googleapis.com/auth/business.manage'],
        };
    }

    /**
     * Whether a repurpose may publish to this platform. A repurpose always
     * carries a video, so a platform whose posts cannot carry one never can.
     */
    public function acceptsRepurposeDestination(): bool
    {
        return $this !== self::GoogleBusiness;
    }

    public function supportsTextOnly(): bool
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage => true,
            self::X => true,
            self::TikTok => false,
            self::YouTube => false,
            self::Facebook => true,
            self::Instagram, self::InstagramFacebook => false,
            self::Threads => true,
            self::Pinterest => false,
            self::Bluesky => true,
            self::Mastodon => true,
            self::Telegram => true,
            self::Discord => true,
            self::GoogleBusiness => true,
        };
    }

    public function requiresContent(): bool
    {
        return match ($this) {
            self::YouTube => true,
            default => false,
        };
    }

    /**
     * Whether this platform refreshes by extending the access_token itself
     * (Instagram/Threads long-lived tokens) instead of exchanging a separate
     * refresh_token. Extension-model tokens cannot be refreshed once expired,
     * so they must be refreshed proactively while still valid — the opposite
     * of rotating refresh_token platforms, which we avoid refreshing until
     * they actually expire so we don't rotate a still-valid single-use token.
     */
    public function extendsAccessTokenOnRefresh(): bool
    {
        return match ($this) {
            self::Instagram, self::Threads => true,
            default => false,
        };
    }

    /**
     * Whether ConnectionVerifier has a real per-account token refresh flow
     * for this platform. Facebook/InstagramFacebook use Page tokens and
     * Mastodon's tokens don't expire (see defaultTokenTtlSeconds()); Telegram
     * and Discord authenticate with one bot token shared across every
     * connected account of that platform, with no per-account credential to
     * refresh at all. For these, a rejected verify call can't be retried
     * after a refresh — there's nothing to refresh.
     */
    public function hasTokenRefreshFlow(): bool
    {
        return match ($this) {
            self::LinkedIn, self::LinkedInPage, self::X, self::Bluesky,
            self::YouTube, self::TikTok, self::Pinterest,
            self::Threads, self::Instagram, self::GoogleBusiness => true,
            default => false,
        };
    }

    /**
     * The `platform` column values of the platforms that refresh by extending
     * their access token in place (Instagram and Threads — see
     * extendsAccessTokenOnRefresh), for use in database whereIn/whereNotIn
     * filters. Derived from extendsAccessTokenOnRefresh() so the two never drift.
     *
     * @return array<int, string>
     */
    public static function accessTokenExtendingPlatformValues(): array
    {
        return array_values(array_map(
            fn (self $platform): string => $platform->value,
            array_filter(self::cases(), fn (self $platform): bool => $platform->extendsAccessTokenOnRefresh()),
        ));
    }

    /**
     * The token lifetime, in seconds, to assume when the provider's OAuth
     * response omits expires_in. Each value is that network's own documented
     * default:
     *
     *  - X: a 2-hour access token.
     *  - Instagram / Threads: Meta's 60-day long-lived token.
     *  - Google Business Profile: standard Google OAuth2 1-hour access token.
     *
     * Networks that always return expires_in (LinkedIn, TikTok, YouTube,
     * Pinterest), whose refresh sets a fixed lifetime directly (Bluesky), or
     * whose tokens never expire (Facebook, Mastodon, Telegram, Discord) have no
     * fallback here and return null.
     */
    public function defaultTokenTtlSeconds(): ?int
    {
        return match ($this) {
            self::X => 7200,
            self::GoogleBusiness => 3600,
            self::Instagram, self::Threads => 5184000,
            default => null,
        };
    }

    public function queue(): string
    {
        return 'social-'.$this->value;
    }

    /**
     * @return array<string>
     */
    public static function allQueues(): array
    {
        return array_map(fn (self $platform) => $platform->queue(), self::cases());
    }

    /**
     * @return array<string>
     */
    public static function enabledQueues(): array
    {
        return collect(self::cases())
            ->filter(fn (self $platform): bool => $platform->isEnabled())
            ->map(fn (self $platform): string => $platform->queue())
            ->values()
            ->all();
    }

    /**
     * The Graph API a Meta platform reads and publishes through.
     */
    public function graphApiUrl(): string
    {
        return match ($this) {
            self::Facebook => config('trypost.platforms.facebook.graph_api'),
            self::Instagram => config('trypost.platforms.instagram.graph_api'),
            self::InstagramFacebook => config('trypost.platforms.instagram-facebook.graph_api'),
            self::Threads => config('trypost.platforms.threads.graph_api'),
        };
    }

    public function isEnabled(): bool
    {
        return (bool) config(
            "trypost.platforms.{$this->value}.enabled",
            env(match ($this) {
                self::LinkedIn => 'LINKEDIN_ENABLED',
                self::LinkedInPage => 'LINKEDIN_PAGE_ENABLED',
                self::X => 'X_ENABLED',
                self::TikTok => 'TIKTOK_ENABLED',
                self::YouTube => 'YOUTUBE_ENABLED',
                self::Facebook => 'FACEBOOK_ENABLED',
                self::Instagram => 'INSTAGRAM_ENABLED',
                self::InstagramFacebook => 'INSTAGRAM_FACEBOOK_ENABLED',
                self::Threads => 'THREADS_ENABLED',
                self::Pinterest => 'PINTEREST_ENABLED',
                self::Bluesky => 'BLUESKY_ENABLED',
                self::Mastodon => 'MASTODON_ENABLED',
                self::Telegram => 'TELEGRAM_ENABLED',
                self::Discord => 'DISCORD_ENABLED',
                self::GoogleBusiness => 'GOOGLE_BUSINESS_ENABLED',
            }, true),
        );
    }

    /**
     * Whether this platform gets its own "Connect" card in the accounts grid.
     * LinkedIn company pages and Instagram-via-Facebook are reached through the
     * unified network card (identity picker / method dialog), never a standalone
     * card. That card stands for the whole network, so it shows whenever any
     * variant capability is enabled (self-hosters may run with only one).
     */
    public function isConnectable(): bool
    {
        return match ($this) {
            self::LinkedInPage, self::InstagramFacebook => false,
            self::LinkedIn => self::LinkedIn->isEnabled() || self::LinkedInPage->isEnabled(),
            self::Instagram => self::Instagram->isEnabled() || self::InstagramFacebook->isEnabled(),
            default => $this->isEnabled(),
        };
    }

    /**
     * OAuth entry points for the Instagram connect dialog. Only enabled methods
     * are returned so self-hosters who disable one variant do not see that option.
     *
     * @return list<string>
     */
    public static function instagramConnectMethods(): array
    {
        return array_values(array_filter([
            self::Instagram->isEnabled() ? self::Instagram->value : null,
            self::InstagramFacebook->isEnabled() ? self::InstagramFacebook->value : null,
        ]));
    }

    /**
     * @return list<array{value: string, label: string, network: string, analytics: bool, text_only: bool, media_types: list<string>, connect_methods?: list<string>}>
     */
    public static function connectableOptions(): array
    {
        return collect(self::cases())
            ->filter(fn (self $platform): bool => $platform->isConnectable())
            ->sortBy(fn (self $platform): string => mb_strtolower($platform->label()))
            ->map(function (self $platform): array {
                $option = [
                    'value' => $platform->value,
                    'label' => $platform->label(),
                    'network' => $platform->network(),
                    'analytics' => $platform->isIncludedInAnalytics(),
                    'text_only' => $platform->supportsTextOnly(),
                    'media_types' => array_map(fn (MediaType $type): string => $type->value, $platform->allowedMediaTypes()),
                ];

                if ($platform === self::Instagram) {
                    $option['connect_methods'] = self::instagramConnectMethods();
                }

                return $option;
            })
            ->values()
            ->all();
    }

    /**
     * Static, platform-specific data exposed to the frontend (e.g. TikTok privacy options,
     * compliance URLs). Returns an empty array for platforms with no extra config.
     *
     * @return array<string, mixed>
     */
    public function publishConfig(): array
    {
        return match ($this) {
            self::TikTok => [
                'privacyLevelOptions' => PrivacyLevel::values(),
                'musicUsageConfirmationUrl' => 'https://www.tiktok.com/legal/page/global/music-usage-confirmation/en',
                'brandedContentPolicyUrl' => 'https://www.tiktok.com/legal/page/global/bc-policy/en',
            ],
            self::YouTube => [
                'categoryOptions' => Category::options(),
                'defaultCategoryId' => Category::DEFAULT->value,
            ],
            self::X => ['poll' => XPoll::limits()],
            self::Mastodon => ['poll' => MastodonPoll::limits()],
            self::Threads => ['poll' => ThreadsPoll::limits()],
            default => [],
        };
    }

    /**
     * Recommended posting windows for this network, best first, as [day, hour]
     * pairs (day 0 = Sunday, local to the channel time zone). Built from a
     * ranked day order and four ranked hours, rotated so the first week does not
     * repeat one hour: block r (0..3) gives every day one window at
     * hours[(r + dayRank) % 4]. Day and hour rankings follow the published
     * "best time to post" industry studies
     * (2024-2025 editions) for each network.
     *
     * @return list<array{0: int, 1: int}>
     */
    public function recommendedPostingWindows(): array
    {
        [$days, $hours] = match ($this->network()) {
            'linkedin' => [[2, 3, 4, 1, 5, 6, 0], [8, 12, 10, 17]],
            'x' => [[2, 3, 4, 1, 5, 6, 0], [9, 12, 15, 18]],
            'instagram' => [[2, 3, 4, 1, 5, 6, 0], [11, 19, 13, 9]],
            'facebook' => [[2, 3, 4, 1, 5, 6, 0], [9, 13, 11, 15]],
            'threads' => [[2, 3, 4, 1, 5, 6, 0], [9, 12, 18, 20]],
            'tiktok' => [[2, 4, 5, 3, 1, 6, 0], [19, 12, 16, 21]],
            'youtube' => [[5, 6, 0, 4, 3, 2, 1], [15, 17, 12, 19]],
            'pinterest' => [[5, 6, 0, 4, 3, 2, 1], [20, 14, 21, 15]],
            'bluesky' => [[2, 3, 4, 1, 5, 6, 0], [9, 12, 17, 20]],
            'mastodon' => [[2, 3, 4, 1, 5, 6, 0], [10, 13, 16, 19]],
            'telegram' => [[1, 2, 3, 4, 5, 6, 0], [9, 12, 18, 20]],
            'discord' => [[5, 6, 0, 4, 3, 2, 1], [18, 20, 15, 21]],
            'google_business' => [[1, 2, 3, 4, 5, 6, 0], [9, 11, 14, 16]],
            default => [[2, 3, 4, 1, 5, 6, 0], [9, 12, 15, 18]],
        };

        $windows = [];

        foreach (range(0, 3) as $block) {
            foreach ($days as $rank => $day) {
                $windows[] = [$day, $hours[($block + $rank) % 4]];
            }
        }

        return $windows;
    }
}