Merge pull request #112 from trypostit/feat/linkedin-pdf-carousel
feat(linkedin): PDF documents, media-inferred post format, and unified connection
This commit is contained in:
commit
93208d4bb2
134 changed files with 4215 additions and 3658 deletions
|
|
@ -107,8 +107,6 @@ LINKEDIN_CLIENT_ID=
|
|||
LINKEDIN_CLIENT_SECRET=
|
||||
LINKEDIN_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin/callback"
|
||||
# LINKEDIN_SCOPES="openid,profile,email,w_member_social"
|
||||
LINKEDIN_PAGE_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin-page/callback"
|
||||
LINKEDIN_PAGE_CLIENT_REDIRECT="${APP_URL}/accounts/linkedin-page/callback"
|
||||
# LINKEDIN_PAGE_SCOPES="openid,profile,email,w_organization_social,r_organization_social,rw_organization_admin,w_member_social"
|
||||
|
||||
# X / Twitter (https://developer.twitter.com)
|
||||
|
|
|
|||
10
CLAUDE.md
10
CLAUDE.md
|
|
@ -291,6 +291,16 @@ ## Per-Platform Post Meta (`PostPlatform.meta`)
|
|||
- 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`.
|
||||
|
||||
## Media Types (image / video / document)
|
||||
|
||||
- A media item is one of exactly three types: **image**, **video**, **document** (PDF). There is no standalone "audio" media type (audio exists only as a video voiceover input).
|
||||
- Media-type detection lives in ONE place per side — NEVER hand-write `type === 'image'`, `mime_type === 'application/pdf'`, `mime.startsWith('video/')`, or extension checks inline.
|
||||
- Backend: `App\Enums\Media\Type` — `classify()`, `fromMime()`, `fromExtension()`, `isGif()`, plus the `allowedMimeTypes()` / `extensions()` allow-lists. Use these, never a raw MIME/extension comparison.
|
||||
- Frontend: `resources/js/lib/mediaType.ts` — the mirror of the backend enum: the `MediaType` union, `classify()`, `fromMimeType()` (for a browser `File.type`), `fromExtension()`, `isImage()`/`isVideo()`/`isDocument()`/`isGif()`. `@/composables/useMedia` re-exports `isImageMedia`/`isVideoMedia`/`isDocumentMedia` aliases for legacy call sites.
|
||||
- Detection trusts the explicit `type` first, then the MIME, then the filename extension — so an item with only a MIME (e.g. AI/Unsplash/Giphy media without a `type`) still classifies correctly. A bare `item.type === 'image'` (with a `v-else` video) silently mis-renders those.
|
||||
- The `type` field on every media-ish interface is the `MediaType` union, never `string` — `MediaItem`, and any sibling picked/asset/saved shape (`PickedMedia`, `AssetMedia`, `SavedMedia`, etc.).
|
||||
- The upload `accept` attribute for "everything we allow" comes from `acceptAttribute()` (frontend) / `Media\Type::allowedMimeTypes()` (backend) — never a hardcoded MIME list. Per-capability `accept` builders driven by content-type rules (e.g. `image/*,video/*`) are fine; those aren't detection.
|
||||
|
||||
## Pest / Feature Tests
|
||||
|
||||
- ALWAYS use named routes via the `route()` helper in feature tests. NEVER hardcode URL strings like `'/posts/ai/create'`.
|
||||
|
|
|
|||
|
|
@ -251,8 +251,8 @@ private function extractContent(array $structured, GeneratorFormat $format, Cont
|
|||
*
|
||||
* Carousel-capable content types:
|
||||
* - instagram_feed (Instagram feed carousel = multi-image feed post)
|
||||
* - linkedin_carousel (LinkedIn personal carousel PDF)
|
||||
* - linkedin_page_carousel (LinkedIn page carousel PDF)
|
||||
* - linkedin_post (LinkedIn multi-image post — 2+ images)
|
||||
* - linkedin_page_post (LinkedIn page multi-image post)
|
||||
* - pinterest_carousel (Pinterest carousel pin)
|
||||
* - tiktok_photo (TikTok photo carousel)
|
||||
*
|
||||
|
|
|
|||
|
|
@ -13,7 +13,15 @@ class DeleteWorkspace
|
|||
{
|
||||
public static function execute(User $user, Workspace $workspace): void
|
||||
{
|
||||
User::where('current_workspace_id', $workspace->id)->update(['current_workspace_id' => null]);
|
||||
User::where('current_workspace_id', $workspace->id)
|
||||
->get()
|
||||
->each(function (User $affected) use ($workspace): void {
|
||||
$fallback = $affected->workspaces()
|
||||
->where('workspaces.id', '!=', $workspace->id)
|
||||
->first();
|
||||
|
||||
$affected->update(['current_workspace_id' => $fallback?->id]);
|
||||
});
|
||||
|
||||
$account = $workspace->account;
|
||||
$accountId = (string) $workspace->account_id;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
namespace App\DataTransferObjects;
|
||||
|
||||
use App\Enums\Media\Source;
|
||||
use App\Enums\Media\Type;
|
||||
|
||||
class MediaItem
|
||||
{
|
||||
|
|
@ -23,29 +24,19 @@ public function __construct(
|
|||
|
||||
public function isVideo(): bool
|
||||
{
|
||||
if ($this->mime_type) {
|
||||
return str_starts_with($this->mime_type, 'video/');
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
|
||||
|
||||
return in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v']);
|
||||
return Type::classify($this->mime_type, $this->path) === Type::Video;
|
||||
}
|
||||
|
||||
public function isImage(): bool
|
||||
{
|
||||
if ($this->mime_type) {
|
||||
return str_starts_with($this->mime_type, 'image/');
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
|
||||
|
||||
return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']);
|
||||
return Type::classify($this->mime_type, $this->path) === Type::Image;
|
||||
}
|
||||
|
||||
public function isDocument(): bool
|
||||
{
|
||||
return Type::classify($this->mime_type, $this->path) === Type::Document;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
|
|
@ -63,6 +54,7 @@ public static function fromArray(array $data): self
|
|||
'webp' => 'image/webp',
|
||||
'mp4' => 'video/mp4',
|
||||
'mov' => 'video/quicktime',
|
||||
'pdf' => 'application/pdf',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,14 @@ enum Type: string
|
|||
{
|
||||
case Image = 'image';
|
||||
case Video = 'video';
|
||||
case Document = 'document';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Image => 'Imagem',
|
||||
self::Video => 'Vídeo',
|
||||
self::Document => 'Documento',
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -31,6 +33,11 @@ public function label(): string
|
|||
* server-side transcoding, accepting WebM would just produce
|
||||
* platform-specific publish failures down the line.
|
||||
*
|
||||
* Document accepts PDF only — the swipeable LinkedIn document
|
||||
* (carousel) format. PPTX/DOCX are also valid LinkedIn documents
|
||||
* but are converted server-side by LinkedIn and lose fonts, so we
|
||||
* keep the surface to PDF.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function allowedMimeTypes(): array
|
||||
|
|
@ -38,6 +45,7 @@ public function allowedMimeTypes(): array
|
|||
return match ($this) {
|
||||
self::Image => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
|
||||
self::Video => ['video/mp4', 'video/quicktime'],
|
||||
self::Document => ['application/pdf'],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -52,6 +60,7 @@ public function extensions(): array
|
|||
return match ($this) {
|
||||
self::Image => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
|
||||
self::Video => ['mp4', 'mov'],
|
||||
self::Document => ['pdf'],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -84,4 +93,50 @@ public static function fromMime(string $mime): ?self
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify media by what it *is* — for "is this an image/video/PDF?" checks,
|
||||
* as opposed to fromMime() which is the strict upload allow-list. Any
|
||||
* `image/*`, `video/*`, or `application/pdf` MIME maps to its type; when the
|
||||
* MIME is missing it falls back to the filename extension so already-stored
|
||||
* files still resolve.
|
||||
*/
|
||||
public static function classify(?string $mimeType, ?string $path = null): ?self
|
||||
{
|
||||
if (filled($mimeType)) {
|
||||
return match (true) {
|
||||
str_starts_with($mimeType, 'image/') => self::Image,
|
||||
str_starts_with($mimeType, 'video/') => self::Video,
|
||||
$mimeType === 'application/pdf' => self::Document,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
return self::fromExtension($path ? pathinfo($path, PATHINFO_EXTENSION) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify by filename extension. Broader than extensions() (the upload
|
||||
* allow-list) so already-stored files in legacy formats still resolve.
|
||||
*/
|
||||
public static function fromExtension(?string $extension): ?self
|
||||
{
|
||||
$extension = strtolower((string) $extension);
|
||||
|
||||
return match (true) {
|
||||
in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif'], true) => self::Image,
|
||||
in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v'], true) => self::Video,
|
||||
$extension === 'pdf' => self::Document,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the MIME is an animated GIF — several publishers handle it
|
||||
* specially (skipped from optimization, or posted as video).
|
||||
*/
|
||||
public static function isGif(?string $mimeType): bool
|
||||
{
|
||||
return $mimeType === 'image/gif';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,13 +13,12 @@ enum ContentType: string
|
|||
case InstagramReel = 'instagram_reel';
|
||||
case InstagramStory = 'instagram_story';
|
||||
|
||||
// LinkedIn
|
||||
// LinkedIn — one type per account kind; the publish format (single image,
|
||||
// multi-image, video, or PDF document) is inferred from the attached media.
|
||||
case LinkedInPost = 'linkedin_post';
|
||||
case LinkedInCarousel = 'linkedin_carousel';
|
||||
|
||||
// LinkedIn Page
|
||||
case LinkedInPagePost = 'linkedin_page_post';
|
||||
case LinkedInPageCarousel = 'linkedin_page_carousel';
|
||||
|
||||
// Facebook
|
||||
case FacebookPost = 'facebook_post';
|
||||
|
|
@ -69,7 +68,6 @@ public function label(): string
|
|||
self::InstagramReel => 'Reel',
|
||||
self::InstagramStory => 'Story',
|
||||
self::LinkedInPost, self::LinkedInPagePost => 'Post',
|
||||
self::LinkedInCarousel, self::LinkedInPageCarousel => 'Carousel',
|
||||
self::FacebookPost => 'Post',
|
||||
self::FacebookReel => 'Reel',
|
||||
self::FacebookStory => 'Story',
|
||||
|
|
@ -97,8 +95,8 @@ public function platform(): SocialPlatform
|
|||
{
|
||||
return match ($this) {
|
||||
self::InstagramFeed, self::InstagramReel, self::InstagramStory => SocialPlatform::Instagram,
|
||||
self::LinkedInPost, self::LinkedInCarousel => SocialPlatform::LinkedIn,
|
||||
self::LinkedInPagePost, self::LinkedInPageCarousel => SocialPlatform::LinkedInPage,
|
||||
self::LinkedInPost => SocialPlatform::LinkedIn,
|
||||
self::LinkedInPagePost => SocialPlatform::LinkedInPage,
|
||||
self::FacebookPost, self::FacebookReel, self::FacebookStory => SocialPlatform::Facebook,
|
||||
self::TikTokVideo, self::TikTokPhoto => SocialPlatform::TikTok,
|
||||
self::YouTubeShort => SocialPlatform::YouTube,
|
||||
|
|
@ -164,8 +162,7 @@ public function maxMediaCount(): int
|
|||
return match ($this) {
|
||||
self::InstagramFeed => 10,
|
||||
self::InstagramReel, self::InstagramStory => 1,
|
||||
self::LinkedInPost, self::LinkedInPagePost => 1,
|
||||
self::LinkedInCarousel, self::LinkedInPageCarousel => 20,
|
||||
self::LinkedInPost, self::LinkedInPagePost => 10,
|
||||
self::FacebookPost => 10,
|
||||
self::FacebookReel, self::FacebookStory => 1,
|
||||
self::TikTokVideo => 1,
|
||||
|
|
@ -187,7 +184,6 @@ public function supportsVideo(): bool
|
|||
return match ($this) {
|
||||
self::InstagramFeed, self::InstagramReel, self::InstagramStory => true,
|
||||
self::LinkedInPost, self::LinkedInPagePost => true,
|
||||
self::LinkedInCarousel, self::LinkedInPageCarousel => false,
|
||||
self::FacebookPost, self::FacebookReel, self::FacebookStory => true,
|
||||
self::TikTokVideo => true,
|
||||
self::TikTokPhoto => false,
|
||||
|
|
@ -216,6 +212,19 @@ public function supportsImage(): bool
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this content type can carry a PDF document (the swipeable LinkedIn
|
||||
* document/carousel). LinkedIn infers the document format from a PDF being
|
||||
* attached; the document is always the only attachment (see the media rule).
|
||||
*/
|
||||
public function supportsDocument(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::LinkedInPost, self::LinkedInPagePost => true,
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a single post may carry images and a video together. Most
|
||||
* targets accept only one or the other; this is conservative and lists
|
||||
|
|
@ -226,6 +235,8 @@ public function supportsMixedMedia(): bool
|
|||
{
|
||||
return match ($this) {
|
||||
self::BlueskyPost => false,
|
||||
// LinkedIn publishes images XOR one video XOR one document — never mixed.
|
||||
self::LinkedInPost, self::LinkedInPagePost => false,
|
||||
default => true,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
16
app/Enums/SocialAccount/LinkedInIdentityType.php
Normal file
16
app/Enums/SocialAccount/LinkedInIdentityType.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums\SocialAccount;
|
||||
|
||||
/**
|
||||
* Which LinkedIn identity a member posts as after the unified connect flow:
|
||||
* their personal profile (creates a `linkedin` account) or a company page
|
||||
* they administer (creates a `linkedin-page` account).
|
||||
*/
|
||||
enum LinkedInIdentityType: string
|
||||
{
|
||||
case Person = 'person';
|
||||
case Organization = 'organization';
|
||||
}
|
||||
|
|
@ -94,7 +94,7 @@ public function color(): string
|
|||
public function allowedMediaTypes(): array
|
||||
{
|
||||
return match ($this) {
|
||||
self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video],
|
||||
self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video, MediaType::Document],
|
||||
self::X => [MediaType::Image, MediaType::Video],
|
||||
self::TikTok => [MediaType::Video],
|
||||
self::YouTube => [MediaType::Video],
|
||||
|
|
@ -112,7 +112,7 @@ public function allowedMediaTypes(): array
|
|||
public function maxImages(): int
|
||||
{
|
||||
return match ($this) {
|
||||
self::LinkedIn, self::LinkedInPage => 1,
|
||||
self::LinkedIn, self::LinkedInPage => 10,
|
||||
self::X => 4,
|
||||
self::TikTok => 0,
|
||||
self::YouTube => 0,
|
||||
|
|
@ -287,6 +287,22 @@ public function isEnabled(): bool
|
|||
return config("trypost.platforms.{$this->value}.enabled", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this platform gets its own "Connect" card in the accounts grid.
|
||||
* LinkedIn company pages are reached through the unified LinkedIn connect
|
||||
* flow's identity picker, never a standalone card. The single LinkedIn card
|
||||
* stands for the whole network, so it shows whenever the profile OR the
|
||||
* company-page capability is enabled (self-hosters may run with only one).
|
||||
*/
|
||||
public function isConnectable(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::LinkedInPage => false,
|
||||
self::LinkedIn => self::LinkedIn->isEnabled() || self::LinkedInPage->isEnabled(),
|
||||
default => $this->isEnabled(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -309,14 +325,4 @@ public function publishConfig(): array
|
|||
default => [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all enabled platforms.
|
||||
*
|
||||
* @return array<self>
|
||||
*/
|
||||
public static function enabled(): array
|
||||
{
|
||||
return array_filter(self::cases(), fn (self $platform) => $platform->isEnabled());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -86,12 +86,14 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
|
||||
$accounts = $workspace->socialAccounts()->orderBy('id')->get();
|
||||
|
||||
$platforms = collect(SocialPlatform::enabled())->map(fn (SocialPlatform $platform): array => [
|
||||
'value' => $platform->value,
|
||||
'label' => $platform->label(),
|
||||
'color' => $platform->color(),
|
||||
'network' => $platform->network(),
|
||||
])->values();
|
||||
$platforms = collect(SocialPlatform::cases())
|
||||
->filter(fn (SocialPlatform $platform): bool => $platform->isConnectable())
|
||||
->map(fn (SocialPlatform $platform): array => [
|
||||
'value' => $platform->value,
|
||||
'label' => $platform->label(),
|
||||
'color' => $platform->color(),
|
||||
'network' => $platform->network(),
|
||||
])->values();
|
||||
|
||||
return Inertia::render('onboarding/Connect', [
|
||||
'platforms' => $platforms,
|
||||
|
|
|
|||
|
|
@ -7,28 +7,23 @@
|
|||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Services\Social\BlueskyLexicon;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
|
||||
class BlueskyController extends SocialController
|
||||
{
|
||||
protected SocialPlatform $platform = SocialPlatform::Bluesky;
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): InertiaResponse
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return Inertia::render('accounts/BlueskyConnect', [
|
||||
|
|
@ -36,7 +31,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request): View|RedirectResponse
|
||||
public function store(Request $request): InertiaResponse
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
|
|
@ -47,10 +42,6 @@ public function store(Request $request): View|RedirectResponse
|
|||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
$service = config('trypost.platforms.bluesky.default_service');
|
||||
|
|
@ -74,7 +65,7 @@ public function store(Request $request): View|RedirectResponse
|
|||
$errorMessage = $body['message'];
|
||||
}
|
||||
|
||||
return back()->withErrors(['password' => $errorMessage]);
|
||||
throw ValidationException::withMessages(['password' => $errorMessage]);
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
|
|
@ -113,13 +104,15 @@ public function store(Request $request): View|RedirectResponse
|
|||
);
|
||||
|
||||
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
|
||||
} catch (ValidationException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Bluesky connection error', [
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
|
||||
return back()->withErrors(['password' => 'Error connecting to Bluesky. Please try again.']);
|
||||
throw ValidationException::withMessages(['password' => 'Error connecting to Bluesky. Please try again.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,8 @@
|
|||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class DiscordController extends SocialController
|
||||
|
|
@ -16,22 +15,18 @@ class DiscordController extends SocialController
|
|||
|
||||
protected SocialPlatform $platform = SocialPlatform::Discord;
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return $this->redirectToProvider($request, $this->driver, config('trypost.platforms.discord.scopes'));
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
return $this->handleCallback($request, $this->platform, $this->driver);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@
|
|||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -32,16 +32,12 @@ class FacebookController extends SocialController
|
|||
'read_insights',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
|
|
@ -58,7 +54,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View|RedirectResponse
|
||||
public function callback(Request $request): InertiaResponse|RedirectResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
@ -174,7 +170,7 @@ public function selectPage(Request $request)
|
|||
]);
|
||||
}
|
||||
|
||||
public function select(Request $request): View
|
||||
public function select(Request $request): InertiaResponse
|
||||
{
|
||||
$request->validate([
|
||||
'page_id' => 'required|string',
|
||||
|
|
|
|||
|
|
@ -8,11 +8,10 @@
|
|||
use App\Enums\SocialAccount\Status;
|
||||
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -28,16 +27,12 @@ class InstagramController extends SocialController
|
|||
'instagram_business_manage_insights',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
|
|
@ -53,7 +48,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
return Inertia::location($url);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
|
|||
|
|
@ -13,8 +13,8 @@
|
|||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -34,16 +34,12 @@ class InstagramFacebookController extends SocialController
|
|||
'instagram_manage_insights',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
|
|
@ -61,7 +57,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
return Inertia::location($url);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View|RedirectResponse
|
||||
public function callback(Request $request): InertiaResponse|RedirectResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
@ -150,7 +146,7 @@ public function selectPage(Request $request)
|
|||
]);
|
||||
}
|
||||
|
||||
public function select(Request $request): View
|
||||
public function select(Request $request): InertiaResponse
|
||||
{
|
||||
$request->validate([
|
||||
'page_id' => 'required|string',
|
||||
|
|
@ -193,7 +189,7 @@ public function select(Request $request): View
|
|||
}
|
||||
}
|
||||
|
||||
private function connectInstagramAccount(Workspace $workspace, array $pageData, $existingAccount): View
|
||||
private function connectInstagramAccount(Workspace $workspace, array $pageData, $existingAccount): InertiaResponse
|
||||
{
|
||||
$avatarPath = data_get($pageData, 'ig_picture') ? uploadFromUrl(data_get($pageData, 'ig_picture')) : null;
|
||||
|
||||
|
|
|
|||
|
|
@ -4,41 +4,59 @@
|
|||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Enums\SocialAccount\LinkedInIdentityType;
|
||||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Social\LinkedInTokenSynchronizer;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rules\Enum;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class LinkedInController extends SocialController
|
||||
{
|
||||
protected string $driver = 'linkedin';
|
||||
protected string $driver = 'linkedin-openid';
|
||||
|
||||
protected SocialPlatform $platform = SocialPlatform::LinkedIn;
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
/**
|
||||
* The LinkedIn card stands for both the personal profile and company-page
|
||||
* capabilities, each independently toggleable so self-hosters can run with
|
||||
* just one. The connect flow is available while either is enabled.
|
||||
*/
|
||||
protected function ensurePlatformEnabled(): void
|
||||
{
|
||||
if (! $this->personEnabled() && ! $this->organizationEnabled()) {
|
||||
abort(Response::HTTP_FORBIDDEN, 'This platform is currently unavailable.');
|
||||
}
|
||||
}
|
||||
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return $this->redirectToProvider($request, $this->driver, config('trypost.platforms.linkedin.scopes'));
|
||||
session(['social_connect_workspace' => $workspace->id]);
|
||||
|
||||
return Inertia::location(
|
||||
Socialite::driver($this->driver)
|
||||
->scopes($this->connectScopes())
|
||||
->redirect()
|
||||
->getTargetUrl()
|
||||
);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse|RedirectResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
@ -55,37 +73,24 @@ public function callback(Request $request): View
|
|||
try {
|
||||
$socialUser = Socialite::driver($this->driver)->user();
|
||||
|
||||
// Fetch vanityName from LinkedIn API (not available via OpenID)
|
||||
$username = $this->fetchVanityName($socialUser->token);
|
||||
|
||||
$avatarPath = uploadFromUrl($socialUser->getAvatar());
|
||||
|
||||
$account = $workspace->socialAccounts()->updateOrCreate(
|
||||
[
|
||||
'platform' => $this->platform->value,
|
||||
'platform_user_id' => $socialUser->getId(),
|
||||
],
|
||||
[
|
||||
'username' => $username,
|
||||
'display_name' => $socialUser->getName(),
|
||||
'avatar_url' => $avatarPath,
|
||||
'access_token' => $socialUser->token,
|
||||
session([
|
||||
'linkedin_pending' => [
|
||||
'workspace_id' => $workspace->id,
|
||||
'token' => $socialUser->token,
|
||||
'refresh_token' => $socialUser->refreshToken,
|
||||
'token_expires_at' => $socialUser->expiresIn ? now()->addSeconds($socialUser->expiresIn) : null,
|
||||
// LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here.
|
||||
'scopes' => explode(',', implode(',', $socialUser->approvedScopes)),
|
||||
'status' => Status::Connected,
|
||||
'error_message' => null,
|
||||
'disconnected_at' => null,
|
||||
'expires_in' => $socialUser->expiresIn,
|
||||
'approved_scopes' => $socialUser->approvedScopes ?? [],
|
||||
'person' => [
|
||||
'id' => $socialUser->getId(),
|
||||
'name' => $socialUser->getName(),
|
||||
'avatar' => $socialUser->getAvatar(),
|
||||
'vanity_name' => $this->personEnabled() ? $this->fetchVanityName($socialUser->token) : null,
|
||||
],
|
||||
'organizations' => $this->organizationEnabled() ? $this->fetchOrganizations($socialUser->token) : [],
|
||||
],
|
||||
);
|
||||
]);
|
||||
|
||||
// Sync tokens to LinkedIn Page if it exists
|
||||
app(LinkedInTokenSynchronizer::class)->syncTokens($account);
|
||||
|
||||
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
|
||||
} catch (NetworkAlreadyConnectedException $e) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value);
|
||||
return redirect()->route('app.social.linkedin.select-identity');
|
||||
} catch (\Exception $e) {
|
||||
Log::error('LinkedIn OAuth Error', [
|
||||
'error' => $e->getMessage(),
|
||||
|
|
@ -95,6 +100,209 @@ public function callback(Request $request): View
|
|||
}
|
||||
}
|
||||
|
||||
public function selectIdentity(Request $request): InertiaResponse
|
||||
{
|
||||
$pending = session('linkedin_pending');
|
||||
|
||||
if (! $pending) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
|
||||
}
|
||||
|
||||
$workspace = Workspace::find($pending['workspace_id']);
|
||||
|
||||
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
|
||||
}
|
||||
|
||||
return Inertia::render('accounts/LinkedInSelect', [
|
||||
'person' => $this->personEnabled() ? $pending['person'] : null,
|
||||
'organizations' => $pending['organizations'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function select(Request $request): InertiaResponse
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'type' => ['required', new Enum(LinkedInIdentityType::class)],
|
||||
'organization_id' => 'required_if:type,organization',
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
||||
}
|
||||
|
||||
$validated = $validator->validated();
|
||||
|
||||
$pending = session('linkedin_pending');
|
||||
|
||||
if (! $pending) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
|
||||
}
|
||||
|
||||
$workspace = Workspace::find($pending['workspace_id']);
|
||||
|
||||
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
|
||||
}
|
||||
|
||||
$type = LinkedInIdentityType::from(data_get($validated, 'type'));
|
||||
|
||||
if (($type === LinkedInIdentityType::Organization && ! $this->organizationEnabled())
|
||||
|| ($type === LinkedInIdentityType::Person && ! $this->personEnabled())) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
||||
}
|
||||
|
||||
try {
|
||||
if ($type === LinkedInIdentityType::Organization) {
|
||||
$organization = $this->resolveAdministeredOrganization($pending, data_get($validated, 'organization_id'));
|
||||
|
||||
if (! $organization) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
||||
}
|
||||
|
||||
$this->connectOrganization($workspace, $pending, $organization);
|
||||
} else {
|
||||
$this->connectPerson($workspace, $pending);
|
||||
}
|
||||
|
||||
session()->forget('linkedin_pending');
|
||||
|
||||
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
|
||||
} catch (NetworkAlreadyConnectedException) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('LinkedIn selection error', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's personal LinkedIn profile becomes a `linkedin` account.
|
||||
*/
|
||||
private function connectPerson(Workspace $workspace, array $pending): void
|
||||
{
|
||||
$person = $pending['person'];
|
||||
|
||||
$workspace->socialAccounts()->updateOrCreate(
|
||||
[
|
||||
'platform' => SocialPlatform::LinkedIn->value,
|
||||
'platform_user_id' => data_get($person, 'id'),
|
||||
],
|
||||
[
|
||||
'username' => data_get($person, 'vanity_name'),
|
||||
'display_name' => data_get($person, 'name'),
|
||||
'avatar_url' => uploadFromUrl(data_get($person, 'avatar')),
|
||||
'access_token' => $pending['token'],
|
||||
'refresh_token' => $pending['refresh_token'],
|
||||
'token_expires_at' => $pending['expires_in'] ? now()->addSeconds($pending['expires_in']) : null,
|
||||
'scopes' => $this->normalizeScopes($pending['approved_scopes'] ?? []),
|
||||
'status' => Status::Connected,
|
||||
'error_message' => null,
|
||||
'disconnected_at' => null,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Match the chosen organization id against the admin-verified list captured at
|
||||
* callback, so a tampered POST cannot connect a company the member does not
|
||||
* administer.
|
||||
*
|
||||
* @param array<string, mixed> $pending
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function resolveAdministeredOrganization(array $pending, mixed $organizationId): ?array
|
||||
{
|
||||
return collect(data_get($pending, 'organizations', []))
|
||||
->first(fn ($organization) => (string) data_get($organization, 'id') === (string) $organizationId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A company the user administers becomes a `linkedin-page` account, with the
|
||||
* acting member recorded in meta so the page publisher can post on its behalf.
|
||||
* The organization data comes from the admin-verified session list, never the
|
||||
* request body.
|
||||
*
|
||||
* @param array<string, mixed> $pending
|
||||
* @param array<string, mixed> $organization
|
||||
*/
|
||||
private function connectOrganization(Workspace $workspace, array $pending, array $organization): void
|
||||
{
|
||||
$organizationId = data_get($organization, 'id');
|
||||
|
||||
$workspace->socialAccounts()->updateOrCreate(
|
||||
[
|
||||
'platform' => SocialPlatform::LinkedInPage->value,
|
||||
'platform_user_id' => $organizationId,
|
||||
],
|
||||
[
|
||||
'username' => data_get($organization, 'vanity_name'),
|
||||
'display_name' => data_get($organization, 'name'),
|
||||
'avatar_url' => uploadFromUrl(data_get($organization, 'logo')),
|
||||
'access_token' => $pending['token'],
|
||||
'refresh_token' => $pending['refresh_token'],
|
||||
'token_expires_at' => $pending['expires_in'] ? now()->addSeconds($pending['expires_in']) : null,
|
||||
'scopes' => $this->normalizeScopes($pending['approved_scopes'] ?? []),
|
||||
'status' => Status::Connected,
|
||||
'error_message' => null,
|
||||
'disconnected_at' => null,
|
||||
'meta' => [
|
||||
'organization_id' => $organizationId,
|
||||
'admin_user_id' => data_get($pending, 'person.id'),
|
||||
'admin_name' => data_get($pending, 'person.name'),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Union of the scopes for the enabled capabilities, so one consent screen
|
||||
* grants exactly what the workspace can use — member posting, company-page
|
||||
* administration, or both — and the user picks the identity afterwards.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function connectScopes(): array
|
||||
{
|
||||
$scopes = [];
|
||||
|
||||
if ($this->personEnabled()) {
|
||||
$scopes = array_merge($scopes, config('trypost.platforms.linkedin.scopes'));
|
||||
}
|
||||
|
||||
if ($this->organizationEnabled()) {
|
||||
$scopes = array_merge($scopes, config('trypost.platforms.linkedin-page.scopes'));
|
||||
}
|
||||
|
||||
return array_values(array_unique($scopes));
|
||||
}
|
||||
|
||||
private function personEnabled(): bool
|
||||
{
|
||||
return SocialPlatform::LinkedIn->isEnabled();
|
||||
}
|
||||
|
||||
private function organizationEnabled(): bool
|
||||
{
|
||||
return SocialPlatform::LinkedInPage->isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* LinkedIn returns approved scopes comma-joined, but Socialite splits OAuth
|
||||
* scopes on space — so the whole CSV lands as a single array element. Re-split
|
||||
* on commas to store individual scope tokens.
|
||||
*
|
||||
* @param array<int, string> $approvedScopes
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function normalizeScopes(array $approvedScopes): array
|
||||
{
|
||||
return array_values(array_filter(explode(',', implode(',', $approvedScopes))));
|
||||
}
|
||||
|
||||
private function fetchVanityName(string $accessToken): ?string
|
||||
{
|
||||
try {
|
||||
|
|
@ -115,4 +323,45 @@ private function fetchVanityName(string $accessToken): ?string
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Organizations the authenticated member administers, used to offer company
|
||||
* pages as a posting identity alongside their personal profile.
|
||||
*
|
||||
* @return array<int, array{id: mixed, name: string, vanity_name: ?string, logo: ?string}>
|
||||
*/
|
||||
private function fetchOrganizations(string $accessToken): array
|
||||
{
|
||||
$response = Http::withToken($accessToken)
|
||||
->get(config('trypost.platforms.linkedin.api').'/v2/organizationAcls', [
|
||||
'q' => 'roleAssignee',
|
||||
'role' => 'ADMINISTRATOR',
|
||||
'projection' => '(elements*(organization~(id,localizedName,vanityName,logoV2(original~:playableStreams))))',
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn Organizations fetch error', [
|
||||
'error' => $response->body(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$organizations = [];
|
||||
|
||||
foreach (data_get($response->json(), 'elements', []) as $element) {
|
||||
$org = data_get($element, 'organization~');
|
||||
|
||||
if ($org) {
|
||||
$organizations[] = [
|
||||
'id' => data_get($org, 'id'),
|
||||
'name' => data_get($org, 'localizedName', 'Unknown'),
|
||||
'vanity_name' => data_get($org, 'vanityName'),
|
||||
'logo' => data_get($org, 'logoV2.original~.elements.0.identifiers.0.identifier'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $organizations;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,273 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Social\LinkedInTokenSynchronizer;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
|
||||
|
||||
class LinkedInPageController extends SocialController
|
||||
{
|
||||
protected string $driver = 'linkedin-openid';
|
||||
|
||||
protected SocialPlatform $platform = SocialPlatform::LinkedInPage;
|
||||
|
||||
public function connect(Request $request): SymfonyResponse|RedirectResponse
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
'social_connect_workspace' => $workspace->id,
|
||||
'linkedin_page_reconnect_id' => null,
|
||||
]);
|
||||
|
||||
return Inertia::location(
|
||||
Socialite::driver($this->driver)
|
||||
->scopes(config('trypost.platforms.linkedin-page.scopes'))
|
||||
->with([
|
||||
'redirect_uri' => config('services.linkedin-openid.redirect_page'),
|
||||
])
|
||||
->redirect()
|
||||
->getTargetUrl()
|
||||
);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View|RedirectResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
if (! $workspaceId) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
|
||||
}
|
||||
|
||||
$workspace = Workspace::find($workspaceId);
|
||||
|
||||
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
|
||||
}
|
||||
|
||||
try {
|
||||
$socialUser = Socialite::driver($this->driver)
|
||||
->scopes(config('trypost.platforms.linkedin-page.scopes'))
|
||||
->with([
|
||||
'redirect_uri' => config('services.linkedin-openid.redirect_page'),
|
||||
])
|
||||
->user();
|
||||
|
||||
// Fetch organizations the user is admin of
|
||||
$organizations = $this->fetchOrganizations($socialUser->token);
|
||||
|
||||
if (empty($organizations)) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.not_linkedin_admin'), $this->platform->value);
|
||||
}
|
||||
|
||||
// Store data in session and redirect to selection page
|
||||
session([
|
||||
'linkedin_page_pending' => [
|
||||
'workspace_id' => $workspace->id,
|
||||
'user_id' => $socialUser->getId(),
|
||||
'name' => $socialUser->getName(),
|
||||
'avatar' => $socialUser->getAvatar(),
|
||||
'token' => $socialUser->token,
|
||||
'refresh_token' => $socialUser->refreshToken,
|
||||
'expires_in' => $socialUser->expiresIn,
|
||||
'approved_scopes' => $socialUser->approvedScopes ?? [],
|
||||
'organizations' => $organizations,
|
||||
'reconnect_id' => session('linkedin_page_reconnect_id'),
|
||||
],
|
||||
]);
|
||||
|
||||
return redirect()->route('app.social.linkedin-page.select-page');
|
||||
} catch (\Exception $e) {
|
||||
Log::error('LinkedIn Page OAuth Error', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting'), $this->platform->value);
|
||||
}
|
||||
}
|
||||
|
||||
public function selectPage(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$pendingData = session('linkedin_page_pending');
|
||||
|
||||
if (! $pendingData) {
|
||||
session()->flash('flash.banner', __('accounts.flash.session_expired'));
|
||||
session()->flash('flash.bannerStyle', 'danger');
|
||||
|
||||
return redirect()->route('app.accounts');
|
||||
}
|
||||
|
||||
$workspace = Workspace::find($pendingData['workspace_id']);
|
||||
|
||||
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
||||
session()->flash('flash.banner', __('accounts.flash.workspace_not_found'));
|
||||
session()->flash('flash.bannerStyle', 'danger');
|
||||
|
||||
return redirect()->route('app.accounts');
|
||||
}
|
||||
|
||||
return Inertia::render('accounts/LinkedInPageSelect', [
|
||||
'workspace' => $workspace,
|
||||
'organizations' => $pendingData['organizations'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function select(Request $request): View
|
||||
{
|
||||
$request->validate([
|
||||
'organization_id' => 'required',
|
||||
'organization_name' => 'required|string',
|
||||
'organization_vanity_name' => 'nullable|string',
|
||||
'organization_logo' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$pendingData = session('linkedin_page_pending');
|
||||
|
||||
if (! $pendingData) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.session_expired'), $this->platform->value);
|
||||
}
|
||||
|
||||
$workspace = Workspace::find($pendingData['workspace_id']);
|
||||
|
||||
if (! $workspace || ! $request->user()->can('manageAccounts', $workspace)) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.workspace_not_found'), $this->platform->value);
|
||||
}
|
||||
|
||||
try {
|
||||
$avatarPath = uploadFromUrl($request->organization_logo);
|
||||
$reconnectId = $pendingData['reconnect_id'] ?? null;
|
||||
|
||||
if ($reconnectId) {
|
||||
// Reconnect existing account
|
||||
$existingAccount = $workspace->socialAccounts()->find($reconnectId);
|
||||
|
||||
if ($existingAccount) {
|
||||
$existingAccount->update([
|
||||
'platform_user_id' => $request->organization_id,
|
||||
'username' => $request->organization_vanity_name,
|
||||
'display_name' => $request->organization_name,
|
||||
'avatar_url' => $avatarPath,
|
||||
'access_token' => $pendingData['token'],
|
||||
'refresh_token' => $pendingData['refresh_token'],
|
||||
'token_expires_at' => $pendingData['expires_in'] ? now()->addSeconds($pendingData['expires_in']) : null,
|
||||
// LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here.
|
||||
'scopes' => explode(',', implode(',', $pendingData['approved_scopes'] ?? [])),
|
||||
'meta' => [
|
||||
'organization_id' => $request->organization_id,
|
||||
'admin_user_id' => $pendingData['user_id'],
|
||||
'admin_name' => $pendingData['name'],
|
||||
],
|
||||
]);
|
||||
$existingAccount->markAsConnected();
|
||||
|
||||
// Sync tokens to LinkedIn personal if it exists
|
||||
app(LinkedInTokenSynchronizer::class)->syncTokens($existingAccount);
|
||||
|
||||
session()->forget(['linkedin_page_pending', 'linkedin_page_reconnect_id']);
|
||||
|
||||
return $this->popupCallback(true, __('accounts.popup_callback.reconnected'), $this->platform->value);
|
||||
}
|
||||
}
|
||||
|
||||
$account = $workspace->socialAccounts()->updateOrCreate(
|
||||
[
|
||||
'platform' => $this->platform->value,
|
||||
'platform_user_id' => $request->organization_id,
|
||||
],
|
||||
[
|
||||
'username' => $request->organization_vanity_name,
|
||||
'display_name' => $request->organization_name,
|
||||
'avatar_url' => $avatarPath,
|
||||
'access_token' => $pendingData['token'],
|
||||
'refresh_token' => $pendingData['refresh_token'],
|
||||
'token_expires_at' => $pendingData['expires_in'] ? now()->addSeconds($pendingData['expires_in']) : null,
|
||||
// LinkedIn returns scope CSV-joined but Socialite splits on space, so re-split here.
|
||||
'scopes' => explode(',', implode(',', $pendingData['approved_scopes'] ?? [])),
|
||||
'status' => Status::Connected,
|
||||
'error_message' => null,
|
||||
'disconnected_at' => null,
|
||||
'meta' => [
|
||||
'organization_id' => $request->organization_id,
|
||||
'admin_user_id' => $pendingData['user_id'],
|
||||
'admin_name' => $pendingData['name'],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
// Sync tokens to LinkedIn personal if it exists
|
||||
app(LinkedInTokenSynchronizer::class)->syncTokens($account);
|
||||
|
||||
session()->forget(['linkedin_page_pending', 'linkedin_page_reconnect_id']);
|
||||
|
||||
return $this->popupCallback(true, __('accounts.popup_callback.connected'), $this->platform->value);
|
||||
} catch (NetworkAlreadyConnectedException) {
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.network_taken'), $this->platform->value);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('LinkedIn Page selection error', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->popupCallback(false, __('accounts.popup_callback.error_connecting_page'), $this->platform->value);
|
||||
}
|
||||
}
|
||||
|
||||
private function fetchOrganizations(string $accessToken): array
|
||||
{
|
||||
$response = Http::withToken($accessToken)
|
||||
->get(config('trypost.platforms.linkedin-page.api').'/v2/organizationAcls', [
|
||||
'q' => 'roleAssignee',
|
||||
'role' => 'ADMINISTRATOR',
|
||||
'projection' => '(elements*(organization~(id,localizedName,vanityName,logoV2(original~:playableStreams))))',
|
||||
]);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn Organizations fetch error', [
|
||||
'error' => $response->body(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
$organizations = [];
|
||||
|
||||
foreach (data_get($data, 'elements', []) as $element) {
|
||||
$org = data_get($element, 'organization~', null);
|
||||
if ($org) {
|
||||
$logoUrl = null;
|
||||
$logoUrl = data_get($org, 'logoV2.original~.elements.0.identifiers.0.identifier');
|
||||
|
||||
$organizations[] = [
|
||||
'id' => data_get($org, 'id'),
|
||||
'name' => data_get($org, 'localizedName', 'Unknown'),
|
||||
'vanity_name' => data_get($org, 'vanityName', null),
|
||||
'logo' => $logoUrl,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $organizations;
|
||||
}
|
||||
}
|
||||
|
|
@ -7,14 +7,12 @@
|
|||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class MastodonController extends SocialController
|
||||
{
|
||||
|
|
@ -25,16 +23,12 @@ class MastodonController extends SocialController
|
|||
/**
|
||||
* Show form to enter Mastodon instance URL
|
||||
*/
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): InertiaResponse
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return Inertia::render('accounts/MastodonConnect', [
|
||||
|
|
@ -45,7 +39,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
/**
|
||||
* Register app on instance and redirect to OAuth
|
||||
*/
|
||||
public function authorizeInstance(Request $request): SymfonyResponse|RedirectResponse
|
||||
public function authorizeInstance(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
|
|
@ -55,10 +49,6 @@ public function authorizeInstance(Request $request): SymfonyResponse|RedirectRes
|
|||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
$instance = rtrim($request->instance, '/');
|
||||
|
|
@ -117,7 +107,7 @@ public function authorizeInstance(Request $request): SymfonyResponse|RedirectRes
|
|||
/**
|
||||
* Handle OAuth callback
|
||||
*/
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
$savedState = session('mastodon_oauth_state');
|
||||
|
|
|
|||
|
|
@ -7,10 +7,9 @@
|
|||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -28,22 +27,18 @@ class PinterestController extends SocialController
|
|||
'user_accounts:read',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return $this->redirectToProvider($request, $this->driver, $this->scopes);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,6 @@
|
|||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
|
|
@ -33,22 +32,20 @@ protected function ensurePlatformEnabled(): void
|
|||
}
|
||||
}
|
||||
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
$platforms = collect(SocialPlatform::enabled())->map(fn ($platform) => [
|
||||
'value' => $platform->value,
|
||||
'label' => $platform->label(),
|
||||
'color' => $platform->color(),
|
||||
'network' => $platform->network(),
|
||||
])->values();
|
||||
$platforms = collect(SocialPlatform::cases())
|
||||
->filter(fn ($platform) => $platform->isConnectable())
|
||||
->map(fn ($platform) => [
|
||||
'value' => $platform->value,
|
||||
'label' => $platform->label(),
|
||||
'color' => $platform->color(),
|
||||
'network' => $platform->network(),
|
||||
])->values();
|
||||
|
||||
return Inertia::render('accounts/Index', [
|
||||
'workspace' => $workspace,
|
||||
|
|
@ -63,10 +60,6 @@ public function disconnect(Request $request, SocialAccount $account): RedirectRe
|
|||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
if ($account->workspace_id !== $workspace->id) {
|
||||
|
|
@ -92,10 +85,6 @@ public function toggleActive(Request $request, SocialAccount $account): Redirect
|
|||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
if ($account->workspace_id !== $workspace->id) {
|
||||
|
|
@ -115,10 +104,6 @@ protected function redirectToProvider(Request $request, string $driver, array $s
|
|||
{
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
session(['social_connect_workspace' => $workspace->id]);
|
||||
|
||||
return Inertia::location(
|
||||
|
|
@ -133,7 +118,7 @@ protected function handleCallback(
|
|||
Request $request,
|
||||
SocialPlatform $platform,
|
||||
string $driver
|
||||
): View {
|
||||
): Response {
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
if (! $workspaceId) {
|
||||
|
|
@ -189,13 +174,15 @@ protected function forgetSocialConnectSession(): void
|
|||
}
|
||||
|
||||
/**
|
||||
* Return a view that closes the popup and notifies the parent window.
|
||||
* Render the Inertia page that notifies the opener and closes the connect
|
||||
* popup. Used by both the GET OAuth callbacks (a fresh popup page load) and
|
||||
* the XHR selection submits (an Inertia visit that swaps to this page).
|
||||
*/
|
||||
protected function popupCallback(bool $success, string $message, ?string $platform = null): View
|
||||
protected function popupCallback(bool $success, string $message, ?string $platform = null): Response
|
||||
{
|
||||
$this->forgetSocialConnectSession();
|
||||
|
||||
return view('auth.social-callback', [
|
||||
return Inertia::render('accounts/PopupCallback', [
|
||||
'success' => $success,
|
||||
'message' => $message,
|
||||
'platform' => $platform,
|
||||
|
|
|
|||
|
|
@ -8,12 +8,11 @@
|
|||
use App\Enums\SocialAccount\Status;
|
||||
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ThreadsController extends SocialController
|
||||
|
|
@ -26,16 +25,12 @@ class ThreadsController extends SocialController
|
|||
'threads_manage_insights',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
|
|
@ -57,7 +52,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
return Inertia::location("https://threads.net/oauth/authorize?{$params}");
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
$savedState = session('threads_oauth_state');
|
||||
|
|
|
|||
|
|
@ -7,10 +7,9 @@
|
|||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use App\Enums\SocialAccount\Status;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -29,16 +28,12 @@ class TikTokController extends SocialController
|
|||
'video.list',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session(['social_reconnect_id' => null]);
|
||||
|
|
@ -46,7 +41,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
return $this->redirectToProvider($request, $this->driver, $this->scopes);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
|
|||
|
|
@ -5,9 +5,8 @@
|
|||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class XController extends SocialController
|
||||
|
|
@ -24,22 +23,18 @@ class XController extends SocialController
|
|||
'offline.access',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
return $this->redirectToProvider($request, $this->driver, $this->scopes);
|
||||
}
|
||||
|
||||
public function callback(Request $request): View
|
||||
public function callback(Request $request): InertiaResponse
|
||||
{
|
||||
return $this->handleCallback($request, $this->platform, $this->driver);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@
|
|||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\View\View;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response as InertiaResponse;
|
||||
use Laravel\Socialite\Facades\Socialite;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
|
|
@ -30,16 +30,12 @@ class YouTubeController extends SocialController
|
|||
'https://www.googleapis.com/auth/yt-analytics.readonly',
|
||||
];
|
||||
|
||||
public function connect(Request $request): Response|RedirectResponse
|
||||
public function connect(Request $request): Response
|
||||
{
|
||||
$this->ensurePlatformEnabled();
|
||||
|
||||
$workspace = $request->user()->currentWorkspace;
|
||||
|
||||
if (! $workspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
$this->authorize('manageAccounts', $workspace);
|
||||
|
||||
session([
|
||||
|
|
@ -50,7 +46,7 @@ public function connect(Request $request): Response|RedirectResponse
|
|||
return $this->redirectToGoogle();
|
||||
}
|
||||
|
||||
public function callback(Request $request): View|RedirectResponse
|
||||
public function callback(Request $request): InertiaResponse|RedirectResponse
|
||||
{
|
||||
$workspaceId = session('social_connect_workspace');
|
||||
|
||||
|
|
@ -168,7 +164,7 @@ public function selectChannel(Request $request)
|
|||
]);
|
||||
}
|
||||
|
||||
public function select(Request $request): View
|
||||
public function select(Request $request): InertiaResponse
|
||||
{
|
||||
$request->validate([
|
||||
'channel_id' => 'required|string',
|
||||
|
|
|
|||
|
|
@ -22,9 +22,8 @@ public function handle(Request $request, Closure $next): Response
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
$account = $user->account;
|
||||
|
||||
if (! config('trypost.self_hosted')) {
|
||||
$account = $user->account;
|
||||
$requiresCardForTrial = (bool) config('trypost.billing.require_card_for_trial', true);
|
||||
$hasAccess = $account && (
|
||||
$account->subscribed(Account::SUBSCRIPTION_NAME)
|
||||
|
|
@ -36,10 +35,6 @@ public function handle(Request $request, Closure $next): Response
|
|||
}
|
||||
}
|
||||
|
||||
if (! $user->workspaces()->exists()) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
30
app/Http/Middleware/App/EnsureHasWorkspace.php
Normal file
30
app/Http/Middleware/App/EnsureHasWorkspace.php
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Middleware\App;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class EnsureHasWorkspace
|
||||
{
|
||||
/**
|
||||
* Ensure the user has a current workspace, redirecting to workspace
|
||||
* creation otherwise. Required in both SaaS and self-hosted modes — every
|
||||
* authenticated app action operates on the current workspace.
|
||||
*
|
||||
* @param Closure(Request): (Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user && ! $user->currentWorkspace) {
|
||||
return redirect()->route('app.workspaces.create');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -22,6 +22,7 @@ public function rules(): array
|
|||
$allowedMimes = [
|
||||
...MediaType::Image->allowedMimeTypes(),
|
||||
...MediaType::Video->allowedMimeTypes(),
|
||||
...MediaType::Document->allowedMimeTypes(),
|
||||
];
|
||||
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
use App\Models\Post;
|
||||
use App\Models\PostPlatform;
|
||||
use App\Rules\ContentFitsPlatformLimits;
|
||||
use App\Rules\ContentTypeCompatibleWithMedia;
|
||||
use App\Rules\ContentTypeMatchesPostPlatform;
|
||||
use App\Support\PostPlatformMetaRules;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
|
@ -73,6 +74,8 @@ public function withValidator(Validator $validator): void
|
|||
return;
|
||||
}
|
||||
|
||||
$this->addMediaCompatibilityErrors($validator);
|
||||
|
||||
$platformsById = $this->resolveSelectedPlatforms();
|
||||
|
||||
PostPlatformMetaRules::addRequiredOnPublishErrors(
|
||||
|
|
@ -83,6 +86,35 @@ public function withValidator(Validator $validator): void
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* On publish/schedule, validate every platform's *effective* content_type
|
||||
* (resubmitted in this request, or its stored value) against the *effective*
|
||||
* media (the request's media when sent, otherwise the post's stored media).
|
||||
* This closes the gap where a client publishes a misconfigured post — e.g. a
|
||||
* PDF on a regular LinkedIn post — without resubmitting content_type, which a
|
||||
* field-level rule on `platforms.*.content_type` would skip.
|
||||
*/
|
||||
private function addMediaCompatibilityErrors(Validator $validator): void
|
||||
{
|
||||
$routePost = $this->route('post');
|
||||
$post = $routePost instanceof Post ? $routePost : Post::find($routePost);
|
||||
|
||||
if (! $post) {
|
||||
return;
|
||||
}
|
||||
|
||||
$media = $this->has('media') ? (array) $this->input('media', []) : (array) ($post->media ?? []);
|
||||
|
||||
$entries = ContentTypeCompatibleWithMedia::entriesForUpdate(
|
||||
$post,
|
||||
$this->has('platforms') ? (array) $this->input('platforms', []) : null,
|
||||
);
|
||||
|
||||
foreach (ContentTypeCompatibleWithMedia::errorsFor($entries, $media) as $key => $message) {
|
||||
$validator->errors()->add($key, $message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int|string, Platform>
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ public function rules(): array
|
|||
$allowed = implode(',', array_merge(
|
||||
MediaType::Image->allowedMimeTypes(),
|
||||
MediaType::Video->allowedMimeTypes(),
|
||||
MediaType::Document->allowedMimeTypes(),
|
||||
));
|
||||
|
||||
$maxKb = (int) config('ai.mcp.upload.max_size_mb') * 1024;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ public function authorize(): bool
|
|||
|
||||
public function rules(): array
|
||||
{
|
||||
$allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes()];
|
||||
$allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes(), ...MediaType::Document->allowedMimeTypes()];
|
||||
|
||||
return [
|
||||
// Use the largest per-type cap as the upper bound; per-type
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ protected function prepareForValidation(): void
|
|||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$allowedSuffixes = collect([MediaType::Image, MediaType::Video])
|
||||
$allowedSuffixes = collect([MediaType::Image, MediaType::Video, MediaType::Document])
|
||||
->flatMap(fn (MediaType $type) => $type->extensions())
|
||||
->map(fn (string $ext) => '.'.$ext)
|
||||
->all();
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ public function toArray(Request $request): array
|
|||
return [
|
||||
'id' => $this->id,
|
||||
'platform' => $this->platform,
|
||||
'network' => $this->platform->network(),
|
||||
'platform_user_id' => $this->platform_user_id,
|
||||
'username' => $this->username,
|
||||
'display_name' => $this->display_name,
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
use Laravel\Mcp\Server\Attributes\Description;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
|
||||
#[Description('Download images or videos from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')]
|
||||
#[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. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')]
|
||||
class AttachMediaFromUrlTool extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response|ResponseFactory
|
||||
|
|
@ -53,7 +53,7 @@ public function schema(JsonSchema $schema): array
|
|||
'urls' => $schema->array()
|
||||
->items($schema->string())
|
||||
->required()
|
||||
->description('Public HTTP/HTTPS URLs of images or videos. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, video/webm.'),
|
||||
->description('Public HTTP/HTTPS URLs of images, videos, or PDFs. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, application/pdf.'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
use App\Enums\Post\Status;
|
||||
use App\Http\Resources\Api\PostResource;
|
||||
use App\Models\Post;
|
||||
use App\Rules\ContentTypeCompatibleWithMedia;
|
||||
use App\Support\PostPlatformMetaRules;
|
||||
use App\Support\PostStatusRules;
|
||||
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||
|
|
@ -43,6 +44,7 @@ public function handle(Request $request): Response|ResponseFactory
|
|||
}
|
||||
|
||||
PostPlatformMetaRules::assertStoredPostPublishable($post);
|
||||
ContentTypeCompatibleWithMedia::assertStoredPostCompatible($post);
|
||||
|
||||
$scheduledAt = data_get($validated, 'scheduled_at');
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
use Laravel\Mcp\Server\Attributes\Description;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
|
||||
#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image or video, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')]
|
||||
#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document, up to the workspace upload cap — 50 MB by default) directly to this workspace. Returns an upload_token and upload_url. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')]
|
||||
class RequestMediaUploadTool extends Tool
|
||||
{
|
||||
public function handle(Request $request): Response|ResponseFactory
|
||||
|
|
|
|||
|
|
@ -10,11 +10,13 @@
|
|||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Http\Resources\Api\PostResource;
|
||||
use App\Models\Post;
|
||||
use App\Rules\ContentTypeCompatibleWithMedia;
|
||||
use App\Rules\ContentTypeMatchesPostPlatform;
|
||||
use App\Support\PostPlatformMetaRules;
|
||||
use App\Support\PostStatusRules;
|
||||
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Laravel\Mcp\Request;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\ResponseFactory;
|
||||
|
|
@ -48,10 +50,30 @@ public function handle(Request $request): Response|ResponseFactory
|
|||
'uuid',
|
||||
Rule::exists('post_platforms', 'id')->where('post_id', $post->id),
|
||||
],
|
||||
'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPostPlatform],
|
||||
'platforms.*.content_type' => [
|
||||
'sometimes',
|
||||
'string',
|
||||
Rule::in(array_column(ContentType::cases(), 'value')),
|
||||
new ContentTypeMatchesPostPlatform,
|
||||
],
|
||||
...PostPlatformMetaRules::rules(),
|
||||
]);
|
||||
|
||||
// On schedule, validate each platform's effective content_type (resubmitted
|
||||
// here, or stored) against the post's stored media — the tool can't change
|
||||
// media, so a misconfigured post can't be scheduled even without resubmitting
|
||||
// content_type. Mirrors the public API's withValidator check.
|
||||
if (data_get($validated, 'status') === Status::Scheduled->value) {
|
||||
$errors = ContentTypeCompatibleWithMedia::errorsFor(
|
||||
ContentTypeCompatibleWithMedia::entriesForUpdate($post, data_get($validated, 'platforms')),
|
||||
(array) ($post->media ?? []),
|
||||
);
|
||||
|
||||
if ($errors !== []) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
$payload = collect($validated)->except('post_id')->all();
|
||||
|
||||
$result = UpdatePost::execute($workspace, $post, $payload);
|
||||
|
|
|
|||
|
|
@ -61,24 +61,17 @@ protected function url(): Attribute
|
|||
|
||||
public function isVideo(): bool
|
||||
{
|
||||
if ($this->mime_type) {
|
||||
return str_starts_with($this->mime_type, 'video/');
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
|
||||
|
||||
return in_array($extension, ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v']);
|
||||
return MediaType::classify($this->mime_type, $this->path) === MediaType::Video;
|
||||
}
|
||||
|
||||
public function isImage(): bool
|
||||
{
|
||||
if ($this->mime_type) {
|
||||
return str_starts_with($this->mime_type, 'image/');
|
||||
}
|
||||
return MediaType::classify($this->mime_type, $this->path) === MediaType::Image;
|
||||
}
|
||||
|
||||
$extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
|
||||
|
||||
return in_array($extension, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif']);
|
||||
public function isDocument(): bool
|
||||
{
|
||||
return MediaType::classify($this->mime_type, $this->path) === MediaType::Document;
|
||||
}
|
||||
|
||||
public function getTemporaryUrl(int $expirationMinutes = 60): string
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
namespace App\Models\Traits;
|
||||
|
||||
use App\Enums\Media\Type;
|
||||
use App\Models\Media;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
|
|
@ -156,15 +157,8 @@ public function isSingleMediaCollection(string $collection): bool
|
|||
|
||||
private function getMediaType(string $mimeType): string
|
||||
{
|
||||
if (str_starts_with($mimeType, 'image/')) {
|
||||
return 'image';
|
||||
}
|
||||
|
||||
if (str_starts_with($mimeType, 'video/')) {
|
||||
return 'video';
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}");
|
||||
return (Type::classify($mimeType)
|
||||
?? throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}"))->value;
|
||||
}
|
||||
|
||||
private function getMediaMeta(UploadedFile $file, string $type): array
|
||||
|
|
|
|||
|
|
@ -6,10 +6,12 @@
|
|||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Models\Post;
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\DataAwareRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Translation\PotentiallyTranslatedString;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule
|
||||
{
|
||||
|
|
@ -18,6 +20,14 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule
|
|||
*/
|
||||
private array $data = [];
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>>|null $fallbackMedia Stored media used
|
||||
* when the request omits the `media` key entirely — lets API/MCP partial
|
||||
* updates (which don't resubmit media) validate a content_type against the
|
||||
* post's already-stored media.
|
||||
*/
|
||||
public function __construct(private ?array $fallbackMedia = null) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
|
|
@ -28,6 +38,83 @@ public function setData(array $data): static
|
|||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate every enabled platform's stored content_type against the post's
|
||||
* stored media. Used by publish flows that don't resubmit media (e.g. the
|
||||
* MCP publish tool) — the media-side mirror of
|
||||
* PostPlatformMetaRules::assertStoredPostPublishable().
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function assertStoredPostCompatible(Post $post): void
|
||||
{
|
||||
$errors = self::errorsFor(
|
||||
self::entriesForUpdate($post, null),
|
||||
(array) ($post->media ?? []),
|
||||
);
|
||||
|
||||
if ($errors !== []) {
|
||||
throw ValidationException::withMessages($errors);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The per-platform entries to validate for a post update: each platform's
|
||||
* effective content_type (resubmitted in this request, else its stored
|
||||
* value), keyed by the error path the caller surfaces. When $requestPlatforms
|
||||
* is null, the post's currently-enabled platforms are used.
|
||||
*
|
||||
* @param array<int, mixed>|null $requestPlatforms
|
||||
* @return array<int, array{key: string, content_type: string|null}>
|
||||
*/
|
||||
public static function entriesForUpdate(Post $post, ?array $requestPlatforms): array
|
||||
{
|
||||
if (is_array($requestPlatforms)) {
|
||||
return collect($requestPlatforms)->map(fn ($platform, $index): array => [
|
||||
'key' => "platforms.{$index}.content_type",
|
||||
'content_type' => data_get($platform, 'content_type')
|
||||
?? $post->postPlatforms()->where('id', data_get($platform, 'id'))->first()?->content_type?->value,
|
||||
])->all();
|
||||
}
|
||||
|
||||
return $post->postPlatforms()->where('enabled', true)->get()->values()
|
||||
->map(fn ($postPlatform, $index): array => [
|
||||
'key' => "platforms.{$index}.content_type",
|
||||
'content_type' => $postPlatform->content_type?->value,
|
||||
])->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a set of platform entries against the given media, returning
|
||||
* `[errorKey => message]` for each incompatible content_type.
|
||||
*
|
||||
* @param array<int, array{key: string, content_type: string|null}> $entries
|
||||
* @param array<int, mixed> $media
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function errorsFor(array $entries, array $media): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$contentType = data_get($entry, 'content_type');
|
||||
|
||||
if ($contentType === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
(new self($media))->validate(
|
||||
$entry['key'],
|
||||
(string) $contentType,
|
||||
function (string $message) use (&$errors, $entry): void {
|
||||
$errors[$entry['key']] = $message;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure(string, ?string=): PotentiallyTranslatedString $fail
|
||||
*/
|
||||
|
|
@ -38,7 +125,11 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
|
|||
return;
|
||||
}
|
||||
|
||||
$media = (array) data_get($this->data, 'media', []);
|
||||
// Use the request's media when present; otherwise fall back to the
|
||||
// post's stored media so partial publish/schedule updates still validate.
|
||||
$media = array_key_exists('media', $this->data)
|
||||
? (array) data_get($this->data, 'media', [])
|
||||
: (array) ($this->fallbackMedia ?? []);
|
||||
$count = count($media);
|
||||
|
||||
if ($contentType->requiresMedia() && $count === 0) {
|
||||
|
|
@ -53,6 +144,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
|
|||
|
||||
$hasImage = collect($media)->contains(fn ($item) => $this->isImage((array) $item));
|
||||
$hasVideo = collect($media)->contains(fn ($item) => $this->isVideo((array) $item));
|
||||
$hasDocument = collect($media)->contains(fn ($item) => $this->isDocument((array) $item));
|
||||
|
||||
if ($hasImage && ! $contentType->supportsImage()) {
|
||||
$fail("{$contentType->label()} does not support images.");
|
||||
|
|
@ -62,6 +154,15 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
|
|||
$fail("{$contentType->label()} does not support videos.");
|
||||
}
|
||||
|
||||
if ($hasDocument && ! $contentType->supportsDocument()) {
|
||||
$fail("{$contentType->label()} does not support PDF documents.");
|
||||
}
|
||||
|
||||
// A PDF document is always published on its own (LinkedIn document post).
|
||||
if ($hasDocument && $count > 1) {
|
||||
$fail('A PDF document must be the only attachment.');
|
||||
}
|
||||
|
||||
if ($hasImage && $hasVideo && ! $contentType->supportsMixedMedia()) {
|
||||
$fail("{$contentType->label()} can't combine an image and a video in the same post.");
|
||||
}
|
||||
|
|
@ -72,11 +173,7 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
|
|||
*/
|
||||
private function isImage(array $item): bool
|
||||
{
|
||||
if (data_get($item, 'type') === MediaType::Image->value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return str_starts_with((string) data_get($item, 'mime_type', ''), 'image/');
|
||||
return $this->isType($item, MediaType::Image);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -84,10 +181,26 @@ private function isImage(array $item): bool
|
|||
*/
|
||||
private function isVideo(array $item): bool
|
||||
{
|
||||
if (data_get($item, 'type') === MediaType::Video->value) {
|
||||
return true;
|
||||
}
|
||||
return $this->isType($item, MediaType::Video);
|
||||
}
|
||||
|
||||
return str_starts_with((string) data_get($item, 'mime_type', ''), 'video/');
|
||||
/**
|
||||
* @param array<string, mixed> $item
|
||||
*/
|
||||
private function isDocument(array $item): bool
|
||||
{
|
||||
return $this->isType($item, MediaType::Document);
|
||||
}
|
||||
|
||||
/**
|
||||
* A media item matches a type when it carries that explicit `type`, or when
|
||||
* its MIME classifies as that type.
|
||||
*
|
||||
* @param array<string, mixed> $item
|
||||
*/
|
||||
private function isType(array $item, MediaType $type): bool
|
||||
{
|
||||
return data_get($item, 'type') === $type->value
|
||||
|| MediaType::classify(data_get($item, 'mime_type')) === $type;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
533
app/Services/Social/AbstractLinkedInPublisher.php
Normal file
533
app/Services/Social/AbstractLinkedInPublisher.php
Normal file
|
|
@ -0,0 +1,533 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\LinkedInPublishException;
|
||||
use App\Exceptions\TokenExpiredException;
|
||||
use App\Models\PostPlatform;
|
||||
use App\Models\SocialAccount;
|
||||
use App\Services\Media\MediaOptimizer;
|
||||
use App\Services\Social\Concerns\HasSocialHttpClient;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Shared LinkedIn publishing pipeline. The publish format follows the attached
|
||||
* media — a PDF becomes a document post, 2+ images a multi-image post, and
|
||||
* anything else (a single image/video or text only) a regular post. Subclasses
|
||||
* provide the author identity (member vs. company page) and its public URL.
|
||||
*/
|
||||
abstract class AbstractLinkedInPublisher
|
||||
{
|
||||
use HasSocialHttpClient;
|
||||
|
||||
private string $apiVersion = '202601';
|
||||
|
||||
private string $accessToken;
|
||||
|
||||
protected SocialAccount $account;
|
||||
|
||||
private bool $hasRetried = false;
|
||||
|
||||
/**
|
||||
* The LinkedIn account kind this publisher targets (member or company page).
|
||||
*/
|
||||
abstract protected function platform(): Platform;
|
||||
|
||||
/**
|
||||
* The URN that authors the post and owns its uploaded media.
|
||||
*/
|
||||
abstract protected function authorUrn(): string;
|
||||
|
||||
/**
|
||||
* Public URL of the created post. Defaults to the member feed update;
|
||||
* company pages override it.
|
||||
*/
|
||||
protected function postUrl(?string $postId): ?string
|
||||
{
|
||||
return $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null;
|
||||
}
|
||||
|
||||
public function publish(PostPlatform $postPlatform): array
|
||||
{
|
||||
$this->validateContentLength($postPlatform);
|
||||
|
||||
$content = $postPlatform->post->content
|
||||
? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
|
||||
: null;
|
||||
|
||||
$this->account = $postPlatform->socialAccount;
|
||||
$this->hasRetried = false;
|
||||
|
||||
if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
}
|
||||
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
try {
|
||||
return $this->dispatchByMedia($content, $postPlatform);
|
||||
} catch (TokenExpiredException $e) {
|
||||
return $this->retryWithRefresh($postPlatform, $content, $e);
|
||||
}
|
||||
}
|
||||
|
||||
private function dispatchByMedia(?string $content, PostPlatform $postPlatform): array
|
||||
{
|
||||
$media = $postPlatform->post->mediaItems;
|
||||
|
||||
if ($media->contains(fn ($item) => $item->isDocument())) {
|
||||
return $this->publishDocument($content, $media, $this->resolveDocumentTitle($postPlatform));
|
||||
}
|
||||
|
||||
if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) {
|
||||
return $this->publishCarousel($content, $media);
|
||||
}
|
||||
|
||||
return $this->publishPost($content, $media);
|
||||
}
|
||||
|
||||
private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array
|
||||
{
|
||||
if ($this->hasRetried) {
|
||||
throw $originalException;
|
||||
}
|
||||
|
||||
$this->hasRetried = true;
|
||||
|
||||
try {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
return $this->dispatchByMedia($content, $postPlatform);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error("{$this->label()} refresh failed during retry", [
|
||||
'account_id' => $this->account->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $originalException;
|
||||
}
|
||||
}
|
||||
|
||||
private function publishPost(?string $content, $media): array
|
||||
{
|
||||
$payload = $this->basePayload($content);
|
||||
|
||||
if ($media->isNotEmpty()) {
|
||||
$mediaUrn = $this->uploadMedia($media->first());
|
||||
|
||||
if ($mediaUrn) {
|
||||
$payload['content'] = ['media' => ['id' => $mediaUrn]];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->createPost($payload, 'post creation');
|
||||
}
|
||||
|
||||
private function publishCarousel(?string $content, $media): array
|
||||
{
|
||||
$images = [];
|
||||
|
||||
$imageItems = collect($media)
|
||||
->filter(fn ($item) => $item->isImage())
|
||||
->take($this->platform()->maxImages());
|
||||
|
||||
foreach ($imageItems as $item) {
|
||||
$imageUrn = $this->uploadImage($item);
|
||||
|
||||
if ($imageUrn) {
|
||||
$images[] = [
|
||||
'id' => $imageUrn,
|
||||
'altText' => $item->original_filename ?? 'Carousel image',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$payload = $this->basePayload($content);
|
||||
$payload['content'] = ['multiImage' => ['images' => $images]];
|
||||
|
||||
return $this->createPost($payload, 'carousel post creation');
|
||||
}
|
||||
|
||||
private function publishDocument(?string $content, $media, string $title): array
|
||||
{
|
||||
$document = $media->first(fn ($item) => $item->isDocument());
|
||||
|
||||
if (! $document) {
|
||||
throw new \Exception("No PDF document for {$this->label()} document post");
|
||||
}
|
||||
|
||||
$documentUrn = $this->uploadDocument($document);
|
||||
|
||||
if (! $documentUrn) {
|
||||
throw new \Exception("{$this->label()} document upload failed");
|
||||
}
|
||||
|
||||
$payload = $this->basePayload($content);
|
||||
$payload['content'] = ['media' => ['id' => $documentUrn, 'title' => $title]];
|
||||
|
||||
return $this->createPost($payload, 'document post creation');
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared post envelope shared by every content shape.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function basePayload(?string $content): array
|
||||
{
|
||||
return [
|
||||
'author' => $this->authorUrn(),
|
||||
'commentary' => $content ?? '',
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => [
|
||||
'feedDistribution' => 'MAIN_FEED',
|
||||
'targetEntities' => [],
|
||||
'thirdPartyDistributionChannels' => [],
|
||||
],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* POST the assembled payload to the Posts API and return the created post.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
* @return array{id: string, url: ?string}
|
||||
*/
|
||||
private function createPost(array $payload, string $context): array
|
||||
{
|
||||
$response = $this->getHttpClient()->post("{$this->baseUrl()}/rest/posts", $payload);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error("{$this->label()} {$context} failed", [
|
||||
'status' => $response->status(),
|
||||
'body' => $this->redactResponseBody($response->body()),
|
||||
]);
|
||||
$this->handleApiError($response);
|
||||
}
|
||||
|
||||
$postId = $response->header('x-restli-id');
|
||||
|
||||
return [
|
||||
'id' => $postId ?? 'unknown',
|
||||
'url' => $this->postUrl($postId ?: null),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The title shown on a LinkedIn document (PDF carousel) post. Falls back to
|
||||
* the uploaded file name, then a generic label, so it's never empty.
|
||||
*/
|
||||
private function resolveDocumentTitle(PostPlatform $postPlatform): string
|
||||
{
|
||||
$title = data_get($postPlatform->meta, 'document_title');
|
||||
|
||||
if (filled($title)) {
|
||||
return (string) $title;
|
||||
}
|
||||
|
||||
return $postPlatform->post->mediaItems->first(fn ($media) => $media->isDocument())?->original_filename ?? 'Document';
|
||||
}
|
||||
|
||||
private function uploadMedia($mediaItem): ?string
|
||||
{
|
||||
return match (true) {
|
||||
$mediaItem->isVideo() => $this->uploadVideo($mediaItem),
|
||||
$mediaItem->isImage() => $this->uploadImage($mediaItem),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
private function uploadImage($mediaItem): ?string
|
||||
{
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl()}/rest/images?action=initializeUpload", [
|
||||
'initializeUploadRequest' => ['owner' => $this->authorUrn()],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error("{$this->label()} image init failed", ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$uploadUrl = data_get($initData, 'value.uploadUrl');
|
||||
$imageUrn = data_get($initData, 'value.image');
|
||||
|
||||
if (! $uploadUrl || ! $imageUrn) {
|
||||
throw new \Exception("{$this->label()} image upload init missing uploadUrl or image URN");
|
||||
}
|
||||
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
|
||||
|
||||
try {
|
||||
$this->downloadToTempFile($mediaItem->url, $tempFile);
|
||||
|
||||
$detectedMime = mime_content_type($tempFile) ?: '';
|
||||
if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {
|
||||
$optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, $this->platform());
|
||||
@unlink($tempFile);
|
||||
$tempFile = $optimizedPath;
|
||||
}
|
||||
|
||||
$stream = fopen($tempFile, 'r');
|
||||
|
||||
$uploadResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders(['Content-Type' => 'application/octet-stream'])
|
||||
->withBody($stream, 'application/octet-stream')
|
||||
->put($uploadUrl);
|
||||
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($uploadResponse->failed()) {
|
||||
Log::error("{$this->label()} image upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);
|
||||
$this->handleApiError($uploadResponse);
|
||||
}
|
||||
|
||||
return $imageUrn;
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function uploadVideo($mediaItem): ?string
|
||||
{
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'li_video_');
|
||||
|
||||
try {
|
||||
return $this->doUploadVideo($tempFile, $mediaItem);
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function doUploadVideo(string $tempFile, $mediaItem): ?string
|
||||
{
|
||||
$this->downloadToTempFile($mediaItem->url, $tempFile);
|
||||
|
||||
$fileSize = (int) filesize($tempFile);
|
||||
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl()}/rest/videos?action=initializeUpload", [
|
||||
'initializeUploadRequest' => [
|
||||
'owner' => $this->authorUrn(),
|
||||
'fileSizeBytes' => $fileSize,
|
||||
'uploadCaptions' => false,
|
||||
'uploadThumbnail' => false,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error("{$this->label()} video init failed", ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$videoUrn = data_get($initData, 'value.video');
|
||||
$uploadInstructions = data_get($initData, 'value.uploadInstructions', []);
|
||||
$uploadToken = data_get($initData, 'value.uploadToken', '');
|
||||
|
||||
if (! $videoUrn || empty($uploadInstructions)) {
|
||||
throw new \Exception("{$this->label()} video upload init missing video URN or upload instructions");
|
||||
}
|
||||
|
||||
$uploadedPartIds = [];
|
||||
$handle = fopen($tempFile, 'r');
|
||||
|
||||
try {
|
||||
foreach ($uploadInstructions as $index => $instruction) {
|
||||
$firstByte = data_get($instruction, 'firstByte');
|
||||
$lastByte = data_get($instruction, 'lastByte');
|
||||
|
||||
$chunkLength = $lastByte - $firstByte + 1;
|
||||
fseek($handle, $firstByte);
|
||||
$chunkData = fread($handle, $chunkLength);
|
||||
|
||||
$chunkResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders(['Content-Type' => 'application/octet-stream'])
|
||||
->timeout(600)
|
||||
->withBody($chunkData, 'application/octet-stream')
|
||||
->put(data_get($instruction, 'uploadUrl'));
|
||||
|
||||
if ($chunkResponse->failed()) {
|
||||
Log::error("{$this->label()} video chunk upload failed", [
|
||||
'index' => $index,
|
||||
'body' => $this->redactResponseBody($chunkResponse->body()),
|
||||
]);
|
||||
$this->handleApiError($chunkResponse);
|
||||
}
|
||||
|
||||
$etag = $chunkResponse->header('etag');
|
||||
if ($etag) {
|
||||
$uploadedPartIds[] = $etag;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
$finalizeResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl()}/rest/videos?action=finalizeUpload", [
|
||||
'finalizeUploadRequest' => [
|
||||
'video' => $videoUrn,
|
||||
'uploadToken' => $uploadToken,
|
||||
'uploadedPartIds' => $uploadedPartIds,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($finalizeResponse->failed()) {
|
||||
Log::error("{$this->label()} video finalize failed", ['body' => $this->redactResponseBody($finalizeResponse->body())]);
|
||||
$this->handleApiError($finalizeResponse);
|
||||
}
|
||||
|
||||
$this->waitForProcessing('videos', $videoUrn, 'video');
|
||||
|
||||
return $videoUrn;
|
||||
}
|
||||
|
||||
private function uploadDocument($mediaItem): ?string
|
||||
{
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl()}/rest/documents?action=initializeUpload", [
|
||||
'initializeUploadRequest' => ['owner' => $this->authorUrn()],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error("{$this->label()} document init failed", ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$uploadUrl = data_get($initData, 'value.uploadUrl');
|
||||
$documentUrn = data_get($initData, 'value.document');
|
||||
|
||||
if (! $uploadUrl || ! $documentUrn) {
|
||||
throw new \Exception("{$this->label()} document upload init missing uploadUrl or document URN");
|
||||
}
|
||||
|
||||
// The Documents API is not chunked — upload the PDF in a single request.
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'li_document_');
|
||||
|
||||
try {
|
||||
$this->downloadToTempFile($mediaItem->url, $tempFile);
|
||||
|
||||
$stream = fopen($tempFile, 'r');
|
||||
|
||||
$uploadResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders(['Content-Type' => 'application/pdf'])
|
||||
->timeout(600)
|
||||
->withBody($stream, 'application/pdf')
|
||||
->put($uploadUrl);
|
||||
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($uploadResponse->failed()) {
|
||||
Log::error("{$this->label()} document upload failed", ['body' => $this->redactResponseBody($uploadResponse->body())]);
|
||||
$this->handleApiError($uploadResponse);
|
||||
}
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
|
||||
$this->waitForProcessing('documents', $documentUrn, 'document');
|
||||
|
||||
return $documentUrn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll an asset until it finishes processing. LinkedIn rejects a post that
|
||||
* references an asset still being processed, so we wait for AVAILABLE and
|
||||
* fail loudly if it never gets there — publishing against an unprocessed
|
||||
* asset would error out at the API anyway, with a far less obvious message.
|
||||
*/
|
||||
private function waitForProcessing(string $resource, string $assetUrn, string $label): void
|
||||
{
|
||||
$encodedUrn = urlencode($assetUrn);
|
||||
|
||||
for ($i = 0; $i < $this->processingMaxAttempts(); $i++) {
|
||||
$response = $this->getHttpClient()->get("{$this->baseUrl()}/rest/{$resource}/{$encodedUrn}");
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::warning("{$this->label()} {$label} status check failed", ['attempt' => $i]);
|
||||
sleep($this->processingPollSeconds());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$status = data_get($response->json(), 'status', 'UNKNOWN');
|
||||
|
||||
if ($status === 'AVAILABLE') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === 'PROCESSING_FAILED') {
|
||||
throw new \Exception("{$this->label()} {$label} processing failed");
|
||||
}
|
||||
|
||||
sleep($this->processingPollSeconds());
|
||||
}
|
||||
|
||||
throw new \Exception("{$this->label()} {$label} processing did not complete in time");
|
||||
}
|
||||
|
||||
/**
|
||||
* How many times to poll an uploaded asset for AVAILABLE before giving up.
|
||||
*/
|
||||
protected function processingMaxAttempts(): int
|
||||
{
|
||||
return 30;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconds to wait between asset processing status checks.
|
||||
*/
|
||||
protected function processingPollSeconds(): int
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
private function downloadToTempFile(string $url, string $tempFile): void
|
||||
{
|
||||
$response = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($url);
|
||||
|
||||
if ($response->failed()) {
|
||||
throw new \Exception('Failed to download media: HTTP '.$response->status());
|
||||
}
|
||||
}
|
||||
|
||||
private function getHttpClient(): PendingRequest
|
||||
{
|
||||
return $this->socialHttp()->withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'X-Restli-Protocol-Version' => '2.0.0',
|
||||
'LinkedIn-Version' => $this->apiVersion,
|
||||
'Content-Type' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
private function baseUrl(): string
|
||||
{
|
||||
return config("trypost.platforms.{$this->platform()->value}.api");
|
||||
}
|
||||
|
||||
private function label(): string
|
||||
{
|
||||
return $this->platform()->label();
|
||||
}
|
||||
|
||||
private function handleApiError(Response $response): never
|
||||
{
|
||||
throw LinkedInPublishException::fromApiResponse($response);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\BlueskyPublishException;
|
||||
use App\Models\PostPlatform;
|
||||
|
|
@ -151,7 +152,7 @@ private function uploadBlob(SocialAccount $account, string $service, string $url
|
|||
|
||||
try {
|
||||
// Optimize images for Bluesky's 1MB limit (GIFs are passed through untouched).
|
||||
if (str_starts_with($mimeType, 'image/') && ! str_starts_with($mimeType, 'image/gif')) {
|
||||
if (MediaType::classify($mimeType) === MediaType::Image && ! MediaType::isGif($mimeType)) {
|
||||
$optimizedPath = app(MediaOptimizer::class)->optimizeImage($tempFile, Platform::Bluesky);
|
||||
@unlink($tempFile);
|
||||
$tempFile = $optimizedPath;
|
||||
|
|
|
|||
|
|
@ -135,9 +135,6 @@ private function refreshLinkedInToken(SocialAccount $account): void
|
|||
]);
|
||||
|
||||
$account->refresh();
|
||||
|
||||
// Sync tokens between LinkedIn personal and LinkedIn Page
|
||||
app(LinkedInTokenSynchronizer::class)->syncTokens($account);
|
||||
}
|
||||
|
||||
private function refreshXToken(SocialAccount $account): void
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
namespace App\Services\Social\Discord;
|
||||
|
||||
use App\DataTransferObjects\MediaItem;
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\DiscordPublishException;
|
||||
use App\Exceptions\Social\ErrorCategory;
|
||||
|
|
@ -156,7 +157,7 @@ private function downloadMedia(MediaItem $item): string
|
|||
}
|
||||
|
||||
// Images are downsized to Discord's limit; videos/gifs are sent as-is.
|
||||
if ($item->mime_type && str_starts_with($item->mime_type, 'image/') && ! str_contains($item->mime_type, 'gif')) {
|
||||
if ($item->isImage() && ! MediaType::isGif($item->mime_type)) {
|
||||
try {
|
||||
return app(MediaOptimizer::class)->optimizeImage($tempFile, Platform::Discord);
|
||||
} catch (Throwable) {
|
||||
|
|
|
|||
|
|
@ -4,454 +4,37 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\LinkedInPublishException;
|
||||
use App\Exceptions\TokenExpiredException;
|
||||
use App\Models\PostPlatform;
|
||||
use App\Models\SocialAccount;
|
||||
use App\Services\Media\MediaOptimizer;
|
||||
use App\Services\Social\Concerns\HasSocialHttpClient;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class LinkedInPagePublisher
|
||||
/**
|
||||
* Publishes posts to a LinkedIn company page on behalf of an administering member.
|
||||
*/
|
||||
class LinkedInPagePublisher extends AbstractLinkedInPublisher
|
||||
{
|
||||
use HasSocialHttpClient;
|
||||
|
||||
private string $baseUrl;
|
||||
|
||||
private string $apiVersion = '202601';
|
||||
|
||||
private string $accessToken;
|
||||
|
||||
public function __construct()
|
||||
protected function platform(): Platform
|
||||
{
|
||||
$this->baseUrl = config('trypost.platforms.linkedin-page.api');
|
||||
return Platform::LinkedInPage;
|
||||
}
|
||||
|
||||
private SocialAccount $account;
|
||||
|
||||
private bool $hasRetried = false;
|
||||
|
||||
public function publish(PostPlatform $postPlatform): array
|
||||
protected function authorUrn(): string
|
||||
{
|
||||
$this->validateContentLength($postPlatform);
|
||||
|
||||
$content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
|
||||
|
||||
$this->account = $postPlatform->socialAccount;
|
||||
$this->hasRetried = false;
|
||||
|
||||
if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
}
|
||||
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
$organizationId = $this->account->meta['organization_id'] ?? null;
|
||||
|
||||
if (! $organizationId) {
|
||||
throw new \Exception('LinkedIn Page organization ID not configured');
|
||||
}
|
||||
|
||||
$organizationUrn = "urn:li:organization:{$organizationId}";
|
||||
$contentType = $postPlatform->content_type;
|
||||
|
||||
try {
|
||||
return match ($contentType) {
|
||||
ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account),
|
||||
ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account),
|
||||
default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"),
|
||||
};
|
||||
} catch (TokenExpiredException $e) {
|
||||
return $this->retryWithRefresh($postPlatform, $content, $e);
|
||||
}
|
||||
return "urn:li:organization:{$organizationId}";
|
||||
}
|
||||
|
||||
private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array
|
||||
protected function postUrl(?string $postId): ?string
|
||||
{
|
||||
if ($this->hasRetried) {
|
||||
throw $originalException;
|
||||
if (! $postId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->hasRetried = true;
|
||||
|
||||
try {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
$organizationId = $this->account->meta['organization_id'] ?? null;
|
||||
$organizationUrn = "urn:li:organization:{$organizationId}";
|
||||
$contentType = $postPlatform->content_type;
|
||||
|
||||
return match ($contentType) {
|
||||
ContentType::LinkedInPageCarousel => $this->publishCarousel($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account),
|
||||
ContentType::LinkedInPagePost => $this->publishPost($organizationUrn, $content, $postPlatform->post->mediaItems, $this->account),
|
||||
default => throw new \Exception("Unsupported LinkedIn Page content type: {$contentType?->value}"),
|
||||
};
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('LinkedIn Page refresh failed during retry', [
|
||||
'account_id' => $this->account->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $originalException;
|
||||
}
|
||||
}
|
||||
|
||||
private function publishPost(string $organizationUrn, ?string $content, $media, $account): array
|
||||
{
|
||||
$payload = [
|
||||
'author' => $organizationUrn,
|
||||
'commentary' => $content ?? '',
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => [
|
||||
'feedDistribution' => 'MAIN_FEED',
|
||||
'targetEntities' => [],
|
||||
'thirdPartyDistributionChannels' => [],
|
||||
],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
];
|
||||
|
||||
if ($media->isNotEmpty()) {
|
||||
$firstMedia = $media->first();
|
||||
$mediaUrn = $this->uploadMedia($firstMedia, $organizationUrn);
|
||||
|
||||
if ($mediaUrn) {
|
||||
$payload['content'] = [
|
||||
'media' => [
|
||||
'id' => $mediaUrn,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/posts", $payload);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn Page post creation failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $this->redactResponseBody($response->body()),
|
||||
]);
|
||||
$this->handleApiError($response);
|
||||
}
|
||||
|
||||
$postId = $response->header('x-restli-id');
|
||||
|
||||
// Build company page URL
|
||||
$username = $account->username;
|
||||
$postUrl = $username
|
||||
? "https://www.linkedin.com/company/{$username}/posts/"
|
||||
return $this->account->username
|
||||
? "https://www.linkedin.com/company/{$this->account->username}/posts/"
|
||||
: "https://www.linkedin.com/feed/update/{$postId}";
|
||||
|
||||
return [
|
||||
'id' => $postId ?? 'unknown',
|
||||
'url' => $postId ? $postUrl : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function publishCarousel(string $organizationUrn, ?string $content, $mediaCollection, $account): array
|
||||
{
|
||||
// Upload images and build carousel items
|
||||
$carouselItems = [];
|
||||
|
||||
foreach ($mediaCollection as $media) {
|
||||
if (! $media->isImage()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$imageUrn = $this->uploadImage($media, $organizationUrn);
|
||||
|
||||
if ($imageUrn) {
|
||||
$carouselItems[] = [
|
||||
'altText' => $media->original_filename ?? 'Carousel image',
|
||||
'media' => $imageUrn,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($carouselItems)) {
|
||||
throw new \Exception('No valid images for LinkedIn Page carousel');
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'author' => $organizationUrn,
|
||||
'commentary' => $content ?? '',
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => [
|
||||
'feedDistribution' => 'MAIN_FEED',
|
||||
'targetEntities' => [],
|
||||
'thirdPartyDistributionChannels' => [],
|
||||
],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
'content' => [
|
||||
'multiImage' => [
|
||||
'images' => $carouselItems,
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/posts", $payload);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn Page carousel post creation failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $this->redactResponseBody($response->body()),
|
||||
]);
|
||||
$this->handleApiError($response);
|
||||
}
|
||||
|
||||
$postId = $response->header('x-restli-id');
|
||||
|
||||
// Build company page URL
|
||||
$username = $account->username;
|
||||
$postUrl = $username
|
||||
? "https://www.linkedin.com/company/{$username}/posts/"
|
||||
: "https://www.linkedin.com/feed/update/{$postId}";
|
||||
|
||||
return [
|
||||
'id' => $postId ?? 'unknown',
|
||||
'url' => $postId ? $postUrl : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function getHttpClient(): PendingRequest
|
||||
{
|
||||
return $this->socialHttp()->withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'X-Restli-Protocol-Version' => '2.0.0',
|
||||
'LinkedIn-Version' => $this->apiVersion,
|
||||
'Content-Type' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
private function uploadMedia($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$mimeType = $mediaItem->mime_type;
|
||||
$isVideo = str_starts_with($mimeType, 'video/');
|
||||
$isImage = str_starts_with($mimeType, 'image/');
|
||||
|
||||
if ($isVideo) {
|
||||
return $this->uploadVideo($mediaItem, $ownerUrn);
|
||||
}
|
||||
|
||||
if ($isImage) {
|
||||
return $this->uploadImage($mediaItem, $ownerUrn);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function uploadImage($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
// Step 1: Initialize upload
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/images?action=initializeUpload", [
|
||||
'initializeUploadRequest' => [
|
||||
'owner' => $ownerUrn,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error('LinkedIn Page image init failed', ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$uploadUrl = $initData['value']['uploadUrl'] ?? null;
|
||||
$imageUrn = $initData['value']['image'] ?? null;
|
||||
|
||||
if (! $uploadUrl || ! $imageUrn) {
|
||||
throw new \Exception('LinkedIn Page image upload init missing uploadUrl or image URN');
|
||||
}
|
||||
|
||||
// Step 2: Download and optimize image
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'lip_image_');
|
||||
|
||||
try {
|
||||
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
|
||||
|
||||
if ($downloadResponse->failed()) {
|
||||
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
|
||||
}
|
||||
|
||||
$detectedMime = mime_content_type($tempFile) ?: '';
|
||||
if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) {
|
||||
$optimizer = app(MediaOptimizer::class);
|
||||
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::LinkedInPage);
|
||||
@unlink($tempFile);
|
||||
$tempFile = $optimizedPath;
|
||||
}
|
||||
|
||||
$stream = fopen($tempFile, 'r');
|
||||
|
||||
$uploadResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'Content-Type' => 'application/octet-stream',
|
||||
])
|
||||
->withBody($stream, 'application/octet-stream')
|
||||
->put($uploadUrl);
|
||||
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($uploadResponse->failed()) {
|
||||
Log::error('LinkedIn Page image upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]);
|
||||
$this->handleApiError($uploadResponse);
|
||||
}
|
||||
|
||||
return $imageUrn;
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function uploadVideo($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'lip_video_');
|
||||
|
||||
try {
|
||||
return $this->doUploadVideo($tempFile, $mediaItem, $ownerUrn);
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function doUploadVideo(string $tempFile, $mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
|
||||
|
||||
if ($downloadResponse->failed()) {
|
||||
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
|
||||
}
|
||||
|
||||
$fileSize = (int) filesize($tempFile);
|
||||
|
||||
// Step 1: Initialize upload
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/videos?action=initializeUpload", [
|
||||
'initializeUploadRequest' => [
|
||||
'owner' => $ownerUrn,
|
||||
'fileSizeBytes' => $fileSize,
|
||||
'uploadCaptions' => false,
|
||||
'uploadThumbnail' => false,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error('LinkedIn Page video init failed', ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$videoUrn = $initData['value']['video'] ?? null;
|
||||
$uploadInstructions = $initData['value']['uploadInstructions'] ?? [];
|
||||
$uploadToken = $initData['value']['uploadToken'] ?? '';
|
||||
|
||||
if (! $videoUrn || empty($uploadInstructions)) {
|
||||
throw new \Exception('LinkedIn Page video upload init missing video URN or upload instructions');
|
||||
}
|
||||
|
||||
// Step 2: Upload chunks
|
||||
$uploadedPartIds = [];
|
||||
$handle = fopen($tempFile, 'r');
|
||||
|
||||
try {
|
||||
foreach ($uploadInstructions as $index => $instruction) {
|
||||
$uploadUrl = data_get($instruction, 'uploadUrl');
|
||||
$firstByte = data_get($instruction, 'firstByte');
|
||||
$lastByte = data_get($instruction, 'lastByte');
|
||||
|
||||
$chunkLength = $lastByte - $firstByte + 1;
|
||||
fseek($handle, $firstByte);
|
||||
$chunkData = fread($handle, $chunkLength);
|
||||
|
||||
$chunkResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'Content-Type' => 'application/octet-stream',
|
||||
])
|
||||
->timeout(600)
|
||||
->withBody($chunkData, 'application/octet-stream')
|
||||
->put($uploadUrl);
|
||||
|
||||
if ($chunkResponse->failed()) {
|
||||
Log::error('LinkedIn Page video chunk upload failed', [
|
||||
'index' => $index,
|
||||
'body' => $this->redactResponseBody($chunkResponse->body()),
|
||||
]);
|
||||
$this->handleApiError($chunkResponse);
|
||||
}
|
||||
|
||||
$etag = $chunkResponse->header('etag');
|
||||
if ($etag) {
|
||||
$uploadedPartIds[] = $etag;
|
||||
}
|
||||
|
||||
}
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
// Step 3: Finalize upload
|
||||
$finalizeResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/videos?action=finalizeUpload", [
|
||||
'finalizeUploadRequest' => [
|
||||
'video' => $videoUrn,
|
||||
'uploadToken' => $uploadToken,
|
||||
'uploadedPartIds' => $uploadedPartIds,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($finalizeResponse->failed()) {
|
||||
Log::error('LinkedIn Page video finalize failed', ['body' => $this->redactResponseBody($finalizeResponse->body())]);
|
||||
$this->handleApiError($finalizeResponse);
|
||||
}
|
||||
|
||||
// Step 4: Wait for processing
|
||||
$this->waitForVideoProcessing($videoUrn);
|
||||
|
||||
return $videoUrn;
|
||||
}
|
||||
|
||||
private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30): void
|
||||
{
|
||||
$encodedUrn = urlencode($videoUrn);
|
||||
|
||||
for ($i = 0; $i < $maxAttempts; $i++) {
|
||||
$response = $this->getHttpClient()
|
||||
->get("{$this->baseUrl}/rest/videos/{$encodedUrn}");
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::warning('LinkedIn Page video status check failed', ['attempt' => $i]);
|
||||
sleep(5);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
$status = data_get($data, 'status', 'UNKNOWN');
|
||||
|
||||
if ($status === 'AVAILABLE') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === 'PROCESSING_FAILED') {
|
||||
throw new \Exception('LinkedIn Page video processing failed');
|
||||
}
|
||||
|
||||
sleep(5);
|
||||
}
|
||||
|
||||
Log::warning('LinkedIn Page video processing timeout, proceeding anyway');
|
||||
}
|
||||
|
||||
private function handleApiError(Response $response): never
|
||||
{
|
||||
throw LinkedInPublishException::fromApiResponse($response);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,435 +4,20 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\LinkedInPublishException;
|
||||
use App\Exceptions\TokenExpiredException;
|
||||
use App\Models\PostPlatform;
|
||||
use App\Models\SocialAccount;
|
||||
use App\Services\Media\MediaOptimizer;
|
||||
use App\Services\Social\Concerns\HasSocialHttpClient;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class LinkedInPublisher
|
||||
/**
|
||||
* Publishes posts to a member's personal LinkedIn profile.
|
||||
*/
|
||||
class LinkedInPublisher extends AbstractLinkedInPublisher
|
||||
{
|
||||
use HasSocialHttpClient;
|
||||
|
||||
private string $baseUrl;
|
||||
|
||||
private string $apiVersion = '202601';
|
||||
|
||||
private string $accessToken;
|
||||
|
||||
public function __construct()
|
||||
protected function platform(): Platform
|
||||
{
|
||||
$this->baseUrl = config('trypost.platforms.linkedin.api');
|
||||
return Platform::LinkedIn;
|
||||
}
|
||||
|
||||
private SocialAccount $account;
|
||||
|
||||
private bool $hasRetried = false;
|
||||
|
||||
public function publish(PostPlatform $postPlatform): array
|
||||
protected function authorUrn(): string
|
||||
{
|
||||
$this->validateContentLength($postPlatform);
|
||||
|
||||
$content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
|
||||
|
||||
$this->account = $postPlatform->socialAccount;
|
||||
$this->hasRetried = false;
|
||||
|
||||
if ($this->account->is_token_expired || $this->account->is_token_expiring_soon) {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
}
|
||||
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
$personUrn = "urn:li:person:{$this->account->platform_user_id}";
|
||||
$contentType = $postPlatform->content_type;
|
||||
|
||||
try {
|
||||
return match ($contentType) {
|
||||
ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems),
|
||||
ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems),
|
||||
default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"),
|
||||
};
|
||||
} catch (TokenExpiredException $e) {
|
||||
return $this->retryWithRefresh($postPlatform, $content, $e);
|
||||
}
|
||||
}
|
||||
|
||||
private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array
|
||||
{
|
||||
if ($this->hasRetried) {
|
||||
throw $originalException;
|
||||
}
|
||||
|
||||
$this->hasRetried = true;
|
||||
|
||||
try {
|
||||
app(ConnectionVerifier::class)->refreshToken($this->account);
|
||||
$this->accessToken = $this->account->access_token;
|
||||
|
||||
$personUrn = "urn:li:person:{$this->account->platform_user_id}";
|
||||
$contentType = $postPlatform->content_type;
|
||||
|
||||
return match ($contentType) {
|
||||
ContentType::LinkedInCarousel => $this->publishCarousel($personUrn, $content, $postPlatform->post->mediaItems),
|
||||
ContentType::LinkedInPost => $this->publishPost($personUrn, $content, $postPlatform->post->mediaItems),
|
||||
default => throw new \Exception("Unsupported LinkedIn content type: {$contentType?->value}"),
|
||||
};
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('LinkedIn refresh failed during retry', [
|
||||
'account_id' => $this->account->id,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
throw $originalException;
|
||||
}
|
||||
}
|
||||
|
||||
private function publishPost(string $personUrn, ?string $content, $media): array
|
||||
{
|
||||
$payload = [
|
||||
'author' => $personUrn,
|
||||
'commentary' => $content ?? '',
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => [
|
||||
'feedDistribution' => 'MAIN_FEED',
|
||||
'targetEntities' => [],
|
||||
'thirdPartyDistributionChannels' => [],
|
||||
],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
];
|
||||
|
||||
if ($media->isNotEmpty()) {
|
||||
$firstMedia = $media->first();
|
||||
$mediaUrn = $this->uploadMedia($firstMedia, $personUrn);
|
||||
|
||||
if ($mediaUrn) {
|
||||
$payload['content'] = [
|
||||
'media' => [
|
||||
'id' => $mediaUrn,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/posts", $payload);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn post creation failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $this->redactResponseBody($response->body()),
|
||||
]);
|
||||
$this->handleApiError($response);
|
||||
}
|
||||
|
||||
$postId = $response->header('x-restli-id');
|
||||
|
||||
return [
|
||||
'id' => $postId ?? 'unknown',
|
||||
'url' => $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function publishCarousel(string $personUrn, ?string $content, $mediaCollection): array
|
||||
{
|
||||
// Upload images and build carousel items
|
||||
$carouselItems = [];
|
||||
|
||||
foreach ($mediaCollection as $media) {
|
||||
if (! $media->isImage()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$imageUrn = $this->uploadImage($media, $personUrn);
|
||||
|
||||
if ($imageUrn) {
|
||||
$carouselItems[] = [
|
||||
'altText' => $media->original_filename ?? 'Carousel image',
|
||||
'media' => $imageUrn,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($carouselItems)) {
|
||||
throw new \Exception('No valid images for LinkedIn carousel');
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'author' => $personUrn,
|
||||
'commentary' => $content ?? '',
|
||||
'visibility' => 'PUBLIC',
|
||||
'distribution' => [
|
||||
'feedDistribution' => 'MAIN_FEED',
|
||||
'targetEntities' => [],
|
||||
'thirdPartyDistributionChannels' => [],
|
||||
],
|
||||
'lifecycleState' => 'PUBLISHED',
|
||||
'content' => [
|
||||
'multiImage' => [
|
||||
'images' => $carouselItems,
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$response = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/posts", $payload);
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::error('LinkedIn carousel post creation failed', [
|
||||
'status' => $response->status(),
|
||||
'body' => $this->redactResponseBody($response->body()),
|
||||
]);
|
||||
$this->handleApiError($response);
|
||||
}
|
||||
|
||||
$postId = $response->header('x-restli-id');
|
||||
|
||||
return [
|
||||
'id' => $postId ?? 'unknown',
|
||||
'url' => $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null,
|
||||
];
|
||||
}
|
||||
|
||||
private function getHttpClient(): PendingRequest
|
||||
{
|
||||
return $this->socialHttp()->withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'X-Restli-Protocol-Version' => '2.0.0',
|
||||
'LinkedIn-Version' => $this->apiVersion,
|
||||
'Content-Type' => 'application/json',
|
||||
]);
|
||||
}
|
||||
|
||||
private function uploadMedia($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$mimeType = $mediaItem->mime_type;
|
||||
$isVideo = str_starts_with($mimeType, 'video/');
|
||||
$isImage = str_starts_with($mimeType, 'image/');
|
||||
|
||||
if ($isVideo) {
|
||||
return $this->uploadVideo($mediaItem, $ownerUrn);
|
||||
}
|
||||
|
||||
if ($isImage) {
|
||||
return $this->uploadImage($mediaItem, $ownerUrn);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function uploadImage($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
// Step 1: Initialize upload
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/images?action=initializeUpload", [
|
||||
'initializeUploadRequest' => [
|
||||
'owner' => $ownerUrn,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error('LinkedIn image init failed', ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$uploadUrl = $initData['value']['uploadUrl'] ?? null;
|
||||
$imageUrn = $initData['value']['image'] ?? null;
|
||||
|
||||
if (! $uploadUrl || ! $imageUrn) {
|
||||
throw new \Exception('LinkedIn image upload init missing uploadUrl or image URN');
|
||||
}
|
||||
|
||||
// Step 2: Download and optimize image
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'li_image_');
|
||||
|
||||
try {
|
||||
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
|
||||
|
||||
if ($downloadResponse->failed()) {
|
||||
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
|
||||
}
|
||||
|
||||
$detectedMime = mime_content_type($tempFile) ?: '';
|
||||
if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) {
|
||||
$optimizer = app(MediaOptimizer::class);
|
||||
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::LinkedIn);
|
||||
@unlink($tempFile);
|
||||
$tempFile = $optimizedPath;
|
||||
}
|
||||
|
||||
$stream = fopen($tempFile, 'r');
|
||||
|
||||
$uploadResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'Content-Type' => 'application/octet-stream',
|
||||
])
|
||||
->withBody($stream, 'application/octet-stream')
|
||||
->put($uploadUrl);
|
||||
|
||||
if (is_resource($stream)) {
|
||||
fclose($stream);
|
||||
}
|
||||
|
||||
if ($uploadResponse->failed()) {
|
||||
Log::error('LinkedIn image upload failed', ['body' => $this->redactResponseBody($uploadResponse->body())]);
|
||||
$this->handleApiError($uploadResponse);
|
||||
}
|
||||
|
||||
return $imageUrn;
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function uploadVideo($mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$tempFile = tempnam(sys_get_temp_dir(), 'li_video_');
|
||||
|
||||
try {
|
||||
return $this->doUploadVideo($tempFile, $mediaItem, $ownerUrn);
|
||||
} finally {
|
||||
@unlink($tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
private function doUploadVideo(string $tempFile, $mediaItem, string $ownerUrn): ?string
|
||||
{
|
||||
$downloadResponse = Http::withOptions(['sink' => $tempFile])->timeout(600)->get($mediaItem->url);
|
||||
|
||||
if ($downloadResponse->failed()) {
|
||||
throw new \Exception('Failed to download media: HTTP '.$downloadResponse->status());
|
||||
}
|
||||
|
||||
$fileSize = (int) filesize($tempFile);
|
||||
|
||||
// Step 1: Initialize upload
|
||||
$initResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/videos?action=initializeUpload", [
|
||||
'initializeUploadRequest' => [
|
||||
'owner' => $ownerUrn,
|
||||
'fileSizeBytes' => $fileSize,
|
||||
'uploadCaptions' => false,
|
||||
'uploadThumbnail' => false,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($initResponse->failed()) {
|
||||
Log::error('LinkedIn video init failed', ['body' => $this->redactResponseBody($initResponse->body())]);
|
||||
$this->handleApiError($initResponse);
|
||||
}
|
||||
|
||||
$initData = $initResponse->json();
|
||||
$videoUrn = $initData['value']['video'] ?? null;
|
||||
$uploadInstructions = $initData['value']['uploadInstructions'] ?? [];
|
||||
$uploadToken = $initData['value']['uploadToken'] ?? '';
|
||||
|
||||
if (! $videoUrn || empty($uploadInstructions)) {
|
||||
throw new \Exception('LinkedIn video upload init missing video URN or upload instructions');
|
||||
}
|
||||
|
||||
// Step 2: Upload chunks
|
||||
$uploadedPartIds = [];
|
||||
$handle = fopen($tempFile, 'r');
|
||||
|
||||
try {
|
||||
foreach ($uploadInstructions as $index => $instruction) {
|
||||
$uploadUrl = data_get($instruction, 'uploadUrl');
|
||||
$firstByte = data_get($instruction, 'firstByte');
|
||||
$lastByte = data_get($instruction, 'lastByte');
|
||||
|
||||
$chunkLength = $lastByte - $firstByte + 1;
|
||||
fseek($handle, $firstByte);
|
||||
$chunkData = fread($handle, $chunkLength);
|
||||
|
||||
$chunkResponse = Http::withToken($this->accessToken)
|
||||
->withHeaders([
|
||||
'Content-Type' => 'application/octet-stream',
|
||||
])
|
||||
->timeout(600)
|
||||
->withBody($chunkData, 'application/octet-stream')
|
||||
->put($uploadUrl);
|
||||
|
||||
if ($chunkResponse->failed()) {
|
||||
Log::error('LinkedIn video chunk upload failed', [
|
||||
'index' => $index,
|
||||
'body' => $this->redactResponseBody($chunkResponse->body()),
|
||||
]);
|
||||
$this->handleApiError($chunkResponse);
|
||||
}
|
||||
|
||||
$etag = $chunkResponse->header('etag');
|
||||
if ($etag) {
|
||||
$uploadedPartIds[] = $etag;
|
||||
}
|
||||
|
||||
}
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
// Step 3: Finalize upload
|
||||
$finalizeResponse = $this->getHttpClient()
|
||||
->post("{$this->baseUrl}/rest/videos?action=finalizeUpload", [
|
||||
'finalizeUploadRequest' => [
|
||||
'video' => $videoUrn,
|
||||
'uploadToken' => $uploadToken,
|
||||
'uploadedPartIds' => $uploadedPartIds,
|
||||
],
|
||||
]);
|
||||
|
||||
if ($finalizeResponse->failed()) {
|
||||
Log::error('LinkedIn video finalize failed', ['body' => $this->redactResponseBody($finalizeResponse->body())]);
|
||||
$this->handleApiError($finalizeResponse);
|
||||
}
|
||||
|
||||
// Step 4: Wait for processing
|
||||
$this->waitForVideoProcessing($videoUrn);
|
||||
|
||||
return $videoUrn;
|
||||
}
|
||||
|
||||
private function waitForVideoProcessing(string $videoUrn, int $maxAttempts = 30): void
|
||||
{
|
||||
$encodedUrn = urlencode($videoUrn);
|
||||
|
||||
for ($i = 0; $i < $maxAttempts; $i++) {
|
||||
$response = $this->getHttpClient()
|
||||
->get("{$this->baseUrl}/rest/videos/{$encodedUrn}");
|
||||
|
||||
if ($response->failed()) {
|
||||
Log::warning('LinkedIn video status check failed', ['attempt' => $i]);
|
||||
sleep(5);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
$status = data_get($data, 'status', 'UNKNOWN');
|
||||
|
||||
if ($status === 'AVAILABLE') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === 'PROCESSING_FAILED') {
|
||||
throw new \Exception('LinkedIn video processing failed');
|
||||
}
|
||||
|
||||
sleep(5);
|
||||
}
|
||||
|
||||
Log::warning('LinkedIn video processing timeout, proceeding anyway');
|
||||
}
|
||||
|
||||
private function handleApiError(Response $response): never
|
||||
{
|
||||
throw LinkedInPublishException::fromApiResponse($response);
|
||||
return "urn:li:person:{$this->account->platform_user_id}";
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Models\SocialAccount;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
class LinkedInTokenSynchronizer
|
||||
{
|
||||
/**
|
||||
* Sync tokens from LinkedIn personal to LinkedIn Page (or vice versa).
|
||||
* When one account gets a new token, update every linked account in the
|
||||
* same workspace so multiple pages sharing the same admin keep working.
|
||||
*/
|
||||
public function syncTokens(SocialAccount $sourceAccount): void
|
||||
{
|
||||
$workspace = $sourceAccount->workspace;
|
||||
$linkedUserId = $this->getLinkedInUserId($sourceAccount);
|
||||
|
||||
if (! $linkedUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$targets = $this->findLinkedAccounts($workspace, $sourceAccount, $linkedUserId);
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$target->update([
|
||||
'access_token' => $sourceAccount->access_token,
|
||||
'refresh_token' => $sourceAccount->refresh_token,
|
||||
'token_expires_at' => $sourceAccount->token_expires_at,
|
||||
]);
|
||||
|
||||
if ($target->isDisconnected()) {
|
||||
$target->markAsConnected();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the LinkedIn user ID from an account.
|
||||
* For personal accounts, it's the platform_user_id.
|
||||
* For page accounts, it's stored in meta.admin_user_id.
|
||||
*/
|
||||
private function getLinkedInUserId(SocialAccount $account): ?string
|
||||
{
|
||||
if ($account->platform === Platform::LinkedIn) {
|
||||
return $account->platform_user_id;
|
||||
}
|
||||
|
||||
if ($account->platform === Platform::LinkedInPage) {
|
||||
return $account->meta['admin_user_id'] ?? null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find every linked LinkedIn account (personal <-> page) in the same workspace.
|
||||
*
|
||||
* @return Collection<int, SocialAccount>
|
||||
*/
|
||||
private function findLinkedAccounts(Workspace $workspace, SocialAccount $sourceAccount, string $linkedUserId): Collection
|
||||
{
|
||||
if ($sourceAccount->platform === Platform::LinkedIn) {
|
||||
// Source is personal: every page admin'd by this LinkedIn user.
|
||||
return $workspace->socialAccounts()
|
||||
->where('platform', Platform::LinkedInPage->value)
|
||||
->whereJsonContains('meta->admin_user_id', $linkedUserId)
|
||||
->get();
|
||||
}
|
||||
|
||||
if ($sourceAccount->platform === Platform::LinkedInPage) {
|
||||
// Source is page: the personal LinkedIn account belonging to its admin.
|
||||
return $workspace->socialAccounts()
|
||||
->where('platform', Platform::LinkedIn->value)
|
||||
->where('platform_user_id', $linkedUserId)
|
||||
->get();
|
||||
}
|
||||
|
||||
return new Collection;
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\MastodonPublishException;
|
||||
use App\Models\PostPlatform;
|
||||
|
|
@ -86,7 +87,7 @@ private function uploadMedia(SocialAccount $account, string $instance, string $u
|
|||
|
||||
// Optimize images (skip GIFs)
|
||||
$detectedMime = mime_content_type($tempFile) ?: '';
|
||||
if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) {
|
||||
if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {
|
||||
$optimizer = app(MediaOptimizer::class);
|
||||
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Mastodon);
|
||||
@unlink($tempFile);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\ErrorCategory;
|
||||
|
|
@ -85,7 +86,7 @@ private function publishImagePin(PostPlatform $postPlatform, ?string $content):
|
|||
}
|
||||
|
||||
$detectedMime = mime_content_type($tempFile) ?: '';
|
||||
if (str_starts_with($detectedMime, 'image/') && ! str_starts_with($detectedMime, 'image/gif')) {
|
||||
if (MediaType::classify($detectedMime) === MediaType::Image && ! MediaType::isGif($detectedMime)) {
|
||||
$optimizer = app(MediaOptimizer::class);
|
||||
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::Pinterest);
|
||||
@unlink($tempFile);
|
||||
|
|
@ -272,6 +273,8 @@ private function publishVideoPin(PostPlatform $postPlatform, ?string $content):
|
|||
|
||||
if (! empty(data_get($postPlatform->meta, 'cover_image_url'))) {
|
||||
$payload['media_source']['cover_image_url'] = data_get($postPlatform->meta, 'cover_image_url');
|
||||
} else {
|
||||
$payload['media_source']['cover_image_key_frame_time'] = 0;
|
||||
}
|
||||
|
||||
$response = $this->socialHttp()->withToken($account->access_token)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
namespace App\Services\Social;
|
||||
|
||||
use App\Enums\Media\Type as MediaType;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Exceptions\Social\XPublishException;
|
||||
use App\Models\PostPlatform;
|
||||
|
|
@ -117,7 +118,7 @@ private function uploadMedia($mediaItem): ?array
|
|||
}
|
||||
|
||||
// Optimize images (skip GIFs — they need special handling)
|
||||
if (str_starts_with($mimeType, 'image/') && ! str_starts_with($mimeType, 'image/gif')) {
|
||||
if ($mediaItem->isImage() && ! MediaType::isGif($mimeType)) {
|
||||
$optimizer = app(MediaOptimizer::class);
|
||||
$optimizedPath = $optimizer->optimizeImage($tempFile, Platform::X);
|
||||
@unlink($tempFile);
|
||||
|
|
@ -128,8 +129,8 @@ private function uploadMedia($mediaItem): ?array
|
|||
$fileSize = filesize($tempFile);
|
||||
$mediaCategory = $this->getMediaCategory($mimeType, $fileSize);
|
||||
|
||||
$isVideo = str_starts_with($mimeType, 'video/');
|
||||
$isGif = $mimeType === 'image/gif';
|
||||
$isVideo = MediaType::classify($mimeType) === MediaType::Video;
|
||||
$isGif = MediaType::isGif($mimeType);
|
||||
|
||||
$useChunkedUpload = $isVideo || $isGif || $fileSize > 5 * 1024 * 1024;
|
||||
|
||||
|
|
@ -256,7 +257,7 @@ private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeTy
|
|||
$finalizeData = $finalizeResponse->json();
|
||||
|
||||
// Wait for processing (videos need transcoding)
|
||||
if (isset($finalizeData['processing_info']) || str_starts_with($mimeType, 'video/')) {
|
||||
if (isset($finalizeData['processing_info']) || MediaType::classify($mimeType) === MediaType::Video) {
|
||||
$this->waitForProcessing($mediaId);
|
||||
}
|
||||
|
||||
|
|
@ -270,15 +271,15 @@ private function chunkedUpload(string $tempFile, int $totalBytes, string $mimeTy
|
|||
|
||||
private function getMediaCategory(string $mimeType, int $fileSize): ?string
|
||||
{
|
||||
if (str_starts_with($mimeType, 'video/')) {
|
||||
if (MediaType::classify($mimeType) === MediaType::Video) {
|
||||
return $fileSize > 15 * 1024 * 1024 ? 'amplify_video' : 'tweet_video';
|
||||
}
|
||||
|
||||
if ($mimeType === 'image/gif') {
|
||||
if (MediaType::isGif($mimeType)) {
|
||||
return 'tweet_gif';
|
||||
}
|
||||
|
||||
if (str_starts_with($mimeType, 'image/')) {
|
||||
if (MediaType::classify($mimeType) === MediaType::Image) {
|
||||
return 'tweet_image';
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -45,6 +45,9 @@ public static function rules(): array
|
|||
// Instagram / Facebook
|
||||
'platforms.*.meta.aspect_ratio' => ['sometimes', 'nullable', 'string', Rule::enum(AspectRatio::class)],
|
||||
|
||||
// LinkedIn — title shown on a document (PDF carousel) post
|
||||
'platforms.*.meta.document_title' => ['sometimes', 'nullable', 'string', 'max:300'],
|
||||
|
||||
// TikTok
|
||||
'platforms.*.meta.privacy_level' => ['sometimes', 'nullable', 'string', Rule::in(self::TIKTOK_PRIVACY_LEVELS)],
|
||||
'platforms.*.meta.auto_add_music' => ['sometimes', 'boolean'],
|
||||
|
|
|
|||
|
|
@ -47,7 +47,6 @@
|
|||
'client_id' => env('LINKEDIN_CLIENT_ID'),
|
||||
'client_secret' => env('LINKEDIN_CLIENT_SECRET'),
|
||||
'redirect' => env('LINKEDIN_CLIENT_REDIRECT'),
|
||||
'redirect_page' => env('LINKEDIN_PAGE_CLIENT_REDIRECT'),
|
||||
],
|
||||
|
||||
'x' => [
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@
|
|||
'max_size_mb' => [
|
||||
'image' => (int) env('MEDIA_IMAGE_MAX_SIZE_MB', 10),
|
||||
'video' => (int) env('MEDIA_VIDEO_MAX_SIZE_MB', 1024),
|
||||
// LinkedIn caps document (PDF carousel) uploads at 100MB.
|
||||
'document' => (int) env('MEDIA_DOCUMENT_MAX_SIZE_MB', 100),
|
||||
],
|
||||
],
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* LinkedIn no longer has per-format content types — the publish format is
|
||||
* inferred from the attached media. Collapse the old carousel/document
|
||||
* variants back onto the single post type for each account kind.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('post_platforms')
|
||||
->whereIn('content_type', ['linkedin_carousel', 'linkedin_document'])
|
||||
->update(['content_type' => 'linkedin_post']);
|
||||
|
||||
DB::table('post_platforms')
|
||||
->whereIn('content_type', ['linkedin_page_carousel', 'linkedin_page_document'])
|
||||
->update(['content_type' => 'linkedin_page_post']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// Irreversible: the per-format variants were merged into the single post
|
||||
// type and the original distinction is no longer recoverable.
|
||||
}
|
||||
};
|
||||
|
|
@ -15,7 +15,7 @@
|
|||
'disconnect' => 'Disconnect',
|
||||
|
||||
'descriptions' => [
|
||||
'linkedin' => 'Connect your LinkedIn personal profile',
|
||||
'linkedin' => 'Connect your LinkedIn profile or company page',
|
||||
'linkedin-page' => 'Connect a LinkedIn company page',
|
||||
'x' => 'Connect your X (Twitter) account',
|
||||
'tiktok' => 'Connect your TikTok account',
|
||||
|
|
@ -83,6 +83,8 @@
|
|||
'no_pages' => 'No pages found',
|
||||
'no_pages_description' => 'You are not an admin of any Facebook page.',
|
||||
'page_label' => 'Facebook Page',
|
||||
'view' => 'View',
|
||||
'choose' => 'Choose',
|
||||
],
|
||||
|
||||
'instagram_facebook' => [
|
||||
|
|
@ -90,6 +92,8 @@
|
|||
'description' => 'Choose which Instagram account you want to connect',
|
||||
'no_pages' => 'No Instagram accounts found',
|
||||
'no_pages_description' => 'No Facebook Pages with linked Instagram Business accounts were found.',
|
||||
'view' => 'View',
|
||||
'choose' => 'Choose',
|
||||
],
|
||||
|
||||
'linkedin' => [
|
||||
|
|
@ -98,6 +102,12 @@
|
|||
'no_pages' => 'No pages found',
|
||||
'no_pages_description' => 'You are not an administrator of any LinkedIn page.',
|
||||
'page_label' => 'LinkedIn Page',
|
||||
'select_title' => 'Where do you want to post?',
|
||||
'select_subtitle' => 'Post as yourself or choose a company page you manage.',
|
||||
'person_tag' => 'Person',
|
||||
'organization_tag' => 'Organization',
|
||||
'view' => 'View',
|
||||
'choose' => 'Choose',
|
||||
],
|
||||
|
||||
'flash' => [
|
||||
|
|
@ -115,7 +125,8 @@
|
|||
'title_success' => 'Connected',
|
||||
'title_error' => 'Error',
|
||||
'closing' => 'This window will close automatically...',
|
||||
'close_now' => 'You can close this window now.',
|
||||
'manual_close' => 'You can close this window.',
|
||||
'popup_blocked' => 'Could not open the connection window. Please allow popups and try again.',
|
||||
'connected' => 'Account connected!',
|
||||
'reconnected' => 'Account reconnected!',
|
||||
'error_connecting' => 'Error connecting account. Please try again.',
|
||||
|
|
|
|||
|
|
@ -11,8 +11,9 @@
|
|||
|
||||
'upload' => [
|
||||
'drag_drop' => 'Drag & drop your files here, or click to select',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF',
|
||||
'uploading' => 'Uploading...',
|
||||
'failed' => 'Could not upload :file. Please try again.',
|
||||
],
|
||||
|
||||
'empty' => [
|
||||
|
|
|
|||
|
|
@ -139,11 +139,8 @@
|
|||
'settings' => 'LinkedIn Settings',
|
||||
'settings_page' => 'LinkedIn Page Settings',
|
||||
'posting_to' => 'Posting to',
|
||||
'variant_label' => 'Post type',
|
||||
'variant' => [
|
||||
'post' => 'Post',
|
||||
'carousel' => 'Carousel',
|
||||
],
|
||||
'document_title' => 'Document title',
|
||||
'document_title_placeholder' => 'Shown on your PDF document post',
|
||||
],
|
||||
'pinterest' => [
|
||||
'settings' => 'Pinterest Settings',
|
||||
|
|
@ -188,9 +185,13 @@
|
|||
'min_files_required' => 'This post type requires at least :min media files (you have :current).',
|
||||
'no_video_allowed' => 'This post type does not accept videos.',
|
||||
'no_image_allowed' => 'This post type accepts only videos.',
|
||||
'no_document_allowed' => 'This post type does not accept PDF documents.',
|
||||
'no_mixed_media' => "Images and a video can't be combined in the same post.",
|
||||
'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.',
|
||||
'gif_not_allowed' => 'This platform does not accept GIF. Remove the GIF or choose a different network.',
|
||||
'image_too_large' => 'Image exceeds the :max limit for this post type (yours is :current).',
|
||||
'video_too_large' => 'Video exceeds the :max limit for this post type (yours is :current).',
|
||||
'document_too_large' => 'PDF exceeds the :max limit for this post type (yours is :current).',
|
||||
'video_too_long' => 'Video is :current long, but this post type allows up to :max.',
|
||||
'aspect_ratio_too_narrow' => 'Aspect ratio :current is too tall for this post type (min :min).',
|
||||
'aspect_ratio_too_wide' => 'Aspect ratio :current is too wide for this post type (max :max).',
|
||||
|
|
@ -344,11 +345,15 @@
|
|||
'no_images' => 'Only videos are allowed for this format.',
|
||||
'no_mixed_media' => "Images and videos can't be combined in the same post.",
|
||||
'no_gifs' => 'GIFs are not supported here.',
|
||||
'no_documents' => 'PDF documents are not supported by this format.',
|
||||
'document_not_alone' => 'A PDF must be posted on its own, without other images or videos.',
|
||||
'video_too_large' => 'Video exceeds the size limit for this platform.',
|
||||
'video_too_long' => 'Video must be under :seconds seconds for this format.',
|
||||
'image_too_large' => 'Image exceeds the size limit for this platform.',
|
||||
'document_too_large' => 'PDF exceeds the size limit for this platform.',
|
||||
'aspect_ratio_invalid' => 'Aspect ratio is not supported by this format.',
|
||||
'no_content_type' => 'Pick a content type for this platform.',
|
||||
'requires_text' => 'Add text — this format needs a title.',
|
||||
],
|
||||
'publishing' => 'Publishing...',
|
||||
'publishing_overlay_title' => 'Your post is being published',
|
||||
|
|
@ -458,19 +463,11 @@
|
|||
],
|
||||
'linkedin_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Standard post with text and media',
|
||||
],
|
||||
'linkedin_carousel' => [
|
||||
'label' => 'Carousel',
|
||||
'description' => 'Swipeable images',
|
||||
'description' => 'Standard post — single image, multi-image, video, or PDF',
|
||||
],
|
||||
'linkedin_page_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Standard post with text and media',
|
||||
],
|
||||
'linkedin_page_carousel' => [
|
||||
'label' => 'Carousel',
|
||||
'description' => 'Swipeable images',
|
||||
'description' => 'Standard post — single image, multi-image, video, or PDF',
|
||||
],
|
||||
'facebook_post' => [
|
||||
'label' => 'Post',
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
'disconnect' => 'Desconectar',
|
||||
|
||||
'descriptions' => [
|
||||
'linkedin' => 'Conecta tu perfil personal de LinkedIn',
|
||||
'linkedin' => 'Conecta tu perfil de LinkedIn o página de empresa',
|
||||
'linkedin-page' => 'Conecta una página de empresa de LinkedIn',
|
||||
'x' => 'Conecta tu cuenta de X (Twitter)',
|
||||
'tiktok' => 'Conecta tu cuenta de TikTok',
|
||||
|
|
@ -83,6 +83,8 @@
|
|||
'no_pages' => 'No se encontraron páginas',
|
||||
'no_pages_description' => 'No eres administrador de ninguna página de Facebook.',
|
||||
'page_label' => 'Página de Facebook',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Elegir',
|
||||
],
|
||||
|
||||
'instagram_facebook' => [
|
||||
|
|
@ -90,6 +92,8 @@
|
|||
'description' => 'Elige qué cuenta de Instagram deseas conectar',
|
||||
'no_pages' => 'No se encontraron cuentas de Instagram',
|
||||
'no_pages_description' => 'No se encontraron páginas de Facebook con cuentas Instagram Business vinculadas.',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Elegir',
|
||||
],
|
||||
|
||||
'linkedin' => [
|
||||
|
|
@ -98,6 +102,12 @@
|
|||
'no_pages' => 'No se encontraron páginas',
|
||||
'no_pages_description' => 'No eres administrador de ninguna página de LinkedIn.',
|
||||
'page_label' => 'Página de LinkedIn',
|
||||
'select_title' => '¿Dónde quieres publicar?',
|
||||
'select_subtitle' => 'Publica como tú mismo o elige una página de empresa que administres.',
|
||||
'person_tag' => 'Persona',
|
||||
'organization_tag' => 'Empresa',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Elegir',
|
||||
],
|
||||
|
||||
'flash' => [
|
||||
|
|
@ -115,7 +125,8 @@
|
|||
'title_success' => 'Conectado',
|
||||
'title_error' => 'Error',
|
||||
'closing' => 'Esta ventana se cerrará automáticamente...',
|
||||
'close_now' => 'Puedes cerrar esta ventana ahora.',
|
||||
'manual_close' => 'Puedes cerrar esta ventana.',
|
||||
'popup_blocked' => 'No se pudo abrir la ventana de conexión. Permite las ventanas emergentes e inténtalo de nuevo.',
|
||||
'connected' => '¡Cuenta conectada!',
|
||||
'reconnected' => '¡Cuenta reconectada!',
|
||||
'error_connecting' => 'Error al conectar la cuenta. Inténtalo de nuevo.',
|
||||
|
|
|
|||
|
|
@ -13,8 +13,9 @@
|
|||
|
||||
'upload' => [
|
||||
'drag_drop' => 'Arrastra y suelta tus archivos aquí o haz clic para seleccionar',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF',
|
||||
'uploading' => 'Subiendo...',
|
||||
'failed' => 'No se pudo subir :file. Inténtalo de nuevo.',
|
||||
],
|
||||
|
||||
'empty' => [
|
||||
|
|
|
|||
|
|
@ -139,11 +139,8 @@
|
|||
'settings' => 'Configuración de LinkedIn',
|
||||
'settings_page' => 'Configuración de la Página de LinkedIn',
|
||||
'posting_to' => 'Publicando en',
|
||||
'variant_label' => 'Tipo de publicación',
|
||||
'variant' => [
|
||||
'post' => 'Publicación',
|
||||
'carousel' => 'Carrusel',
|
||||
],
|
||||
'document_title' => 'Título del documento',
|
||||
'document_title_placeholder' => 'Se muestra en tu publicación de documento PDF',
|
||||
],
|
||||
'pinterest' => [
|
||||
'settings' => 'Configuración de Pinterest',
|
||||
|
|
@ -188,9 +185,13 @@
|
|||
'min_files_required' => 'Este tipo requiere al menos :min archivos (tienes :current).',
|
||||
'no_video_allowed' => 'Este tipo no acepta videos.',
|
||||
'no_image_allowed' => 'Este tipo acepta solo videos.',
|
||||
'no_document_allowed' => 'Este tipo no acepta documentos PDF.',
|
||||
'no_mixed_media' => 'No se pueden combinar imágenes y un video en la misma publicación.',
|
||||
'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.',
|
||||
'gif_not_allowed' => 'Esta red no acepta GIF. Elimínalo o selecciona otra red.',
|
||||
'image_too_large' => 'La imagen supera el límite de :max (la tuya es :current).',
|
||||
'video_too_large' => 'El video supera el límite de :max (el tuyo es :current).',
|
||||
'document_too_large' => 'El PDF supera el límite de :max (el tuyo es :current).',
|
||||
'video_too_long' => 'El video dura :current, pero este tipo permite hasta :max.',
|
||||
'aspect_ratio_too_narrow' => 'La proporción :current es demasiado alta (mínimo :min).',
|
||||
'aspect_ratio_too_wide' => 'La proporción :current es demasiado ancha (máximo :max).',
|
||||
|
|
@ -344,11 +345,15 @@
|
|||
'no_images' => 'Solo se permiten videos en este formato.',
|
||||
'no_mixed_media' => 'No se pueden combinar imágenes y videos en la misma publicación.',
|
||||
'no_gifs' => 'Los GIFs no son compatibles aquí.',
|
||||
'no_documents' => 'Los documentos PDF no son compatibles con este formato.',
|
||||
'document_not_alone' => 'Un PDF debe publicarse solo, sin otras imágenes ni videos.',
|
||||
'video_too_large' => 'El video supera el límite de tamaño de esta plataforma.',
|
||||
'video_too_long' => 'El video debe durar menos de :seconds segundos en este formato.',
|
||||
'image_too_large' => 'La imagen supera el límite de tamaño de esta plataforma.',
|
||||
'document_too_large' => 'El PDF supera el límite de tamaño de esta plataforma.',
|
||||
'aspect_ratio_invalid' => 'La proporción de aspecto no es compatible con este formato.',
|
||||
'no_content_type' => 'Elige un tipo de contenido para esta plataforma.',
|
||||
'requires_text' => 'Agrega texto — este formato necesita un título.',
|
||||
],
|
||||
'publishing' => 'Publicando...',
|
||||
'publishing_overlay_title' => 'Tu publicación se está enviando',
|
||||
|
|
@ -458,19 +463,11 @@
|
|||
],
|
||||
'linkedin_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Post estándar con texto y multimedia',
|
||||
],
|
||||
'linkedin_carousel' => [
|
||||
'label' => 'Carrusel',
|
||||
'description' => 'Imágenes deslizables',
|
||||
'description' => 'Post estándar — imagen, varias imágenes, video o PDF',
|
||||
],
|
||||
'linkedin_page_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Post estándar con texto y multimedia',
|
||||
],
|
||||
'linkedin_page_carousel' => [
|
||||
'label' => 'Carrusel',
|
||||
'description' => 'Imágenes deslizables',
|
||||
'description' => 'Post estándar — imagen, varias imágenes, video o PDF',
|
||||
],
|
||||
'facebook_post' => [
|
||||
'label' => 'Post',
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@
|
|||
'disconnect' => 'Desconectar',
|
||||
|
||||
'descriptions' => [
|
||||
'linkedin' => 'Conecte seu perfil pessoal do LinkedIn',
|
||||
'linkedin' => 'Conecte seu perfil do LinkedIn ou página de empresa',
|
||||
'linkedin-page' => 'Conecte uma página de empresa do LinkedIn',
|
||||
'x' => 'Conecte sua conta do X (Twitter)',
|
||||
'tiktok' => 'Conecte sua conta do TikTok',
|
||||
|
|
@ -83,6 +83,8 @@
|
|||
'no_pages' => 'Nenhuma página encontrada',
|
||||
'no_pages_description' => 'Você não é administrador de nenhuma página do Facebook.',
|
||||
'page_label' => 'Página do Facebook',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Escolher',
|
||||
],
|
||||
|
||||
'instagram_facebook' => [
|
||||
|
|
@ -90,6 +92,8 @@
|
|||
'description' => 'Escolha qual conta do Instagram você deseja conectar',
|
||||
'no_pages' => 'Nenhuma conta do Instagram encontrada',
|
||||
'no_pages_description' => 'Nenhuma Página do Facebook com conta Instagram Business vinculada foi encontrada.',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Escolher',
|
||||
],
|
||||
|
||||
'linkedin' => [
|
||||
|
|
@ -98,6 +102,12 @@
|
|||
'no_pages' => 'Nenhuma página encontrada',
|
||||
'no_pages_description' => 'Você não é administrador de nenhuma página do LinkedIn.',
|
||||
'page_label' => 'Página do LinkedIn',
|
||||
'select_title' => 'Onde você quer publicar?',
|
||||
'select_subtitle' => 'Publique como você mesmo ou escolha uma página de empresa que você administra.',
|
||||
'person_tag' => 'Pessoa',
|
||||
'organization_tag' => 'Empresa',
|
||||
'view' => 'Ver',
|
||||
'choose' => 'Escolher',
|
||||
],
|
||||
|
||||
'flash' => [
|
||||
|
|
@ -115,7 +125,8 @@
|
|||
'title_success' => 'Conectado',
|
||||
'title_error' => 'Erro',
|
||||
'closing' => 'Esta janela será fechada automaticamente...',
|
||||
'close_now' => 'Você pode fechar esta janela agora.',
|
||||
'manual_close' => 'Você pode fechar esta janela.',
|
||||
'popup_blocked' => 'Não foi possível abrir a janela de conexão. Permita pop-ups e tente novamente.',
|
||||
'connected' => 'Conta conectada!',
|
||||
'reconnected' => 'Conta reconectada!',
|
||||
'error_connecting' => 'Erro ao conectar conta. Por favor, tente novamente.',
|
||||
|
|
|
|||
|
|
@ -13,8 +13,9 @@
|
|||
|
||||
'upload' => [
|
||||
'drag_drop' => 'Arraste e solte seus arquivos aqui ou clique para selecionar',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4',
|
||||
'formats' => 'JPEG, PNG, GIF, WebP, MP4, PDF',
|
||||
'uploading' => 'Enviando...',
|
||||
'failed' => 'Não foi possível enviar :file. Tente novamente.',
|
||||
],
|
||||
|
||||
'empty' => [
|
||||
|
|
|
|||
|
|
@ -139,11 +139,8 @@
|
|||
'settings' => 'Configurações do LinkedIn',
|
||||
'settings_page' => 'Configurações da Página do LinkedIn',
|
||||
'posting_to' => 'Publicando em',
|
||||
'variant_label' => 'Tipo de publicação',
|
||||
'variant' => [
|
||||
'post' => 'Post',
|
||||
'carousel' => 'Carrossel',
|
||||
],
|
||||
'document_title' => 'Título do documento',
|
||||
'document_title_placeholder' => 'Aparece no seu post de documento PDF',
|
||||
],
|
||||
'pinterest' => [
|
||||
'settings' => 'Configurações do Pinterest',
|
||||
|
|
@ -188,9 +185,13 @@
|
|||
'min_files_required' => 'Este tipo exige pelo menos :min arquivos (você tem :current).',
|
||||
'no_video_allowed' => 'Este tipo não aceita vídeos.',
|
||||
'no_image_allowed' => 'Este tipo aceita apenas vídeos.',
|
||||
'no_document_allowed' => 'Este tipo não aceita documentos PDF.',
|
||||
'no_mixed_media' => 'Não dá pra combinar imagens e um vídeo no mesmo post.',
|
||||
'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.',
|
||||
'gif_not_allowed' => 'Esta rede não aceita GIF. Remova o GIF ou escolha outra rede.',
|
||||
'image_too_large' => 'A imagem passa do limite de :max (a sua tem :current).',
|
||||
'video_too_large' => 'O vídeo passa do limite de :max (o seu tem :current).',
|
||||
'document_too_large' => 'O PDF passa do limite de :max (o seu tem :current).',
|
||||
'video_too_long' => 'O vídeo dura :current, mas este tipo permite no máximo :max.',
|
||||
'aspect_ratio_too_narrow' => 'A proporção :current está muito alta (mínimo :min).',
|
||||
'aspect_ratio_too_wide' => 'A proporção :current está muito larga (máximo :max).',
|
||||
|
|
@ -344,11 +345,15 @@
|
|||
'no_images' => 'Apenas vídeos são permitidos neste formato.',
|
||||
'no_mixed_media' => 'Não é possível combinar imagem e vídeo na mesma publicação.',
|
||||
'no_gifs' => 'GIFs não são suportados aqui.',
|
||||
'no_documents' => 'Documentos PDF não são suportados por este formato.',
|
||||
'document_not_alone' => 'Um PDF precisa ser publicado sozinho, sem outras imagens ou vídeos.',
|
||||
'video_too_large' => 'Vídeo excede o limite de tamanho desta plataforma.',
|
||||
'video_too_long' => 'Vídeo deve ter menos de :seconds segundos neste formato.',
|
||||
'image_too_large' => 'Imagem excede o limite de tamanho desta plataforma.',
|
||||
'document_too_large' => 'O PDF excede o limite de tamanho desta plataforma.',
|
||||
'aspect_ratio_invalid' => 'A proporção da imagem não é suportada por este formato.',
|
||||
'no_content_type' => 'Escolha um tipo de conteúdo para esta plataforma.',
|
||||
'requires_text' => 'Adicione texto — este formato precisa de um título.',
|
||||
],
|
||||
'publishing' => 'Publicando...',
|
||||
'publishing_overlay_title' => 'Seu post está sendo publicado',
|
||||
|
|
@ -458,19 +463,11 @@
|
|||
],
|
||||
'linkedin_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Post padrão com texto e mídia',
|
||||
],
|
||||
'linkedin_carousel' => [
|
||||
'label' => 'Carrossel',
|
||||
'description' => 'Imagens deslizáveis',
|
||||
'description' => 'Post padrão — imagem, várias imagens, vídeo ou PDF',
|
||||
],
|
||||
'linkedin_page_post' => [
|
||||
'label' => 'Post',
|
||||
'description' => 'Post padrão com texto e mídia',
|
||||
],
|
||||
'linkedin_page_carousel' => [
|
||||
'label' => 'Carrossel',
|
||||
'description' => 'Imagens deslizáveis',
|
||||
'description' => 'Post padrão — imagem, várias imagens, vídeo ou PDF',
|
||||
],
|
||||
'facebook_post' => [
|
||||
'label' => 'Post',
|
||||
|
|
|
|||
|
|
@ -163,11 +163,11 @@ const selectedChannels = computed(() => props.channels.filter((channel) => isSel
|
|||
v-else-if="channel.platform === Platform.LinkedIn || channel.platform === Platform.LinkedInPage"
|
||||
:social-account="channel.socialAccount"
|
||||
:platform="channel.platform"
|
||||
:content-type="channel.contentType"
|
||||
:media="media"
|
||||
:meta="channel.meta"
|
||||
:disabled="disabled"
|
||||
:preview-only="previewOnly"
|
||||
@update:content-type="emit('update:contentType', channel.id, $event)"
|
||||
@update:meta="emit('update:meta', channel.id, $event)"
|
||||
/>
|
||||
<DiscordSettings
|
||||
v-else-if="channel.platform === Platform.Discord"
|
||||
|
|
|
|||
|
|
@ -3,13 +3,14 @@ import { IconChevronLeft, IconChevronRight } from '@tabler/icons-vue';
|
|||
import { computed, onUnmounted, ref, watch } from 'vue';
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
|
||||
import { MediaType } from '@/lib/mediaType';
|
||||
|
||||
interface MediaItem {
|
||||
interface PreviewItem {
|
||||
url: string;
|
||||
type: 'image' | 'video';
|
||||
type: MediaType;
|
||||
}
|
||||
|
||||
const items = ref<MediaItem[]>([]);
|
||||
const items = ref<PreviewItem[]>([]);
|
||||
const index = ref<number | null>(null);
|
||||
|
||||
const isOpen = computed({
|
||||
|
|
@ -27,12 +28,12 @@ const hasPrev = computed(() => safeIndex.value > 0);
|
|||
const hasNext = computed(() => safeIndex.value < items.value.length - 1);
|
||||
const showNav = computed(() => items.value.length > 1);
|
||||
|
||||
const open = (url: string, type: 'image' | 'video' = 'image') => {
|
||||
const open = (url: string, type: MediaType = MediaType.Image) => {
|
||||
items.value = [{ url, type }];
|
||||
index.value = 0;
|
||||
};
|
||||
|
||||
const openCollection = (collection: MediaItem[], startIndex = 0) => {
|
||||
const openCollection = (collection: PreviewItem[], startIndex = 0) => {
|
||||
if (collection.length === 0) return;
|
||||
items.value = [...collection];
|
||||
index.value = Math.max(0, Math.min(startIndex, collection.length - 1));
|
||||
|
|
@ -106,6 +107,15 @@ defineExpose({ open, openCollection, close });
|
|||
@click.stop
|
||||
/>
|
||||
|
||||
<iframe
|
||||
v-else-if="currentItem && currentItem.type === 'document'"
|
||||
:key="currentItem.url"
|
||||
:src="currentItem.url"
|
||||
title="PDF preview"
|
||||
class="h-[85vh] w-full rounded-2xl bg-white"
|
||||
@click.stop
|
||||
/>
|
||||
|
||||
<button
|
||||
v-if="showNav && hasPrev"
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -1,313 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { IconCloudUpload, IconPhoto, IconVideo, IconX, IconLoader2, IconPlus } from '@tabler/icons-vue';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import type { MediaItem } from '@/types/media';
|
||||
|
||||
interface Props {
|
||||
media: MediaItem[];
|
||||
maxFiles: number;
|
||||
minFiles?: number;
|
||||
acceptImages: boolean;
|
||||
acceptVideos: boolean;
|
||||
isUploading?: boolean;
|
||||
disabled?: boolean;
|
||||
aspectRatio?: string;
|
||||
variant?: 'default' | 'compact' | 'vertical';
|
||||
showGrid?: boolean;
|
||||
emptyStateText?: string;
|
||||
emptyStateSubtext?: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
minFiles: 0,
|
||||
isUploading: false,
|
||||
disabled: false,
|
||||
aspectRatio: 'aspect-square',
|
||||
variant: 'default',
|
||||
showGrid: true,
|
||||
emptyStateText: 'Drag & drop or click to upload',
|
||||
emptyStateSubtext: '',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
upload: [files: File[]];
|
||||
remove: [mediaId: string];
|
||||
}>();
|
||||
|
||||
const isDragging = ref(false);
|
||||
const fileInput = ref<HTMLInputElement | null>(null);
|
||||
|
||||
const acceptMimeTypes = computed(() => {
|
||||
const types: string[] = [];
|
||||
if (props.acceptImages) {
|
||||
types.push('image/*');
|
||||
}
|
||||
if (props.acceptVideos) {
|
||||
types.push('video/*');
|
||||
}
|
||||
return types.join(',');
|
||||
});
|
||||
|
||||
const acceptDescription = computed(() => {
|
||||
if (props.acceptImages && props.acceptVideos) {
|
||||
return props.emptyStateSubtext || 'Images or videos';
|
||||
}
|
||||
if (props.acceptImages) {
|
||||
return props.emptyStateSubtext || 'Images only';
|
||||
}
|
||||
if (props.acceptVideos) {
|
||||
return props.emptyStateSubtext || 'Videos only';
|
||||
}
|
||||
return 'No media allowed';
|
||||
});
|
||||
|
||||
const canAddMore = computed(() => props.media.length < props.maxFiles);
|
||||
const isMultiple = computed(() => props.maxFiles > 1);
|
||||
|
||||
const isValidFileType = (file: File): boolean => {
|
||||
const isImage = file.type.startsWith('image/');
|
||||
const isVideo = file.type.startsWith('video/');
|
||||
|
||||
if (isImage && !props.acceptImages) {
|
||||
return false;
|
||||
}
|
||||
if (isVideo && !props.acceptVideos) {
|
||||
return false;
|
||||
}
|
||||
return isImage || isVideo;
|
||||
};
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
if (!props.disabled && canAddMore.value) {
|
||||
isDragging.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragging.value = false;
|
||||
};
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragging.value = false;
|
||||
|
||||
if (props.disabled || !canAddMore.value || !e.dataTransfer?.files) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
processFiles(files);
|
||||
};
|
||||
|
||||
const handleFileSelect = (e: Event) => {
|
||||
const input = e.target as HTMLInputElement;
|
||||
if (!input.files || input.files.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = Array.from(input.files);
|
||||
processFiles(files);
|
||||
|
||||
// Reset input
|
||||
input.value = '';
|
||||
};
|
||||
|
||||
const processFiles = (files: File[]) => {
|
||||
// Filter valid files
|
||||
const validFiles = files.filter(isValidFileType);
|
||||
|
||||
if (validFiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Limit to remaining slots
|
||||
const remainingSlots = props.maxFiles - props.media.length;
|
||||
const filesToUpload = validFiles.slice(0, remainingSlots);
|
||||
|
||||
emit('upload', filesToUpload);
|
||||
};
|
||||
|
||||
const openFilePicker = () => {
|
||||
if (!props.disabled && canAddMore.value) {
|
||||
fileInput.value?.click();
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = (mediaId: string) => {
|
||||
emit('remove', mediaId);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="relative"
|
||||
@dragover="handleDragOver"
|
||||
@dragleave="handleDragLeave"
|
||||
@drop="handleDrop"
|
||||
>
|
||||
<!-- Empty state: dropzone -->
|
||||
<div
|
||||
v-if="media.length === 0"
|
||||
class="flex flex-col items-center justify-center cursor-pointer transition-all duration-200"
|
||||
:class="[
|
||||
aspectRatio,
|
||||
isDragging
|
||||
? 'bg-primary/5 border-primary border-2 border-dashed'
|
||||
: 'bg-muted/50 hover:bg-muted/70 border-2 border-dashed border-muted-foreground/20 hover:border-muted-foreground/40',
|
||||
variant === 'vertical' ? 'rounded-2xl' : 'rounded-lg',
|
||||
disabled ? 'opacity-50 cursor-not-allowed' : '',
|
||||
]"
|
||||
@click="openFilePicker"
|
||||
>
|
||||
<div v-if="isUploading" class="flex flex-col items-center gap-3">
|
||||
<div class="p-4 rounded-full bg-muted">
|
||||
<IconLoader2 class="h-8 w-8 text-muted-foreground animate-spin" />
|
||||
</div>
|
||||
<p class="text-sm text-muted-foreground">Uploading...</p>
|
||||
</div>
|
||||
<div v-else class="flex flex-col items-center gap-3">
|
||||
<div class="p-4 rounded-full bg-muted">
|
||||
<IconCloudUpload v-if="isDragging" class="h-8 w-8 text-primary" />
|
||||
<IconVideo v-else-if="acceptVideos && !acceptImages" class="h-8 w-8 text-muted-foreground" />
|
||||
<IconPhoto v-else class="h-8 w-8 text-muted-foreground" />
|
||||
</div>
|
||||
<div class="text-center">
|
||||
<p class="text-sm font-medium text-muted-foreground">{{ emptyStateText }}</p>
|
||||
<p class="text-xs text-muted-foreground/70 mt-1">{{ acceptDescription }}</p>
|
||||
<p v-if="maxFiles > 1" class="text-xs text-muted-foreground/50 mt-1">
|
||||
Up to {{ maxFiles }} {{ maxFiles === 1 ? 'file' : 'files' }}
|
||||
<span v-if="minFiles && minFiles > 1">(min {{ minFiles }})</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Media grid with thumbnails -->
|
||||
<div v-else>
|
||||
<div
|
||||
v-if="showGrid && media.length > 1"
|
||||
class="grid gap-2"
|
||||
:class="media.length === 2 ? 'grid-cols-2' : 'grid-cols-3'"
|
||||
>
|
||||
<div
|
||||
v-for="item in media"
|
||||
:key="item.id"
|
||||
class="relative group aspect-square rounded-lg overflow-hidden bg-muted"
|
||||
>
|
||||
<img
|
||||
v-if="item.type === 'image'"
|
||||
:src="item.url"
|
||||
:alt="item.original_filename"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<video
|
||||
v-else
|
||||
:src="item.url"
|
||||
class="w-full h-full object-cover bg-black"
|
||||
muted
|
||||
playsinline
|
||||
/>
|
||||
<!-- Video indicator -->
|
||||
<div
|
||||
v-if="item.type === 'video'"
|
||||
class="absolute bottom-1 left-1 bg-black/60 text-white text-[10px] px-1.5 py-0.5 rounded flex items-center gap-0.5"
|
||||
>
|
||||
<IconVideo class="h-3 w-3" />
|
||||
</div>
|
||||
<!-- Remove button -->
|
||||
<button
|
||||
v-if="!disabled"
|
||||
type="button"
|
||||
@click.stop="handleRemove(item.id)"
|
||||
class="absolute top-1 right-1 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<IconX class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<!-- Add more button -->
|
||||
<button
|
||||
v-if="canAddMore && !disabled"
|
||||
type="button"
|
||||
@click="openFilePicker"
|
||||
class="aspect-square rounded-lg border-2 border-dashed border-muted-foreground/20 hover:border-muted-foreground/40 flex items-center justify-center transition-colors"
|
||||
:class="isUploading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-muted/50'"
|
||||
>
|
||||
<IconLoader2 v-if="isUploading" class="h-6 w-6 text-muted-foreground animate-spin" />
|
||||
<IconPlus v-else class="h-6 w-6 text-muted-foreground" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Single media display -->
|
||||
<div
|
||||
v-else
|
||||
class="relative group overflow-hidden bg-muted"
|
||||
:class="[aspectRatio, variant === 'vertical' ? 'rounded-2xl' : 'rounded-lg']"
|
||||
>
|
||||
<img
|
||||
v-if="media[0].type === 'image'"
|
||||
:src="media[0].url"
|
||||
:alt="media[0].original_filename"
|
||||
class="w-full h-full object-cover"
|
||||
/>
|
||||
<video
|
||||
v-else
|
||||
:src="media[0].url"
|
||||
class="w-full h-full object-cover bg-black"
|
||||
muted
|
||||
loop
|
||||
playsinline
|
||||
/>
|
||||
<!-- Video indicator -->
|
||||
<div
|
||||
v-if="media[0].type === 'video'"
|
||||
class="absolute bottom-2 left-2 bg-black/60 text-white text-xs px-2 py-1 rounded-full flex items-center gap-1"
|
||||
>
|
||||
<IconVideo class="h-3.5 w-3.5" />
|
||||
<span>Video</span>
|
||||
</div>
|
||||
<!-- Remove button -->
|
||||
<button
|
||||
v-if="!disabled"
|
||||
type="button"
|
||||
@click.stop="handleRemove(media[0].id)"
|
||||
class="absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<IconX class="h-4 w-4" />
|
||||
</button>
|
||||
<!-- Carousel indicator (if more than 1 and not showing grid) -->
|
||||
<div v-if="media.length > 1 && !showGrid" class="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1">
|
||||
<div
|
||||
v-for="(_, index) in media.slice(0, 5)"
|
||||
:key="index"
|
||||
class="w-1.5 h-1.5 rounded-full"
|
||||
:class="index === 0 ? 'bg-white' : 'bg-white/50'"
|
||||
/>
|
||||
<span v-if="media.length > 5" class="text-white text-[10px] ml-1">+{{ media.length - 5 }}</span>
|
||||
</div>
|
||||
<!-- Upload more overlay (if can add more and single display) -->
|
||||
<button
|
||||
v-if="canAddMore && !disabled && !showGrid"
|
||||
type="button"
|
||||
@click="openFilePicker"
|
||||
class="absolute bottom-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<IconPlus class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Hidden file input -->
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
:accept="acceptMimeTypes"
|
||||
:multiple="isMultiple"
|
||||
class="hidden"
|
||||
@change="handleFileSelect"
|
||||
:disabled="disabled || isUploading"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -3,6 +3,7 @@ import { router } from '@inertiajs/vue3';
|
|||
import { IconAlertTriangle, IconCheck, IconPlus } from '@tabler/icons-vue';
|
||||
import { trans } from 'laravel-vue-i18n';
|
||||
import { computed, ref } from 'vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
|
||||
import TelegramConnectDialog from '@/components/accounts/TelegramConnectDialog.vue';
|
||||
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
|
||||
|
|
@ -21,6 +22,7 @@ export interface AvailablePlatform {
|
|||
export interface ConnectedAccount {
|
||||
id: string;
|
||||
platform: string;
|
||||
network: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
avatar_url: string | null;
|
||||
|
|
@ -44,8 +46,8 @@ const getPlatformDescription = (platform: string): string =>
|
|||
|
||||
// Mirrors `NetworksGrid.vue` from the marketing site — pastel tile bg
|
||||
// + ink 2px border + slight rotation per platform, real PNG logo inside.
|
||||
// `linkedin-page` / `instagram-facebook` fall back to the base brand
|
||||
// image and same color since they're variants of the same network.
|
||||
// `instagram-facebook` falls back to the base brand image and same color
|
||||
// since it's a variant of the same network.
|
||||
const platformTheme: Record<
|
||||
string,
|
||||
{ bg: string; rotate: string; image: string }
|
||||
|
|
@ -70,11 +72,6 @@ const platformTheme: Record<
|
|||
rotate: '-rotate-1',
|
||||
image: '/images/accounts/linkedin.png',
|
||||
},
|
||||
'linkedin-page': {
|
||||
bg: 'bg-blue-200',
|
||||
rotate: '-rotate-1',
|
||||
image: '/images/accounts/linkedin.png',
|
||||
},
|
||||
x: {
|
||||
bg: 'bg-amber-200',
|
||||
rotate: 'rotate-2',
|
||||
|
|
@ -125,20 +122,14 @@ const platformTheme: Record<
|
|||
const themeFor = (value: string) =>
|
||||
platformTheme[value] ?? { bg: 'bg-muted', rotate: '', image: '' };
|
||||
|
||||
const networkOf = (value: string): string =>
|
||||
props.platforms.find((platform) => platform.value === value)?.network ??
|
||||
value;
|
||||
|
||||
// One account per network: map each connected network to its account so every
|
||||
// platform card belonging to that network reflects the connection.
|
||||
const connectedByNetwork = computed((): Record<string, ConnectedAccount> => {
|
||||
const map: Record<string, ConnectedAccount> = {};
|
||||
|
||||
for (const account of props.connectedAccounts) {
|
||||
const network = networkOf(account.platform);
|
||||
|
||||
if (!map[network]) {
|
||||
map[network] = account;
|
||||
if (!map[account.network]) {
|
||||
map[account.network] = account;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -163,8 +154,14 @@ const disconnectModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(
|
|||
null,
|
||||
);
|
||||
|
||||
const { openOAuthPopup } = useOAuthPopup(() => {
|
||||
router.reload();
|
||||
const { openOAuthPopup } = useOAuthPopup((result) => {
|
||||
if (result.success) {
|
||||
toast.success(result.message);
|
||||
router.reload();
|
||||
return;
|
||||
}
|
||||
|
||||
toast.error(result.message);
|
||||
});
|
||||
|
||||
const disconnectAccount = (account: ConnectedAccount) => {
|
||||
|
|
@ -177,6 +174,9 @@ const disconnectAccount = (account: ConnectedAccount) => {
|
|||
const needsReconnect = (account: ConnectedAccount): boolean =>
|
||||
account.status === 'disconnected' || account.status === 'token_expired';
|
||||
|
||||
const connectEntryFor = (platformValue: string): string =>
|
||||
platformValue === Platform.LinkedInPage ? Platform.LinkedIn : platformValue;
|
||||
|
||||
const openConnect = (platformValue: string) => {
|
||||
if (platformValue === Platform.Telegram) {
|
||||
telegramOpen.value = true;
|
||||
|
|
@ -195,7 +195,7 @@ const connectPlatform = (platformValue: string) => {
|
|||
};
|
||||
|
||||
const reconnectAccount = (account: ConnectedAccount) => {
|
||||
openConnect(account.platform);
|
||||
openConnect(connectEntryFor(account.platform));
|
||||
};
|
||||
|
||||
const CardState = {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup lang="ts">
|
||||
import { router, useHttp } from '@inertiajs/vue3';
|
||||
import { IconCloudUpload, IconLoader2, IconPencilPlus, IconPhoto, IconPlus, IconSearch, IconTrash } from '@tabler/icons-vue';
|
||||
import { IconCloudUpload, IconFileTypePdf, IconLoader2, IconPencilPlus, IconPhoto, IconPlus, IconSearch, IconTrash } from '@tabler/icons-vue';
|
||||
import { trans } from 'laravel-vue-i18n';
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
|
|
@ -14,6 +14,7 @@ import { Skeleton } from '@/components/ui/skeleton';
|
|||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import debounce from '@/debounce';
|
||||
import { acceptAttribute, classify, isDocument, isVideo, MediaType } from '@/lib/mediaType';
|
||||
import { destroy as assetsDestroy, search as assetsSearch, storeChunked as assetsStoreChunked, storeFromUrl } from '@/routes/app/assets';
|
||||
import { search as giphySearch, trending as giphyTrending } from '@/routes/app/assets/giphy';
|
||||
import { search as unsplashSearch, trending as unsplashTrending } from '@/routes/app/assets/unsplash';
|
||||
|
|
@ -24,7 +25,7 @@ interface AssetMedia {
|
|||
id: string;
|
||||
path: string;
|
||||
url: string;
|
||||
type: string;
|
||||
type: MediaType;
|
||||
mime_type: string;
|
||||
original_filename: string;
|
||||
size: number;
|
||||
|
|
@ -59,7 +60,7 @@ interface SavedMedia {
|
|||
id: string;
|
||||
path: string;
|
||||
url: string;
|
||||
type: string;
|
||||
type: MediaType;
|
||||
mime_type: string;
|
||||
}
|
||||
|
||||
|
|
@ -67,7 +68,7 @@ interface PickedMedia {
|
|||
id: string;
|
||||
path: string;
|
||||
url: string;
|
||||
type: string;
|
||||
type: MediaType;
|
||||
mime_type: string;
|
||||
original_filename?: string;
|
||||
size?: number;
|
||||
|
|
@ -84,6 +85,9 @@ const selected = defineModel<PickedMedia[]>('selected', { default: () => [] });
|
|||
|
||||
const isPicker = computed(() => props.mode === 'picker');
|
||||
|
||||
// The upload file picker accepts everything the backend's Media\Type allow-list does.
|
||||
const acceptedUploadTypes = acceptAttribute();
|
||||
|
||||
const lightbox = ref<InstanceType<typeof ImagePreviewDialog> | null>(null);
|
||||
|
||||
const handleAssetClick = (asset: AssetMedia) => {
|
||||
|
|
@ -93,7 +97,7 @@ const handleAssetClick = (asset: AssetMedia) => {
|
|||
}
|
||||
const items = uploads.value.map((a) => ({
|
||||
url: a.url,
|
||||
type: a.type === 'video' ? ('video' as const) : ('image' as const),
|
||||
type: classify(a) ?? MediaType.Image,
|
||||
}));
|
||||
const idx = uploads.value.findIndex((a) => a.id === asset.id);
|
||||
lightbox.value?.openCollection(items, idx);
|
||||
|
|
@ -134,6 +138,9 @@ const toggleSelect = (asset: AssetMedia | SavedMedia, extra?: Partial<PickedMedi
|
|||
url: asset.url,
|
||||
type: asset.type,
|
||||
mime_type: asset.mime_type,
|
||||
original_filename: 'original_filename' in asset ? asset.original_filename : undefined,
|
||||
size: 'size' in asset ? asset.size : undefined,
|
||||
meta: 'meta' in asset ? (asset.meta ?? undefined) : undefined,
|
||||
...extra,
|
||||
},
|
||||
];
|
||||
|
|
@ -242,7 +249,7 @@ const uploadFiles = async (files: File[]) => {
|
|||
collection: 'assets',
|
||||
});
|
||||
} catch {
|
||||
// ignore individual failure
|
||||
toast.error(trans('assets.upload.failed', { file: file.name }));
|
||||
}
|
||||
}
|
||||
uploading.value = false;
|
||||
|
|
@ -617,7 +624,7 @@ onUnmounted(() => {
|
|||
type="file"
|
||||
class="hidden"
|
||||
multiple
|
||||
accept="image/jpeg,image/png,image/gif,image/webp,video/mp4"
|
||||
:accept="acceptedUploadTypes"
|
||||
@change="handleFileSelect"
|
||||
/>
|
||||
<div v-if="uploading" class="absolute inset-0 flex items-center justify-center rounded-2xl bg-card/85">
|
||||
|
|
@ -655,19 +662,26 @@ onUnmounted(() => {
|
|||
:key="asset.id"
|
||||
class="group relative overflow-hidden rounded-xl border-2 border-foreground bg-muted shadow-2xs transition-all hover:-translate-y-0.5 hover:shadow-md"
|
||||
:class="[
|
||||
(isPicker || asset.type !== 'video') ? 'cursor-pointer' : '',
|
||||
'cursor-pointer',
|
||||
isPicker && isSelected(asset.id) ? 'ring-2 ring-primary ring-offset-2 ring-offset-background' : '',
|
||||
]"
|
||||
@click="handleAssetClick(asset)"
|
||||
>
|
||||
<div class="aspect-square">
|
||||
<video
|
||||
v-if="asset.type === 'video'"
|
||||
v-if="isVideo(asset)"
|
||||
:src="asset.url"
|
||||
class="size-full object-cover"
|
||||
muted
|
||||
preload="metadata"
|
||||
/>
|
||||
<div
|
||||
v-else-if="isDocument(asset)"
|
||||
class="flex size-full flex-col items-center justify-center gap-1.5 bg-rose-50 p-3 text-center"
|
||||
>
|
||||
<IconFileTypePdf class="size-9 text-rose-600" />
|
||||
<span class="line-clamp-2 break-all text-[11px] font-medium text-foreground/70">{{ asset.original_filename }}</span>
|
||||
</div>
|
||||
<img
|
||||
v-else
|
||||
:src="asset.url"
|
||||
|
|
|
|||
|
|
@ -213,7 +213,7 @@ const getBoards = (account: SocialAccount): PinterestBoard[] =>
|
|||
|
||||
// Image-capability is derived from the SAME media rules the post editor uses
|
||||
// (per content type), never a hardcoded list — facebook_post, tiktok_photo,
|
||||
// linkedin_carousel etc. all accept multiple images. We cap AI image generation
|
||||
// linkedin_post etc. all accept multiple images. We cap AI image generation
|
||||
// at MAX_GENERATED_IMAGES regardless of how many a platform technically allows.
|
||||
const MAX_GENERATED_IMAGES = 10;
|
||||
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ import { computed, ref } from 'vue';
|
|||
import GalleryBrowser from '@/components/assets/GalleryBrowser.vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { type MediaType } from '@/lib/mediaType';
|
||||
|
||||
interface PickedMedia {
|
||||
id: string;
|
||||
path: string;
|
||||
url: string;
|
||||
type: string;
|
||||
type: MediaType;
|
||||
mime_type: string;
|
||||
original_filename?: string;
|
||||
size?: number;
|
||||
|
|
|
|||
|
|
@ -1,12 +1,13 @@
|
|||
<script setup lang="ts">
|
||||
import { IconAlertTriangle, IconChevronDown, IconChevronUp } from '@tabler/icons-vue';
|
||||
import { IconChevronDown, IconChevronUp } from '@tabler/icons-vue';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Avatar } from '@/components/ui/avatar';
|
||||
import { getMediaValidationWarning } from '@/composables/useMedia';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { isDocumentMedia } from '@/composables/useMedia';
|
||||
import { getPlatformLogo } from '@/composables/usePlatformLogo';
|
||||
import { ContentType } from '@/types/content-type';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
import { Platform } from '@/types/platform';
|
||||
|
||||
interface SocialAccount {
|
||||
id: string;
|
||||
|
|
@ -19,47 +20,43 @@ interface SocialAccount {
|
|||
interface Props {
|
||||
socialAccount: SocialAccount | null;
|
||||
platform: string;
|
||||
contentType: string;
|
||||
media: MediaItem[];
|
||||
meta?: Record<string, any>;
|
||||
disabled?: boolean;
|
||||
previewOnly?: boolean;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
meta: () => ({}),
|
||||
disabled: false,
|
||||
previewOnly: false,
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:contentType': [value: string];
|
||||
'update:meta': [value: Record<string, any>];
|
||||
}>();
|
||||
|
||||
const open = ref(false);
|
||||
|
||||
const isPage = computed(() => props.platform === 'linkedin-page');
|
||||
const isPage = computed(() => props.platform === Platform.LinkedInPage);
|
||||
|
||||
const variants = computed(() =>
|
||||
isPage.value
|
||||
? [
|
||||
{ value: ContentType.LinkedInPagePost, labelKey: 'posts.form.linkedin.variant.post' },
|
||||
{ value: ContentType.LinkedInPageCarousel, labelKey: 'posts.form.linkedin.variant.carousel' },
|
||||
]
|
||||
: [
|
||||
{ value: ContentType.LinkedInPost, labelKey: 'posts.form.linkedin.variant.post' },
|
||||
{ value: ContentType.LinkedInCarousel, labelKey: 'posts.form.linkedin.variant.carousel' },
|
||||
],
|
||||
const pdfDocument = computed(
|
||||
() => props.media.find((item) => isDocumentMedia(item)) ?? null,
|
||||
);
|
||||
|
||||
const pickVariant = (value: string) => {
|
||||
if (props.disabled) return;
|
||||
emit('update:contentType', value);
|
||||
};
|
||||
const hasPdf = computed(() => pdfDocument.value !== null);
|
||||
|
||||
const warning = computed(() => getMediaValidationWarning(props.contentType, props.media));
|
||||
const documentTitle = computed({
|
||||
get: () =>
|
||||
(props.meta?.document_title as string | undefined) ||
|
||||
pdfDocument.value?.original_filename ||
|
||||
'',
|
||||
set: (value: string) => emit('update:meta', { ...props.meta, document_title: value || null }),
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl border-2 border-foreground bg-card shadow-2xs">
|
||||
<div v-if="hasPdf" class="rounded-xl border-2 border-foreground bg-card shadow-2xs">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full cursor-pointer items-center justify-between gap-3 p-4 text-sm"
|
||||
|
|
@ -93,31 +90,14 @@ const warning = computed(() => getMediaValidationWarning(props.contentType, prop
|
|||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.linkedin.variant_label') }}</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="variant in variants"
|
||||
:key="variant.value"
|
||||
type="button"
|
||||
class="cursor-pointer rounded-full border-2 px-3 py-1 text-xs font-bold uppercase tracking-widest transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="contentType === variant.value
|
||||
? 'border-foreground bg-violet-100 text-foreground shadow-2xs'
|
||||
: 'border-foreground/30 text-foreground/70 hover:border-foreground hover:text-foreground'"
|
||||
:disabled="disabled"
|
||||
@click="pickVariant(variant.value)"
|
||||
>
|
||||
{{ $t(variant.labelKey) }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-[11px] font-black uppercase tracking-widest text-foreground/60">{{ $t('posts.form.linkedin.document_title') }}</p>
|
||||
<Input
|
||||
v-model="documentTitle"
|
||||
type="text"
|
||||
:placeholder="$t('posts.form.linkedin.document_title_placeholder')"
|
||||
:disabled="disabled || previewOnly"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="warning && !previewOnly"
|
||||
class="flex items-start gap-2 rounded-lg border-2 border-foreground bg-rose-50 p-2 text-xs font-semibold text-rose-700"
|
||||
>
|
||||
<IconAlertTriangle class="mt-0.5 size-3.5 shrink-0" />
|
||||
{{ $t(`posts.form.warnings.${warning.key}`, warning.params) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
<script setup lang="ts">
|
||||
import {
|
||||
IconAlertTriangle,
|
||||
IconFileTypePdf,
|
||||
IconGripVertical,
|
||||
IconHash,
|
||||
IconLibraryPhoto,
|
||||
|
|
@ -22,6 +23,8 @@ import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover'
|
|||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { formatBytes } from '@/composables/useMedia';
|
||||
import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';
|
||||
import date from '@/date';
|
||||
import { classify, isDocument, isVideo, MediaType } from '@/lib/mediaType';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
|
||||
interface Signature {
|
||||
|
|
@ -78,22 +81,12 @@ const openPreview = (item: MediaItem) => {
|
|||
lightbox.value?.openCollection(
|
||||
media.value.map((m) => ({
|
||||
url: m.url,
|
||||
type: isVideo(m) ? 'video' as const : 'image' as const,
|
||||
type: classify(m) ?? MediaType.Image,
|
||||
})),
|
||||
idx,
|
||||
);
|
||||
};
|
||||
|
||||
const isVideo = (item: MediaItem): boolean =>
|
||||
item.type === 'video' || Boolean(item.mime_type?.startsWith('video/'));
|
||||
|
||||
const formatDuration = (seconds: number): string => {
|
||||
const total = Math.round(seconds);
|
||||
const m = Math.floor(total / 60);
|
||||
const s = total % 60;
|
||||
return `${m}:${s.toString().padStart(2, '0')}`;
|
||||
};
|
||||
|
||||
const limitsWithUsage = computed(() =>
|
||||
props.platformLimits.map((p) => {
|
||||
const used = content.value.length;
|
||||
|
|
@ -245,6 +238,13 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
|
|||
class="h-full w-full object-cover"
|
||||
muted
|
||||
/>
|
||||
<div
|
||||
v-else-if="isDocument(item)"
|
||||
class="flex h-full w-full flex-col items-center justify-center gap-1 bg-rose-50 p-2 text-center"
|
||||
>
|
||||
<IconFileTypePdf class="size-7 text-rose-600" />
|
||||
<span class="line-clamp-2 break-all text-[10px] font-medium text-foreground/70">{{ item.original_filename || 'PDF' }}</span>
|
||||
</div>
|
||||
<img
|
||||
v-else
|
||||
:src="item.url"
|
||||
|
|
@ -261,7 +261,7 @@ const canRegenerateWithAi = (item: MediaItem): boolean => props.allowAiRegenerat
|
|||
class="inline-flex items-center gap-0.5 rounded-md bg-black/65 px-1.5 py-0.5 backdrop-blur-sm"
|
||||
>
|
||||
<IconVideo class="size-2.5" />
|
||||
{{ formatDuration(item.meta.duration) }}
|
||||
{{ date.formatClock(item.meta.duration) }}
|
||||
</span>
|
||||
<span
|
||||
v-if="item.size"
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import LabelBadge from '@/components/labels/LabelBadge.vue';
|
|||
import { Badge } from '@/components/ui/badge';
|
||||
import { usePageErrors } from '@/composables/usePageErrors';
|
||||
import { getPlatformLogo } from '@/composables/usePlatformLogo';
|
||||
import { isVideo } from '@/lib/mediaType';
|
||||
import type { PinterestBoard } from '@/types';
|
||||
import type { Channel } from '@/types/channel';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
|
|
@ -97,7 +98,7 @@ const getBoards = (pp: PostPlatform): PinterestBoard[] =>
|
|||
pp.social_account_id ? props.pinterestBoards?.[pp.social_account_id] ?? [] : [];
|
||||
|
||||
const videoDurationSec = computed(() => {
|
||||
const video = props.media?.find((m) => m.type === 'video' || m.mime_type?.startsWith('video/'));
|
||||
const video = props.media?.find((m) => isVideo(m));
|
||||
const duration = video?.meta?.duration;
|
||||
return typeof duration === 'number' ? Math.ceil(duration) : null;
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup lang="ts">
|
||||
import VideoPreview from "@/components/posts/previews/VideoPreview.vue";
|
||||
import { isVideoMedia } from '@/composables/useMedia';
|
||||
import { isDocumentMedia, isVideoMedia } from '@/composables/useMedia';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
|
||||
interface SocialAccount {
|
||||
|
|
@ -77,7 +77,12 @@ defineProps<Props>();
|
|||
'row-span-2': media.length === 3 && index === 0,
|
||||
'aspect-square': media.length > 1,
|
||||
}">
|
||||
<img v-if="!isVideoMedia(item)" :src="item.url" :alt="item.original_filename"
|
||||
<div v-if="isDocumentMedia(item)" class="aspect-[4/5] w-full bg-[#f4f2ee] dark:bg-[#38434f]">
|
||||
<iframe :src="`${item.url}#toolbar=0&navpanes=0&view=FitH`"
|
||||
:title="item.original_filename || 'PDF document'"
|
||||
class="h-full w-full border-0" loading="lazy" />
|
||||
</div>
|
||||
<img v-else-if="!isVideoMedia(item)" :src="item.url" :alt="item.original_filename"
|
||||
class="w-full h-full object-cover" />
|
||||
<VideoPreview v-else :src="item.url" video-class="w-full h-full object-cover bg-black" />
|
||||
<div v-if="media.length > 4 && index === 3"
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
import { ref } from 'vue';
|
||||
|
||||
export interface DragAndDropOptions {
|
||||
acceptImages: boolean;
|
||||
acceptVideos: boolean;
|
||||
maxFiles: number;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function useDragAndDrop(options: DragAndDropOptions) {
|
||||
const isDragging = ref(false);
|
||||
|
||||
const isValidFileType = (file: File): boolean => {
|
||||
const isImage = file.type.startsWith('image/');
|
||||
const isVideo = file.type.startsWith('video/');
|
||||
|
||||
if (isImage && !options.acceptImages) {
|
||||
return false;
|
||||
}
|
||||
if (isVideo && !options.acceptVideos) {
|
||||
return false;
|
||||
}
|
||||
return isImage || isVideo;
|
||||
};
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
if (!options.disabled) {
|
||||
isDragging.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
isDragging.value = false;
|
||||
};
|
||||
|
||||
const handleDrop = (e: DragEvent, currentMediaCount: number, onUpload: (files: File[]) => void) => {
|
||||
e.preventDefault();
|
||||
isDragging.value = false;
|
||||
|
||||
if (options.disabled || !e.dataTransfer?.files) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
const validFiles = files.filter(isValidFileType);
|
||||
|
||||
if (validFiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Limit to remaining slots
|
||||
const remainingSlots = options.maxFiles - currentMediaCount;
|
||||
const filesToUpload = validFiles.slice(0, remainingSlots);
|
||||
|
||||
if (filesToUpload.length > 0) {
|
||||
onUpload(filesToUpload);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
isDragging,
|
||||
handleDragOver,
|
||||
handleDragLeave,
|
||||
handleDrop,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,8 +1,16 @@
|
|||
import { getMediaRulesForContentType } from '@/composables/useMediaRules';
|
||||
import date from '@/date';
|
||||
import { isDocument, isGif, isImage, isVideo } from '@/lib/mediaType';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
|
||||
export type { MediaItem } from '@/types/media';
|
||||
|
||||
// Media-type detection lives in '@/lib/mediaType' — these aliases keep the
|
||||
// names the rest of the app already imports from here pointing at it.
|
||||
export const isVideoMedia = isVideo;
|
||||
export const isDocumentMedia = isDocument;
|
||||
export const isImageMedia = isImage;
|
||||
|
||||
export interface MediaValidationWarning {
|
||||
key: string; // short key, e.g. 'gif_not_allowed'
|
||||
params: Record<string, string>;
|
||||
|
|
@ -15,14 +23,6 @@ export const formatBytes = (bytes: number): string => {
|
|||
return bytes + ' B';
|
||||
};
|
||||
|
||||
const formatDuration = (seconds: number): string => {
|
||||
const s = Math.round(seconds);
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
const rem = s % 60;
|
||||
return rem === 0 ? `${m}min` : `${m}min ${rem}s`;
|
||||
};
|
||||
|
||||
const formatAspect = (ratio: number): string => ratio.toFixed(2);
|
||||
|
||||
/**
|
||||
|
|
@ -37,9 +37,10 @@ export const getMediaValidationWarning = (
|
|||
if (! contentType) return { key: 'no_variant', params: {} };
|
||||
|
||||
const rules = getMediaRulesForContentType(contentType);
|
||||
const videos = media.filter((m) => m.type === 'video' || m.mime_type?.startsWith('video/'));
|
||||
const images = media.filter((m) => m.type === 'image' || m.mime_type?.startsWith('image/'));
|
||||
const gifs = media.filter((m) => m.mime_type === 'image/gif');
|
||||
const videos = media.filter(isVideo);
|
||||
const documents = media.filter(isDocument);
|
||||
const images = media.filter(isImage);
|
||||
const gifs = media.filter(isGif);
|
||||
const total = media.length;
|
||||
|
||||
if (rules.requiresMedia && total === 0) {
|
||||
|
|
@ -57,18 +58,36 @@ export const getMediaValidationWarning = (
|
|||
if (! rules.acceptImages && images.length > 0) {
|
||||
return { key: 'no_image_allowed', params: {} };
|
||||
}
|
||||
if (! rules.acceptDocuments && documents.length > 0) {
|
||||
return { key: 'no_document_allowed', params: {} };
|
||||
}
|
||||
if (rules.forbidsMixedMedia && videos.length > 0 && images.length > 0) {
|
||||
return { key: 'no_mixed_media', params: {} };
|
||||
}
|
||||
if (rules.acceptDocuments && documents.length > 0 && total > 1) {
|
||||
return { key: 'document_not_alone', params: {} };
|
||||
}
|
||||
if (! rules.acceptsGif && gifs.length > 0) {
|
||||
return { key: 'gif_not_allowed', params: {} };
|
||||
}
|
||||
|
||||
for (const m of media) {
|
||||
const isVideo = m.type === 'video' || m.mime_type?.startsWith('video/');
|
||||
const size = m.size ?? 0;
|
||||
const width = m.meta?.width ?? 0;
|
||||
const height = m.meta?.height ?? 0;
|
||||
const duration = m.meta?.duration ?? 0;
|
||||
|
||||
if (isVideo) {
|
||||
if (isDocument(m)) {
|
||||
if (rules.maxDocumentBytes && size > rules.maxDocumentBytes) {
|
||||
return {
|
||||
key: 'document_too_large',
|
||||
params: { max: formatBytes(rules.maxDocumentBytes), current: formatBytes(size) },
|
||||
};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isVideo(m)) {
|
||||
if (rules.maxVideoBytes && size > rules.maxVideoBytes) {
|
||||
return {
|
||||
key: 'video_too_large',
|
||||
|
|
@ -78,7 +97,7 @@ export const getMediaValidationWarning = (
|
|||
if (rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {
|
||||
return {
|
||||
key: 'video_too_long',
|
||||
params: { max: formatDuration(rules.maxVideoDurationSec), current: formatDuration(duration) },
|
||||
params: { max: date.formatDurationWords(rules.maxVideoDurationSec), current: date.formatDurationWords(duration) },
|
||||
};
|
||||
}
|
||||
} else if (rules.maxImageBytes && size > rules.maxImageBytes) {
|
||||
|
|
@ -118,19 +137,27 @@ export const getMediaItemIssue = (item: MediaItem, contentType: string): string
|
|||
if (! contentType) return null;
|
||||
|
||||
const rules = getMediaRulesForContentType(contentType);
|
||||
const isVideo = item.type === 'video' || Boolean(item.mime_type?.startsWith('video/'));
|
||||
const isGif = item.mime_type === 'image/gif';
|
||||
const itemIsVideo = isVideo(item);
|
||||
const itemIsDocument = isDocument(item);
|
||||
const itemIsGif = isGif(item);
|
||||
|
||||
if (isVideo && ! rules.acceptVideos) return 'no_video_allowed';
|
||||
if (! isVideo && ! rules.acceptImages) return 'no_image_allowed';
|
||||
if (isGif && ! rules.acceptsGif) return 'gif_not_allowed';
|
||||
if (itemIsDocument) {
|
||||
if (! rules.acceptDocuments) return 'no_document_allowed';
|
||||
const docSize = item.size ?? 0;
|
||||
if (rules.maxDocumentBytes && docSize > rules.maxDocumentBytes) return 'document_too_large';
|
||||
return null;
|
||||
}
|
||||
|
||||
if (itemIsVideo && ! rules.acceptVideos) return 'no_video_allowed';
|
||||
if (! itemIsVideo && ! rules.acceptImages) return 'no_image_allowed';
|
||||
if (itemIsGif && ! rules.acceptsGif) return 'gif_not_allowed';
|
||||
|
||||
const size = item.size ?? 0;
|
||||
if (isVideo && rules.maxVideoBytes && size > rules.maxVideoBytes) return 'video_too_large';
|
||||
if (! isVideo && rules.maxImageBytes && size > rules.maxImageBytes) return 'image_too_large';
|
||||
if (itemIsVideo && rules.maxVideoBytes && size > rules.maxVideoBytes) return 'video_too_large';
|
||||
if (! itemIsVideo && rules.maxImageBytes && size > rules.maxImageBytes) return 'image_too_large';
|
||||
|
||||
const duration = item.meta?.duration ?? 0;
|
||||
if (isVideo && rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {
|
||||
if (itemIsVideo && rules.maxVideoDurationSec && duration > rules.maxVideoDurationSec) {
|
||||
return 'video_too_long';
|
||||
}
|
||||
|
||||
|
|
@ -144,14 +171,3 @@ export const getMediaItemIssue = (item: MediaItem, contentType: string): string
|
|||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const isVideoMedia = (item: MediaItem | null | undefined): boolean => {
|
||||
if (! item) return false;
|
||||
return item.type === 'video' || Boolean(item.mime_type?.startsWith('video/'));
|
||||
};
|
||||
|
||||
export const isImageMedia = (item: MediaItem | null | undefined): boolean => {
|
||||
if (! item) return false;
|
||||
if (isVideoMedia(item)) return false;
|
||||
return true;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,15 +1,19 @@
|
|||
import { computed, type Ref, type ComputedRef } from 'vue';
|
||||
|
||||
import { fromMimeType, MediaType } from '@/lib/mediaType';
|
||||
|
||||
export interface MediaRules {
|
||||
maxFiles: number;
|
||||
minFiles?: number;
|
||||
acceptImages: boolean;
|
||||
acceptVideos: boolean;
|
||||
acceptDocuments?: boolean;
|
||||
requiresMedia: boolean;
|
||||
acceptsGif: boolean;
|
||||
forbidsMixedMedia?: boolean;
|
||||
maxImageBytes?: number;
|
||||
maxVideoBytes?: number;
|
||||
maxDocumentBytes?: number;
|
||||
maxVideoDurationSec?: number;
|
||||
aspectRatioMin?: number;
|
||||
aspectRatioMax?: number;
|
||||
|
|
@ -58,28 +62,18 @@ const CONTENT_TYPE_RULES: Record<string, MediaRules> = {
|
|||
aspectRatioMin: 0.5, aspectRatioMax: 0.6,
|
||||
},
|
||||
|
||||
// LinkedIn
|
||||
// LinkedIn — one type per account kind; the publish format (single image,
|
||||
// multi-image, video, or PDF document) is inferred from the attached media.
|
||||
// Images (up to 10) XOR one video XOR one PDF, never mixed.
|
||||
linkedin_post: {
|
||||
maxFiles: 1, acceptImages: true, acceptVideos: true, requiresMedia: false,
|
||||
acceptsGif: false,
|
||||
maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60,
|
||||
},
|
||||
linkedin_carousel: {
|
||||
maxFiles: 20, acceptImages: true, acceptVideos: false, requiresMedia: true,
|
||||
acceptsGif: false,
|
||||
maxImageBytes: 5 * MB,
|
||||
aspectRatioMin: 0.5, aspectRatioMax: 1,
|
||||
maxFiles: 10, acceptImages: true, acceptVideos: true, acceptDocuments: true,
|
||||
requiresMedia: false, acceptsGif: false, forbidsMixedMedia: true,
|
||||
maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, maxDocumentBytes: 100 * MB,
|
||||
},
|
||||
linkedin_page_post: {
|
||||
maxFiles: 1, acceptImages: true, acceptVideos: true, requiresMedia: false,
|
||||
acceptsGif: false,
|
||||
maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60,
|
||||
},
|
||||
linkedin_page_carousel: {
|
||||
maxFiles: 20, acceptImages: true, acceptVideos: false, requiresMedia: true,
|
||||
acceptsGif: false,
|
||||
maxImageBytes: 5 * MB,
|
||||
aspectRatioMin: 0.5, aspectRatioMax: 1,
|
||||
maxFiles: 10, acceptImages: true, acceptVideos: true, acceptDocuments: true,
|
||||
requiresMedia: false, acceptsGif: false, forbidsMixedMedia: true,
|
||||
maxImageBytes: 5 * MB, maxVideoBytes: 5 * GB, maxVideoDurationSec: 10 * 60, maxDocumentBytes: 100 * MB,
|
||||
},
|
||||
|
||||
// TikTok
|
||||
|
|
@ -169,6 +163,9 @@ export function useMediaRules(contentType: Ref<string> | ComputedRef<string>) {
|
|||
if (rules.value.acceptVideos) {
|
||||
types.push('video/*');
|
||||
}
|
||||
if (rules.value.acceptDocuments) {
|
||||
types.push('application/pdf');
|
||||
}
|
||||
return types.join(',');
|
||||
});
|
||||
|
||||
|
|
@ -178,20 +175,25 @@ export function useMediaRules(contentType: Ref<string> | ComputedRef<string>) {
|
|||
|
||||
const isValidFileType = computed(() => {
|
||||
return (file: File): boolean => {
|
||||
const isImage = file.type.startsWith('image/');
|
||||
const isVideo = file.type.startsWith('video/');
|
||||
const type = fromMimeType(file.type);
|
||||
|
||||
if (isImage && !rules.value.acceptImages) {
|
||||
if (type === MediaType.Image && !rules.value.acceptImages) {
|
||||
return false;
|
||||
}
|
||||
if (isVideo && !rules.value.acceptVideos) {
|
||||
if (type === MediaType.Video && !rules.value.acceptVideos) {
|
||||
return false;
|
||||
}
|
||||
return isImage || isVideo;
|
||||
if (type === MediaType.Document) {
|
||||
return Boolean(rules.value.acceptDocuments);
|
||||
}
|
||||
return type === MediaType.Image || type === MediaType.Video;
|
||||
};
|
||||
});
|
||||
|
||||
const getAcceptDescription = computed<string>(() => {
|
||||
if (rules.value.acceptDocuments && !rules.value.acceptImages && !rules.value.acceptVideos) {
|
||||
return 'PDF document';
|
||||
}
|
||||
if (rules.value.acceptImages && rules.value.acceptVideos) {
|
||||
return 'Images or videos';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,30 +1,81 @@
|
|||
import { trans } from 'laravel-vue-i18n';
|
||||
import { onMounted, onUnmounted } from 'vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
|
||||
import { connect as blueskyConnect } from '@/routes/app/social/bluesky';
|
||||
import { connect as discordConnect } from '@/routes/app/social/discord';
|
||||
import { connect as facebookConnect } from '@/routes/app/social/facebook';
|
||||
import { connect as instagramConnect } from '@/routes/app/social/instagram';
|
||||
import { connect as instagramFacebookConnect } from '@/routes/app/social/instagram-facebook';
|
||||
import { connect as linkedinConnect } from '@/routes/app/social/linkedin';
|
||||
import { connect as mastodonConnect } from '@/routes/app/social/mastodon';
|
||||
import { connect as pinterestConnect } from '@/routes/app/social/pinterest';
|
||||
import { connect as threadsConnect } from '@/routes/app/social/threads';
|
||||
import { connect as tiktokConnect } from '@/routes/app/social/tiktok';
|
||||
import { connect as xConnect } from '@/routes/app/social/x';
|
||||
import { connect as youtubeConnect } from '@/routes/app/social/youtube';
|
||||
import { Platform } from '@/types/platform';
|
||||
|
||||
const POPUP_WIDTH = 600;
|
||||
const POPUP_HEIGHT = 700;
|
||||
|
||||
const CONNECT_ROUTES: Record<string, { url: () => string }> = {
|
||||
[Platform.Bluesky]: blueskyConnect,
|
||||
[Platform.Discord]: discordConnect,
|
||||
[Platform.Facebook]: facebookConnect,
|
||||
[Platform.Instagram]: instagramConnect,
|
||||
[Platform.InstagramFacebook]: instagramFacebookConnect,
|
||||
[Platform.LinkedIn]: linkedinConnect,
|
||||
[Platform.Mastodon]: mastodonConnect,
|
||||
[Platform.Pinterest]: pinterestConnect,
|
||||
[Platform.Threads]: threadsConnect,
|
||||
[Platform.TikTok]: tiktokConnect,
|
||||
[Platform.X]: xConnect,
|
||||
[Platform.YouTube]: youtubeConnect,
|
||||
};
|
||||
|
||||
export interface SocialOAuthResult {
|
||||
success: boolean;
|
||||
message: string;
|
||||
platform: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a platform's `/connect/{platform}` OAuth flow in a centered popup and
|
||||
* invokes `onSuccess` when the popup posts back the `social-oauth-callback`
|
||||
* message. The listener is wired to the calling component's lifecycle.
|
||||
* Opens a platform's OAuth connect flow in a centered popup and invokes
|
||||
* `onResult` with the popup's `{success, message}` outcome. The listener is
|
||||
* wired to the calling component's lifecycle.
|
||||
*/
|
||||
export const useOAuthPopup = (onSuccess: () => void) => {
|
||||
export const useOAuthPopup = (onResult: (result: SocialOAuthResult) => void) => {
|
||||
const openOAuthPopup = (platform: string) => {
|
||||
const route = CONNECT_ROUTES[platform];
|
||||
|
||||
if (!route) {
|
||||
return;
|
||||
}
|
||||
|
||||
const left = window.screenX + (window.outerWidth - POPUP_WIDTH) / 2;
|
||||
const top = window.screenY + (window.outerHeight - POPUP_HEIGHT) / 2;
|
||||
|
||||
window.open(
|
||||
`/connect/${platform}`,
|
||||
const popup = window.open(
|
||||
route.url(),
|
||||
'oauth-popup',
|
||||
`width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},scrollbars=yes,resizable=yes`,
|
||||
);
|
||||
|
||||
if (!popup) {
|
||||
toast.error(trans('accounts.popup_callback.popup_blocked'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== window.location.origin) return;
|
||||
if (event.data?.type !== 'social-oauth-callback') return;
|
||||
|
||||
onSuccess();
|
||||
onResult({
|
||||
success: Boolean(event.data.success),
|
||||
message: String(event.data.message ?? ''),
|
||||
platform: event.data.platform ?? null,
|
||||
});
|
||||
};
|
||||
|
||||
onMounted(() => window.addEventListener('message', handleMessage));
|
||||
|
|
|
|||
|
|
@ -39,8 +39,8 @@ const PLATFORM_CONTENT_TYPES: Record<string, string[]> = {
|
|||
'instagram_reel',
|
||||
'instagram_story',
|
||||
],
|
||||
linkedin: ['linkedin_post', 'linkedin_carousel'],
|
||||
'linkedin-page': ['linkedin_page_post', 'linkedin_page_carousel'],
|
||||
linkedin: ['linkedin_post'],
|
||||
'linkedin-page': ['linkedin_page_post'],
|
||||
facebook: ['facebook_post', 'facebook_reel', 'facebook_story'],
|
||||
tiktok: ['tiktok_video'],
|
||||
youtube: ['youtube_short'],
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { trans } from 'laravel-vue-i18n';
|
||||
import { computed, type ComputedRef, type Ref } from 'vue';
|
||||
|
||||
import { getMediaItemIssue } from '@/composables/useMedia';
|
||||
import { getMediaItemIssue, getMediaValidationWarning } from '@/composables/useMedia';
|
||||
import { getMediaRulesForContentType } from '@/composables/useMediaRules';
|
||||
import { getPlatformLabel } from '@/composables/usePlatformLogo';
|
||||
import { ContentType } from '@/types/content-type';
|
||||
|
|
@ -24,12 +24,16 @@ export const PLATFORM_VARIANTS: Record<string, string[]> = {
|
|||
[Platform.Facebook]: [ContentType.FacebookPost, ContentType.FacebookReel, ContentType.FacebookStory],
|
||||
[Platform.Instagram]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory],
|
||||
[Platform.InstagramFacebook]: [ContentType.InstagramFeed, ContentType.InstagramReel, ContentType.InstagramStory],
|
||||
[Platform.LinkedIn]: [ContentType.LinkedInPost, ContentType.LinkedInCarousel],
|
||||
[Platform.LinkedInPage]: [ContentType.LinkedInPagePost, ContentType.LinkedInPageCarousel],
|
||||
[Platform.LinkedIn]: [ContentType.LinkedInPost],
|
||||
[Platform.LinkedInPage]: [ContentType.LinkedInPagePost],
|
||||
[Platform.TikTok]: [ContentType.TikTokVideo, ContentType.TikTokPhoto],
|
||||
[Platform.Pinterest]: [ContentType.PinterestPin, ContentType.PinterestVideoPin, ContentType.PinterestCarousel],
|
||||
};
|
||||
|
||||
// Content types whose post needs text to publish — YouTube Shorts derive their
|
||||
// required title from the post content, so an empty post can't be scheduled.
|
||||
const CONTENT_TYPES_REQUIRING_TEXT = new Set<string>([ContentType.YouTubeShort]);
|
||||
|
||||
type MetaRule = (meta: Record<string, any>) => { valid: boolean; tooltipKey: string | null };
|
||||
|
||||
// Platforms whose `meta` blob has publish-time requirements. `valid` gates
|
||||
|
|
@ -86,48 +90,47 @@ export const getPlatformMetaIssue = (platform: string, meta: Record<string, any>
|
|||
return result.tooltipKey ? trans(result.tooltipKey) : trans('posts.edit.compliance_incomplete');
|
||||
};
|
||||
|
||||
// The editor's compliance copy keyed by the shared media-warning core's key.
|
||||
// Detection + rule evaluation live once in getMediaValidationWarning; only the
|
||||
// wording (and a couple of params) differ between the settings dialogs and this
|
||||
// publish gate.
|
||||
const COMPLIANCE_KEY_BY_WARNING: Record<string, string> = {
|
||||
no_variant: 'no_content_type',
|
||||
requires_media: 'requires_media',
|
||||
max_files_exceeded: 'too_many_files',
|
||||
min_files_required: 'too_few_files',
|
||||
no_video_allowed: 'no_videos',
|
||||
no_image_allowed: 'no_images',
|
||||
no_document_allowed: 'no_documents',
|
||||
no_mixed_media: 'no_mixed_media',
|
||||
document_not_alone: 'document_not_alone',
|
||||
gif_not_allowed: 'no_gifs',
|
||||
image_too_large: 'image_too_large',
|
||||
video_too_large: 'video_too_large',
|
||||
document_too_large: 'document_too_large',
|
||||
video_too_long: 'video_too_long',
|
||||
aspect_ratio_too_narrow: 'aspect_ratio_invalid',
|
||||
aspect_ratio_too_wide: 'aspect_ratio_invalid',
|
||||
};
|
||||
|
||||
export const getMediaIncompatibilityReason = (
|
||||
contentType: string,
|
||||
mediaItems: MediaItem[],
|
||||
): string | null => {
|
||||
const rules = getMediaRulesForContentType(contentType);
|
||||
const videos = mediaItems.filter((m) => m.type === 'video' || m.mime_type?.startsWith('video/'));
|
||||
const images = mediaItems.filter((m) => m.type === 'image' || m.mime_type?.startsWith('image/'));
|
||||
const gifs = mediaItems.filter((m) => m.mime_type === 'image/gif');
|
||||
const total = mediaItems.length;
|
||||
const warning = getMediaValidationWarning(contentType, mediaItems);
|
||||
if (!warning) return null;
|
||||
|
||||
if (rules.requiresMedia && total === 0) return trans('posts.edit.compliance.requires_media');
|
||||
if (!rules.acceptVideos && videos.length > 0) return trans('posts.edit.compliance.no_videos');
|
||||
if (!rules.acceptImages && images.length > 0) return trans('posts.edit.compliance.no_images');
|
||||
if (rules.forbidsMixedMedia && videos.length > 0 && images.length > 0) return trans('posts.edit.compliance.no_mixed_media');
|
||||
if (!rules.acceptsGif && gifs.length > 0) return trans('posts.edit.compliance.no_gifs');
|
||||
if (total > rules.maxFiles) return trans('posts.edit.compliance.too_many_files', { max: String(rules.maxFiles) });
|
||||
if (rules.minFiles && total < rules.minFiles) return trans('posts.edit.compliance.too_few_files', { min: String(rules.minFiles) });
|
||||
const complianceKey = COMPLIANCE_KEY_BY_WARNING[warning.key];
|
||||
if (!complianceKey) return trans('posts.edit.compliance_incomplete');
|
||||
|
||||
for (const m of mediaItems) {
|
||||
const isVideo = m.type === 'video' || m.mime_type?.startsWith('video/');
|
||||
const size = m.size ?? 0;
|
||||
const duration = m.meta?.duration ?? 0;
|
||||
const width = m.meta?.width ?? 0;
|
||||
const height = m.meta?.height ?? 0;
|
||||
|
||||
if (isVideo) {
|
||||
if (rules.maxVideoBytes && size > 0 && size > rules.maxVideoBytes) return trans('posts.edit.compliance.video_too_large');
|
||||
if (rules.maxVideoDurationSec && duration > 0 && duration > rules.maxVideoDurationSec) {
|
||||
return trans('posts.edit.compliance.video_too_long', { seconds: String(rules.maxVideoDurationSec) });
|
||||
}
|
||||
} else if (rules.maxImageBytes && size > 0 && size > rules.maxImageBytes) {
|
||||
return trans('posts.edit.compliance.image_too_large');
|
||||
}
|
||||
|
||||
if (width > 0 && height > 0 && (rules.aspectRatioMin || rules.aspectRatioMax)) {
|
||||
const ratio = width / height;
|
||||
if (rules.aspectRatioMin && ratio < rules.aspectRatioMin) return trans('posts.edit.compliance.aspect_ratio_invalid');
|
||||
if (rules.aspectRatioMax && ratio > rules.aspectRatioMax) return trans('posts.edit.compliance.aspect_ratio_invalid');
|
||||
}
|
||||
const params: Record<string, string> = {};
|
||||
if (warning.key === 'max_files_exceeded') params.max = warning.params.max;
|
||||
if (warning.key === 'min_files_required') params.min = warning.params.min;
|
||||
if (warning.key === 'video_too_long') {
|
||||
params.seconds = String(getMediaRulesForContentType(contentType).maxVideoDurationSec ?? '');
|
||||
}
|
||||
|
||||
return null;
|
||||
return trans(`posts.edit.compliance.${complianceKey}`, params);
|
||||
};
|
||||
|
||||
export const firstCompatibleVariant = (
|
||||
|
|
@ -199,6 +202,11 @@ export const usePostCompliance = (opts: UsePostComplianceOptions) => {
|
|||
continue;
|
||||
}
|
||||
|
||||
if (CONTENT_TYPES_REQUIRING_TEXT.has(contentType) && content.value.trim() === '') {
|
||||
issues[pp.id] = trans('posts.edit.compliance.requires_text');
|
||||
continue;
|
||||
}
|
||||
|
||||
const reason = getMediaIncompatibilityReason(contentType, media.value);
|
||||
if (!reason) continue;
|
||||
|
||||
|
|
|
|||
|
|
@ -214,4 +214,50 @@ export default {
|
|||
}
|
||||
return `${m}min`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Format seconds as a clock (m:ss, or h:mm:ss past one hour).
|
||||
* For media badges and stopwatches (e.g. "5:30", "1:05:30").
|
||||
*/
|
||||
formatClock(seconds: number): string {
|
||||
const d = dayjs.duration(Math.round(seconds), 'seconds');
|
||||
|
||||
return d.asHours() >= 1 ? d.format('H:mm:ss') : d.format('m:ss');
|
||||
},
|
||||
|
||||
/**
|
||||
* Format seconds as short words (e.g. "45s", "5min", "5min 30s").
|
||||
*/
|
||||
formatDurationWords(seconds: number): string {
|
||||
const s = Math.round(seconds);
|
||||
if (s < 60) {
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
const m = Math.floor(s / 60);
|
||||
const rem = s % 60;
|
||||
|
||||
return rem === 0 ? `${m}min` : `${m}min ${rem}s`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Format a duration in milliseconds (e.g. "—", "500ms", "1.5s", "2m 30s").
|
||||
*/
|
||||
formatDurationMs(ms: number | null | undefined): string {
|
||||
if (ms == null) {
|
||||
return '—';
|
||||
}
|
||||
if (ms < 1000) {
|
||||
return `${Math.round(ms)}ms`;
|
||||
}
|
||||
|
||||
const seconds = ms / 1000;
|
||||
if (seconds < 60) {
|
||||
return `${seconds.toFixed(1)}s`;
|
||||
}
|
||||
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
|
||||
return `${minutes}m ${Math.round(seconds % 60)}s`;
|
||||
},
|
||||
};
|
||||
|
|
|
|||
88
resources/js/lib/mediaType.ts
Normal file
88
resources/js/lib/mediaType.ts
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/**
|
||||
* Single source of truth for media-type detection on the frontend — the mirror
|
||||
* of the backend `App\Enums\Media\Type`. Every "is this an image / video / PDF?"
|
||||
* check goes through here so the answer can't drift between components.
|
||||
*/
|
||||
|
||||
export const MediaType = {
|
||||
Image: 'image',
|
||||
Video: 'video',
|
||||
Document: 'document',
|
||||
} as const;
|
||||
|
||||
export type MediaType = (typeof MediaType)[keyof typeof MediaType];
|
||||
|
||||
/** MIME allow-list we accept on upload — mirrors Type::allowedMimeTypes(). */
|
||||
export const ALLOWED_MIME_TYPES: Record<MediaType, readonly string[]> = {
|
||||
[MediaType.Image]: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
|
||||
[MediaType.Video]: ['video/mp4', 'video/quicktime'],
|
||||
[MediaType.Document]: ['application/pdf'],
|
||||
};
|
||||
|
||||
// Broader than the upload allow-list so already-stored files in legacy formats
|
||||
// still resolve — mirrors Type::fromExtension() on the backend.
|
||||
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'heic', 'heif'];
|
||||
const VIDEO_EXTENSIONS = ['mp4', 'mov', 'avi', 'wmv', 'webm', 'mkv', 'm4v'];
|
||||
|
||||
const GIF_MIME = 'image/gif';
|
||||
const PDF_MIME = 'application/pdf';
|
||||
|
||||
/** The `accept` attribute value for a file input that takes any media we allow. */
|
||||
export const acceptAttribute = (): string => Object.values(ALLOWED_MIME_TYPES).flat().join(',');
|
||||
|
||||
/** The structural shape every classifiable media item satisfies. */
|
||||
interface ClassifiableMedia {
|
||||
type?: string | null;
|
||||
mime_type?: string | null;
|
||||
original_filename?: string | null;
|
||||
path?: string | null;
|
||||
}
|
||||
|
||||
/** Resolve a MediaType from a raw MIME string (e.g. a browser `File.type`). */
|
||||
export const fromMimeType = (mime: string | null | undefined): MediaType | null => {
|
||||
const value = mime ?? '';
|
||||
|
||||
if (value.startsWith('image/')) return MediaType.Image;
|
||||
if (value.startsWith('video/')) return MediaType.Video;
|
||||
if (value === PDF_MIME) return MediaType.Document;
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Resolve a MediaType from a filename or path extension. */
|
||||
export const fromExtension = (nameOrPath: string | null | undefined): MediaType | null => {
|
||||
if (! nameOrPath) return null;
|
||||
|
||||
const ext = nameOrPath.split('.').pop()?.toLowerCase() ?? '';
|
||||
|
||||
if (IMAGE_EXTENSIONS.includes(ext)) return MediaType.Image;
|
||||
if (VIDEO_EXTENSIONS.includes(ext)) return MediaType.Video;
|
||||
if (ext === 'pdf') return MediaType.Document;
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Classify a media item. Trusts the server-assigned `type` first, then the MIME,
|
||||
* then falls back to the filename extension so already-stored items still
|
||||
* resolve. Returns null only when nothing identifies the item.
|
||||
*/
|
||||
export const classify = (item: ClassifiableMedia | null | undefined): MediaType | null => {
|
||||
if (! item) return null;
|
||||
|
||||
const explicit = item.type;
|
||||
if (explicit === MediaType.Image || explicit === MediaType.Video || explicit === MediaType.Document) {
|
||||
return explicit;
|
||||
}
|
||||
|
||||
return fromMimeType(item.mime_type) ?? fromExtension(item.original_filename ?? item.path);
|
||||
};
|
||||
|
||||
export const isImage = (item: ClassifiableMedia | null | undefined): boolean => classify(item) === MediaType.Image;
|
||||
|
||||
export const isVideo = (item: ClassifiableMedia | null | undefined): boolean => classify(item) === MediaType.Video;
|
||||
|
||||
export const isDocument = (item: ClassifiableMedia | null | undefined): boolean => classify(item) === MediaType.Document;
|
||||
|
||||
/** Whether the item is an animated GIF — several platforms treat it specially. */
|
||||
export const isGif = (item: ClassifiableMedia | null | undefined): boolean => (item?.mime_type ?? '') === GIF_MIME;
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
<script setup lang="ts">
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { IconInfoCircle } from '@tabler/icons-vue';
|
||||
import { trans } from 'laravel-vue-i18n';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
|
@ -10,56 +10,40 @@ import { Label } from '@/components/ui/label';
|
|||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { store as storeBluesky } from '@/routes/app/social/bluesky';
|
||||
|
||||
interface Props {
|
||||
errors?: Record<string, string>;
|
||||
}
|
||||
const form = useForm({ identifier: '', password: '' });
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
const identifier = ref('');
|
||||
const password = ref('');
|
||||
const isSubmitting = ref(false);
|
||||
|
||||
const submit = () => {
|
||||
isSubmitting.value = true;
|
||||
formRef.value?.submit();
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
|
||||
const onSubmit = () => form.post(storeBluesky.url());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.bluesky.title')">
|
||||
<div class="max-w-md mx-auto">
|
||||
<div class="flex items-center gap-3 mb-6">
|
||||
<img src="/images/accounts/bluesky.png" alt="Bluesky" class="h-12 w-12" />
|
||||
<img src="/images/accounts/bluesky.png" alt="Bluesky" class="h-10 w-10" />
|
||||
<div>
|
||||
<h1 class="text-xl font-bold tracking-tight">{{ $t('accounts.bluesky.title') }}</h1>
|
||||
<p class="text-sm text-muted-foreground">{{ $t('accounts.bluesky.description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form ref="formRef" :action="storeBluesky.url()" method="POST" @submit.prevent="submit" class="space-y-4">
|
||||
<input type="hidden" name="_token" :value="csrfToken" />
|
||||
|
||||
<form @submit.prevent="onSubmit" class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="identifier">{{ $t('accounts.bluesky.email') }}</Label>
|
||||
<Input id="identifier" name="identifier" v-model="identifier" type="text"
|
||||
:placeholder="trans('accounts.bluesky.email_placeholder')" :class="{ 'border-destructive': errors?.identifier }"
|
||||
<Input id="identifier" v-model="form.identifier" type="text"
|
||||
:placeholder="trans('accounts.bluesky.email_placeholder')" :class="{ 'border-destructive': form.errors.identifier }"
|
||||
/>
|
||||
<p v-if="errors?.identifier" class="text-sm text-destructive">
|
||||
{{ errors.identifier }}
|
||||
<p v-if="form.errors.identifier" class="text-sm text-destructive">
|
||||
{{ form.errors.identifier }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label for="password">{{ $t('accounts.bluesky.app_password') }}</Label>
|
||||
<Input id="password" name="password" v-model="password" type="password"
|
||||
:placeholder="trans('accounts.bluesky.app_password_placeholder')" :class="{ 'border-destructive': errors?.password }"
|
||||
<Input id="password" v-model="form.password" type="password"
|
||||
:placeholder="trans('accounts.bluesky.app_password_placeholder')" :class="{ 'border-destructive': form.errors.password }"
|
||||
/>
|
||||
<p v-if="errors?.password" class="text-sm text-destructive">
|
||||
{{ errors.password }}
|
||||
<p v-if="form.errors.password" class="text-sm text-destructive">
|
||||
{{ form.errors.password }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
@ -70,10 +54,10 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button type="submit" :disabled="isSubmitting" class="w-full">
|
||||
{{ isSubmitting ? $t('accounts.bluesky.submitting') : $t('accounts.bluesky.submit') }}
|
||||
<Button type="submit" :disabled="form.processing" class="w-full">
|
||||
{{ form.processing ? $t('accounts.bluesky.submitting') : $t('accounts.bluesky.submit') }}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
</template>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script setup lang="ts">
|
||||
import { IconBrandFacebook, IconCheck } from '@tabler/icons-vue';
|
||||
import { ref } from 'vue';
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { IconBrandFacebook, IconExternalLink } from '@tabler/icons-vue';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { select as selectFacebookPage } from '@/routes/app/social/facebook';
|
||||
|
||||
|
|
@ -12,7 +12,6 @@ interface Page {
|
|||
name: string;
|
||||
username: string | null;
|
||||
picture: string | null;
|
||||
access_token: string;
|
||||
}
|
||||
|
||||
interface Workspace {
|
||||
|
|
@ -23,30 +22,29 @@ interface Workspace {
|
|||
interface Props {
|
||||
workspace: Workspace;
|
||||
pages: Page[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
const selectedPageId = ref<string | null>(null);
|
||||
const form = useForm({ page_id: '' });
|
||||
|
||||
const handleSelectPage = (page: Page) => {
|
||||
selectedPageId.value = page.id;
|
||||
setTimeout(() => formRef.value?.submit(), 0);
|
||||
form.page_id = page.id;
|
||||
form.post(selectFacebookPage.url());
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
|
||||
const openExternal = (url: string | null) => {
|
||||
if (url) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
}
|
||||
};
|
||||
|
||||
const pageUrl = (username: string | null): string | null =>
|
||||
username ? `https://www.facebook.com/${username}` : null;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.facebook.title')">
|
||||
<!-- Hidden form for regular POST submission -->
|
||||
<form ref="formRef" :action="selectFacebookPage.url()" method="POST" class="hidden">
|
||||
<input type="hidden" name="_token" :value="csrfToken" />
|
||||
<input type="hidden" name="page_id" :value="selectedPageId" />
|
||||
</form>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<img src="/images/accounts/facebook.png" alt="Facebook" class="h-10 w-10" />
|
||||
|
|
@ -56,11 +54,7 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<Alert v-if="error" variant="destructive">
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div v-if="pages.length === 0 && !error" class="text-center py-12">
|
||||
<div v-if="pages.length === 0" class="py-12 text-center">
|
||||
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted">
|
||||
<IconBrandFacebook class="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
|
|
@ -71,37 +65,40 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
</div>
|
||||
|
||||
<div v-else class="grid gap-3">
|
||||
<button
|
||||
<div
|
||||
v-for="page in pages"
|
||||
:key="page.id"
|
||||
@click="handleSelectPage(page)"
|
||||
class="group relative overflow-hidden rounded-lg border bg-card p-4 text-left transition-all hover:border-primary hover:shadow-md focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
|
||||
class="flex items-center gap-4 rounded-lg border bg-card p-4"
|
||||
dusk="facebook-page"
|
||||
>
|
||||
<div class="flex items-center gap-4">
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="page.picture" :src="page.picture" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-blue-100 dark:bg-blue-900">
|
||||
<IconBrandFacebook class="h-6 w-6 text-blue-600 dark:text-blue-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold truncate group-hover:text-primary transition-colors">
|
||||
{{ page.name }}
|
||||
</h3>
|
||||
<p v-if="page.username" class="text-sm text-muted-foreground truncate">
|
||||
facebook.com/{{ page.username }}
|
||||
</p>
|
||||
<p v-else class="text-sm text-muted-foreground">{{ $t('accounts.facebook.page_label') }}</p>
|
||||
</div>
|
||||
<div class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground"
|
||||
>
|
||||
<IconCheck class="h-4 w-4" />
|
||||
</div>
|
||||
</div>
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="page.picture" :src="page.picture" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-blue-100 dark:bg-blue-900">
|
||||
<IconBrandFacebook class="h-6 w-6 text-blue-600 dark:text-blue-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 class="truncate font-semibold">{{ page.name }}</h3>
|
||||
<p v-if="page.username" class="truncate text-sm text-muted-foreground">
|
||||
facebook.com/{{ page.username }}
|
||||
</p>
|
||||
<p v-else class="truncate text-sm text-muted-foreground">{{ $t('accounts.facebook.page_label') }}</p>
|
||||
</div>
|
||||
</button>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
v-if="pageUrl(page.username)"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="openExternal(pageUrl(page.username))"
|
||||
>
|
||||
<IconExternalLink class="h-4 w-4" />
|
||||
{{ $t('accounts.facebook.view') }}
|
||||
</Button>
|
||||
<Button size="sm" dusk="choose-facebook-page" :disabled="form.processing" @click="handleSelectPage(page)">
|
||||
{{ $t('accounts.facebook.choose') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script setup lang="ts">
|
||||
import { IconBrandInstagram, IconCheck } from '@tabler/icons-vue';
|
||||
import { ref } from 'vue';
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { IconBrandInstagram, IconExternalLink } from '@tabler/icons-vue';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { select as selectPage } from '@/routes/app/social/instagram-facebook';
|
||||
|
||||
|
|
@ -25,29 +25,28 @@ interface Workspace {
|
|||
interface Props {
|
||||
workspace: Workspace;
|
||||
pages: Page[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
const selectedPageId = ref<string | null>(null);
|
||||
const form = useForm({ page_id: '' });
|
||||
|
||||
const handleSelectPage = (page: Page) => {
|
||||
selectedPageId.value = page.page_id;
|
||||
setTimeout(() => formRef.value?.submit(), 0);
|
||||
form.page_id = page.page_id;
|
||||
form.post(selectPage.url());
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
|
||||
const openExternal = (url: string | null) => {
|
||||
if (url) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
}
|
||||
};
|
||||
|
||||
const igUrl = (username: string): string => `https://www.instagram.com/${username}`;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.instagram_facebook.title')">
|
||||
<form ref="formRef" :action="selectPage.url()" method="POST" class="hidden">
|
||||
<input type="hidden" name="_token" :value="csrfToken" />
|
||||
<input type="hidden" name="page_id" :value="selectedPageId" />
|
||||
</form>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<img src="/images/accounts/instagram.png" alt="Instagram" class="h-10 w-10" />
|
||||
|
|
@ -57,11 +56,7 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<Alert v-if="error" variant="destructive">
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div v-if="pages.length === 0 && !error" class="text-center py-12">
|
||||
<div v-if="pages.length === 0" class="py-12 text-center">
|
||||
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted">
|
||||
<IconBrandInstagram class="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
|
|
@ -72,34 +67,36 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
</div>
|
||||
|
||||
<div v-else class="grid gap-3">
|
||||
<button
|
||||
<div
|
||||
v-for="page in pages"
|
||||
:key="page.ig_id"
|
||||
@click="handleSelectPage(page)"
|
||||
class="group relative overflow-hidden rounded-lg border bg-card p-4 text-left transition-all hover:border-primary hover:shadow-md focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
|
||||
class="flex items-center gap-4 rounded-lg border bg-card p-4"
|
||||
dusk="instagram-page"
|
||||
>
|
||||
<div class="flex items-center gap-4">
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="page.ig_picture" :src="page.ig_picture" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-pink-100 dark:bg-pink-900">
|
||||
<IconBrandInstagram class="h-6 w-6 text-pink-600 dark:text-pink-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold truncate group-hover:text-primary transition-colors">
|
||||
@{{ page.ig_username }}
|
||||
</h3>
|
||||
<p class="text-sm text-muted-foreground truncate">
|
||||
{{ page.page_name }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground">
|
||||
<IconCheck class="h-4 w-4" />
|
||||
</div>
|
||||
</div>
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="page.ig_picture" :src="page.ig_picture" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-pink-100 dark:bg-pink-900">
|
||||
<IconBrandInstagram class="h-6 w-6 text-pink-600 dark:text-pink-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 class="truncate font-semibold">@{{ page.ig_username }}</h3>
|
||||
<p class="truncate text-sm text-muted-foreground">{{ page.page_name }}</p>
|
||||
</div>
|
||||
</button>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="openExternal(igUrl(page.ig_username))"
|
||||
>
|
||||
<IconExternalLink class="h-4 w-4" />
|
||||
{{ $t('accounts.instagram_facebook.view') }}
|
||||
</Button>
|
||||
<Button size="sm" dusk="choose-instagram-page" :disabled="form.processing" @click="handleSelectPage(page)">
|
||||
{{ $t('accounts.instagram_facebook.choose') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
|
|
|
|||
|
|
@ -1,111 +0,0 @@
|
|||
<script setup lang="ts">
|
||||
import { IconBuilding, IconCheck } from '@tabler/icons-vue';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { select as selectLinkedInPage } from '@/routes/app/social/linkedin-page';
|
||||
|
||||
interface Organization {
|
||||
id: string;
|
||||
name: string;
|
||||
vanity_name: string | null;
|
||||
logo: string | null;
|
||||
}
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
workspace: Workspace;
|
||||
organizations: Organization[];
|
||||
error?: string;
|
||||
}
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
const selectedOrg = ref<Organization | null>(null);
|
||||
|
||||
const handleSelectPage = (org: Organization) => {
|
||||
selectedOrg.value = org;
|
||||
// Submit via regular form to get Blade response
|
||||
setTimeout(() => formRef.value?.submit(), 0);
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.linkedin.title')">
|
||||
<!-- Hidden form for regular POST submission -->
|
||||
<form ref="formRef" :action="selectLinkedInPage.url()" method="POST" class="hidden">
|
||||
<input type="hidden" name="_token" :value="csrfToken" />
|
||||
<input type="hidden" name="organization_id" :value="selectedOrg?.id" />
|
||||
<input type="hidden" name="organization_name" :value="selectedOrg?.name" />
|
||||
<input type="hidden" name="organization_vanity_name" :value="selectedOrg?.vanity_name ?? ''" />
|
||||
<input type="hidden" name="organization_logo" :value="selectedOrg?.logo ?? ''" />
|
||||
</form>
|
||||
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<img src="/images/accounts/linkedin.png" alt="LinkedIn" class="h-10 w-10" />
|
||||
<div>
|
||||
<h1 class="text-xl font-bold tracking-tight">{{ $t('accounts.linkedin.title') }}</h1>
|
||||
<p class="text-sm text-muted-foreground">{{ $t('accounts.linkedin.description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Alert v-if="error" variant="destructive">
|
||||
<AlertDescription>{{ error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div v-if="organizations.length === 0 && !error" class="text-center py-12">
|
||||
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted">
|
||||
<IconBuilding class="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 class="mt-4 text-lg font-semibold">{{ $t('accounts.linkedin.no_pages') }}</h3>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
{{ $t('accounts.linkedin.no_pages_description') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid gap-3">
|
||||
<button
|
||||
v-for="org in organizations"
|
||||
:key="org.id"
|
||||
@click="handleSelectPage(org)"
|
||||
class="group relative overflow-hidden rounded-lg border bg-card p-4 text-left transition-all hover:border-primary hover:shadow-md focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
|
||||
>
|
||||
<div class="flex items-center gap-4">
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="org.logo" :src="org.logo" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-blue-100 dark:bg-blue-900">
|
||||
<IconBuilding class="h-6 w-6 text-blue-600 dark:text-blue-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="flex-1 min-w-0">
|
||||
<h3 class="font-semibold truncate group-hover:text-primary transition-colors">
|
||||
{{ org.name }}
|
||||
</h3>
|
||||
<p v-if="org.vanity_name" class="text-sm text-muted-foreground truncate">
|
||||
linkedin.com/company/{{ org.vanity_name }}
|
||||
</p>
|
||||
<p v-else class="text-sm text-muted-foreground">{{ $t('accounts.linkedin.page_label') }}</p>
|
||||
</div>
|
||||
<div class="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div
|
||||
class="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground"
|
||||
>
|
||||
<IconCheck class="h-4 w-4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
</template>
|
||||
176
resources/js/pages/accounts/LinkedInSelect.vue
Normal file
176
resources/js/pages/accounts/LinkedInSelect.vue
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
<script setup lang="ts">
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import {
|
||||
IconBuilding,
|
||||
IconExternalLink,
|
||||
IconUser,
|
||||
} from '@tabler/icons-vue';
|
||||
import { computed } from 'vue';
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { select as selectLinkedIn } from '@/routes/app/social/linkedin';
|
||||
|
||||
interface Person {
|
||||
id: string;
|
||||
name: string;
|
||||
avatar: string | null;
|
||||
vanity_name: string | null;
|
||||
}
|
||||
|
||||
interface Organization {
|
||||
id: string;
|
||||
name: string;
|
||||
vanity_name: string | null;
|
||||
logo: string | null;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
person: Person | null;
|
||||
organizations: Organization[];
|
||||
}>();
|
||||
|
||||
const form = useForm({ type: 'person', organization_id: '' });
|
||||
|
||||
const isEmpty = computed(
|
||||
() => !props.person && props.organizations.length === 0,
|
||||
);
|
||||
|
||||
const choosePerson = () => {
|
||||
form.type = 'person';
|
||||
form.organization_id = '';
|
||||
form.post(selectLinkedIn.url());
|
||||
};
|
||||
|
||||
const chooseOrganization = (org: Organization) => {
|
||||
form.type = 'organization';
|
||||
form.organization_id = org.id;
|
||||
form.post(selectLinkedIn.url());
|
||||
};
|
||||
|
||||
const openExternal = (url: string | null) => {
|
||||
if (url) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
}
|
||||
};
|
||||
|
||||
const personUrl = (vanity: string | null): string | null =>
|
||||
vanity ? `https://www.linkedin.com/in/${vanity}` : null;
|
||||
|
||||
const organizationUrl = (vanity: string | null): string | null =>
|
||||
vanity ? `https://www.linkedin.com/company/${vanity}` : null;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.linkedin.select_title')">
|
||||
<div class="flex flex-col gap-6">
|
||||
<div class="flex items-center gap-3">
|
||||
<img src="/images/accounts/linkedin.png" alt="LinkedIn" class="h-10 w-10" />
|
||||
<div>
|
||||
<h1 class="text-xl font-bold tracking-tight">
|
||||
{{ $t('accounts.linkedin.select_title') }}
|
||||
</h1>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
{{ $t('accounts.linkedin.select_subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="isEmpty" class="py-12 text-center" dusk="linkedin-identity-empty">
|
||||
<div class="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-muted">
|
||||
<IconBuilding class="h-7 w-7 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 class="mt-4 text-lg font-semibold">{{ $t('accounts.linkedin.no_pages') }}</h3>
|
||||
<p class="mt-1 text-sm text-muted-foreground">
|
||||
{{ $t('accounts.linkedin.no_pages_description') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-else class="grid gap-3">
|
||||
<div
|
||||
v-if="person"
|
||||
class="flex items-center gap-4 rounded-lg border bg-card p-4"
|
||||
dusk="linkedin-identity-person"
|
||||
>
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="person.avatar" :src="person.avatar" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-blue-100 dark:bg-blue-900">
|
||||
<IconUser class="h-6 w-6 text-blue-600 dark:text-blue-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="truncate font-semibold">{{ person.name }}</h3>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground"
|
||||
>
|
||||
<IconUser class="h-3 w-3" />
|
||||
{{ $t('accounts.linkedin.person_tag') }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="person.vanity_name" class="truncate text-sm text-muted-foreground">
|
||||
linkedin.com/in/{{ person.vanity_name }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
v-if="personUrl(person.vanity_name)"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="openExternal(personUrl(person.vanity_name))"
|
||||
>
|
||||
<IconExternalLink class="h-4 w-4" />
|
||||
{{ $t('accounts.linkedin.view') }}
|
||||
</Button>
|
||||
<Button size="sm" dusk="choose-person" :disabled="form.processing" @click="choosePerson">
|
||||
{{ $t('accounts.linkedin.choose') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="org in organizations"
|
||||
:key="org.id"
|
||||
class="flex items-center gap-4 rounded-lg border bg-card p-4"
|
||||
dusk="linkedin-identity-organization"
|
||||
>
|
||||
<Avatar class="h-12 w-12 rounded-lg">
|
||||
<AvatarImage v-if="org.logo" :src="org.logo" class="object-cover" />
|
||||
<AvatarFallback class="rounded-lg bg-blue-100 dark:bg-blue-900">
|
||||
<IconBuilding class="h-6 w-6 text-blue-600 dark:text-blue-400" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="truncate font-semibold">{{ org.name }}</h3>
|
||||
<span
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground"
|
||||
>
|
||||
<IconBuilding class="h-3 w-3" />
|
||||
{{ $t('accounts.linkedin.organization_tag') }}
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="org.vanity_name" class="truncate text-sm text-muted-foreground">
|
||||
linkedin.com/company/{{ org.vanity_name }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<Button
|
||||
v-if="organizationUrl(org.vanity_name)"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="openExternal(organizationUrl(org.vanity_name))"
|
||||
>
|
||||
<IconExternalLink class="h-4 w-4" />
|
||||
{{ $t('accounts.linkedin.view') }}
|
||||
</Button>
|
||||
<Button size="sm" dusk="choose-organization" :disabled="form.processing" @click="chooseOrganization(org)">
|
||||
{{ $t('accounts.linkedin.choose') }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
</template>
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
<script setup lang="ts">
|
||||
import { useForm } from '@inertiajs/vue3';
|
||||
import { IconInfoCircle } from '@tabler/icons-vue';
|
||||
import { trans } from 'laravel-vue-i18n';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
|
@ -10,56 +10,34 @@ import { Label } from '@/components/ui/label';
|
|||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
import { authorize as authorizeMastodon } from '@/routes/app/social/mastodon';
|
||||
|
||||
interface Props {
|
||||
errors?: Record<string, string>;
|
||||
}
|
||||
const form = useForm({ instance: 'https://mastodon.social' });
|
||||
|
||||
defineProps<Props>();
|
||||
|
||||
const formRef = ref<HTMLFormElement | null>(null);
|
||||
const instance = ref('https://mastodon.social');
|
||||
const isSubmitting = ref(false);
|
||||
|
||||
const submit = () => {
|
||||
isSubmitting.value = true;
|
||||
formRef.value?.submit();
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
|
||||
const onSubmit = () => form.post(authorizeMastodon.url());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="$t('accounts.mastodon.title')">
|
||||
<div class="max-w-md mx-auto">
|
||||
<div class="flex items-center gap-3 mb-6">
|
||||
<img src="/images/accounts/mastodon.png" alt="Mastodon" class="h-12 w-12" />
|
||||
<img src="/images/accounts/mastodon.png" alt="Mastodon" class="h-10 w-10" />
|
||||
<div>
|
||||
<h1 class="text-xl font-bold tracking-tight">{{ $t('accounts.mastodon.title') }}</h1>
|
||||
<p class="text-sm text-muted-foreground">{{ $t('accounts.mastodon.description') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form
|
||||
ref="formRef"
|
||||
:action="authorizeMastodon.url()"
|
||||
method="POST"
|
||||
@submit.prevent="submit"
|
||||
class="space-y-4"
|
||||
>
|
||||
<input type="hidden" name="_token" :value="csrfToken" />
|
||||
|
||||
<form @submit.prevent="onSubmit" class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="instance">{{ $t('accounts.mastodon.instance_url') }}</Label>
|
||||
<Input
|
||||
id="instance"
|
||||
name="instance"
|
||||
v-model="instance"
|
||||
v-model="form.instance"
|
||||
type="url"
|
||||
:placeholder="trans('accounts.mastodon.instance_placeholder')"
|
||||
:class="{ 'border-destructive': errors?.instance }"
|
||||
:class="{ 'border-destructive': form.errors.instance }"
|
||||
/>
|
||||
<p v-if="errors?.instance" class="text-sm text-destructive">
|
||||
{{ errors.instance }}
|
||||
<p v-if="form.errors.instance" class="text-sm text-destructive">
|
||||
{{ form.errors.instance }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
@ -68,8 +46,8 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
|
|||
<AlertDescription class="inline">{{ $t('accounts.mastodon.instance_hint') }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button type="submit" :disabled="isSubmitting" class="w-full">
|
||||
{{ isSubmitting ? $t('accounts.mastodon.submitting') : $t('accounts.mastodon.submit') }}
|
||||
<Button type="submit" :disabled="form.processing" class="w-full">
|
||||
{{ form.processing ? $t('accounts.mastodon.submitting') : $t('accounts.mastodon.submit') }}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
61
resources/js/pages/accounts/PopupCallback.vue
Normal file
61
resources/js/pages/accounts/PopupCallback.vue
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
<script setup lang="ts">
|
||||
import { IconCircleCheck, IconCircleX } from '@tabler/icons-vue';
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import PopupLayout from '@/layouts/PopupLayout.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
platform?: string | null;
|
||||
}>();
|
||||
|
||||
const CLOSE_DELAY = 1500;
|
||||
|
||||
// A window not opened by script can't be closed via window.close() in modern
|
||||
// browsers, so only promise an auto-close when we actually have an opener.
|
||||
const canAutoClose = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
const opener = window.opener && !window.opener.closed ? window.opener : null;
|
||||
canAutoClose.value = opener !== null;
|
||||
|
||||
if (opener) {
|
||||
try {
|
||||
opener.postMessage(
|
||||
{
|
||||
type: 'social-oauth-callback',
|
||||
success: props.success,
|
||||
message: props.message,
|
||||
platform: props.platform ?? null,
|
||||
},
|
||||
window.location.origin,
|
||||
);
|
||||
} catch {
|
||||
// Opener may be cross-origin or already gone; the timed close still applies.
|
||||
}
|
||||
|
||||
window.setTimeout(() => window.close(), CLOSE_DELAY);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopupLayout :title="success ? $t('accounts.popup_callback.title_success') : $t('accounts.popup_callback.title_error')">
|
||||
<div class="flex flex-col items-center justify-center gap-3 py-16 text-center" dusk="popup-callback" role="status" aria-live="polite">
|
||||
<div
|
||||
class="flex h-14 w-14 items-center justify-center rounded-full"
|
||||
:class="
|
||||
success
|
||||
? 'bg-green-100 text-green-600 dark:bg-green-900 dark:text-green-400'
|
||||
: 'bg-red-100 text-red-600 dark:bg-red-900 dark:text-red-400'
|
||||
"
|
||||
>
|
||||
<IconCircleCheck v-if="success" class="h-7 w-7" aria-hidden="true" />
|
||||
<IconCircleX v-else class="h-7 w-7" aria-hidden="true" />
|
||||
</div>
|
||||
<p class="text-lg font-medium text-foreground">{{ message }}</p>
|
||||
<p class="text-sm text-muted-foreground">{{ canAutoClose ? $t('accounts.popup_callback.closing') : $t('accounts.popup_callback.manual_close') }}</p>
|
||||
</div>
|
||||
</PopupLayout>
|
||||
</template>
|
||||
|
|
@ -100,14 +100,6 @@ const summary = (invocation: Invocation): string => {
|
|||
return trans('automations.invocations.summary.pending');
|
||||
};
|
||||
|
||||
const formatDuration = (ms: number | null): string => {
|
||||
if (ms === null) return '—';
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
const seconds = ms / 1000;
|
||||
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}m ${Math.round(seconds % 60)}s`;
|
||||
};
|
||||
|
||||
const stepsLabel = (count: number): string =>
|
||||
transChoice('automations.invocations.steps', count, {
|
||||
|
|
@ -362,7 +354,7 @@ const toggleExpand = async (invocation: Invocation) => {
|
|||
<TableCell
|
||||
class="text-right text-sm text-foreground/70 tabular-nums"
|
||||
>{{
|
||||
formatDuration(
|
||||
date.formatDurationMs(
|
||||
invocation.duration_ms,
|
||||
)
|
||||
}}</TableCell
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { computed, ref, watch } from 'vue';
|
|||
import AutomationDetailLayout from '@/components/automations/AutomationDetailLayout.vue';
|
||||
import AutomationRunsChart from '@/components/automations/AutomationRunsChart.vue';
|
||||
import { DateRangePicker } from '@/components/ui/date-range-picker';
|
||||
import date from '@/date';
|
||||
import dayjs from '@/dayjs';
|
||||
import type { Automation } from '@/types/automation/automation';
|
||||
|
||||
|
|
@ -47,22 +48,13 @@ watch(
|
|||
{ deep: true },
|
||||
);
|
||||
|
||||
const formatDuration = (ms: number | null): string => {
|
||||
if (ms === null) return '—';
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
const seconds = ms / 1000;
|
||||
if (seconds < 60) return `${seconds.toFixed(1)}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}m ${Math.round(seconds % 60)}s`;
|
||||
};
|
||||
|
||||
const cards = computed(() => [
|
||||
{ key: 'runs', label: 'automations.metrics.cards.runs', value: String(props.metrics.totals.runs) },
|
||||
{ key: 'completed', label: 'automations.metrics.cards.completed', value: String(props.metrics.totals.completed) },
|
||||
{ key: 'failed', label: 'automations.metrics.cards.failed', value: String(props.metrics.totals.failed) },
|
||||
{ key: 'in_progress', label: 'automations.metrics.cards.in_progress', value: String(props.metrics.totals.in_progress) },
|
||||
{ key: 'success_rate', label: 'automations.metrics.cards.success_rate', value: props.metrics.totals.success_rate === null ? '—' : `${props.metrics.totals.success_rate}%` },
|
||||
{ key: 'avg_duration', label: 'automations.metrics.cards.avg_duration', value: formatDuration(props.metrics.totals.avg_duration_ms) },
|
||||
{ key: 'avg_duration', label: 'automations.metrics.cards.avg_duration', value: date.formatDurationMs(props.metrics.totals.avg_duration_ms) },
|
||||
{ key: 'posts_created', label: 'automations.metrics.cards.posts_created', value: String(props.metrics.totals.posts_created) },
|
||||
]);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup lang="ts">
|
||||
import { Head, Link, router } from '@inertiajs/vue3';
|
||||
import { IconArrowLeft, IconCalendar, IconExternalLink, IconLoader2 } from '@tabler/icons-vue';
|
||||
import { IconArrowLeft, IconCalendar, IconExternalLink, IconFileTypePdf, IconLoader2 } from '@tabler/icons-vue';
|
||||
import { trans } from 'laravel-vue-i18n';
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
|
|
@ -17,6 +17,7 @@ import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo
|
|||
import { getPlatformStatusConfig, getPostStatusConfig } from '@/composables/usePostStatus';
|
||||
import dayjs from '@/dayjs';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { classify, isDocument as isDocumentItem, isVideo as isVideoItem, MediaType } from '@/lib/mediaType';
|
||||
import { index as postsIndex } from '@/routes/app/posts';
|
||||
import type { MediaItem } from '@/types/media';
|
||||
import { PostPlatformStatus, PostStatus } from '@/types/post';
|
||||
|
|
@ -87,13 +88,10 @@ const formatDateTime = (date: string | null): string =>
|
|||
|
||||
const lightbox = ref<InstanceType<typeof ImagePreviewDialog> | null>(null);
|
||||
|
||||
const isVideoItem = (item: MediaItem): boolean =>
|
||||
item.type === 'video' || (item.mime_type?.startsWith('video/') ?? false);
|
||||
|
||||
const openLightbox = (i: number) => {
|
||||
const collection = props.post.media.map((m) => ({
|
||||
url: m.url,
|
||||
type: isVideoItem(m) ? ('video' as const) : ('image' as const),
|
||||
type: classify(m) ?? MediaType.Image,
|
||||
}));
|
||||
lightbox.value?.openCollection(collection, i);
|
||||
};
|
||||
|
|
@ -171,6 +169,13 @@ usePostEcho(props.post.id, '.post.platform.status.updated', () => {
|
|||
class="h-full w-full object-cover"
|
||||
muted
|
||||
/>
|
||||
<div
|
||||
v-else-if="isDocumentItem(item)"
|
||||
class="flex h-full w-full flex-col items-center justify-center gap-1.5 bg-rose-50 p-2 text-center"
|
||||
>
|
||||
<IconFileTypePdf class="size-8 text-rose-600" />
|
||||
<span class="line-clamp-2 break-all text-[10px] font-medium text-foreground/70">{{ item.original_filename || 'PDF' }}</span>
|
||||
</div>
|
||||
<img
|
||||
v-else
|
||||
:src="item.url"
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { trans } from 'laravel-vue-i18n';
|
|||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import date from '@/date';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import { calendar as calendarRoute } from '@/routes/app';
|
||||
import { create as createPostRoute, edit as editPostRoute } from '@/routes/app/posts';
|
||||
|
|
@ -53,11 +54,7 @@ const currentTip = computed(() => trans(tipKeys[tipIndex.value % tipKeys.length]
|
|||
const elapsed = ref(0);
|
||||
let elapsedTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const elapsedLabel = computed(() => {
|
||||
const minutes = Math.floor(elapsed.value / 60);
|
||||
const seconds = elapsed.value % 60;
|
||||
return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||
});
|
||||
const elapsedLabel = computed(() => date.formatClock(elapsed.value));
|
||||
|
||||
const progress = computed(() => {
|
||||
const ratio = elapsed.value / estimatedSeconds.value;
|
||||
|
|
|
|||
|
|
@ -3,9 +3,7 @@ export const ContentType = {
|
|||
InstagramStory: 'instagram_story',
|
||||
InstagramReel: 'instagram_reel',
|
||||
LinkedInPost: 'linkedin_post',
|
||||
LinkedInCarousel: 'linkedin_carousel',
|
||||
LinkedInPagePost: 'linkedin_page_post',
|
||||
LinkedInPageCarousel: 'linkedin_page_carousel',
|
||||
FacebookPost: 'facebook_post',
|
||||
FacebookReel: 'facebook_reel',
|
||||
FacebookStory: 'facebook_story',
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
import type { MediaType } from '@/lib/mediaType';
|
||||
|
||||
export type MediaSource = 'ai' | 'unsplash' | 'giphy';
|
||||
|
||||
export interface MediaItem {
|
||||
id: string;
|
||||
url: string;
|
||||
path?: string;
|
||||
type?: string;
|
||||
type?: MediaType;
|
||||
mime_type?: string;
|
||||
original_filename?: string;
|
||||
size?: number;
|
||||
|
|
|
|||
|
|
@ -1,89 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>{{ $success ? __('accounts.popup_callback.title_success') : __('accounts.popup_callback.title_error') }}</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
background: #f9fafb;
|
||||
}
|
||||
.container {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
.icon {
|
||||
font-size: 3rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.message {
|
||||
color: #374151;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
.submessage {
|
||||
color: #6b7280;
|
||||
font-size: 0.875rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="icon">{{ $success ? '✓' : '✕' }}</div>
|
||||
<div class="message">{{ $message }}</div>
|
||||
<div class="submessage">{{ __('accounts.popup_callback.closing') }}</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
const result = {
|
||||
success: {{ $success ? 'true' : 'false' }},
|
||||
message: @json($message),
|
||||
platform: @json($platform ?? null)
|
||||
};
|
||||
|
||||
// Try to notify the parent window
|
||||
if (window.opener && !window.opener.closed) {
|
||||
try {
|
||||
window.opener.postMessage({
|
||||
type: 'social-oauth-callback',
|
||||
...result
|
||||
}, window.location.origin);
|
||||
} catch (e) {
|
||||
// If postMessage fails, just reload the opener
|
||||
try {
|
||||
window.opener.location.reload();
|
||||
} catch (e2) {}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to close immediately and with delay
|
||||
function closeWindow() {
|
||||
try {
|
||||
window.open('', '_self', '');
|
||||
window.close();
|
||||
} catch (e) {}
|
||||
|
||||
// Fallback: try again
|
||||
try {
|
||||
window.close();
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
// Close after a short delay
|
||||
setTimeout(closeWindow, 2000);
|
||||
|
||||
// If still open after 2 seconds, show manual close message
|
||||
setTimeout(function() {
|
||||
if (!window.closed) {
|
||||
document.querySelector('.submessage').textContent = @json(__('accounts.popup_callback.close_now'));
|
||||
}
|
||||
}, 2000);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -36,7 +36,6 @@
|
|||
use App\Http\Controllers\Auth\InstagramController;
|
||||
use App\Http\Controllers\Auth\InstagramFacebookController;
|
||||
use App\Http\Controllers\Auth\LinkedInController;
|
||||
use App\Http\Controllers\Auth\LinkedInPageController;
|
||||
use App\Http\Controllers\Auth\MastodonController;
|
||||
use App\Http\Controllers\Auth\PinterestController;
|
||||
use App\Http\Controllers\Auth\SocialController;
|
||||
|
|
@ -46,6 +45,7 @@
|
|||
use App\Http\Controllers\Auth\XController;
|
||||
use App\Http\Controllers\Auth\YouTubeController;
|
||||
use App\Http\Middleware\App\EnsureAccountReady;
|
||||
use App\Http\Middleware\App\EnsureHasWorkspace;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
// Subscription selection (requires auth but not subscription)
|
||||
|
|
@ -78,66 +78,69 @@
|
|||
|
||||
// Social Connect routes
|
||||
Route::middleware(['auth'])->group(function () {
|
||||
Route::get('connect/linkedin', [LinkedInController::class, 'connect'])->name('app.social.linkedin.connect');
|
||||
// Starting a connection reads the user's current workspace, so these require
|
||||
// one — during onboarding they redirect to workspace creation. Disconnecting
|
||||
// lives here too (and not behind EnsureAccountReady) so it works before a
|
||||
// subscription exists; the controller still authorizes workspace ownership.
|
||||
Route::middleware(EnsureHasWorkspace::class)->group(function () {
|
||||
Route::get('connect/linkedin', [LinkedInController::class, 'connect'])->name('app.social.linkedin.connect');
|
||||
Route::get('connect/x', [XController::class, 'connect'])->name('app.social.x.connect');
|
||||
Route::get('connect/tiktok', [TikTokController::class, 'connect'])->name('app.social.tiktok.connect');
|
||||
Route::get('connect/youtube', [YouTubeController::class, 'connect'])->name('app.social.youtube.connect');
|
||||
Route::get('connect/facebook', [FacebookController::class, 'connect'])->name('app.social.facebook.connect');
|
||||
Route::get('connect/instagram', [InstagramController::class, 'connect'])->name('app.social.instagram.connect');
|
||||
Route::get('connect/instagram-facebook', [InstagramFacebookController::class, 'connect'])->name('app.social.instagram-facebook.connect');
|
||||
Route::get('connect/threads', [ThreadsController::class, 'connect'])->name('app.social.threads.connect');
|
||||
Route::get('connect/pinterest', [PinterestController::class, 'connect'])->name('app.social.pinterest.connect');
|
||||
Route::get('connect/bluesky', [BlueskyController::class, 'connect'])->name('app.social.bluesky.connect');
|
||||
Route::post('connect/bluesky', [BlueskyController::class, 'store'])->name('app.social.bluesky.store');
|
||||
Route::get('connect/mastodon', [MastodonController::class, 'connect'])->name('app.social.mastodon.connect');
|
||||
Route::post('connect/mastodon', [MastodonController::class, 'authorizeInstance'])->name('app.social.mastodon.authorize');
|
||||
Route::post('connect/telegram', [TelegramController::class, 'connect'])->name('app.social.telegram.connect');
|
||||
Route::get('connect/discord', [DiscordController::class, 'connect'])->name('app.social.discord.connect');
|
||||
|
||||
Route::delete('accounts/{account}', [SocialController::class, 'disconnect'])->name('app.accounts.disconnect');
|
||||
});
|
||||
|
||||
// OAuth callbacks and identity selection resolve their workspace from the
|
||||
// session set when the flow started, then self-close the popup. They run
|
||||
// without the current-workspace gate so a momentarily missing current
|
||||
// workspace can't HTML-redirect the popup instead of closing it cleanly.
|
||||
Route::get('accounts/linkedin/callback', [LinkedInController::class, 'callback'])->name('app.social.linkedin.callback');
|
||||
Route::get('accounts/linkedin/select', [LinkedInController::class, 'selectIdentity'])->name('app.social.linkedin.select-identity');
|
||||
Route::post('accounts/linkedin/select', [LinkedInController::class, 'select'])->name('app.social.linkedin.select');
|
||||
|
||||
Route::get('connect/linkedin-page', [LinkedInPageController::class, 'connect'])->name('app.social.linkedin-page.connect');
|
||||
Route::get('accounts/linkedin-page/callback', [LinkedInPageController::class, 'callback'])->name('app.social.linkedin-page.callback');
|
||||
Route::get('accounts/linkedin-page/select', [LinkedInPageController::class, 'selectPage'])->name('app.social.linkedin-page.select-page');
|
||||
Route::post('accounts/linkedin-page/select', [LinkedInPageController::class, 'select'])->name('app.social.linkedin-page.select');
|
||||
|
||||
Route::get('connect/x', [XController::class, 'connect'])->name('app.social.x.connect');
|
||||
Route::get('accounts/x/callback', [XController::class, 'callback'])->name('app.social.x.callback');
|
||||
|
||||
Route::get('connect/tiktok', [TikTokController::class, 'connect'])->name('app.social.tiktok.connect');
|
||||
Route::get('accounts/tiktok/callback', [TikTokController::class, 'callback'])->name('app.social.tiktok.callback');
|
||||
|
||||
Route::get('connect/youtube', [YouTubeController::class, 'connect'])->name('app.social.youtube.connect');
|
||||
Route::get('accounts/youtube/callback', [YouTubeController::class, 'callback'])->name('app.social.youtube.callback');
|
||||
Route::get('accounts/youtube/select', [YouTubeController::class, 'selectChannel'])->name('app.social.youtube.select-channel');
|
||||
Route::post('accounts/youtube/select', [YouTubeController::class, 'select'])->name('app.social.youtube.select');
|
||||
|
||||
Route::get('connect/facebook', [FacebookController::class, 'connect'])->name('app.social.facebook.connect');
|
||||
Route::get('accounts/facebook/callback', [FacebookController::class, 'callback'])->name('app.social.facebook.callback');
|
||||
Route::get('accounts/facebook/select', [FacebookController::class, 'selectPage'])->name('app.social.facebook.select-page');
|
||||
Route::post('accounts/facebook/select', [FacebookController::class, 'select'])->name('app.social.facebook.select');
|
||||
|
||||
Route::get('connect/instagram', [InstagramController::class, 'connect'])->name('app.social.instagram.connect');
|
||||
Route::get('accounts/instagram/callback', [InstagramController::class, 'callback'])->name('app.social.instagram.callback');
|
||||
Route::get('accounts/instagram/select', [InstagramController::class, 'selectAccount'])->name('app.social.instagram.select-account');
|
||||
Route::post('accounts/instagram/select', [InstagramController::class, 'select'])->name('app.social.instagram.select');
|
||||
|
||||
Route::get('connect/instagram-facebook', [InstagramFacebookController::class, 'connect'])->name('app.social.instagram-facebook.connect');
|
||||
Route::get('accounts/instagram-facebook/callback', [InstagramFacebookController::class, 'callback'])->name('app.social.instagram-facebook.callback');
|
||||
Route::get('accounts/instagram-facebook/select-page', [InstagramFacebookController::class, 'selectPage'])->name('app.social.instagram-facebook.select-page');
|
||||
Route::post('accounts/instagram-facebook/select', [InstagramFacebookController::class, 'select'])->name('app.social.instagram-facebook.select');
|
||||
|
||||
Route::get('connect/threads', [ThreadsController::class, 'connect'])->name('app.social.threads.connect');
|
||||
Route::get('accounts/threads/callback', [ThreadsController::class, 'callback'])->name('app.social.threads.callback');
|
||||
|
||||
Route::get('connect/pinterest', [PinterestController::class, 'connect'])->name('app.social.pinterest.connect');
|
||||
Route::get('accounts/pinterest/callback', [PinterestController::class, 'callback'])->name('app.social.pinterest.callback');
|
||||
|
||||
Route::get('connect/bluesky', [BlueskyController::class, 'connect'])->name('app.social.bluesky.connect');
|
||||
Route::post('connect/bluesky', [BlueskyController::class, 'store'])->name('app.social.bluesky.store');
|
||||
|
||||
Route::get('connect/mastodon', [MastodonController::class, 'connect'])->name('app.social.mastodon.connect');
|
||||
Route::post('connect/mastodon', [MastodonController::class, 'authorizeInstance'])->name('app.social.mastodon.authorize');
|
||||
Route::get('accounts/mastodon/callback', [MastodonController::class, 'callback'])->name('app.social.mastodon.callback');
|
||||
|
||||
Route::post('connect/telegram', [TelegramController::class, 'connect'])->name('app.social.telegram.connect');
|
||||
|
||||
Route::get('connect/discord', [DiscordController::class, 'connect'])->name('app.social.discord.connect');
|
||||
Route::get('accounts/discord/callback', [DiscordController::class, 'callback'])->name('app.social.discord.callback');
|
||||
|
||||
// Disconnecting must also work during onboarding (before a subscription
|
||||
// exists), so it lives here rather than behind EnsureAccountReady — the
|
||||
// controller still authorizes workspace ownership.
|
||||
Route::delete('accounts/{account}', [SocialController::class, 'disconnect'])->name('app.accounts.disconnect');
|
||||
});
|
||||
|
||||
// Routes that require active subscription and completed onboarding
|
||||
Route::middleware(['auth', EnsureAccountReady::class])->group(function () {
|
||||
Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class])->group(function () {
|
||||
// Discord — live lookups for the composer (channel picker + mention autocomplete).
|
||||
// Throttled because they proxy the shared bot's (rate-limited) Discord API.
|
||||
Route::get('discord/accounts/{account}/channels', [AppDiscordController::class, 'channels'])
|
||||
|
|
|
|||
|
|
@ -51,6 +51,138 @@
|
|||
->and(data_get($meta, 'embeds.0.color'))->toBe('#5865F2');
|
||||
});
|
||||
|
||||
it('persists the LinkedIn document_title meta on store', function () {
|
||||
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
|
||||
|
||||
$this->withHeaders($this->headers)
|
||||
->postJson(route('api.posts.store'), [
|
||||
'content' => 'Check our latest deck',
|
||||
'platforms' => [[
|
||||
'social_account_id' => $linkedin->id,
|
||||
'content_type' => ContentType::LinkedInPost->value,
|
||||
'meta' => ['document_title' => 'Q2 Report'],
|
||||
]],
|
||||
])
|
||||
->assertCreated();
|
||||
|
||||
expect(PostPlatform::where('social_account_id', $linkedin->id)->sole()->meta['document_title'])->toBe('Q2 Report');
|
||||
});
|
||||
|
||||
it('publishes a LinkedIn document post that has a PDF', function () {
|
||||
Queue::fake();
|
||||
|
||||
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
|
||||
$post = Post::factory()->create([
|
||||
'workspace_id' => $this->workspace->id,
|
||||
'user_id' => $this->user->id,
|
||||
'content' => 'Our latest deck',
|
||||
'media' => [[
|
||||
'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf',
|
||||
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
|
||||
]],
|
||||
]);
|
||||
$platform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id, 'social_account_id' => $linkedin->id,
|
||||
'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
|
||||
]);
|
||||
|
||||
$this->withHeaders($this->headers)
|
||||
->putJson(route('api.posts.update', $post), [
|
||||
'status' => PostStatus::Publishing->value,
|
||||
'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],
|
||||
])
|
||||
->assertOk();
|
||||
|
||||
Queue::assertPushed(PublishPost::class);
|
||||
});
|
||||
|
||||
it('rejects publishing a LinkedIn post that mixes a PDF with an image', function () {
|
||||
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
|
||||
$post = Post::factory()->create([
|
||||
'workspace_id' => $this->workspace->id,
|
||||
'user_id' => $this->user->id,
|
||||
'media' => [
|
||||
['id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf'],
|
||||
['id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg'],
|
||||
],
|
||||
]);
|
||||
$platform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id, 'social_account_id' => $linkedin->id,
|
||||
'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
|
||||
]);
|
||||
|
||||
$this->withHeaders($this->headers)
|
||||
->putJson(route('api.posts.update', $post), [
|
||||
'status' => PostStatus::Publishing->value,
|
||||
'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['platforms.0.content_type']);
|
||||
});
|
||||
|
||||
it('publishes a valid LinkedIn document without resubmitting content_type', function () {
|
||||
Queue::fake();
|
||||
|
||||
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
|
||||
$post = Post::factory()->create([
|
||||
'workspace_id' => $this->workspace->id,
|
||||
'user_id' => $this->user->id,
|
||||
'content' => 'Our deck',
|
||||
'media' => [[
|
||||
'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf',
|
||||
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
|
||||
]],
|
||||
]);
|
||||
$platform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id, 'social_account_id' => $linkedin->id,
|
||||
'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
|
||||
]);
|
||||
|
||||
$this->withHeaders($this->headers)
|
||||
->putJson(route('api.posts.update', $post), [
|
||||
'status' => PostStatus::Publishing->value,
|
||||
'platforms' => [['id' => $platform->id]],
|
||||
])
|
||||
->assertOk();
|
||||
|
||||
Queue::assertPushed(PublishPost::class);
|
||||
});
|
||||
|
||||
it('rejects only the platform that cannot take a PDF in a multi-platform post', function () {
|
||||
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
|
||||
$x = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::X]);
|
||||
|
||||
$post = Post::factory()->create([
|
||||
'workspace_id' => $this->workspace->id,
|
||||
'user_id' => $this->user->id,
|
||||
'content' => 'Deck',
|
||||
'media' => [[
|
||||
'id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf',
|
||||
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
|
||||
]],
|
||||
]);
|
||||
$linkedinPlatform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id, 'social_account_id' => $linkedin->id,
|
||||
'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
|
||||
]);
|
||||
$xPlatform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id, 'social_account_id' => $x->id,
|
||||
'platform' => Platform::X, 'content_type' => ContentType::XPost, 'enabled' => true,
|
||||
]);
|
||||
|
||||
$this->withHeaders($this->headers)
|
||||
->putJson(route('api.posts.update', $post), [
|
||||
'status' => PostStatus::Publishing->value,
|
||||
'platforms' => [
|
||||
['id' => $linkedinPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
|
||||
['id' => $xPlatform->id, 'content_type' => ContentType::XPost->value],
|
||||
],
|
||||
])
|
||||
->assertUnprocessable()
|
||||
->assertJsonValidationErrors(['platforms.1.content_type'])
|
||||
->assertJsonMissingValidationErrors(['platforms.0.content_type']);
|
||||
});
|
||||
|
||||
it('persists per-platform meta across networks on store', function () {
|
||||
$instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
|
||||
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
|
||||
|
|
|
|||
|
|
@ -189,6 +189,29 @@
|
|||
expect($this->workspace->getMedia('assets')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('chunked upload completes for a pdf document', function () {
|
||||
// Real %PDF magic bytes so mime_content_type detects application/pdf.
|
||||
$content = "%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n";
|
||||
$size = strlen($content);
|
||||
|
||||
$response = $this->actingAs($this->user)->call(
|
||||
'POST',
|
||||
route('app.assets.store-chunked'),
|
||||
[], [], [],
|
||||
[
|
||||
'HTTP_CONTENT_RANGE' => 'bytes 0-'.($size - 1).'/'.$size,
|
||||
'HTTP_X_FILE_NAME' => 'deck.pdf',
|
||||
'HTTP_ACCEPT' => 'application/json',
|
||||
'CONTENT_TYPE' => 'application/octet-stream',
|
||||
],
|
||||
$content,
|
||||
);
|
||||
|
||||
$response->assertSuccessful();
|
||||
$response->assertJson(['done' => true]);
|
||||
expect($this->workspace->getMedia('assets')->first()->type->value)->toBe('document');
|
||||
});
|
||||
|
||||
test('chunked upload reports progress on intermediate chunks', function () {
|
||||
$response = $this->actingAs($this->user)->call(
|
||||
'POST',
|
||||
|
|
|
|||
|
|
@ -285,7 +285,7 @@
|
|||
$action = app(RunGenerateNode::class);
|
||||
|
||||
$accountsConfig = [
|
||||
['social_account_id' => '1', 'content_type' => ContentType::LinkedInPost->value, 'meta' => []],
|
||||
['social_account_id' => '1', 'content_type' => ContentType::PinterestPin->value, 'meta' => []],
|
||||
['social_account_id' => '2', 'content_type' => ContentType::InstagramReel->value, 'meta' => []],
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,9 @@
|
|||
declare(strict_types=1);
|
||||
|
||||
use App\Enums\Post\Status as PostStatus;
|
||||
use App\Enums\PostPlatform\ContentType;
|
||||
use App\Enums\PostPlatform\Status as PlatformStatus;
|
||||
use App\Enums\SocialAccount\Platform;
|
||||
use App\Enums\SocialAccount\Status as AccountStatus;
|
||||
use App\Enums\UserWorkspace\Role;
|
||||
use App\Events\PostPlatformStatusUpdated;
|
||||
|
|
@ -19,10 +21,12 @@
|
|||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Services\Social\ConnectionVerifier;
|
||||
use App\Services\Social\LinkedInPagePublisher;
|
||||
use App\Services\Social\LinkedInPublisher;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
|
||||
|
|
@ -79,6 +83,92 @@
|
|||
expect($this->postPlatform->platform_url)->toBe('https://linkedin.com/post/123');
|
||||
});
|
||||
|
||||
test('publish job dispatches a linkedin-page post to the page publisher', function () {
|
||||
Event::fake();
|
||||
|
||||
$workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
|
||||
$pageAccount = SocialAccount::factory()->linkedinPage()->create(['workspace_id' => $workspace->id]);
|
||||
$post = Post::factory()->scheduled()->create([
|
||||
'workspace_id' => $workspace->id,
|
||||
'user_id' => $this->user->id,
|
||||
]);
|
||||
$pagePostPlatform = PostPlatform::factory()->create([
|
||||
'post_id' => $post->id,
|
||||
'social_account_id' => $pageAccount->id,
|
||||
'platform' => Platform::LinkedInPage,
|
||||
'content_type' => ContentType::LinkedInPagePost,
|
||||
'enabled' => true,
|
||||
]);
|
||||
|
||||
$publisher = Mockery::mock(LinkedInPagePublisher::class);
|
||||
$publisher->shouldReceive('publish')->once()->andReturn([
|
||||
'id' => 'org-post-1',
|
||||
'url' => 'https://linkedin.com/company/post/1',
|
||||
]);
|
||||
$this->app->instance(LinkedInPagePublisher::class, $publisher);
|
||||
|
||||
(new PublishToSocialPlatform($pagePostPlatform))->handle();
|
||||
|
||||
$pagePostPlatform->refresh();
|
||||
expect($pagePostPlatform->status)->toBe(PlatformStatus::Published);
|
||||
expect($pagePostPlatform->platform_post_id)->toBe('org-post-1');
|
||||
});
|
||||
|
||||
test('publish job runs the real document flow end-to-end for a LinkedIn PDF post', function () {
|
||||
Event::fake();
|
||||
|
||||
// Real publisher (no mock) — exercise the full job -> getPublisher -> publishDocument chain.
|
||||
$this->socialAccount->update([
|
||||
'platform_user_id' => 'person-xyz',
|
||||
'token_expires_at' => now()->addDays(60),
|
||||
]);
|
||||
$this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
|
||||
$this->post->update([
|
||||
'content' => 'Our deck',
|
||||
'media' => [[
|
||||
'id' => 'doc-1', 'path' => 'media/deck.pdf', 'url' => 'https://example.com/deck.pdf',
|
||||
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
|
||||
]],
|
||||
]);
|
||||
|
||||
$uploadUrl = 'https://www.linkedin.com/dms-uploads/document/e2e';
|
||||
|
||||
Http::fake(function ($request) use ($uploadUrl) {
|
||||
$url = $request->url();
|
||||
|
||||
if (str_contains($url, '/rest/documents') && str_contains($url, 'initializeUpload')) {
|
||||
return Http::response(['value' => ['uploadUrl' => $uploadUrl, 'document' => 'urn:li:document:E2E']], 200);
|
||||
}
|
||||
|
||||
if ($url === $uploadUrl) {
|
||||
return Http::response(null, 201);
|
||||
}
|
||||
|
||||
if (str_contains($url, '/rest/documents/')) {
|
||||
return Http::response(['status' => 'AVAILABLE'], 200);
|
||||
}
|
||||
|
||||
if (str_contains($url, '/rest/posts')) {
|
||||
return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:e2e']);
|
||||
}
|
||||
|
||||
return Http::response('fake-pdf-bytes', 200);
|
||||
});
|
||||
|
||||
(new PublishToSocialPlatform($this->postPlatform))->handle();
|
||||
|
||||
$this->postPlatform->refresh();
|
||||
expect($this->postPlatform->status)->toBe(PlatformStatus::Published);
|
||||
expect($this->postPlatform->platform_post_id)->toBe('urn:li:share:e2e');
|
||||
|
||||
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/documents') && str_contains($request->url(), 'initializeUpload'));
|
||||
Http::assertSent(function ($request) {
|
||||
return str_contains($request->url(), '/rest/posts')
|
||||
&& data_get($request->data(), 'content.media.id') === 'urn:li:document:E2E'
|
||||
&& data_get($request->data(), 'content.media.title') === 'deck.pdf';
|
||||
});
|
||||
});
|
||||
|
||||
test('publish to social platform marks platform as failed on error', function () {
|
||||
Event::fake();
|
||||
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue