Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Accept GIFs on LinkedIn, add GIPHY to the composer, and settle media imports over the socket (#514)

Almer ibarra63eedd541ec8
diff --git a/.env.example b/.env.example
index c5408b2d6..985be729a 100644
--- a/.env.example
+++ b/.env.example
@@ -304,6 +304,9 @@ NIGHTWATCH_TOKEN=
# Media Services
UNSPLASH_ACCESS_KEY=
UNSPLASH_SECRET_KEY=
+# GIPHY (https://developers.giphy.com/dashboard): GIFs in the composer's media menu.
+GIPHY_ENABLED=true
+GIPHY_API_KEY=
# Composer media sources (Google Drive, Google Photos, Canva).
# Each source is hidden until its flag is on AND its keys are set. Nothing falls back to GOOGLE_CLIENT_ID
diff --git a/app/Actions/Media/StartMediaImport.php b/app/Actions/Media/StartMediaImport.php
index 555ccacab..febe87a2b 100644
--- a/app/Actions/Media/StartMediaImport.php
+++ b/app/Actions/Media/StartMediaImport.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Actions\Media;
use App\Dto\RemoteFile;
-use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
use App\Jobs\Media\ImportRemoteMedia;
use App\Models\User;
use App\Models\Workspace;
@@ -21,14 +21,16 @@ class StartMediaImport
* download of a file. The file's headers go to MediaImportHeaders,
* never into the queued job. A string is a Google Photos picker
* session: every item picked in it becomes its own import, in the
- * user's order. Returns the import ids the composer polls.
+ * user's order. `$types` are the media types the file may be.
+ * Returns the import ids the composer waits on.
*
+ * @param list<MediaType> $types
* @return list<string>
*/
- public static function execute(User $user, Workspace $workspace, Source $source, RemoteFile|string $fileOrSession): array
+ public static function execute(User $user, Workspace $workspace, RemoteFile|string $fileOrSession, array $types): array
{
if (is_string($fileOrSession)) {
- return self::startGooglePhotosSession($user, $workspace, $fileOrSession);
+ return self::startGooglePhotosSession($user, $workspace, $fileOrSession, $types);
}
$importId = self::pending($user, $workspace);
@@ -38,7 +40,7 @@ class StartMediaImport
$fileOrSession = $fileOrSession->withHeaders([]);
}
- ImportRemoteMedia::dispatch($importId, $workspace->id, $user->id, $fileOrSession);
+ ImportRemoteMedia::dispatch($importId, $workspace->id, $user->id, $fileOrSession, $types);
return [$importId];
}
@@ -48,9 +50,10 @@ class StartMediaImport
* on their own tile; the session's token stays in the cache until the
* last download finished.
*
+ * @param list<MediaType> $types
* @return list<string>
*/
- private static function startGooglePhotosSession(User $user, Workspace $workspace, string $sessionId): array
+ private static function startGooglePhotosSession(User $user, Workspace $workspace, string $sessionId, array $types): array
{
$picker = app(GooglePhotosPicker::class);
$accessToken = GooglePhotosPicker::token($user->id, $sessionId);
@@ -72,17 +75,19 @@ class StartMediaImport
GooglePhotosPicker::trackImports($user->id, $sessionId, count($downloads));
}
- return array_map(function (RemoteFile|string $file) use ($user, $workspace, $sessionId): string {
- $importId = self::pending($user, $workspace);
+ return collect($files)
+ ->map(function (RemoteFile|string $file) use ($user, $workspace, $sessionId, $types): string {
+ $importId = self::pending($user, $workspace);
- if (is_string($file)) {
- MediaImportStatus::fail($importId, $file);
- } else {
- ImportRemoteMedia::dispatch($importId, $workspace->id, $user->id, $file, $sessionId);
- }
+ if (is_string($file)) {
+ MediaImportStatus::fail($importId, $file);
+ } else {
+ ImportRemoteMedia::dispatch($importId, $workspace->id, $user->id, $file, $types, $sessionId);
+ }
- return $importId;
- }, $files);
+ return $importId;
+ })
+ ->all();
}
private static function pending(User $user, Workspace $workspace): string
diff --git a/app/Enums/Media/Source.php b/app/Enums/Media/Source.php
index d53621628..2239e7a85 100644
--- a/app/Enums/Media/Source.php
+++ b/app/Enums/Media/Source.php
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Enums\Media;
+use App\Services\GiphyService;
+
/**
* Origin of a media attachment on a post. `null`/absent means "uploaded by
* the user". The picker sources are the ones offered in the composer's media
@@ -13,6 +15,7 @@ enum Source: string
{
case Ai = 'ai';
case Unsplash = 'unsplash';
+ case Giphy = 'giphy';
case GoogleDrive = 'google_drive';
case GooglePhotos = 'google_photos';
case Canva = 'canva';
@@ -20,13 +23,14 @@ enum Source: string
/** @return list<self> */
public static function pickerSources(): array
{
- return [self::Canva, self::GoogleDrive, self::GooglePhotos, self::Unsplash];
+ return [self::Canva, self::Giphy, self::GoogleDrive, self::GooglePhotos, self::Unsplash];
}
public function isEnabled(): bool
{
return match ($this) {
self::Unsplash => filled(config('services.unsplash.access_key')),
+ self::Giphy => GiphyService::isEnabled(),
self::GoogleDrive => (bool) config('trypost.media_sources.google_drive.enabled')
&& self::googleOAuthConfigured()
&& filled(config('services.google_media.api_key'))
@@ -56,6 +60,7 @@ enum Source: string
return match ($this) {
self::Ai => 'AI',
self::Unsplash => 'Unsplash',
+ self::Giphy => 'GIPHY',
self::GoogleDrive => 'Google Drive',
self::GooglePhotos => 'Google Photos',
self::Canva => 'Canva',
@@ -66,7 +71,7 @@ enum Source: string
public function downloadHosts(): array
{
$hosts = match ($this) {
- self::Unsplash, self::GoogleDrive, self::GooglePhotos, self::Canva => config("trypost.media_sources.{$this->value}.download_hosts"),
+ self::Unsplash, self::Giphy, self::GoogleDrive, self::GooglePhotos, self::Canva => config("trypost.media_sources.{$this->value}.download_hosts"),
default => '',
};
diff --git a/app/Enums/PostPlatform/ContentType.php b/app/Enums/PostPlatform/ContentType.php
index c9d63b927..eadb1bd6e 100644
--- a/app/Enums/PostPlatform/ContentType.php
+++ b/app/Enums/PostPlatform/ContentType.php
@@ -320,7 +320,8 @@ enum ContentType: string
{
return match ($this) {
self::XPost, self::BlueskyPost, self::MastodonPost,
- self::DiscordMessage, self::TelegramPost => true,
+ self::DiscordMessage, self::TelegramPost,
+ self::LinkedInPost, self::LinkedInPagePost => true,
default => false,
};
}
diff --git a/app/Events/MediaImportSettled.php b/app/Events/MediaImportSettled.php
new file mode 100644
index 000000000..5ac77e2ef
--- /dev/null
+++ b/app/Events/MediaImportSettled.php
@@ -0,0 +1,49 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Events;
+
+use Illuminate\Broadcasting\InteractsWithSockets;
+use Illuminate\Broadcasting\PrivateChannel;
+use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
+use Illuminate\Foundation\Events\Dispatchable;
+
+/**
+ * A queued media import finished, imported or failed. It names the import
+ * only: the workspace channel reaches every member, so the composer that
+ * started it reads the result from the import's status, which answers its
+ * starter alone.
+ */
+class MediaImportSettled implements ShouldBroadcast
+{
+ use Dispatchable, InteractsWithSockets;
+
+ public function __construct(
+ public string $importId,
+ public string $workspaceId,
+ ) {}
+
+ public function broadcastAs(): string
+ {
+ return 'media.import.settled';
+ }
+
+ public function broadcastOn(): array
+ {
+ return [
+ new PrivateChannel("workspace.{$this->workspaceId}"),
+ ];
+ }
+
+ /** @return array{import_id: string} */
+ public function broadcastWith(): array
+ {
+ return ['import_id' => $this->importId];
+ }
+
+ public function broadcastQueue(): string
+ {
+ return 'broadcasts';
+ }
+}
diff --git a/app/Http/Controllers/App/GiphyController.php b/app/Http/Controllers/App/GiphyController.php
new file mode 100644
index 000000000..5b0c8f5b8
--- /dev/null
+++ b/app/Http/Controllers/App/GiphyController.php
@@ -0,0 +1,43 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Http\Controllers\App;
+
+use App\Http\Requests\App\Media\SearchRequest;
+use App\Http\Requests\App\Media\TrendingRequest;
+use App\Services\GiphyService;
+use Illuminate\Http\JsonResponse;
+use Symfony\Component\HttpFoundation\Response;
+
+/**
+ * The composer's GIPHY picker: search and trending GIFs. The GIF the user
+ * picks is imported through the media import queue, like the other sources.
+ */
+class GiphyController extends Controller
+{
+ public function search(SearchRequest $request, GiphyService $giphy): JsonResponse
+ {
+ return $this->respond($giphy->search(
+ query: $request->safe()->string('query')->value(),
+ page: $request->safe()->integer('page', 1),
+ ));
+ }
+
+ public function trending(TrendingRequest $request, GiphyService $giphy): JsonResponse
+ {
+ return $this->respond($giphy->trending(page: $request->safe()->integer('page', 1)));
+ }
+
+ /**
+ * @param array{results: list<array<string, mixed>>, has_more: bool}|null $page
+ */
+ private function respond(?array $page): JsonResponse
+ {
+ if (blank($page)) {
+ return response()->json(['message' => __('posts.composer.giphy.error')], Response::HTTP_SERVICE_UNAVAILABLE);
+ }
+
+ return response()->json($page);
+ }
+}
diff --git a/app/Http/Controllers/App/LinkPreviewMediaController.php b/app/Http/Controllers/App/LinkPreviewMediaController.php
index ab271b983..5a0226c2f 100644
--- a/app/Http/Controllers/App/LinkPreviewMediaController.php
+++ b/app/Http/Controllers/App/LinkPreviewMediaController.php
@@ -4,24 +4,26 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
+use App\Actions\Media\StartMediaImport;
use App\Dto\RemoteFile;
use App\Enums\Media\Type as MediaType;
use App\Http\Controllers\Controller;
use App\Http\Requests\App\Post\StoreLinkPreviewMediaRequest;
-use App\Http\Resources\App\MediaResource;
-use App\Services\Media\RemoteMediaImporter;
+use App\Http\Resources\App\MediaImportStartedResource;
use App\Services\Social\LinkCard\LinkCardFetcher;
+use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
+use Symfony\Component\HttpFoundation\Response;
/**
- * "Replace link preview with media": imports the card's image as a temporary
- * upload that the first save adopts, like any other composer upload.
+ * "Replace link preview with media": reads the card's image (the composer
+ * already fetched the card, so it comes from the cache) and queues its
+ * import as a temporary upload the first save adopts, like any other
+ * composer import.
*/
class LinkPreviewMediaController extends Controller
{
- private const int TIMEOUT_SECONDS = 30;
-
- public function __invoke(StoreLinkPreviewMediaRequest $request, LinkCardFetcher $fetcher, RemoteMediaImporter $importer): MediaResource
+ public function __invoke(StoreLinkPreviewMediaRequest $request, LinkCardFetcher $fetcher): JsonResponse
{
$imageUrl = $fetcher->fetch($request->validated('url'))?->imageUrl;
@@ -29,18 +31,15 @@ class LinkPreviewMediaController extends Controller
throw ValidationException::withMessages(['url' => __('posts.composer.link_preview.no_image')]);
}
- $imported = $importer->import(
+ $importIds = StartMediaImport::execute(
+ $request->user(),
$request->user()->currentWorkspace,
RemoteFile::fromUrl($imageUrl),
[MediaType::Image],
- self::TIMEOUT_SECONDS,
- followRedirects: true,
);
- if (! $imported->succeeded()) {
- throw ValidationException::withMessages(['url' => __('posts.composer.media_sources.errors.import_failed')]);
- }
-
- return new MediaResource($imported->media);
+ return (new MediaImportStartedResource($importIds))
+ ->response()
+ ->setStatusCode(Response::HTTP_ACCEPTED);
}
}
diff --git a/app/Http/Controllers/App/MediaImportController.php b/app/Http/Controllers/App/MediaImportController.php
index 1a4418c90..0095a3b73 100644
--- a/app/Http/Controllers/App/MediaImportController.php
+++ b/app/Http/Controllers/App/MediaImportController.php
@@ -21,8 +21,8 @@ class MediaImportController extends Controller
$importIds = StartMediaImport::execute(
$request->user(),
$request->user()->currentWorkspace,
- $request->importSource(),
$request->importPayload(),
+ $request->importTypes(),
);
return (new MediaImportStartedResource($importIds))
diff --git a/app/Http/Controllers/App/MediaUploadController.php b/app/Http/Controllers/App/MediaUploadController.php
index e835f874b..b3ddf2cc4 100644
--- a/app/Http/Controllers/App/MediaUploadController.php
+++ b/app/Http/Controllers/App/MediaUploadController.php
@@ -4,17 +4,9 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
-use App\Dto\RemoteFile;
-use App\Enums\Media\Source;
-use App\Enums\Media\Type as MediaType;
use App\Http\Requests\App\Media\StoreChunkedMediaRequest;
-use App\Http\Requests\App\Media\StoreMediaFromUrlRequest;
-use App\Http\Resources\App\MediaResource;
use App\Services\Media\ChunkedAssetReceiver;
-use App\Services\Media\RemoteMediaImporter;
-use App\Services\UnsplashService;
use Illuminate\Http\JsonResponse;
-use Illuminate\Validation\ValidationException;
/**
* Brings files in before an owner exists: every completed upload is a
@@ -23,8 +15,6 @@ use Illuminate\Validation\ValidationException;
*/
class MediaUploadController extends Controller
{
- private const int UNSPLASH_TIMEOUT_SECONDS = 30;
-
public function storeChunked(StoreChunkedMediaRequest $request, ChunkedAssetReceiver $receiver): JsonResponse
{
$workspace = $request->user()->currentWorkspace;
@@ -45,28 +35,4 @@ class MediaUploadController extends Controller
return $receipt->toResponse();
}
-
- public function storeFromUrl(StoreMediaFromUrlRequest $request, RemoteMediaImporter $importer, UnsplashService $unsplash): MediaResource
- {
- $imported = $importer->import(
- $request->user()->currentWorkspace,
- new RemoteFile(
- $request->validated('url'),
- $request->validated('filename'),
- allowedHosts: Source::Unsplash->downloadHosts(),
- source: Source::Unsplash,
- sourceMeta: $request->attribution(),
- ),
- [MediaType::Image],
- self::UNSPLASH_TIMEOUT_SECONDS,
- );
-
- if (! $imported->succeeded()) {
- throw ValidationException::withMessages(['url' => __('posts.composer.media_sources.errors.import_failed')]);
- }
-
- $unsplash->trackDownload($request->validated('download_location'));
-
- return new MediaResource($imported->media);
- }
}
diff --git a/app/Http/Requests/App/Media/StoreMediaFromUrlRequest.php b/app/Http/Requests/App/Media/StoreMediaFromUrlRequest.php
deleted file mode 100644
index 6bfb548bc..000000000
--- a/app/Http/Requests/App/Media/StoreMediaFromUrlRequest.php
+++ /dev/null
@@ -1,67 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Http\Requests\App\Media;
-
-use App\Enums\Media\Source;
-use App\Services\Media\RemoteMediaImporter;
-use Closure;
-use Illuminate\Foundation\Http\FormRequest;
-
-/**
- * One Unsplash photo picked in the composer: the image URL on the
- * configured download hosts, the photo's `download_location` on the
- * configured API host, and the attribution kept on the item.
- */
-class StoreMediaFromUrlRequest extends FormRequest
-{
- public function authorize(): bool
- {
- return $this->user()->can('createPost', $this->user()->currentWorkspace);
- }
-
- /**
- * @return array<string, array<int, mixed>>
- */
- public function rules(): array
- {
- return [
- 'url' => ['bail', 'required', 'string', 'url:https', $this->onHosts(Source::Unsplash->downloadHosts())],
- 'filename' => ['required', 'string', 'max:255'],
- 'download_location' => ['bail', 'required', 'string', 'url:https', $this->onHosts([$this->configuredHost('trypost.media_sources.unsplash.api')])],
- 'photo_id' => ['required', 'string', 'max:255'],
- 'author_name' => ['required', 'string', 'max:255'],
- 'author_url' => ['bail', 'nullable', 'string', 'url:https', 'max:2048', $this->onHosts([$this->configuredHost('trypost.media_sources.unsplash.website')])],
- ];
- }
-
- /**
- * @return array{photo_id: string, author_name: string, author_url: ?string}
- */
- public function attribution(): array
- {
- return [
- 'photo_id' => (string) $this->validated('photo_id'),
- 'author_name' => (string) $this->validated('author_name'),
- 'author_url' => $this->validated('author_url'),
- ];
- }
-
- /**
- * @param list<string> $hosts
- */
- private function onHosts(array $hosts): Closure
- {
- return function (string $attribute, mixed $value, Closure $fail) use ($hosts): void {
- if (! Source::Unsplash->isEnabled() || ! app(RemoteMediaImporter::class)->hostAllowed((string) $value, array_values(array_filter($hosts)))) {
- $fail(__('validation.url', ['attribute' => $attribute]));
- }
- };
- }
-
- private function configuredHost(string $key): string
- {
- return (string) parse_url((string) config($key), PHP_URL_HOST);
- }
-}
diff --git a/app/Http/Requests/App/Media/StoreMediaImportRequest.php b/app/Http/Requests/App/Media/StoreMediaImportRequest.php
index 7a8242f9e..60473c1f7 100644
--- a/app/Http/Requests/App/Media/StoreMediaImportRequest.php
+++ b/app/Http/Requests/App/Media/StoreMediaImportRequest.php
@@ -6,16 +6,20 @@ namespace App\Http\Requests\App\Media;
use App\Dto\RemoteFile;
use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
+use App\Services\Media\RemoteMediaImporter;
use App\Services\Media\Sources\GoogleDriveFiles;
use App\Services\Media\Sources\GooglePhotosPicker;
use Closure;
use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Uri;
use Illuminate\Validation\Rule;
use LogicException;
/**
* One pick per request. A picker source is importable once it has an arm
- * here (its own rules and the payload the job downloads) and is enabled.
+ * here (its own rules, the payload the job downloads and the media types
+ * it may be) and is enabled.
*/
class StoreMediaImportRequest extends FormRequest
{
@@ -38,16 +42,32 @@ class StoreMediaImportRequest extends FormRequest
];
}
- public function importSource(): Source
+ private function importSource(): Source
{
return Source::from((string) $this->validated('source'));
}
public function importPayload(): RemoteFile|string
{
- $arm = data_get($this->arms(), $this->importSource()->value) ?? throw new LogicException("No import arm for {$this->importSource()->value}.");
+ return data_get($this->arm(), 'payload')();
+ }
+
+ /**
+ * The media types the pick may be.
+ *
+ * @return list<MediaType>
+ */
+ public function importTypes(): array
+ {
+ return data_get($this->arm(), 'types');
+ }
- return data_get($arm, 'payload')();
+ /**
+ * @return array{rules: Closure(): array<string, array<int, mixed>>, payload: Closure(): (RemoteFile|string), types: list<MediaType>}
+ */
+ private function arm(): array
+ {
+ return data_get($this->arms(), $this->importSource()->value) ?? throw new LogicException("No import arm for {$this->importSource()->value}.");
}
/**
@@ -64,11 +84,44 @@ class StoreMediaImportRequest extends FormRequest
/**
* Per-source rules and payload, keyed by the source value.
*
- * @return array<string, array{rules: Closure(): array<string, array<int, mixed>>, payload: Closure(): (RemoteFile|string)}>
+ * @return array<string, array{rules: Closure(): array<string, array<int, mixed>>, payload: Closure(): (RemoteFile|string), types: list<MediaType>}>
*/
private function arms(): array
{
return [
+ Source::Giphy->value => [
+ 'rules' => fn (): array => [
+ 'url' => ['bail', 'required', 'string', 'url:https', $this->onHosts(Source::Giphy->downloadHosts())],
+ 'gif_id' => ['required', 'string', 'alpha_num', 'max:64'],
+ 'giphy_url' => ['bail', 'nullable', 'string', 'url:https', 'max:2048', $this->onHosts([$this->configuredHost('trypost.media_sources.giphy.website')])],
+ ],
+ 'payload' => fn (): RemoteFile => new RemoteFile(
+ $this->safe()->string('url')->value(),
+ "giphy-{$this->safe()->string('gif_id')}.gif",
+ allowedHosts: Source::Giphy->downloadHosts(),
+ source: Source::Giphy,
+ sourceMeta: $this->safe()->only(['gif_id', 'giphy_url']),
+ ),
+ 'types' => [MediaType::Image],
+ ],
+ Source::Unsplash->value => [
+ 'rules' => fn (): array => [
+ 'url' => ['bail', 'required', 'string', 'url:https', $this->onHosts(Source::Unsplash->downloadHosts())],
+ 'filename' => ['required', 'string', 'max:255'],
+ 'download_location' => ['bail', 'required', 'string', 'url:https', $this->onHosts([$this->configuredHost('trypost.media_sources.unsplash.api')])],
+ 'photo_id' => ['required', 'string', 'max:255'],
+ 'author_name' => ['required', 'string', 'max:255'],
+ 'author_url' => ['bail', 'nullable', 'string', 'url:https', 'max:2048', $this->onHosts([$this->configuredHost('trypost.media_sources.unsplash.website')])],
+ ],
+ 'payload' => fn (): RemoteFile => new RemoteFile(
+ $this->safe()->string('url')->value(),
+ $this->safe()->string('filename')->value(),
+ allowedHosts: Source::Unsplash->downloadHosts(),
+ source: Source::Unsplash,
+ sourceMeta: $this->safe()->only(['photo_id', 'author_name', 'author_url', 'download_location']),
+ ),
+ 'types' => [MediaType::Image],
+ ],
Source::GoogleDrive->value => [
'rules' => fn (): array => [
'access_token' => ['required', 'string', 'max:4096'],
@@ -80,6 +133,7 @@ class StoreMediaImportRequest extends FormRequest
(string) $this->validated('access_token'),
(array) $this->validated('file'),
),
+ 'types' => MediaType::cases(),
],
Source::GooglePhotos->value => [
'rules' => fn (): array => [
@@ -97,7 +151,27 @@ class StoreMediaImportRequest extends FormRequest
],
],
'payload' => fn (): string => (string) $this->validated('session_id'),
+ 'types' => MediaType::cases(),
],
];
}
+
+ /**
+ * The URL must sit on one of the hosts.
+ *
+ * @param list<string> $hosts
+ */
+ private function onHosts(array $hosts): Closure
+ {
+ return function (string $attribute, mixed $value, Closure $fail) use ($hosts): void {
+ if (! app(RemoteMediaImporter::class)->hostAllowed((string) $value, $hosts)) {
+ $fail(__('validation.url', ['attribute' => $attribute]));
+ }
+ };
+ }
+
+ private function configuredHost(string $key): string
+ {
+ return (string) Uri::of((string) config($key))->host();
+ }
}
diff --git a/app/Jobs/Media/ImportRemoteMedia.php b/app/Jobs/Media/ImportRemoteMedia.php
index 3b90d4e68..444c92cad 100644
--- a/app/Jobs/Media/ImportRemoteMedia.php
+++ b/app/Jobs/Media/ImportRemoteMedia.php
@@ -6,11 +6,13 @@ namespace App\Jobs\Media;
use App\Dto\ImportedFile;
use App\Dto\RemoteFile;
+use App\Enums\Media\Source;
use App\Enums\Media\Type as MediaType;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Media\RemoteMediaImporter;
use App\Services\Media\Sources\GooglePhotosPicker;
+use App\Services\UnsplashService;
use App\Support\MediaImportHeaders;
use App\Support\MediaImportStatus;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
@@ -43,11 +45,15 @@ class ImportRemoteMedia implements ShouldBeEncrypted, ShouldQueue
public int $timeout;
+ /**
+ * @param list<MediaType> $types the media types the file may be
+ */
public function __construct(
public string $importId,
public string $workspaceId,
public string $userId,
public RemoteFile $file,
+ public array $types,
public ?string $googlePhotosSession = null,
) {
$this->onQueue(self::QUEUE);
@@ -117,7 +123,7 @@ class ImportRemoteMedia implements ShouldBeEncrypted, ShouldQueue
$imported = $importer->import(
$workspace,
$file,
- MediaType::cases(),
+ $this->types,
$this->timeout,
now()->addSeconds(intdiv($this->timeout, 2)),
followRedirects: true,
@@ -130,6 +136,25 @@ class ImportRemoteMedia implements ShouldBeEncrypted, ShouldQueue
}
MediaImportStatus::complete($this->importId, $imported->media);
+
+ $this->trackUnsplashDownload($file);
+ }
+
+ /**
+ * Unsplash asks to be told when one of its photos is used, once the
+ * photo landed and never for a failed import.
+ *
+ * @see https://help.unsplash.com/en/articles/2511258-guideline-triggering-a-download
+ */
+ private function trackUnsplashDownload(RemoteFile $file): void
+ {
+ $downloadLocation = data_get($file->sourceMeta, 'download_location');
+
+ if ($file->source !== Source::Unsplash || blank($downloadLocation)) {
+ return;
+ }
+
+ app(UnsplashService::class)->trackDownload((string) $downloadLocation);
}
public function failed(?Throwable $exception): void
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 95e2d3903..4d51069b7 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -208,6 +208,12 @@ class AppServiceProvider extends ServiceProvider
->by("user:{$request->user()?->id}"),
);
+ RateLimiter::for(
+ 'giphy',
+ fn (Request $request): Limit => Limit::perMinute((int) config('trypost.media_sources.giphy.requests_per_user_per_minute'))
+ ->by("user:{$request->user()?->id}"),
+ );
+
RateLimiter::for(
'unsplash',
fn (Request $request): Limit => Limit::perMinute((int) config('trypost.media_sources.unsplash.requests_per_user_per_minute'))
diff --git a/app/Services/GiphyService.php b/app/Services/GiphyService.php
new file mode 100644
index 000000000..b755afe52
--- /dev/null
+++ b/app/Services/GiphyService.php
@@ -0,0 +1,193 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Services;
+
+use Closure;
+use Illuminate\Http\Client\ConnectionException;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
+
+/**
+ * GIF search for the composer's GIPHY picker. Results are the same for every
+ * user, so each page is cached for a few minutes.
+ *
+ * @see https://developers.giphy.com/docs/api/endpoint
+ */
+class GiphyService
+{
+ private const int CACHE_MINUTES = 10;
+
+ private const int TIMEOUT_SECONDS = 10;
+
+ /** GIPHY refuses an offset past this one. */
+ private const int MAX_OFFSET = 4999;
+
+ private string $baseUrl;
+
+ private string $apiKey;
+
+ public function __construct()
+ {
+ $this->baseUrl = config('trypost.media_sources.giphy.api');
+ $this->apiKey = (string) config('services.giphy.api_key', '');
+ }
+
+ /** GIPHY needs its flag on and an API key. */
+ public static function isEnabled(): bool
+ {
+ return (bool) config('trypost.media_sources.giphy.enabled')
+ && filled(config('services.giphy.api_key'));
+ }
+
+ /**
+ * Null when GIPHY could not answer (unreachable, rate limited, rejected).
+ *
+ * @return array{results: list<array<string, mixed>>, has_more: bool}|null
+ */
+ public function search(string $query, int $page = 1): ?array
+ {
+ $term = Str::lower(Str::trim($query));
+ $hash = md5($term);
+
+ return $this->page("search:{$page}:{$hash}", 'gifs/search', ['q' => $term], $page);
+ }
+
+ /**
+ * Null when GIPHY could not answer.
+ *
+ * @return array{results: list<array<string, mixed>>, has_more: bool}|null
+ */
+ public function trending(int $page = 1): ?array
+ {
+ return $this->page("trending:{$page}", 'gifs/trending', [], $page);
+ }
+
+ /**
+ * @param array<string, string> $query
+ * @return array{results: list<array<string, mixed>>, has_more: bool}|null
+ */
+ private function page(string $key, string $path, array $query, int $page): ?array
+ {
+ if (! self::isEnabled()) {
+ return ['results' => [], 'has_more' => false];
+ }
+
+ $offset = ($page - 1) * $this->perPage();
+
+ return $this->remember("{$key}:{$this->perPage()}", function () use ($path, $query, $offset): ?array {
+ $data = $this->fetch($path, [
+ ...$query,
+ 'limit' => $this->perPage(),
+ 'offset' => $offset,
+ 'rating' => config('trypost.media_sources.giphy.rating'),
+ ]);
+
+ if (blank($data)) {
+ return null;
+ }
+
+ $count = (int) data_get($data, 'pagination.count', 0);
+ $next = $offset + $count;
+
+ return [
+ 'results' => collect(data_get($data, 'data', []))
+ ->filter(fn (mixed $gif): bool => Arr::accessible($gif) && filled(data_get($gif, 'images.downsized_medium.url')))
+ ->map(fn (array $gif): array => $this->formatGif($gif))
+ ->values()
+ ->all(),
+ 'has_more' => $this->hasMore($count, $next, (int) data_get($data, 'pagination.total_count', 0)),
+ ];
+ });
+ }
+
+ /**
+ * Whether another page follows. GIPHY's `total_count` runs ahead of what a
+ * search can reach, so an empty page ends the list whatever it says.
+ */
+ private function hasMore(int $count, int $next, int $total): bool
+ {
+ if ($count === 0 || $next > self::MAX_OFFSET) {
+ return false;
+ }
+
+ return $next < $total;
+ }
+
+ /**
+ * @param Closure(): ?array<mixed> $load
+ * @return array<mixed>|null
+ */
+ private function remember(string $key, Closure $load): ?array
+ {
+ $cacheKey = "giphy:{$key}";
+ $cached = Cache::get($cacheKey);
+
+ if (filled($cached)) {
+ return $cached;
+ }
+
+ $fresh = $load();
+
+ if (filled($fresh)) {
+ Cache::put($cacheKey, $fresh, now()->addMinutes(self::CACHE_MINUTES));
+ }
+
+ return $fresh;
+ }
+
+ /**
+ * @param array<string, mixed> $query
+ * @return array<mixed>|null
+ */
+ private function fetch(string $path, array $query): ?array
+ {
+ try {
+ $response = Http::timeout(self::TIMEOUT_SECONDS)->get("{$this->baseUrl}/{$path}", [...$query, 'api_key' => $this->apiKey]);
+ } catch (ConnectionException $exception) {
+ Log::warning('GIPHY request failed', ['path' => $path, 'error' => $exception->getMessage()]);
+
+ return null;
+ }
+
+ $data = $response->json();
+
+ if ($response->failed() || ! Arr::accessible($data)) {
+ Log::warning('GIPHY request failed', ['path' => $path, 'status' => $response->status()]);
+
+ return null;
+ }
+
+ return $data;
+ }
+
+ /**
+ * A GIF as the picker shows it: a light preview, and the rendition the
+ * post takes (`downsized_medium`, which GIPHY keeps under 5 MB, the
+ * smallest GIF cap of the networks that accept one).
+ *
+ * @param array<string, mixed> $gif
+ * @return array<string, mixed>
+ */
+ private function formatGif(array $gif): array
+ {
+ return [
+ 'id' => (string) data_get($gif, 'id'),
+ 'title' => data_get($gif, 'title'),
+ 'url_preview' => data_get($gif, 'images.fixed_width.url'),
+ 'url' => data_get($gif, 'images.downsized_medium.url'),
+ 'width' => (int) data_get($gif, 'images.fixed_width.width'),
+ 'height' => (int) data_get($gif, 'images.fixed_width.height'),
+ 'giphy_url' => data_get($gif, 'url'),
+ ];
+ }
+
+ private function perPage(): int
+ {
+ return (int) config('app.pagination.default');
+ }
+}
diff --git a/app/Services/Media/RemoteMediaImporter.php b/app/Services/Media/RemoteMediaImporter.php
index ce9fd5cdd..2930db60b 100644
--- a/app/Services/Media/RemoteMediaImporter.php
+++ b/app/Services/Media/RemoteMediaImporter.php
@@ -33,7 +33,7 @@ class RemoteMediaImporter
* that ends past it fails as `unreachable` before anything is stored.
* Redirects are refused unless `$followRedirects`.
*
- * @param array<MediaType> $allowedTypes
+ * @param list<MediaType> $allowedTypes
*/
public function import(Workspace $workspace, RemoteFile $file, array $allowedTypes, int $timeoutSeconds, ?CarbonInterface $deadline = null, bool $followRedirects = false): ImportedFile
{
diff --git a/app/Support/MediaImportStatus.php b/app/Support/MediaImportStatus.php
index 1bd55435d..035908046 100644
--- a/app/Support/MediaImportStatus.php
+++ b/app/Support/MediaImportStatus.php
@@ -4,12 +4,14 @@ declare(strict_types=1);
namespace App\Support;
+use App\Events\MediaImportSettled;
use App\Models\Media;
use Illuminate\Support\Facades\Cache;
/**
* The state of one queued import, kept in the cache for an hour and bound
- * to the user and workspace that started it.
+ * to the user and workspace that started it. Settling it (imported or
+ * failed) tells the workspace's composers through MediaImportSettled.
*/
final class MediaImportStatus
{
@@ -35,12 +37,12 @@ final class MediaImportStatus
public static function complete(string $importId, Media $media): void
{
- self::transition($importId, ['status' => self::DONE, 'media_id' => $media->id]);
+ self::settle($importId, ['status' => self::DONE, 'media_id' => $media->id]);
}
public static function fail(string $importId, string $reason): void
{
- self::transition($importId, ['status' => self::FAILED, 'reason' => $reason]);
+ self::settle($importId, ['status' => self::FAILED, 'reason' => $reason]);
}
/**
@@ -65,7 +67,7 @@ final class MediaImportStatus
/**
* @param array<string, mixed> $changes
*/
- private static function transition(string $importId, array $changes): void
+ private static function settle(string $importId, array $changes): void
{
$entry = Cache::get(self::key($importId));
@@ -74,6 +76,8 @@ final class MediaImportStatus
}
self::put($importId, [...$entry, ...$changes]);
+
+ MediaImportSettled::dispatch($importId, (string) data_get($entry, 'workspace_id'));
}
/**
diff --git a/config/services.php b/config/services.php
index 99f6758b0..469d1bfac 100644
--- a/config/services.php
+++ b/config/services.php
@@ -136,6 +136,10 @@ return [
'host' => env('POSTHOG_HOST', 'https://us.i.posthog.com'),
],
+ 'giphy' => [
+ 'api_key' => env('GIPHY_API_KEY'),
+ ],
+
'unsplash' => [
'access_key' => env('UNSPLASH_ACCESS_KEY'),
'secret_key' => env('UNSPLASH_SECRET_KEY'),
diff --git a/config/trypost.php b/config/trypost.php
index e308da1ff..a868db244 100644
--- a/config/trypost.php
+++ b/config/trypost.php
@@ -201,6 +201,14 @@ return [
*/
'media_sources' => [
+ 'giphy' => [
+ 'enabled' => (bool) env('GIPHY_ENABLED', true),
+ 'api' => 'https://api.giphy.com/v1',
+ 'website' => 'https://giphy.com',
+ 'download_hosts' => '*.giphy.com',
+ 'rating' => 'g',
+ 'requests_per_user_per_minute' => 30,
+ ],
'unsplash' => [
'api' => $url('UNSPLASH_API_URL', 'https://api.unsplash.com'),
'website' => $url('UNSPLASH_WEBSITE_URL', 'https://unsplash.com'),
diff --git a/docker/.env.docker.example b/docker/.env.docker.example
index b2515ca37..6cfa90543 100644
--- a/docker/.env.docker.example
+++ b/docker/.env.docker.example
@@ -197,6 +197,9 @@ NIGHTWATCH_TOKEN=
# Media Services
UNSPLASH_ACCESS_KEY=
UNSPLASH_SECRET_KEY=
+# GIPHY (https://developers.giphy.com/dashboard): GIFs in the composer's media menu.
+GIPHY_ENABLED=true
+GIPHY_API_KEY=
# Composer media sources (Google Drive, Google Photos, Canva).
# Each source is hidden until its flag is on AND its keys are set. Nothing falls back to GOOGLE_CLIENT_ID
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index 5a9e674aa..3dc10bcca 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'إلغاء الرفع',
'upload_remove' => 'إزالة',
'dropzone_select' => 'اختر ملفًا',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'ابحث عن صور GIF',
+ 'empty' => 'لم يتم العثور على صور GIF. جرّب بحثًا آخر.',
+ 'load_more' => 'تحميل المزيد',
+ 'error' => 'GIPHY غير متاح الآن. حاول مرة أخرى بعد بضع دقائق.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'ابحث عن صور مجانية عالية الدقة',
diff --git a/lang/de/posts.php b/lang/de/posts.php
index 14df5425b..34f8340ff 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Upload abbrechen',
'upload_remove' => 'Entfernen',
'dropzone_select' => 'Datei auswählen',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'GIFs suchen',
+ 'empty' => 'Keine GIFs gefunden. Versuche eine andere Suche.',
+ 'load_more' => 'Mehr laden',
+ 'error' => 'GIPHY ist gerade nicht erreichbar. Versuche es in ein paar Minuten erneut.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Kostenlose hochauflösende Fotos suchen',
diff --git a/lang/el/posts.php b/lang/el/posts.php
index 196a295c4..ca75240f9 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Ακύρωση μεταφόρτωσης',
'upload_remove' => 'Αφαίρεση',
'dropzone_select' => 'επιλέξτε αρχείο',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Αναζήτηση GIF',
+ 'empty' => 'Δεν βρέθηκαν GIF. Δοκιμάστε άλλη αναζήτηση.',
+ 'load_more' => 'Φόρτωση περισσότερων',
+ 'error' => 'Το GIPHY δεν είναι διαθέσιμο αυτή τη στιγμή. Δοκιμάστε ξανά σε λίγα λεπτά.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Αναζήτηση δωρεάν φωτογραφιών υψηλής ανάλυσης',
diff --git a/lang/en/posts.php b/lang/en/posts.php
index c05b9c034..a0a5b2ad3 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Cancel upload',
'upload_remove' => 'Remove',
'dropzone_select' => 'select a file',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Search GIFs',
+ 'empty' => 'No GIFs found. Try another search.',
+ 'load_more' => 'Load more',
+ 'error' => 'GIPHY isn\'t available right now. Try again in a few minutes.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Search free high-resolution photos',
diff --git a/lang/es/posts.php b/lang/es/posts.php
index c19572117..cef0d686a 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Cancelar subida',
'upload_remove' => 'Quitar',
'dropzone_select' => 'selecciona un archivo',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Busca GIFs',
+ 'empty' => 'No se encontraron GIFs. Prueba con otra búsqueda.',
+ 'load_more' => 'Cargar más',
+ 'error' => 'GIPHY no está disponible ahora. Inténtalo de nuevo en unos minutos.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Busca fotos gratuitas en alta resolución',
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index 9d6d38dcf..1891f413f 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Annuler l’import',
'upload_remove' => 'Retirer',
'dropzone_select' => 'sélectionnez un fichier',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Rechercher des GIF',
+ 'empty' => 'Aucun GIF trouvé. Essayez une autre recherche.',
+ 'load_more' => 'Charger plus',
+ 'error' => 'GIPHY n\'est pas disponible pour le moment. Réessayez dans quelques minutes.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Rechercher des photos gratuites en haute résolution',
diff --git a/lang/id/posts.php b/lang/id/posts.php
index d43911f57..3c1204d29 100644
--- a/lang/id/posts.php
+++ b/lang/id/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Batalkan unggahan',
'upload_remove' => 'Hapus',
'dropzone_select' => 'pilih file',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Cari GIF',
+ 'empty' => 'GIF tidak ditemukan. Coba kata kunci lain.',
+ 'load_more' => 'Muat lainnya',
+ 'error' => 'GIPHY sedang tidak tersedia. Coba lagi dalam beberapa menit.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Cari foto resolusi tinggi gratis',
diff --git a/lang/it/posts.php b/lang/it/posts.php
index e384bec59..10333e408 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Annulla caricamento',
'upload_remove' => 'Rimuovi',
'dropzone_select' => 'seleziona un file',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Cerca GIF',
+ 'empty' => 'Nessuna GIF trovata. Prova un\'altra ricerca.',
+ 'load_more' => 'Carica altro',
+ 'error' => 'GIPHY non è disponibile al momento. Riprova tra qualche minuto.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Cerca foto gratuite ad alta risoluzione',
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index befa5a262..410f3995a 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'アップロードをキャンセル',
'upload_remove' => '削除',
'dropzone_select' => 'ファイルを選択',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'GIFを検索',
+ 'empty' => 'GIFが見つかりません。別のキーワードで検索してください。',
+ 'load_more' => 'さらに読み込む',
+ 'error' => '現在 GIPHY を利用できません。数分後にもう一度お試しください。',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => '高解像度の無料写真を検索',
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index 0e2898f3e..a77ae82b4 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => '업로드 취소',
'upload_remove' => '제거',
'dropzone_select' => '파일 선택',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'GIF 검색',
+ 'empty' => 'GIF를 찾을 수 없습니다. 다른 검색어를 입력해 보세요.',
+ 'load_more' => '더 불러오기',
+ 'error' => '지금은 GIPHY를 사용할 수 없습니다. 몇 분 후에 다시 시도해 주세요.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => '무료 고해상도 사진 검색',
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index f3c9152a2..d44eb6dc6 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Upload annuleren',
'upload_remove' => 'Verwijderen',
'dropzone_select' => 'selecteer een bestand',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Zoek GIF\'s',
+ 'empty' => 'Geen GIF\'s gevonden. Probeer een andere zoekopdracht.',
+ 'load_more' => 'Meer laden',
+ 'error' => 'GIPHY is nu niet beschikbaar. Probeer het over een paar minuten opnieuw.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Zoek gratis foto\'s in hoge resolutie',
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index 91d73aef7..902bbb392 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Anuluj przesyłanie',
'upload_remove' => 'Usuń',
'dropzone_select' => 'wybierz plik',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Szukaj GIF-ów',
+ 'empty' => 'Nie znaleziono GIF-ów. Spróbuj innego wyszukiwania.',
+ 'load_more' => 'Wczytaj więcej',
+ 'error' => 'GIPHY jest teraz niedostępny. Spróbuj ponownie za kilka minut.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Szukaj darmowych zdjęć w wysokiej rozdzielczości',
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index 91e6e4220..c509b4948 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Cancelar envio',
'upload_remove' => 'Remover',
'dropzone_select' => 'selecione um arquivo',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Pesquise GIFs',
+ 'empty' => 'Nenhum GIF encontrado. Tente outra pesquisa.',
+ 'load_more' => 'Carregar mais',
+ 'error' => 'O GIPHY não está disponível agora. Tente novamente em alguns minutos.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Pesquise fotos gratuitas em alta resolução',
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 1f4ea9c7a..473430599 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Отменить загрузку',
'upload_remove' => 'Удалить',
'dropzone_select' => 'выберите файл',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Искать GIF',
+ 'empty' => 'GIF не найдены. Попробуйте другой запрос.',
+ 'load_more' => 'Загрузить ещё',
+ 'error' => 'GIPHY сейчас недоступен. Попробуйте снова через несколько минут.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Искать бесплатные фото в высоком разрешении',
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index ad189188e..df4fee9ed 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Yüklemeyi iptal et',
'upload_remove' => 'Kaldır',
'dropzone_select' => 'bir dosya seçin',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'GIF ara',
+ 'empty' => 'GIF bulunamadı. Başka bir arama deneyin.',
+ 'load_more' => 'Daha fazla yükle',
+ 'error' => 'GIPHY şu anda kullanılamıyor. Birkaç dakika sonra tekrar deneyin.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Ücretsiz yüksek çözünürlüklü fotoğraf ara',
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index bd280e963..100bf78f6 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => 'Скасувати завантаження',
'upload_remove' => 'Вилучити',
'dropzone_select' => 'виберіть файл',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => 'Шукати GIF',
+ 'empty' => 'GIF не знайдено. Спробуйте інший запит.',
+ 'load_more' => 'Завантажити ще',
+ 'error' => 'GIPHY зараз недоступний. Спробуйте ще раз за кілька хвилин.',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => 'Шукати безкоштовні фото у високій роздільності',
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index e25ed0174..be9f9a31d 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -53,6 +53,13 @@ return [
'upload_cancel' => '取消上传',
'upload_remove' => '移除',
'dropzone_select' => '选择文件',
+ 'giphy' => [
+ 'title' => 'GIPHY',
+ 'search_placeholder' => '搜索 GIF',
+ 'empty' => '未找到 GIF,请换个关键词试试。',
+ 'load_more' => '加载更多',
+ 'error' => 'GIPHY 当前不可用,请几分钟后重试。',
+ ],
'unsplash' => [
'title' => 'Unsplash',
'search_placeholder' => '搜索免费高清图片',
diff --git a/resources/js/components/create/ideas/IdeaEditorDialog.vue b/resources/js/components/create/ideas/IdeaEditorDialog.vue
index 87d7a5ae8..b729bce1e 100644
--- a/resources/js/components/create/ideas/IdeaEditorDialog.vue
+++ b/resources/js/components/create/ideas/IdeaEditorDialog.vue
@@ -15,6 +15,7 @@ import { computed, nextTick, ref, watch } from 'vue';
import WritingAssistantPanel from '@/components/ai/WritingAssistantPanel.vue';
import LabelChips from '@/components/labels/LabelChips.vue';
import LabelFilter from '@/components/labels/LabelFilter.vue';
+import GiphyDialog from '@/components/media/GiphyDialog.vue';
import MediaTray from '@/components/media/MediaTray.vue';
import UnsplashDialog from '@/components/media/UnsplashDialog.vue';
import MediaEditorDialog, {
@@ -114,8 +115,14 @@ const openUnsplash = (): void => {
unsplashOpen.value = true;
};
+const giphyOpen = ref(false);
+
+const openGiphy = (): void => {
+ giphyOpen.value = true;
+};
+
const mediaImport = useMediaImport();
-const onImportStarted = (started: MediaImportStarted): void =>
+const onImportStarted = (started: MediaImportStarted): Promise<void> =>
mediaImport.track(uploader, started);
const {
uploading: editUploading,
@@ -606,6 +613,7 @@ const iconButtonClass =
<MediaSourceMenu
test-id-prefix="idea-editor"
@import-started="onImportStarted"
+ @open-giphy="openGiphy"
@open-unsplash="openUnsplash"
@upload="pickFiles"
/>
@@ -689,5 +697,9 @@ const iconButtonClass =
:content-types="[]"
@apply="onMediaEdited"
/>
- <UnsplashDialog v-model:open="unsplashOpen" @picked="appendMedia" />
+ <UnsplashDialog
+ v-model:open="unsplashOpen"
+ @import-started="onImportStarted"
+ />
+ <GiphyDialog v-model:open="giphyOpen" @import-started="onImportStarted" />
</template>
diff --git a/resources/js/components/media/GiphyDialog.vue b/resources/js/components/media/GiphyDialog.vue
new file mode 100644
index 000000000..611a5a15c
--- /dev/null
+++ b/resources/js/components/media/GiphyDialog.vue
@@ -0,0 +1,337 @@
+<script setup lang="ts">
+import { useHttp } from '@inertiajs/vue3';
+import { IconLoader2, IconSearch } from '@tabler/icons-vue';
+import Giphy from '@thesvg/vue/giphy';
+import { useIntersectionObserver } from '@vueuse/core';
+import { trans } from 'laravel-vue-i18n';
+import { computed, ref, useTemplateRef, watch } from 'vue';
+
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import {
+ type MediaImportStarted,
+ startMediaImport,
+} from '@/composables/useMediaImport';
+import debounce from '@/debounce';
+import { blank, filled, transform } from '@/lib/helpers';
+import { search, trending } from '@/routes/app/media/giphy';
+
+interface GiphyGif {
+ id: string;
+ title: string | null;
+ url_preview: string;
+ url: string;
+ width: number;
+ height: number;
+ giphy_url: string | null;
+}
+
+interface GiphyPage {
+ results: GiphyGif[];
+ has_more: boolean;
+}
+
+const open = defineModel<boolean>('open', { required: true });
+
+const emit = defineEmits<{
+ (event: 'import-started', started: MediaImportStarted): void;
+}>();
+
+const SEARCH_DEBOUNCE_MS = 400;
+
+const query = ref('');
+const gifs = ref<GiphyGif[]>([]);
+const page = ref(1);
+const hasMore = ref(false);
+const loading = ref(false);
+const failed = ref(false);
+const savingId = ref<string | null>(null);
+const scroller = useTemplateRef<HTMLElement>('scroller');
+const sentinel = useTemplateRef<HTMLElement>('sentinel');
+let latestRequest = 0;
+
+const browseHttp = useHttp<Record<string, never>, GiphyPage>({});
+
+const hasGifs = computed((): boolean => filled(gifs.value));
+
+const showsEmpty = computed((): boolean => {
+ if (loading.value || failed.value) {
+ return false;
+ }
+
+ return blank(gifs.value);
+});
+
+const showsLoadMore = computed((): boolean => {
+ if (loading.value || failed.value) {
+ return false;
+ }
+
+ return hasMore.value;
+});
+
+const isPicking = computed((): boolean => filled(savingId.value));
+
+/** The page URL to read: a search while there is a term, else trending. */
+const pageUrl = (term: string, nextPage: number): string => {
+ if (blank(term)) {
+ return trending.url({ query: { page: String(nextPage) } });
+ }
+
+ return search.url({ query: { query: term, page: String(nextPage) } });
+};
+
+/** The GIFs already shown, plus the new page without the ones GIPHY repeats. */
+const mergedGifs = (results: GiphyGif[], nextPage: number): GiphyGif[] => {
+ if (nextPage === 1) {
+ return results;
+ }
+
+ const known = new Set(gifs.value.map((gif) => gif.id));
+
+ return [...gifs.value, ...results.filter((gif) => !known.has(gif.id))];
+};
+
+const load = async (nextPage: number): Promise<void> => {
+ const request = ++latestRequest;
+ loading.value = true;
+ failed.value = false;
+
+ try {
+ const response = await browseHttp.get(
+ pageUrl(query.value.trim(), nextPage),
+ );
+
+ if (request !== latestRequest) {
+ return;
+ }
+
+ gifs.value = mergedGifs(
+ transform(response, (found) => found.results, []),
+ nextPage,
+ );
+ page.value = nextPage;
+ hasMore.value = transform(response, (found) => found.has_more, false);
+ } catch {
+ if (request !== latestRequest) {
+ return;
+ }
+
+ if (nextPage === 1) {
+ gifs.value = [];
+ }
+
+ failed.value = true;
+ } finally {
+ if (request === latestRequest) {
+ loading.value = false;
+ }
+ }
+};
+
+const loadMore = (): void => {
+ if (!showsLoadMore.value) {
+ return;
+ }
+
+ void load(page.value + 1);
+};
+
+useIntersectionObserver(
+ sentinel,
+ ([entry]) => {
+ if (entry?.isIntersecting) {
+ loadMore();
+ }
+ },
+ { root: scroller, rootMargin: '200px' },
+);
+
+const searchDebounced = debounce(() => {
+ void load(1);
+}, SEARCH_DEBOUNCE_MS);
+
+const onSearchInput = (): void => {
+ searchDebounced();
+};
+
+watch(
+ open,
+ (isOpen) => {
+ if (!isOpen) {
+ searchDebounced.cancel();
+
+ return;
+ }
+
+ query.value = '';
+ gifs.value = [];
+ hasMore.value = false;
+ failed.value = false;
+ savingId.value = null;
+ void load(1);
+ },
+ { immediate: true },
+);
+
+/** The GIF's own size, so the grid keeps its shape while it loads. */
+const gifAspectRatio = (gif: GiphyGif): string | undefined => {
+ if (gif.width === 0 || gif.height === 0) {
+ return undefined;
+ }
+
+ return `${gif.width} / ${gif.height}`;
+};
+
+/** What a screen reader says for a GIF: its title, else the picker's name. */
+const gifLabel = (gif: GiphyGif, t: (key: string) => string): string => {
+ if (filled(gif.title)) {
+ return gif.title;
+ }
+
+ return t('posts.composer.giphy.title');
+};
+
+const isSaving = (gif: GiphyGif): boolean => savingId.value === gif.id;
+
+/** Starts the GIF's import and hands it to the post, which shows it loading. */
+const pick = async (gif: GiphyGif): Promise<void> => {
+ if (isPicking.value) {
+ return;
+ }
+
+ savingId.value = gif.id;
+
+ try {
+ const importIds = await startMediaImport({
+ source: 'giphy',
+ url: gif.url,
+ gif_id: gif.id,
+ giphy_url: gif.giphy_url,
+ });
+
+ if (blank(importIds)) {
+ return;
+ }
+
+ importIds.forEach((importId) =>
+ emit('import-started', {
+ importId,
+ label: trans('posts.composer.giphy.title'),
+ }),
+ );
+ open.value = false;
+ } finally {
+ savingId.value = null;
+ }
+};
+</script>
+
+<template>
+ <Dialog v-model:open="open">
+ <DialogContent
+ class="flex max-h-[85vh] flex-col gap-4 sm:max-w-3xl"
+ data-testid="giphy-dialog"
+ :aria-describedby="undefined"
+ >
+ <DialogHeader>
+ <DialogTitle class="flex items-center gap-2">
+ <Giphy class="size-5" aria-hidden="true" />
+ {{ $t('posts.composer.giphy.title') }}
+ </DialogTitle>
+ </DialogHeader>
+ <div class="relative">
+ <IconSearch
+ class="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ v-model="query"
+ type="search"
+ class="ps-9"
+ data-testid="giphy-search"
+ :placeholder="$t('posts.composer.giphy.search_placeholder')"
+ :aria-label="$t('posts.composer.giphy.search_placeholder')"
+ @update:model-value="onSearchInput"
+ />
+ </div>
+ <div
+ ref="scroller"
+ class="-mx-1 min-h-48 overflow-y-auto px-1"
+ :aria-busy="loading"
+ >
+ <div
+ v-if="hasGifs"
+ class="columns-2 gap-3 sm:columns-3"
+ data-testid="giphy-grid"
+ >
+ <button
+ v-for="(gif, i) in gifs"
+ :key="gif.id"
+ type="button"
+ :data-testid="`giphy-gif-${i}`"
+ :disabled="isPicking"
+ :aria-label="gifLabel(gif, $t)"
+ class="relative mb-3 block w-full break-inside-avoid overflow-hidden rounded-lg bg-muted transition-control hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-wait"
+ :style="{ aspectRatio: gifAspectRatio(gif) }"
+ @click="pick(gif)"
+ >
+ <img
+ :src="gif.url_preview"
+ alt=""
+ class="size-full object-cover"
+ loading="lazy"
+ />
+ <span
+ v-if="isSaving(gif)"
+ class="absolute inset-0 flex items-center justify-center bg-background/60"
+ >
+ <IconLoader2 class="size-5 animate-spin" />
+ </span>
+ </button>
+ </div>
+ <p
+ v-if="failed"
+ role="alert"
+ class="py-6 text-center text-sm text-destructive"
+ data-testid="giphy-error"
+ >
+ {{ $t('posts.composer.giphy.error') }}
+ </p>
+ <p
+ v-if="showsEmpty"
+ class="py-12 text-center text-sm text-muted-foreground"
+ data-testid="giphy-empty"
+ >
+ {{ $t('posts.composer.giphy.empty') }}
+ </p>
+ <div v-if="loading" class="flex justify-center py-6">
+ <IconLoader2
+ class="size-5 animate-spin text-muted-foreground"
+ aria-hidden="true"
+ />
+ </div>
+ <div
+ v-if="showsLoadMore"
+ class="flex flex-col items-center pt-1 pb-2"
+ >
+ <div ref="sentinel" class="h-px w-full" />
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ data-testid="giphy-load-more"
+ @click="loadMore"
+ >
+ {{ $t('posts.composer.giphy.load_more') }}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+</template>
diff --git a/resources/js/components/media/UnsplashDialog.vue b/resources/js/components/media/UnsplashDialog.vue
index ca34a8896..b8f5a7d00 100644
--- a/resources/js/components/media/UnsplashDialog.vue
+++ b/resources/js/components/media/UnsplashDialog.vue
@@ -1,10 +1,9 @@
<script setup lang="ts">
import { useHttp } from '@inertiajs/vue3';
import { IconLoader2, IconSearch } from '@tabler/icons-vue';
+import Unsplash from '@thesvg/vue/unsplash';
import { useIntersectionObserver } from '@vueuse/core';
-import { trans } from 'laravel-vue-i18n';
import { ref, useTemplateRef, watch } from 'vue';
-import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import {
@@ -14,11 +13,13 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
+import {
+ type MediaImportStarted,
+ startMediaImport,
+} from '@/composables/useMediaImport';
import debounce from '@/debounce';
-import { extractErrorMessage } from '@/lib/httpError';
-import { storeFromUrl } from '@/routes/app/media';
+import { blank } from '@/lib/helpers';
import { search, trending } from '@/routes/app/media/unsplash';
-import type { MediaItem, MediaSource, SourceMetaValue } from '@/types/media';
interface UnsplashPhoto {
id: string;
@@ -37,20 +38,14 @@ interface UnsplashPage {
total_pages?: number;
}
-type ImportedMedia = MediaItem & {
- meta?: MediaItem['meta'] & {
- source?: MediaSource;
- source_meta?: Record<string, SourceMetaValue>;
- };
-};
-
const open = defineModel<boolean>('open', { required: true });
const emit = defineEmits<{
- (event: 'picked', item: MediaItem): void;
+ (event: 'import-started', started: MediaImportStarted): void;
}>();
const SEARCH_DEBOUNCE_MS = 400;
+const SOURCE_LABEL = 'Unsplash';
const query = ref('');
const photos = ref<UnsplashPhoto[]>([]);
@@ -64,24 +59,6 @@ const sentinel = useTemplateRef<HTMLElement>('sentinel');
let latestRequest = 0;
const browseHttp = useHttp<Record<string, never>, UnsplashPage>({});
-const pickHttp = useHttp<
- {
- url: string;
- filename: string;
- download_location: string;
- photo_id: string;
- author_name: string;
- author_url: string | null;
- },
- ImportedMedia
->({
- url: '',
- filename: '',
- download_location: '',
- photo_id: '',
- author_name: '',
- author_url: null,
-});
const load = async (nextPage: number): Promise<void> => {
const request = ++latestRequest;
@@ -150,28 +127,30 @@ watch(
{ immediate: true },
);
+/** Starts the photo's import and hands it to the post, which shows it loading. */
const pick = async (photo: UnsplashPhoto): Promise<void> => {
if (savingId.value) return;
savingId.value = photo.id;
- pickHttp.url = photo.url_regular;
- pickHttp.filename = `unsplash-${photo.id}.jpg`;
- pickHttp.download_location = photo.download_location;
- pickHttp.photo_id = photo.id;
- pickHttp.author_name = photo.author.name;
- pickHttp.author_url = photo.author.url;
+
try {
- const media = await pickHttp.post(storeFromUrl.url());
- emit('picked', {
- ...media,
- source: media.meta?.source,
- source_meta: media.meta?.source_meta,
+ const importIds = await startMediaImport({
+ source: 'unsplash',
+ url: photo.url_regular,
+ filename: `unsplash-${photo.id}.jpg`,
+ download_location: photo.download_location,
+ photo_id: photo.id,
+ author_name: photo.author.name,
+ author_url: photo.author.url,
});
- open.value = false;
- } catch (exception) {
- toast.error(
- extractErrorMessage(exception) ??
- trans('posts.composer.media_sources.errors.import_failed'),
+
+ if (blank(importIds)) {
+ return;
+ }
+
+ importIds.forEach((importId) =>
+ emit('import-started', { importId, label: SOURCE_LABEL }),
);
+ open.value = false;
} finally {
savingId.value = null;
}
@@ -206,9 +185,13 @@ const creditParts = (
:aria-describedby="undefined"
>
<DialogHeader>
- <DialogTitle>{{
- $t('posts.composer.unsplash.title')
- }}</DialogTitle>
+ <DialogTitle class="flex items-center gap-2">
+ <Unsplash
+ class="size-5 fill-current text-foreground"
+ aria-hidden="true"
+ />
+ {{ $t('posts.composer.unsplash.title') }}
+ </DialogTitle>
</DialogHeader>
<div class="relative">
<IconSearch
diff --git a/resources/js/components/posts/composer/ComposerEditorToolbar.vue b/resources/js/components/posts/composer/ComposerEditorToolbar.vue
index 05896bc9b..57c51ed10 100644
--- a/resources/js/components/posts/composer/ComposerEditorToolbar.vue
+++ b/resources/js/components/posts/composer/ComposerEditorToolbar.vue
@@ -39,6 +39,7 @@ withDefaults(
const emit = defineEmits<{
(event: 'import-started', payload: { importId: string; label: string }): void;
+ (event: 'open-giphy'): void;
(event: 'open-unsplash'): void;
(event: 'upload'): void;
(event: 'add-poll'): void;
@@ -90,6 +91,7 @@ const selectEmoji = (emoji: string): void => {
:disabled="mediaDisabled"
:disabled-reason="$t(mediaDisabledReasonKey)"
@import-started="emit('import-started', $event)"
+ @open-giphy="emit('open-giphy')"
@open-unsplash="emit('open-unsplash')"
@upload="requestUpload"
/>
diff --git a/resources/js/components/posts/composer/MediaSourceMenu.vue b/resources/js/components/posts/composer/MediaSourceMenu.vue
index 4d5ee9b33..f9b57baf3 100644
--- a/resources/js/components/posts/composer/MediaSourceMenu.vue
+++ b/resources/js/components/posts/composer/MediaSourceMenu.vue
@@ -2,6 +2,7 @@
import { usePage } from '@inertiajs/vue3';
import { IconPhotoPlus, IconUpload } from '@tabler/icons-vue';
import Canva from '@thesvg/vue/canva';
+import Giphy from '@thesvg/vue/giphy';
import GoogleDrive from '@thesvg/vue/google-drive-2026';
import GooglePhotos from '@thesvg/vue/google-photos';
import Unsplash from '@thesvg/vue/unsplash';
@@ -27,7 +28,7 @@ import {
} from '@/components/ui/tooltip';
import {
type MediaImportPayload,
- useMediaImport,
+ startMediaImport,
} from '@/composables/useMediaImport';
import { filled } from '@/lib/helpers';
import { defaultCanvaPreset, openCanva } from '@/lib/mediaSources/canva';
@@ -55,12 +56,14 @@ withDefaults(
const emit = defineEmits<{
(event: 'import-started', payload: { importId: string; label: string }): void;
+ (event: 'open-giphy'): void;
(event: 'open-unsplash'): void;
(event: 'upload'): void;
}>();
const ICONS: Record<SourceKey, Component> = {
canva: Canva,
+ giphy: Giphy,
google_drive: GoogleDrive,
google_photos: GooglePhotos,
unsplash: Unsplash,
@@ -72,13 +75,12 @@ const ICON_CLASSES: Partial<Record<SourceKey, string>> = {
};
const page = usePage();
-const mediaImport = useMediaImport();
const startImport = async (
option: MediaSourceOption,
payload: MediaImportPayload,
): Promise<void> => {
- const importIds = await mediaImport.run(payload);
+ const importIds = await startMediaImport(payload);
importIds.forEach((importId) =>
emit('import-started', { importId, label: option.label }),
);
@@ -170,6 +172,7 @@ const handlers: Partial<
session_id: picked.sessionId,
});
},
+ giphy: () => emit('open-giphy'),
unsplash: () => emit('open-unsplash'),
};
diff --git a/resources/js/components/posts/composer/PostComposerDialog.vue b/resources/js/components/posts/composer/PostComposerDialog.vue
index c06c7a6f7..35d2346ef 100644
--- a/resources/js/components/posts/composer/PostComposerDialog.vue
+++ b/resources/js/components/posts/composer/PostComposerDialog.vue
@@ -38,6 +38,7 @@ import {
ref,
shallowReactive,
watch,
+ type WritableComputedRef,
} from 'vue';
import { toast } from 'vue-sonner';
@@ -50,6 +51,7 @@ import EmptyState from '@/components/EmptyState.vue';
import FilterEmptyState from '@/components/FilterEmptyState.vue';
import LabelChips from '@/components/labels/LabelChips.vue';
import LabelFilter from '@/components/labels/LabelFilter.vue';
+import GiphyDialog from '@/components/media/GiphyDialog.vue';
import MediaTray from '@/components/media/MediaTray.vue';
import UnsplashDialog from '@/components/media/UnsplashDialog.vue';
import PlatformLogo from '@/components/PlatformLogo.vue';
@@ -123,6 +125,7 @@ import {
import { useMediaEditSwap, withMediaAdded } from '@/composables/useMediaEditSwap';
import {
type MediaImportStarted,
+ startMediaImport,
useMediaImport,
} from '@/composables/useMediaImport';
import { getMediaRulesForContentType } from '@/composables/useMediaRules';
@@ -162,7 +165,6 @@ import {
} from '@/lib/googleBusiness';
import { countHashtags } from '@/lib/hashtags';
import { blank, filled, transform } from '@/lib/helpers';
-import { extractErrorMessage } from '@/lib/httpError';
import { getInstagramImageAspectIssues } from '@/lib/instagramImageAspect';
import { linkPreviewDroppable, linkPreviewUrl } from '@/lib/linkPreview';
import {
@@ -699,20 +701,31 @@ watch(
},
{ immediate: true },
);
-const linkCardMediaHttp = useHttp<{ url: string }, MediaItem>({ url: '' });
+const replacingLinkCard = ref(false);
+/**
+ * Imports the link card's image into the card's post, which shows it
+ * loading under the link's site; the card's button waits until it landed.
+ */
const replaceLinkCardWithMedia = async (group: NetworkGroup): Promise<void> => {
if (!openLinkCard.value) return;
- linkCardMediaHttp.url = openLinkCard.value.uri;
+ if (replacingLinkCard.value) return;
+ const link = openLinkCard.value.uri;
+ const label = new URL(link).hostname;
+ replacingLinkCard.value = true;
+
try {
- appendMedia(
- group.key,
- await linkCardMediaHttp.post(linkPreviewMedia.url()),
+ const importIds = await startMediaImport(
+ { url: link },
+ linkPreviewMedia.url(),
);
- } catch (exception) {
- toast.error(
- extractErrorMessage(exception) ??
- trans('posts.composer.media_sources.errors.import_failed'),
+
+ await Promise.all(
+ importIds.map((importId) =>
+ mediaImport.track(uploaderFor(group.key), { importId, label }),
+ ),
);
+ } finally {
+ replacingLinkCard.value = false;
}
};
const uploadScope = effectScope();
@@ -771,33 +784,61 @@ watch(
if (!open) suggestedMedia.value = {};
},
);
-const unsplashOpen = ref(false);
-const unsplashGroupKey = ref<string | null>(null);
-const unsplashReplyKey = ref<string | null>(null);
-const openUnsplash = (
+/** The media libraries the composer opens in a dialog of its own. */
+type LibrarySource = 'giphy' | 'unsplash';
+
+const openLibrarySource = ref<LibrarySource | null>(null);
+const libraryGroupKey = ref<string | null>(null);
+const libraryReplyKey = ref<string | null>(null);
+const openLibrary = (
+ source: LibrarySource,
groupKey: string | null,
replyKey: string | null = null,
): void => {
- unsplashGroupKey.value = groupKey;
- unsplashReplyKey.value = replyKey;
- unsplashOpen.value = true;
-};
-const onUnsplashPicked = (item: MediaItem): void => {
- if (unsplashGroupKey.value !== null && unsplashReplyKey.value !== null) {
- setReplyMedia(unsplashGroupKey.value, unsplashReplyKey.value, (media) =>
- withMediaAdded(media, item, null),
+ libraryGroupKey.value = groupKey;
+ libraryReplyKey.value = replyKey;
+ openLibrarySource.value = source;
+};
+/** One library dialog's `open`: it is open while it is the library picked. */
+const libraryOpen = (source: LibrarySource): WritableComputedRef<boolean> =>
+ computed({
+ get: (): boolean => openLibrarySource.value === source,
+ set: (open: boolean): void => {
+ if (open) {
+ openLibrarySource.value = source;
+
+ return;
+ }
+
+ if (openLibrarySource.value === source) {
+ openLibrarySource.value = null;
+ }
+ },
+ });
+const unsplashOpen = libraryOpen('unsplash');
+const giphyOpen = libraryOpen('giphy');
+/** The uploader of the post the open library adds to: the thread reply it was opened on, else the card or the shared post. */
+const libraryUploader = (): MediaUploader => {
+ if (filled(libraryGroupKey.value) && filled(libraryReplyKey.value)) {
+ const replyUploader = replyUploaders.get(
+ replyUploaderKey(libraryGroupKey.value, libraryReplyKey.value),
);
- return;
+ if (filled(replyUploader)) {
+ return replyUploader;
+ }
}
- appendMedia(unsplashGroupKey.value, item);
+
+ return uploaderFor(libraryGroupKey.value);
};
const mediaImport = useMediaImport();
+const onLibraryImportStarted = (started: MediaImportStarted): Promise<void> =>
+ mediaImport.track(libraryUploader(), started);
const onImportStarted = (
started: MediaImportStarted,
groupKey: string | null,
-): void => mediaImport.track(uploaderFor(groupKey), started);
+): Promise<void> => mediaImport.track(uploaderFor(groupKey), started);
watch(customizing, (isCustomizing) => {
if (isCustomizing) return;
uploaders.forEach((uploader, key) => {
@@ -1379,9 +1420,19 @@ const groupAcceptsMedia = (group: NetworkGroup): boolean => {
const onGroupImportStarted = (
started: MediaImportStarted,
group: NetworkGroup,
-): void => mediaImport.track(groupMediaUploader(group), started);
-const openGroupUnsplash = (group: NetworkGroup): void =>
- openUnsplash(group.key, activeReply(group)?.key ?? null);
+): Promise<void> => mediaImport.track(groupMediaUploader(group), started);
+/** Opens a library for a network card, or for the thread reply being edited on it. */
+const openGroupLibrary = (source: LibrarySource, group: NetworkGroup): void => {
+ const reply = activeReply(group);
+
+ if (filled(reply)) {
+ openLibrary(source, group.key, reply.key);
+
+ return;
+ }
+
+ openLibrary(source, group.key);
+};
const onGroupMediaDropped = (event: DragEvent, group: NetworkGroup): void => {
if (!activeReply(group)) {
onMediaDropped(event, group.key);
@@ -2707,7 +2758,8 @@ const onDialogOpenChange = (value: boolean): void => {
:signatures="availableSignatures"
:media-disabled="!acceptsMedia(null)"
@import-started="onImportStarted($event, null)"
- @open-unsplash="openUnsplash(null)"
+ @open-giphy="openLibrary('giphy', null)"
+ @open-unsplash="openLibrary('unsplash', null)"
@upload="pickBaseFiles"
@select-emoji="appendEmoji($event, null)"
@select-signature="appendSignature($event, null)"
@@ -2880,7 +2932,7 @@ const onDialogOpenChange = (value: boolean): void => {
:removable="
linkPreviewDroppable(group.platform)
"
- :replacing="linkCardMediaHttp.processing"
+ :replacing="replacingLinkCard"
:disabled="cropUploading"
@remove="dropLinkCard(group)"
@replace="replaceLinkCardWithMedia(group)"
@@ -3120,7 +3172,12 @@ const onDialogOpenChange = (value: boolean): void => {
@import-started="
onGroupImportStarted($event, group)
"
- @open-unsplash="openGroupUnsplash(group)"
+ @open-giphy="
+ openGroupLibrary('giphy', group)
+ "
+ @open-unsplash="
+ openGroupLibrary('unsplash', group)
+ "
@upload="pickGroupFiles(group)"
@select-emoji="
appendEmoji($event, group.key)
@@ -3650,8 +3707,9 @@ const onDialogOpenChange = (value: boolean): void => {
/>
<UnsplashDialog
v-model:open="unsplashOpen"
- @picked="onUnsplashPicked"
+ @import-started="onLibraryImportStarted"
/>
+ <GiphyDialog v-model:open="giphyOpen" @import-started="onLibraryImportStarted" />
<ComposerDiscardDialog
v-model:open="unsavedChanges.confirming.value"
:title="$t('common.unsaved_changes.title')"
diff --git a/resources/js/composables/useMediaImport.ts b/resources/js/composables/useMediaImport.ts
index d60786fde..eec9a2233 100644
--- a/resources/js/composables/useMediaImport.ts
+++ b/resources/js/composables/useMediaImport.ts
@@ -1,15 +1,25 @@
import { useHttp } from '@inertiajs/vue3';
+import { useConnectionStatus } from '@laravel/echo-vue';
import { trans } from 'laravel-vue-i18n';
-import { getCurrentScope, onScopeDispose } from 'vue';
+import { getCurrentScope, onScopeDispose, watch } from 'vue';
import { toast } from 'vue-sonner';
+import { useWorkspaceEcho } from '@/composables/echo/useWorkspaceEcho';
import type { MediaUploader } from '@/composables/useMediaUpload';
+import { filled } from '@/lib/helpers';
+import { extractErrorMessage } from '@/lib/httpError';
import { show, store } from '@/routes/app/media/imports';
import type { MediaItem } from '@/types/media';
+/** The fields a request that starts an import sends. */
+export type MediaImportRequest = Record<
+ string,
+ string | number | null | Record<string, string>
+>;
+
export type MediaImportPayload = {
source: string;
-} & Record<string, string | number | null | Record<string, string>>;
+} & MediaImportRequest;
export interface MediaImportStarted {
importId: string;
@@ -29,8 +39,6 @@ interface MediaImportStatus {
replaces: string | null;
}
-export const IMPORT_POLL_INTERVAL_MS = 1500;
-
const FAILURE_REASONS = [
'unreachable',
'host_not_allowed',
@@ -47,95 +55,180 @@ export const importErrorKey = (reason: string): string =>
? `posts.composer.media_sources.errors.${reason}`
: 'posts.composer.media_sources.errors.import_failed';
-const MAX_POLLS = 800;
+/** Why a failed import failed; an import without a reason could not be reached. */
+const failureReason = (status: MediaImportStatus): string => {
+ if (filled(status.reason)) {
+ return status.reason;
+ }
+
+ return 'unreachable';
+};
+
+/** What the workspace channel says when one of its imports settled. */
+interface MediaImportSettled {
+ import_id: string;
+}
+
+/**
+ * Why an import could not start: the first validation error the server
+ * gave, else its message, else a generic failure.
+ */
+const startFailureMessage = (
+ errors: Record<string, string>,
+ exception: unknown,
+): string => {
+ const [validationError] = Object.values(errors);
+
+ if (filled(validationError)) {
+ return validationError;
+ }
+
+ const message = extractErrorMessage(exception);
-const wait = (milliseconds: number): Promise<void> =>
- new Promise((resolve) => window.setTimeout(resolve, milliseconds));
+ if (filled(message)) {
+ return message;
+ }
+
+ return trans('posts.composer.media_sources.errors.import_failed');
+};
/**
- * Starts a queued import and polls its status until the file is a
- * temporary upload or the import failed. Failures toast; successes are
- * shown by the tile they fill.
+ * Starts a queued import (a picker source by default, or another endpoint
+ * that queues one). The ids of the imports it started, in tile order; empty
+ * when it could not start, which toasts why.
+ */
+export const startMediaImport = async (
+ payload: MediaImportRequest,
+ url: string = store.url(),
+): Promise<string[]> => {
+ const http = useHttp<MediaImportRequest, { import_ids: string[] }>(
+ payload,
+ );
+
+ try {
+ const response = await http.post(url);
+
+ return response.import_ids;
+ } catch (exception) {
+ toast.error(startFailureMessage(http.errors, exception));
+
+ return [];
+ }
+};
+
+/**
+ * Waits for started imports until each file is a temporary upload or the
+ * import failed. The job tells the workspace channel when an import
+ * settled (`MediaImportSettled`), and only then is its status read; it is
+ * also read once right after the tile appears, in case the job finished
+ * before the composer heard of the import, and again whenever the socket
+ * connects anew, since an event sent while it was down never arrives.
+ * Failures toast; successes are shown by the tile they fill.
*/
export const useMediaImport = () => {
let disposed = false;
+ const waiting = new Map<string, () => void>();
- if (getCurrentScope()) {
- onScopeDispose(() => {
- disposed = true;
- });
- }
+ const wake = (importId: string): void => {
+ const resume = waiting.get(importId);
- const failed = (): null => {
- if (!disposed) {
- toast.error(trans('posts.composer.media_sources.errors.import_failed'));
+ if (resume === undefined) {
+ return;
}
- return null;
+ waiting.delete(importId);
+ resume();
};
- /** The imports a pick started, in tile order; empty when it could not start. */
- const run = async (payload: MediaImportPayload): Promise<string[]> => {
- const http = useHttp<MediaImportPayload, { import_ids: string[] }>(
- payload,
- );
+ useWorkspaceEcho<MediaImportSettled>('.media.import.settled', (payload) =>
+ wake(payload.import_id),
+ );
- try {
- const response = await http.post(store.url());
+ watch(useConnectionStatus(), (status) => {
+ if (status !== 'connected') {
+ return;
+ }
- return response.import_ids;
- } catch {
- failed();
+ [...waiting.keys()].forEach(wake);
+ });
- return [];
- }
- };
+ if (getCurrentScope()) {
+ onScopeDispose(() => {
+ disposed = true;
+ [...waiting.keys()].forEach(wake);
+ });
+ }
+
+ const settledOnce = (importId: string): Promise<void> =>
+ new Promise((resolve) => waiting.set(importId, resolve));
const waitFor = async (
importId: string,
- onFailed?: (reason: string) => void,
- isWanted: () => boolean = () => true,
+ onFailed: (reason: string) => void,
+ isWanted: () => boolean,
): Promise<MediaImportResult | null> => {
const fail = (reason: string): null => {
- onFailed?.(reason);
+ onFailed(reason);
- return failed();
+ if (!disposed) {
+ toast.error(
+ trans('posts.composer.media_sources.errors.import_failed'),
+ );
+ }
+
+ return null;
};
const http = useHttp<Record<string, never>, MediaImportStatus>({});
+ const stillWanted = (): boolean => {
+ if (disposed) {
+ return false;
+ }
- const polling = (): boolean => !disposed && isWanted();
+ return isWanted();
+ };
- for (let poll = 0; poll < MAX_POLLS && polling(); poll++) {
+ while (stillWanted()) {
+ const settled = settledOnce(importId);
let status: MediaImportStatus;
try {
status = await http.get(show.url(importId));
} catch {
+ waiting.delete(importId);
+
return fail('unreachable');
}
- if (!polling()) {
+ if (!stillWanted()) {
+ waiting.delete(importId);
+
return null;
}
if (status.status === 'done') {
- return status.media
- ? { item: status.media, replaces: status.replaces }
- : fail('unreachable');
+ waiting.delete(importId);
+
+ if (filled(status.media)) {
+ return { item: status.media, replaces: status.replaces };
+ }
+
+ return fail('unreachable');
}
if (status.status === 'failed') {
- return fail(status.reason ?? 'unreachable');
+ waiting.delete(importId);
+
+ return fail(failureReason(status));
}
- await wait(IMPORT_POLL_INTERVAL_MS);
+ await settled;
}
- return polling() ? fail('unreachable') : null;
+ return null;
};
/**
* Shows a started import as a pending tile of `uploader` and fills or
* fails that tile when the import settles; a tile removed meanwhile
- * stops the polling.
+ * stops waiting for it. Resolves once the tile settled.
*/
const track = (
uploader: Pick<
@@ -143,9 +236,10 @@ export const useMediaImport = () => {
'addPending' | 'resolvePending' | 'imports'
>,
{ importId, label, replaces = null }: MediaImportStarted,
- ): void => {
+ ): Promise<void> => {
uploader.addPending(importId, label, replaces);
- void waitFor(
+
+ return waitFor(
importId,
(reason) => uploader.resolvePending(importId, null, reason),
() =>
@@ -158,5 +252,5 @@ export const useMediaImport = () => {
});
};
- return { run, waitFor, track };
+ return { track };
};
diff --git a/resources/js/lib/mediaSources/googlePhotos.ts b/resources/js/lib/mediaSources/googlePhotos.ts
index 081dcc744..4840c128b 100644
--- a/resources/js/lib/mediaSources/googlePhotos.ts
+++ b/resources/js/lib/mediaSources/googlePhotos.ts
@@ -36,15 +36,16 @@ const discardSession = (sessionId: string): void => {
};
/**
- * Polls the session until the user picked, closed the window or Google's
- * timeout passed. `popup.closed` only means "closed" when the window was
- * still reachable once the session arrived: a popup cut off from this
- * window reads closed while the user is still picking.
+ * Polls the session until the user picked or Google's timeout passed.
+ * Whether the window was closed cannot be told: Google's picker cuts the
+ * popup off from this window (its opener policy), so `popup.closed` reads
+ * true while the user is still picking, and deleting the session then
+ * makes Google refuse their "Done". A picker closed without choosing is
+ * discarded when the session times out.
*/
const waitForPick = async (
popup: Window,
session: ClaimedSession,
- closeIsReliable: boolean,
): Promise<GooglePhotosPick | null> => {
const http = useHttp<Record<string, never>, SessionStatus>({});
const deadline = dayjs().add(session.polling.timeout_ms, 'millisecond');
@@ -53,7 +54,6 @@ const waitForPick = async (
while (dayjs().isBefore(deadline)) {
await wait(interval);
- const closed = closeIsReliable && popup.closed;
let status: SessionStatus;
try {
@@ -70,11 +70,6 @@ const waitForPick = async (
return { sessionId: session.session_id };
}
- if (closed) {
- discardSession(session.session_id);
-
- return null;
- }
interval = status.polling.interval_ms;
}
@@ -91,8 +86,8 @@ const waitForPick = async (
* server then creates the picker session with the token it keeps, and the
* popup moves on to the picker. Resolves the session the server imports
* every picked item from, or null when the popup was
- * blocked, sign-in failed (a toast says why) or the user closed the picker
- * without choosing.
+ * blocked, sign-in failed (a toast says why) or the session timed out
+ * without a choice.
*/
export const pickFromGooglePhotos = async (
signal?: AbortSignal,
@@ -107,5 +102,5 @@ export const pickFromGooglePhotos = async (
const session = await signIn.result;
if (!session?.session_id) return null;
- return waitForPick(signIn.popup, session, !signIn.popup.closed);
+ return waitForPick(signIn.popup, session);
};
diff --git a/resources/js/types/index.d.ts b/resources/js/types/index.d.ts
index 3ee5adb2f..0bc96f74e 100644
--- a/resources/js/types/index.d.ts
+++ b/resources/js/types/index.d.ts
@@ -87,7 +87,7 @@ export interface CanvaPresetOption {
}
export interface MediaSourceOption {
- source: 'google_drive' | 'google_photos' | 'canva' | 'unsplash';
+ source: 'google_drive' | 'google_photos' | 'canva' | 'giphy' | 'unsplash';
label: string;
config: Record<string, string>;
presets?: CanvaPresetOption[];
diff --git a/resources/js/types/media.ts b/resources/js/types/media.ts
index 90f375a8e..36e5dbf3e 100644
--- a/resources/js/types/media.ts
+++ b/resources/js/types/media.ts
@@ -2,7 +2,7 @@ import type { ImageSize } from '@/composables/useImageCrop';
import type { MediaEdit } from '@/lib/mediaEditor';
import type { MediaType } from '@/lib/mediaType';
-export type MediaSource = 'ai' | 'unsplash' | 'google_drive' | 'google_photos' | 'canva';
+export type MediaSource = 'ai' | 'unsplash' | 'giphy' | 'google_drive' | 'google_photos' | 'canva';
export type SourceMetaValue = string | number | boolean | null | SourceMetaValue[];
diff --git a/routes/app.php b/routes/app.php
index 48a798668..4649dcda1 100644
--- a/routes/app.php
+++ b/routes/app.php
@@ -14,6 +14,7 @@ use App\Http\Controllers\App\ChannelQueueController;
use App\Http\Controllers\App\ComposerAccountDataController;
use App\Http\Controllers\App\ComposerLiveDataController;
use App\Http\Controllers\App\DiscordController as AppDiscordController;
+use App\Http\Controllers\App\GiphyController;
use App\Http\Controllers\App\GoogleMediaController;
use App\Http\Controllers\App\GooglePhotosSessionController;
use App\Http\Controllers\App\IdeaController;
@@ -300,9 +301,12 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]
Route::post('media/chunked', [MediaUploadController::class, 'storeChunked'])->name('app.media.store-chunked');
Route::get('media/{media}/file', [MediaFileController::class, 'show'])->whereUuid('media')->name('app.media.file');
- Route::post('media/from-url', [MediaUploadController::class, 'storeFromUrl'])
- ->middleware('throttle:media-imports')
- ->name('app.media.store-from-url');
+ Route::get('media/giphy/search', [GiphyController::class, 'search'])
+ ->middleware('throttle:giphy')
+ ->name('app.media.giphy.search');
+ Route::get('media/giphy/trending', [GiphyController::class, 'trending'])
+ ->middleware('throttle:giphy')
+ ->name('app.media.giphy.trending');
Route::get('media/unsplash/search', [UnsplashController::class, 'search'])
->middleware('throttle:unsplash')
->name('app.media.unsplash.search');
diff --git a/tests/Browser/ComposerCanvaMenuTest.php b/tests/Browser/ComposerCanvaMenuTest.php
index 951d133dd..90f2c62bd 100644
--- a/tests/Browser/ComposerCanvaMenuTest.php
+++ b/tests/Browser/ComposerCanvaMenuTest.php
@@ -23,6 +23,7 @@ function openComposerWithOnlyCanva(mixed $test): array
{
config()->set([
'services.unsplash.access_key' => null,
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => null,
'services.google_media.api_key' => null,
'services.google_media.app_id' => null,
diff --git a/tests/Browser/ComposerEditInCanvaTest.php b/tests/Browser/ComposerEditInCanvaTest.php
index 44ef8b8c8..ecd6455ec 100644
--- a/tests/Browser/ComposerEditInCanvaTest.php
+++ b/tests/Browser/ComposerEditInCanvaTest.php
@@ -88,6 +88,7 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
Storage::fake();
config()->set([
'services.unsplash.access_key' => null,
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => null,
'services.google_media.api_key' => null,
'services.google_media.app_id' => null,
@@ -161,6 +162,7 @@ test('the Canva button shows only on Canva-made tiles and replaces the tile in p
->and($page->script("document.querySelectorAll('[data-testid^=\"composer-media-item-\"]').length"))->toBe(2);
MediaImportStatus::complete($exporting, $sharedEdited['media']);
+ broadcastToPage($page, "workspace.{$workspace->id}", 'media.import.settled', ['import_id' => $exporting]);
waitForState($page, '@composer-media-item-0 img', "element.getAttribute('src') === '{$sharedEdited['media']->url}'");
expect(editInCanvaTileSrc($page, 'composer', 0))->toBe($sharedEdited['media']->url)
diff --git a/tests/Browser/ComposerGooglePhotosTest.php b/tests/Browser/ComposerGooglePhotosTest.php
index 50f5927ba..82b5a4bd1 100644
--- a/tests/Browser/ComposerGooglePhotosTest.php
+++ b/tests/Browser/ComposerGooglePhotosTest.php
@@ -48,10 +48,16 @@ function chooseComposerGooglePhotos(mixed $page): void
$page->click('@media-source-google_photos');
}
-function enableOnlyGooglePhotosForComposer(bool $mediaItemsSet = true): string
+/**
+ * Google Photos alone in the media menu, with Google faked. The session
+ * answers "not picked yet" to its first `$readsBeforePicked` reads, then
+ * picked.
+ */
+function enableOnlyGooglePhotosForComposer(int $readsBeforePicked = 0): string
{
config()->set([
'services.unsplash.access_key' => null,
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => 'media-client-id',
'services.google_media.client_secret' => 'media-client-secret',
'services.google_media.redirect' => 'https://trypost.example/integrations/google/callback',
@@ -68,6 +74,7 @@ function enableOnlyGooglePhotosForComposer(bool $mediaItemsSet = true): string
test()->mock(HostResolver::class)->shouldReceive('addresses')->andReturn(['142.250.0.10']);
$api = config('trypost.media_sources.google_photos.api').'/v1';
+ $sessionReads = 0;
Http::fake([
'https://oauth2.google.test/token' => Http::response([
@@ -75,13 +82,19 @@ function enableOnlyGooglePhotosForComposer(bool $mediaItemsSet = true): string
'expires_in' => 3599,
'scope' => COMPOSER_GOOGLE_PHOTOS_SCOPE,
]),
- "{$api}/sessions/*" => fn (Request $request) => $request->method() === 'DELETE'
- ? Http::response([], 200)
- : Http::response([
+ "{$api}/sessions/*" => function (Request $request) use (&$sessionReads, $readsBeforePicked) {
+ if ($request->method() === 'DELETE') {
+ return Http::response([], 200);
+ }
+
+ $sessionReads++;
+
+ return Http::response([
'id' => COMPOSER_GOOGLE_PHOTOS_SESSION,
- 'mediaItemsSet' => $mediaItemsSet,
+ 'mediaItemsSet' => $sessionReads > $readsBeforePicked,
'pollingConfig' => ['pollInterval' => '1s', 'timeoutIn' => '60s'],
- ]),
+ ]);
+ },
"{$api}/sessions" => Http::response([
'id' => COMPOSER_GOOGLE_PHOTOS_SESSION,
'pickerUri' => COMPOSER_GOOGLE_PHOTOS_PICKER_URI,
@@ -206,14 +219,13 @@ test('the real sign-in popup opens the picker and every picked photo becomes its
Http::assertSent(fn (Request $request): bool => $request->url() === 'https://lh3.googleusercontent.com/composer-logo=d');
});
-test('closing the google photos window without picking adds nothing and discards the session', function () {
- $api = enableOnlyGooglePhotosForComposer(mediaItemsSet: false);
-
- $page = openComposerForGooglePhotos($this);
- stubGooglePhotosPopupForComposer($page);
+/**
+ * Hands the composer the picker session as the sign-in popup does, with
+ * `$timeoutMs` as Google's timeout.
+ */
+function deliverGooglePhotosSessionToComposer(mixed $page, int $timeoutMs): void
+{
$user = User::query()->sole();
-
- chooseComposerGooglePhotos($page);
parse_str((string) parse_url(googlePhotosSignInUrl($page), PHP_URL_QUERY), $query);
$nonce = (string) data_get($query, 'nonce');
@@ -223,7 +235,7 @@ test('closing the google photos window without picking adds nothing and discards
'workspace_id' => $user->current_workspace_id,
'source' => 'google_photos',
'session_id' => COMPOSER_GOOGLE_PHOTOS_SESSION,
- 'polling' => ['interval_ms' => 1000, 'timeout_ms' => 60000],
+ 'polling' => ['interval_ms' => 1000, 'timeout_ms' => $timeoutMs],
], 600);
$page->script(<<<JS
@@ -234,7 +246,34 @@ test('closing the google photos window without picking adds nothing and discards
true;
JS);
waitForCondition($page, "window.__photos.finished.some((request) => request.includes('/integrations/google/returns/'))");
+}
+
+test('the picker window reading closed once it reaches google keeps the session until the user picks', function () {
+ enableOnlyGooglePhotosForComposer(readsBeforePicked: 3);
+
+ $page = openComposerForGooglePhotos($this);
+ stubGooglePhotosPopupForComposer($page);
+
+ chooseComposerGooglePhotos($page);
+ deliverGooglePhotosSessionToComposer($page, timeoutMs: 60000);
$page->script('window.__photos.popup.closed = true; true;');
+
+ waitForCount($page, '@composer-media-item', 2);
+
+ $page->assertNoJavaScriptErrors();
+ expect($page->script("window.__photos.finished.some((request) => request.startsWith('DELETE '))"))->toBeFalse()
+ ->and(Media::query()->count())->toBe(2);
+});
+
+test('a google photos session nobody picks in time adds nothing and is discarded', function () {
+ $api = enableOnlyGooglePhotosForComposer(readsBeforePicked: PHP_INT_MAX);
+
+ $page = openComposerForGooglePhotos($this);
+ stubGooglePhotosPopupForComposer($page);
+ $user = User::query()->sole();
+
+ chooseComposerGooglePhotos($page);
+ deliverGooglePhotosSessionToComposer($page, timeoutMs: 3000);
waitForCondition($page, "window.__photos.finished.some((request) => request.startsWith('DELETE ') && request.includes('/media/google-photos/sessions/'))");
$page->assertNotPresent('@composer-media-item')
diff --git a/tests/Browser/ComposerMediaSourcesTest.php b/tests/Browser/ComposerMediaSourcesTest.php
index c1cf870b2..3ee84a00d 100644
--- a/tests/Browser/ComposerMediaSourcesTest.php
+++ b/tests/Browser/ComposerMediaSourcesTest.php
@@ -3,7 +3,11 @@
declare(strict_types=1);
use App\Enums\Media\Source;
+use App\Enums\PostPlatform\ContentType;
+use App\Jobs\Media\ImportRemoteMedia;
+use App\Models\Idea;
use App\Models\Media;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -12,6 +16,9 @@ use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Str;
+use Illuminate\Support\Uri;
function openComposerForMediaSources(mixed $test): mixed
{
@@ -74,6 +81,7 @@ function enableOnlyUnsplashForMediaSources(int $apiStatus = 200): void
fakePublicDns();
config()->set([
'services.unsplash.access_key' => 'unsplash-key',
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => null,
'services.google_media.api_key' => null,
'services.google_media.app_id' => null,
@@ -114,6 +122,7 @@ test('the toolbar has one media button whose menu lists the upload first, then t
config()->set([
'services.canva.client_id' => 'canva-client-id',
'services.canva.client_secret' => 'canva-client-secret',
+ 'services.giphy.api_key' => 'giphy-key',
'trypost.media_sources.canva.enabled' => true,
'trypost.media_sources.google_drive.enabled' => false,
'trypost.media_sources.google_photos.enabled' => false,
@@ -146,7 +155,7 @@ test('the toolbar has one media button whose menu lists the upload first, then t
waitFor($page, '@composer-base-media-source-list');
expect($page->script("Array.from(document.querySelectorAll('[data-testid=\"composer-base-media-source-list\"] [data-testid^=\"media-source-\"]')).map((item) => item.dataset.testid)"))
- ->toBe(['media-source-upload', 'media-source-canva', 'media-source-unsplash']);
+ ->toBe(['media-source-upload', 'media-source-canva', 'media-source-giphy', 'media-source-unsplash']);
expect($page->script(<<<'JS'
(() => {
@@ -246,10 +255,254 @@ test('an unsplash outage shows an error instead of an empty result', function ()
->assertNoJavaScriptErrors();
});
+/**
+ * @return array<string, mixed>
+ */
+function giphyBrowserGif(string $id): array
+{
+ $png = 'data:image/png;base64,'.base64_encode(file_get_contents(base_path('tests/fixtures/1x1.png')));
+
+ return [
+ 'id' => $id,
+ 'title' => "Dancing {$id} GIF",
+ 'url' => "https://giphy.com/gifs/dancing-{$id}",
+ 'images' => [
+ 'fixed_width' => ['url' => $png, 'width' => '200', 'height' => '150'],
+ 'downsized_medium' => ['url' => "https://media1.giphy.com/media/{$id}/giphy.gif"],
+ ],
+ ];
+}
+
+/**
+ * Trending answers one GIF on page 1 and says there is a second page with
+ * another; `$apiStatus` makes every GIPHY API call fail instead.
+ */
+function enableOnlyGiphyForMediaSources(int $apiStatus = 200): void
+{
+ fakePublicDns();
+ Cache::flush();
+ config()->set([
+ 'services.giphy.api_key' => 'giphy-key',
+ 'services.unsplash.access_key' => null,
+ 'services.google_media.client_id' => null,
+ 'services.google_media.api_key' => null,
+ 'services.google_media.app_id' => null,
+ 'services.canva.client_id' => null,
+ 'services.canva.client_secret' => null,
+ ]);
+
+ $api = config('trypost.media_sources.giphy.api');
+ $gif = file_get_contents(base_path('tests/fixtures/1x1.gif'));
+ $trendingPage = fn (string $id, int $offset): array => ['data' => [giphyBrowserGif($id)], 'pagination' => ['total_count' => 2, 'count' => 1, 'offset' => $offset]];
+
+ if ($apiStatus !== 200) {
+ Http::fake([
+ "{$api}/*" => Http::response(['message' => 'Too many requests'], $apiStatus),
+ '*' => Http::response('', 404),
+ ]);
+
+ return;
+ }
+
+ Http::fake([
+ 'media1.giphy.com/*' => Http::response($gif, 200, ['Content-Type' => 'image/gif']),
+ "{$api}/gifs/search*" => Http::response(['data' => [giphyBrowserGif('happy')], 'pagination' => ['total_count' => 1, 'count' => 1, 'offset' => 0]]),
+ "{$api}/gifs/trending*" => function (Request $request) use ($trendingPage) {
+ if ((int) Uri::of($request->url())->query()->get('offset', 0) === 0) {
+ return Http::response($trendingPage('party', 0));
+ }
+
+ return Http::response($trendingPage('cheers', 1));
+ },
+ '*' => Http::response('', 404),
+ ]);
+}
+
+test('picking a gif from giphy adds a tile and keeps where it came from', function () {
+ enableOnlyGiphyForMediaSources();
+
+ $page = openComposerForMediaSources($this);
+ waitFor($page, '@composer-base-media-source-menu');
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-dialog');
+ waitFor($page, '@giphy-gif-0');
+
+ $page->assertAttribute('@giphy-gif-0', 'aria-label', 'Dancing party GIF');
+
+ $page->click('@giphy-gif-0');
+ waitFor($page, '@composer-media-item');
+ waitForGone($page, '@giphy-dialog');
+
+ $page->assertPresent('@composer-media-item')
+ ->assertNoJavaScriptErrors();
+
+ $media = Media::query()->sole();
+ expect($media->collection)->toBe(Media::COLLECTION_UPLOADS)
+ ->and($media->mime_type)->toBe('image/gif')
+ ->and(data_get($media->meta, 'source'))->toBe(Source::Giphy->value)
+ ->and(data_get($media->meta, 'source_meta.gif_id'))->toBe('party');
+});
+
+test('a picked gif loads on the post until the socket says its import settled, with no polling', function () {
+ enableOnlyGiphyForMediaSources();
+ Queue::fake([ImportRemoteMedia::class]);
+
+ $page = openComposerForMediaSources($this);
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-gif-0');
+ $page->click('@giphy-gif-0');
+ waitForGone($page, '@giphy-dialog');
+ waitFor($page, '@composer-import-item');
+
+ $job = Queue::pushed(ImportRemoteMedia::class)->sole();
+ app()->call([$job, 'handle']);
+ letPageRun($page, 3000);
+
+ $page->assertPresent('@composer-import-item')
+ ->assertMissing('@composer-media-item');
+
+ broadcastToPage($page, "workspace.{$job->workspaceId}", 'media.import.settled', ['import_id' => $job->importId]);
+ waitFor($page, '@composer-media-item');
+
+ $page->assertMissing('@composer-import-item')
+ ->assertNoJavaScriptErrors();
+ expect(Media::query()->sole()->mime_type)->toBe('image/gif');
+});
+
+test('an import that settled while the socket was down lands once the socket connects again', function () {
+ enableOnlyGiphyForMediaSources();
+ Queue::fake([ImportRemoteMedia::class]);
+
+ $page = openComposerForMediaSources($this);
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-gif-0');
+ $page->click('@giphy-gif-0');
+ waitFor($page, '@composer-import-item');
+
+ app()->call([Queue::pushed(ImportRemoteMedia::class)->sole(), 'handle']);
+ reconnectPageSocket($page);
+ waitFor($page, '@composer-media-item');
+
+ $page->assertMissing('@composer-import-item')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a gif whose import cannot start says why and keeps the dialog open', function () {
+ enableOnlyGiphyForMediaSources();
+
+ $page = openComposerForMediaSources($this);
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-gif-0');
+
+ config()->set('trypost.media_sources.giphy.enabled', false);
+ $page->click('@giphy-gif-0');
+ waitForText($page, '[data-sonner-toast]', __('validation.in', ['attribute' => 'source']));
+
+ $page->assertPresent('@giphy-dialog')
+ ->assertMissing('@composer-import-item')
+ ->assertMissing('@composer-media-item')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a gif picked while a thread reply is edited lands on that reply, not on the post', function () {
+ enableOnlyGiphyForMediaSources();
+
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ $account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create(['user_id' => $user->id, 'content' => 'The thread starts here']);
+ $this->actingAs($user);
+ $id = $account->id;
+
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
+ waitFor($page, '@thread-start');
+ $page->click('@thread-start');
+ waitFor($page, '@thread-reply-0');
+
+ chooseComposerMediaSource($page, "composer-{$id}", 'giphy');
+ waitFor($page, '@giphy-gif-0');
+ $page->click('@giphy-gif-0');
+ waitFor($page, "@composer-{$id}-reply-0-media-item-0");
+
+ $page->assertMissing("@composer-{$id}-media-item-0")
+ ->assertNotPresent('@giphy-dialog')
+ ->assertNoJavaScriptErrors();
+});
+
+test('a gif picked in the idea editor joins the idea', function () {
+ enableOnlyGiphyForMediaSources();
+
+ $user = User::factory()->create();
+ $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
+ $workspace->members()->attach($user->id, membershipPivot('admin'));
+ $user->update(['current_workspace_id' => $workspace->id]);
+ subscribeAccount($user->account);
+ $idea = Idea::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'idea_stage_id' => null, 'position' => 0, 'title' => 'GIF idea']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.create.ideas.show', $idea));
+ waitFor($page, '@idea-editor-media-source-menu');
+
+ chooseComposerMediaSource($page, 'idea-editor', 'giphy');
+ waitFor($page, '@giphy-gif-0');
+ $page->click('@giphy-gif-0');
+ waitFor($page, '@idea-media-item-0');
+ waitForGone($page, '@giphy-dialog');
+
+ $page->click('@idea-editor-save');
+ waitForGone($page, '@idea-editor');
+
+ $media = Media::query()->sole();
+
+ expect($media->idea_id)->toBe($idea->id)
+ ->and(data_get($media->meta, 'source'))->toBe(Source::Giphy->value)
+ ->and(data_get($idea->refresh()->media, '0.id'))->toBe($media->id);
+
+ $page->assertNoJavaScriptErrors();
+});
+
+test('the giphy dialog loads the next page and searches as the user types', function () {
+ enableOnlyGiphyForMediaSources();
+
+ $page = openComposerForMediaSources($this);
+ waitFor($page, '@composer-base-media-source-menu');
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-gif-1');
+
+ $page->assertAttribute('@giphy-gif-1', 'aria-label', 'Dancing cheers GIF')
+ ->assertNotPresent('@giphy-error');
+
+ $page->type('@giphy-search', 'happy');
+ waitForState($page, '@giphy-gif-0', "element.getAttribute('aria-label') === 'Dancing happy GIF'");
+ waitForCount($page, '[data-testid^="giphy-gif-"]', 1);
+
+ $page->assertNoJavaScriptErrors();
+
+ Http::assertSent(fn (Request $request) => Str::is(config('trypost.media_sources.giphy.api').'/gifs/search*', $request->url())
+ && Uri::of($request->url())->query()->get('q') === 'happy');
+});
+
+test('a giphy outage shows an error instead of an empty result', function () {
+ enableOnlyGiphyForMediaSources(apiStatus: 429);
+
+ $page = openComposerForMediaSources($this);
+ waitFor($page, '@composer-base-media-source-menu');
+ chooseComposerMediaSource($page, 'composer-base', 'giphy');
+ waitFor($page, '@giphy-error');
+
+ $page->assertSeeIn('@giphy-error', __('posts.composer.giphy.error'))
+ ->assertNotPresent('@giphy-empty')
+ ->assertNoJavaScriptErrors();
+});
+
function enableOnlyGoogleDriveForMediaSources(): string
{
config()->set([
'services.unsplash.access_key' => null,
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => 'media-client-id',
'services.google_media.client_secret' => 'media-client-secret',
'services.google_media.redirect' => 'https://trypost.example/integrations/google/callback',
diff --git a/tests/Browser/LinkCardPreviewTest.php b/tests/Browser/LinkCardPreviewTest.php
index e94446f4a..c8980e28c 100644
--- a/tests/Browser/LinkCardPreviewTest.php
+++ b/tests/Browser/LinkCardPreviewTest.php
@@ -279,7 +279,7 @@ test('a threads poll fetches no link card for a link in its question', function
Http::assertNothingSent();
});
-test('replacing the link card with media attaches the card image', function () {
+test('replacing the link card with media attaches the card image once, however fast it is clicked', function () {
$url = 'https://93.184.216.34/article';
$fake = UploadedFile::fake()->image('card.jpg', 1200, 630);
$image = file_get_contents($fake->getPathname());
@@ -294,7 +294,8 @@ test('replacing the link card with media attaches the card image', function () {
waitForOpen($page, '@post-composer-dialog');
waitFor($page, "@{$card}");
- $page->click("@{$card}-replace");
+ $replace = jsSelector("@{$card}-replace");
+ $page->script("const button = document.querySelector({$replace}); button.click(); button.click();");
waitForOpen($page, '@post-composer-dialog');
waitFor($page, "@composer-{$account->id}-media-item-0");
diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.php
index 21966e899..e3540b52c 100644
--- a/tests/Feature/Api/PostApiPlatformMetaTest.php
+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php
@@ -304,9 +304,9 @@ it('rejects publishing when the uploaded video runs past the content type durati
->assertJsonFragment(['Video is 1min 30s long, but this post type allows up to 1min.']);
});
-it('rejects publishing a LinkedIn post with a GIF', function () {
- $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
+it('rejects publishing a Facebook post with a GIF', function () {
+ $facebook = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Facebook]);
+ $post = Post::factory()->forAccount($facebook, ContentType::FacebookPost)->create([
'user_id' => $this->user->id,
'media' => [[
'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/loop.gif',
@@ -317,13 +317,37 @@ it('rejects publishing a LinkedIn post with a GIF', function () {
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'content_type' => ContentType::LinkedInPost->value,
+ 'content_type' => ContentType::FacebookPost->value,
])
->assertUnprocessable()
->assertJsonValidationErrors(['content_type'])
->assertJsonFragment(['This platform does not accept GIF. Remove the GIF or choose a different network.']);
});
+it('accepts scheduling a LinkedIn post with a GIF', function (Platform $platform, ContentType $type) {
+ $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => $platform]);
+ $post = Post::factory()->forAccount($linkedin, $type)->create([
+ 'user_id' => $this->user->id,
+ 'media' => [[
+ 'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/loop.gif',
+ 'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif', 'size' => 2 * 1024 * 1024,
+ ]],
+ ]);
+
+ $this->withHeaders($this->headers)
+ ->putJson(route('api.posts.update', $post), [
+ 'status' => PostStatus::Scheduled->value,
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'content_type' => $type->value,
+ ])
+ ->assertOk();
+
+ expect($post->fresh()->status)->toBe(PostStatus::Scheduled);
+})->with([
+ 'profile' => [Platform::LinkedIn, ContentType::LinkedInPost],
+ 'page' => [Platform::LinkedInPage, ContentType::LinkedInPagePost],
+]);
+
it('rejects publishing an Instagram Reel whose stored video exceeds 300 MB', function () {
$instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
$post = Post::factory()->forAccount($instagram, ContentType::InstagramReel)->create([
diff --git a/tests/Feature/App/Post/LinkPreviewMediaControllerTest.php b/tests/Feature/App/Post/LinkPreviewMediaControllerTest.php
index b3560f3f3..41e220b84 100644
--- a/tests/Feature/App/Post/LinkPreviewMediaControllerTest.php
+++ b/tests/Feature/App/Post/LinkPreviewMediaControllerTest.php
@@ -2,6 +2,7 @@
declare(strict_types=1);
+use App\Dto\ImportedFile;
use App\Enums\Media\Type as MediaType;
use App\Models\Account;
use App\Models\Media;
@@ -9,6 +10,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Services\Social\LinkCard\LinkCardFetcher;
use App\Services\Social\LinkCard\LinkCardMetadata;
+use App\Support\MediaImportStatus;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
@@ -43,20 +45,25 @@ function linkPreviewMediaCard(?string $image): void
));
}
-test('the card image is imported as a temporary upload', function () {
+test('the card image is imported through the queue as a temporary upload', function () {
linkPreviewMediaCard('https://93.184.216.34/card.jpg');
$fake = UploadedFile::fake()->image('card.jpg', 1200, 630);
$image = file_get_contents($fake->getPathname());
Http::fake(['https://93.184.216.34/card.jpg' => Http::response($image, 200, ['Content-Type' => 'image/jpeg'])]);
- $response = $this->actingAs($this->user)
+ $importId = $this->actingAs($this->user)
->postJson(route('app.posts.link-preview-media'), ['url' => 'https://example.com/article'])
- ->assertCreated()
- ->assertJsonPath('type', MediaType::Image->value);
+ ->assertAccepted()
+ ->json('import_id');
+
+ $status = $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::DONE)
+ ->assertJsonPath('media.type', MediaType::Image->value);
$media = Media::query()->sole();
- expect($response->json('upload_token'))->toBe($media->upload_token)
+ expect($status->json('media.upload_token'))->toBe($media->upload_token)
->and($media->collection)->toBe(Media::COLLECTION_UPLOADS)
->and($media->workspace_id)->toBe($this->workspace->id)
->and($media->post_id)->toBeNull()
@@ -74,18 +81,39 @@ test('a card without an image is rejected', function () {
expect(Media::query()->count())->toBe(0);
});
-test('an image the importer refuses is rejected', function () {
+test('an image the importer refuses fails the import', function () {
linkPreviewMediaCard('https://93.184.216.34/card.jpg');
Http::fake(['https://93.184.216.34/card.jpg' => Http::response('not an image', 200, ['Content-Type' => 'text/html'])]);
- $this->actingAs($this->user)
+ $importId = $this->actingAs($this->user)
->postJson(route('app.posts.link-preview-media'), ['url' => 'https://example.com/article'])
- ->assertUnprocessable()
- ->assertJsonValidationErrors(['url' => __('posts.composer.media_sources.errors.import_failed')]);
+ ->assertAccepted()
+ ->json('import_id');
+
+ $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED);
expect(Media::query()->count())->toBe(0);
});
+test('a video behind the card is refused, since the card shows an image', function () {
+ linkPreviewMediaCard('https://93.184.216.34/card.mp4');
+ Http::fake(['https://93.184.216.34/card.mp4' => Http::response(file_get_contents(base_path('tests/fixtures/sample.mp4')), 200, ['Content-Type' => 'video/mp4'])]);
+
+ $importId = $this->actingAs($this->user)
+ ->postJson(route('app.posts.link-preview-media'), ['url' => 'https://example.com/article'])
+ ->assertAccepted()
+ ->json('import_id');
+
+ $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED)
+ ->assertJsonPath('reason', ImportedFile::TYPE_NOT_ALLOWED);
+
+ $this->assertDatabaseEmpty(Media::class);
+});
+
test('the url is required and guests are refused', function () {
$this->actingAs($this->user)
->postJson(route('app.posts.link-preview-media'), [])
diff --git a/tests/Feature/Jobs/ImportRemoteMediaTest.php b/tests/Feature/Jobs/ImportRemoteMediaTest.php
index 965ed791e..3e1a9101a 100644
--- a/tests/Feature/Jobs/ImportRemoteMediaTest.php
+++ b/tests/Feature/Jobs/ImportRemoteMediaTest.php
@@ -6,6 +6,8 @@ use App\Actions\Media\StartMediaImport;
use App\Dto\ImportedFile;
use App\Dto\RemoteFile;
use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
+use App\Events\MediaImportSettled;
use App\Jobs\Media\ImportRemoteMedia;
use App\Models\Media;
use App\Models\User;
@@ -13,7 +15,9 @@ use App\Models\Workspace;
use App\Services\Media\RemoteMediaImporter;
use App\Support\MediaImportStatus;
use Carbon\CarbonInterface;
+use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
+use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
@@ -47,7 +51,7 @@ test('starting an import queues an encrypted job and records it as pending', fun
Queue::fake();
config()->set('trypost.media_sources.import_timeout_seconds', 321);
- [$importId] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, driveFile());
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
Queue::assertPushed(ImportRemoteMedia::class, fn (ImportRemoteMedia $job): bool => $job instanceof ShouldBeEncrypted
&& $job->importId === $importId
@@ -64,8 +68,8 @@ test('a successful job ends done with one temporary upload the status endpoint r
Queue::fake();
Http::fake(['https://93.184.216.34/*' => Http::response(file_get_contents(base_path('tests/fixtures/1x1.png')))]);
- [$importId] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, driveFile());
- (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile()))->handle(app(RemoteMediaImporter::class));
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
+ (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile(), MediaType::cases()))->handle(app(RemoteMediaImporter::class));
$media = Media::query()->sole();
@@ -83,13 +87,47 @@ test('a successful job ends done with one temporary upload the status endpoint r
->assertJsonPath('media.upload_token', $media->upload_token);
});
+test('settling an import tells the workspace channel which import it was, and nothing else', function (int $downloadStatus) {
+ Queue::fake();
+ Event::fake([MediaImportSettled::class]);
+ Http::fake(['https://93.184.216.34/*' => Http::response(file_get_contents(base_path('tests/fixtures/1x1.png')), $downloadStatus)]);
+
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
+
+ Event::assertNotDispatched(MediaImportSettled::class);
+
+ (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile(), MediaType::cases()))->handle(app(RemoteMediaImporter::class));
+
+ Event::assertDispatchedTimes(MediaImportSettled::class, 1);
+ Event::assertDispatched(MediaImportSettled::class, function (MediaImportSettled $event) use ($importId): bool {
+ $channels = collect($event->broadcastOn())->map(fn (PrivateChannel $channel): string => $channel->name)->all();
+
+ return $event->importId === $importId
+ && $channels === ["private-workspace.{$this->workspace->id}"]
+ && $event->broadcastWith() === ['import_id' => $importId];
+ });
+})->with([
+ 'imported' => [200],
+ 'failed' => [404],
+]);
+
+test('a job that dies tells the workspace channel too', function () {
+ Queue::fake();
+ Event::fake([MediaImportSettled::class]);
+
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
+ (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile(), MediaType::cases()))->failed(new RuntimeException('timed out'));
+
+ Event::assertDispatched(MediaImportSettled::class, fn (MediaImportSettled $event): bool => $event->importId === $importId);
+});
+
test('a disallowed host ends failed with host_not_allowed', function () {
Queue::fake();
Http::fake();
$file = driveFile('https://93.184.216.99/files/abc');
- [$importId] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, $file);
- (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, $file))->handle(app(RemoteMediaImporter::class));
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, $file, MediaType::cases());
+ (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, $file, MediaType::cases()))->handle(app(RemoteMediaImporter::class));
expect(MediaImportStatus::find($importId, $this->user->id, $this->workspace->id))
->toMatchArray(['status' => 'failed', 'reason' => 'host_not_allowed'])
@@ -101,8 +139,8 @@ test('a disallowed host ends failed with host_not_allowed', function () {
test('a job that dies marks the import failed', function () {
Queue::fake();
- [$importId] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, driveFile());
- (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile()))->failed(new RuntimeException('timed out'));
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
+ (new ImportRemoteMedia($importId, $this->workspace->id, $this->user->id, driveFile(), MediaType::cases()))->failed(new RuntimeException('timed out'));
expect(MediaImportStatus::find($importId, $this->user->id, $this->workspace->id))
->toMatchArray(['status' => 'failed', 'reason' => 'unreachable']);
@@ -111,8 +149,8 @@ test('a job that dies marks the import failed', function () {
test('a deleted workspace ends failed', function () {
Queue::fake();
- [$importId] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, driveFile());
- (new ImportRemoteMedia($importId, (string) Str::uuid(), $this->user->id, driveFile()))->handle(app(RemoteMediaImporter::class));
+ [$importId] = StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
+ (new ImportRemoteMedia($importId, (string) Str::uuid(), $this->user->id, driveFile(), MediaType::cases()))->handle(app(RemoteMediaImporter::class));
expect(MediaImportStatus::find($importId, $this->user->id, $this->workspace->id))
->toMatchArray(['status' => 'failed']);
@@ -121,13 +159,13 @@ test('a deleted workspace ends failed', function () {
test('the job runs on the media-imports queue', function () {
Queue::fake();
- StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, driveFile());
+ StartMediaImport::execute($this->user, $this->workspace, driveFile(), MediaType::cases());
Queue::assertPushedOn(ImportRemoteMedia::QUEUE, ImportRemoteMedia::class);
});
test('the transfer gets a deadline well inside the job timeout and follows redirects', function () {
- $job = new ImportRemoteMedia('import', $this->workspace->id, $this->user->id, driveFile());
+ $job = new ImportRemoteMedia('import', $this->workspace->id, $this->user->id, driveFile(), MediaType::cases());
$this->mock(RemoteMediaImporter::class)
->shouldReceive('import')
@@ -148,10 +186,10 @@ test('a user who lost access by the time the job runs gets nothing imported', fu
$member = User::factory()->create();
$this->workspace->members()->attach($member->id, membershipPivot('member'));
- [$importId] = StartMediaImport::execute($member, $this->workspace, Source::GoogleDrive, driveFile());
+ [$importId] = StartMediaImport::execute($member, $this->workspace, driveFile(), MediaType::cases());
$this->workspace->members()->detach($member->id);
- (new ImportRemoteMedia($importId, $this->workspace->id, $member->id, driveFile()))->handle(app(RemoteMediaImporter::class));
+ (new ImportRemoteMedia($importId, $this->workspace->id, $member->id, driveFile(), MediaType::cases()))->handle(app(RemoteMediaImporter::class));
expect(MediaImportStatus::find($importId, $member->id, $this->workspace->id))
->toMatchArray(['status' => 'failed'])
diff --git a/tests/Feature/Media/GiphyControllerTest.php b/tests/Feature/Media/GiphyControllerTest.php
new file mode 100644
index 000000000..4d5ae8a61
--- /dev/null
+++ b/tests/Feature/Media/GiphyControllerTest.php
@@ -0,0 +1,311 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Dto\ImportedFile;
+use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
+use App\Models\Account;
+use App\Models\Media;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Support\MediaImportStatus;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Storage;
+
+beforeEach(function () {
+ Storage::fake();
+ fakePublicDns();
+ Cache::flush();
+ config()->set([
+ 'services.giphy.api_key' => 'giphy-key',
+ 'trypost.media_sources.giphy.enabled' => true,
+ ]);
+
+ $this->account = Account::factory()->create();
+ $this->user = User::factory()->create(['account_id' => $this->account->id]);
+ $this->account->update(['owner_id' => $this->user->id]);
+ $this->workspace = Workspace::factory()->create([
+ 'account_id' => $this->account->id,
+ 'user_id' => $this->user->id,
+ ]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('member'));
+ $this->user->update(['current_workspace_id' => $this->workspace->id]);
+ subscribeAccount($this->account);
+});
+
+/**
+ * One GIF as the GIPHY API returns it.
+ *
+ * @return array<string, mixed>
+ */
+function giphyApiGif(string $id, array $overrides = []): array
+{
+ return [
+ 'id' => $id,
+ 'title' => "Dancing {$id} GIF",
+ 'url' => "https://giphy.com/gifs/dancing-{$id}",
+ 'images' => [
+ 'fixed_width' => ['url' => "https://media1.giphy.com/media/{$id}/200w.gif", 'width' => '200', 'height' => '150'],
+ 'downsized_medium' => ['url' => "https://media1.giphy.com/media/{$id}/giphy.gif", 'size' => '1048576'],
+ ],
+ ...$overrides,
+ ];
+}
+
+/**
+ * @param list<array<string, mixed>> $gifs
+ * @return array<string, mixed>
+ */
+function giphyApiPage(array $gifs, int $total, int $offset = 0): array
+{
+ return ['data' => $gifs, 'pagination' => ['total_count' => $total, 'count' => count($gifs), 'offset' => $offset], 'meta' => ['status' => 200]];
+}
+
+/**
+ * @return array<string, mixed>
+ */
+function giphyPick(array $overrides = []): array
+{
+ return [
+ 'source' => Source::Giphy->value,
+ 'url' => 'https://media1.giphy.com/media/abc123/giphy.gif',
+ 'gif_id' => 'abc123',
+ 'giphy_url' => 'https://giphy.com/gifs/dancing-abc123',
+ ...$overrides,
+ ];
+}
+
+function giphyApi(string $path): string
+{
+ return config('trypost.media_sources.giphy.api').$path;
+}
+
+test('trending gifs come back in the picker shape, with a next page while giphy has more', function () {
+ Http::fake([giphyApi('/gifs/trending*') => Http::response(giphyApiPage([giphyApiGif('one'), giphyApiGif('two')], 100))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertOk()
+ ->assertJsonPath('has_more', true)
+ ->assertJsonCount(2, 'results')
+ ->assertJsonPath('results.0', [
+ 'id' => 'one',
+ 'title' => 'Dancing one GIF',
+ 'url_preview' => 'https://media1.giphy.com/media/one/200w.gif',
+ 'url' => 'https://media1.giphy.com/media/one/giphy.gif',
+ 'width' => 200,
+ 'height' => 150,
+ 'giphy_url' => 'https://giphy.com/gifs/dancing-one',
+ ]);
+
+ Http::assertSent(fn ($request) => $request['api_key'] === 'giphy-key'
+ && $request['rating'] === 'g'
+ && (int) $request['offset'] === 0);
+});
+
+test('a search asks giphy for the page offset and stops when there is no more', function () {
+ $perPage = (int) config('app.pagination.default');
+ Http::fake([giphyApi('/gifs/search*') => Http::response(giphyApiPage([giphyApiGif('last')], $perPage + 1, $perPage))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.search', ['query' => ' Happy Dance ', 'page' => 2]))
+ ->assertOk()
+ ->assertJsonPath('has_more', false)
+ ->assertJsonPath('results.0.id', 'last');
+
+ Http::assertSent(fn ($request) => $request['q'] === 'happy dance' && (int) $request['offset'] === $perPage);
+});
+
+test('a gif without a rendition to import is left out', function () {
+ Http::fake([giphyApi('/*') => Http::response(giphyApiPage([
+ giphyApiGif('kept'),
+ giphyApiGif('dropped', ['images' => ['fixed_width' => ['url' => 'https://media1.giphy.com/x/200w.gif']]]),
+ ], 2))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertOk()
+ ->assertJsonCount(1, 'results')
+ ->assertJsonPath('results.0.id', 'kept');
+});
+
+test('giphy being down answers 503 with a message, and is not cached', function () {
+ Http::fake([giphyApi('/*') => Http::sequence()
+ ->push(['message' => 'Too many requests'], 429)
+ ->push(giphyApiPage([giphyApiGif('back')], 1))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertStatus(503)
+ ->assertJsonPath('message', __('posts.composer.giphy.error'));
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertOk()
+ ->assertJsonPath('results.0.id', 'back');
+});
+
+test('a page giphy answered is cached for the next user', function () {
+ Http::fake([giphyApi('/*') => Http::response(giphyApiPage([giphyApiGif('one')], 1))]);
+
+ $this->actingAs($this->user)->getJson(route('app.media.giphy.trending'))->assertOk();
+ $this->actingAs($this->user)->getJson(route('app.media.giphy.trending'))->assertOk();
+
+ Http::assertSentCount(1);
+});
+
+test('while giphy is off or has no key the picker gets nothing and giphy is never called', function (array $config) {
+ config()->set($config);
+ Http::fake();
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertOk()
+ ->assertExactJson(['results' => [], 'has_more' => false]);
+
+ Http::assertNothingSent();
+})->with([
+ 'no key' => [['services.giphy.api_key' => null]],
+ 'turned off' => [['trypost.media_sources.giphy.enabled' => false]],
+]);
+
+test('a picked gif imports through the queue as a temporary upload with its giphy attribution', function () {
+ $gif = file_get_contents(base_path('tests/fixtures/1x1.gif'));
+ Http::fake(['media1.giphy.com/*' => Http::response($gif, 200, ['Content-Type' => 'image/gif'])]);
+
+ $importId = $this->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), giphyPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ $status = $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::DONE)
+ ->assertJsonPath('media.type', MediaType::Image->value)
+ ->assertJsonPath('media.mime_type', 'image/gif');
+
+ $media = Media::query()->sole();
+
+ expect($status->json('media.upload_token'))->toBe($media->upload_token)
+ ->and($media->collection)->toBe(Media::COLLECTION_UPLOADS)
+ ->and($media->workspace_id)->toBe($this->workspace->id)
+ ->and($media->original_filename)->toBe('giphy-abc123.gif')
+ ->and(data_get($media->meta, 'source'))->toBe(Source::Giphy->value)
+ ->and(data_get($media->meta, 'source_meta'))->toEqual([
+ 'gif_id' => 'abc123',
+ 'giphy_url' => 'https://giphy.com/gifs/dancing-abc123',
+ ])
+ ->and(Storage::get($media->path))->toBe($gif);
+});
+
+test('a gif off the giphy hosts is refused before any request', function (array $overrides, string $field) {
+ Http::fake();
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), giphyPick($overrides))
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors($field);
+
+ Http::assertNothingSent();
+ $this->assertDatabaseEmpty(Media::class);
+})->with([
+ 'another host' => [['url' => 'https://images.unsplash.com/photo.gif'], 'url'],
+ 'a look-alike host' => [['url' => 'https://media1.giphy.com.evil.test/x.gif'], 'url'],
+ 'plain http' => [['url' => 'http://media1.giphy.com/media/abc123/giphy.gif'], 'url'],
+ 'a page off the giphy website' => [['giphy_url' => 'https://evil.test/gifs/abc123'], 'giphy_url'],
+ 'an id that is not one' => [['gif_id' => '../../etc'], 'gif_id'],
+]);
+
+test('gif picks are refused while giphy is off or has no key', function (array $config) {
+ config()->set($config);
+ Http::fake();
+
+ $this->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), giphyPick())
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('source');
+
+ Http::assertNothingSent();
+})->with([
+ 'no key' => [['services.giphy.api_key' => null]],
+ 'turned off' => [['trypost.media_sources.giphy.enabled' => false]],
+]);
+
+test('a file giphy serves that is not an image is refused and leaves nothing', function () {
+ Http::fake(['media1.giphy.com/*' => Http::response('<html>not a gif</html>', 200, ['Content-Type' => 'text/html'])]);
+
+ $importId = $this->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), giphyPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED);
+
+ $this->assertDatabaseEmpty(Media::class);
+});
+
+test('a video giphy serves is refused, since a pick is a gif', function () {
+ Http::fake(['media1.giphy.com/*' => Http::response(file_get_contents(base_path('tests/fixtures/sample.mp4')), 200, ['Content-Type' => 'video/mp4'])]);
+
+ $importId = $this->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), giphyPick(['url' => 'https://media1.giphy.com/media/abc123/giphy.mp4']))
+ ->assertAccepted()
+ ->json('import_id');
+
+ $this->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED)
+ ->assertJsonPath('reason', ImportedFile::TYPE_NOT_ALLOWED);
+
+ $this->assertDatabaseEmpty(Media::class);
+});
+
+test('searching giphy is throttled per user, while another user keeps searching', function () {
+ config()->set('trypost.media_sources.giphy.requests_per_user_per_minute', 2);
+ Http::fake([giphyApi('/*') => Http::response(giphyApiPage([giphyApiGif('one')], 1))]);
+
+ foreach (range(1, 2) as $attempt) {
+ $this->actingAs($this->user)->getJson(route('app.media.giphy.search', ['query' => "cats {$attempt}"]))->assertOk();
+ }
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending'))
+ ->assertTooManyRequests();
+
+ $other = User::factory()->create(['account_id' => $this->account->id]);
+ $this->workspace->members()->attach($other->id, membershipPivot('member'));
+ $other->update(['current_workspace_id' => $this->workspace->id]);
+
+ $this->actingAs($other)->getJson(route('app.media.giphy.trending'))->assertOk();
+});
+
+test('the last page giphy can serve has no next one, whatever its total says', function () {
+ config()->set('app.pagination.default', 100);
+ $perPage = 100;
+ $lastPage = intdiv(4999, $perPage) + 1;
+ Http::fake([giphyApi('/*') => Http::response(giphyApiPage(Collection::times($perPage, fn (int $i): array => giphyApiGif("g{$i}"))->all(), 100000, ($lastPage - 1) * $perPage))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending', ['page' => $lastPage]))
+ ->assertOk()
+ ->assertJsonPath('has_more', false);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.trending', ['page' => $lastPage - 1]))
+ ->assertOk()
+ ->assertJsonPath('has_more', true);
+});
+
+test('an empty page ends the list, even when giphy counts more results', function () {
+ Http::fake([giphyApi('/*') => Http::response(giphyApiPage([], 5000, 25))]);
+
+ $this->actingAs($this->user)
+ ->getJson(route('app.media.giphy.search', ['query' => 'rare', 'page' => 2]))
+ ->assertOk()
+ ->assertExactJson(['results' => [], 'has_more' => false]);
+});
diff --git a/tests/Feature/Media/GoogleDriveImportTest.php b/tests/Feature/Media/GoogleDriveImportTest.php
index ccefbe9a8..8d0c85929 100644
--- a/tests/Feature/Media/GoogleDriveImportTest.php
+++ b/tests/Feature/Media/GoogleDriveImportTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Actions\Media\StartMediaImport;
use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
use App\Jobs\Media\ImportRemoteMedia;
use App\Models\Account;
use App\Models\Media;
@@ -210,12 +211,12 @@ test('the stashed token is dropped when the job fails or the user lost access',
Queue::fake();
$file = GoogleDriveFiles::toRemoteFile(GOOGLE_DRIVE_TEST_TOKEN, ['id' => 'abc', 'name' => 'a.png']);
- [$failed] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, $file);
- (new ImportRemoteMedia($failed, $this->workspace->id, $this->user->id, $file->withHeaders([])))->failed(new RuntimeException('worker died'));
+ [$failed] = StartMediaImport::execute($this->user, $this->workspace, $file, MediaType::cases());
+ (new ImportRemoteMedia($failed, $this->workspace->id, $this->user->id, $file->withHeaders([]), MediaType::cases()))->failed(new RuntimeException('worker died'));
- [$revoked] = StartMediaImport::execute($this->user, $this->workspace, Source::GoogleDrive, $file);
+ [$revoked] = StartMediaImport::execute($this->user, $this->workspace, $file, MediaType::cases());
$this->workspace->members()->detach($this->user->id);
- app()->call([new ImportRemoteMedia($revoked, $this->workspace->id, $this->user->id, $file->withHeaders([])), 'handle']);
+ app()->call([new ImportRemoteMedia($revoked, $this->workspace->id, $this->user->id, $file->withHeaders([]), MediaType::cases()), 'handle']);
expect(Cache::has(MediaImportHeaders::key($failed)))->toBeFalse()
->and(Cache::has(MediaImportHeaders::key($revoked)))->toBeFalse();
@@ -246,7 +247,7 @@ test('the bearer token is not forwarded on a redirect to googleusercontent', fun
});
test('telescope never records the access token', function () {
- $job = new ImportRemoteMedia('import-id', $this->workspace->id, $this->user->id, GoogleDriveFiles::toRemoteFile(GOOGLE_DRIVE_TEST_TOKEN, ['id' => 'abc', 'name' => 'a.png']));
+ $job = new ImportRemoteMedia('import-id', $this->workspace->id, $this->user->id, GoogleDriveFiles::toRemoteFile(GOOGLE_DRIVE_TEST_TOKEN, ['id' => 'abc', 'name' => 'a.png']), MediaType::cases());
expect(json_encode(ExtractProperties::from($job)))->not->toContain(GOOGLE_DRIVE_TEST_TOKEN)
->and(data_get(ExtractProperties::from($job), 'file.properties.headers.Authorization'))->toBe('********');
diff --git a/tests/Feature/Media/GooglePhotosTest.php b/tests/Feature/Media/GooglePhotosTest.php
index 19db674d0..d49009cec 100644
--- a/tests/Feature/Media/GooglePhotosTest.php
+++ b/tests/Feature/Media/GooglePhotosTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Dto\RemoteFile;
use App\Enums\Media\Source;
+use App\Enums\Media\Type as MediaType;
use App\Jobs\Media\ImportRemoteMedia;
use App\Models\Account;
use App\Models\Media;
@@ -244,7 +245,7 @@ test('the token is in no response, queued job or database table', function () {
expect($rows)->not->toContain(GOOGLE_PHOTOS_TEST_TOKEN);
- $job = new ImportRemoteMedia('import-id', $this->workspace->id, $this->user->id, new RemoteFile('https://lh3.googleusercontent.com/photo-one=d', 'beach.png'), GOOGLE_PHOTOS_TEST_SESSION);
+ $job = new ImportRemoteMedia('import-id', $this->workspace->id, $this->user->id, new RemoteFile('https://lh3.googleusercontent.com/photo-one=d', 'beach.png'), MediaType::cases(), GOOGLE_PHOTOS_TEST_SESSION);
expect(serialize($job))->not->toContain(GOOGLE_PHOTOS_TEST_TOKEN);
});
diff --git a/tests/Feature/Media/MediaImportControllerTest.php b/tests/Feature/Media/MediaImportControllerTest.php
index c14701093..f724778bc 100644
--- a/tests/Feature/Media/MediaImportControllerTest.php
+++ b/tests/Feature/Media/MediaImportControllerTest.php
@@ -49,7 +49,7 @@ test('a source that cannot be imported is rejected', function (string $source) {
->assertJsonValidationErrors('source');
Queue::assertNotPushed(ImportRemoteMedia::class);
-})->with(['canva', 'unsplash', 'giphy', 'ai', 'dropbox']);
+})->with(['canva', 'ai', 'dropbox']);
test('a disabled source is rejected', function () {
config()->set('trypost.media_sources.google_drive.enabled', false);
diff --git a/tests/Feature/Media/MediaSourcesSharePropTest.php b/tests/Feature/Media/MediaSourcesSharePropTest.php
index 59df96f10..744d1f0ef 100644
--- a/tests/Feature/Media/MediaSourcesSharePropTest.php
+++ b/tests/Feature/Media/MediaSourcesSharePropTest.php
@@ -4,8 +4,10 @@ declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
+use App\Services\GiphyService;
use App\Services\UnsplashService;
use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Str;
beforeEach(function () {
$this->user = User::factory()->create();
@@ -22,6 +24,7 @@ function mediaSourcesEnableAll(): void
config()->set([
'services.unsplash.access_key' => 'SENTINEL-UNSPLASH-KEY',
'services.unsplash.secret_key' => 'SENTINEL-UNSPLASH-SECRET',
+ 'services.giphy.api_key' => 'SENTINEL-GIPHY-KEY',
'services.google_media.client_id' => 'google-client-id',
'services.google_media.client_secret' => 'SENTINEL-GOOGLE-SECRET',
'services.google_media.redirect' => 'https://trypost.example/integrations/google/callback',
@@ -39,6 +42,7 @@ test('the prop lists only enabled sources in menu order', function () {
mediaSourcesEnableAll();
config()->set('trypost.media_sources.google_photos.enabled', false);
config()->set('services.unsplash.access_key', null);
+ config()->set('services.giphy.api_key', null);
$this->actingAs($this->user)
->get(route('app.workspace.channels'))
@@ -65,7 +69,7 @@ test('secrets never reach the shared prop', function () {
$menu = $response->viewData('page')['props']['mediaSources'];
$json = json_encode($menu);
- expect($menu['menu'])->toHaveCount(4)
+ expect($menu['menu'])->toHaveCount(5)
->and($json)->not->toContain('SENTINEL')
->and($json)->not->toContain('google-client-id')
->and($json)->toContain('google-app-id');
@@ -80,3 +84,16 @@ test('unsplash calls the configured api host', function () {
Http::assertSent(fn ($request) => str_starts_with($request->url(), 'https://unsplash.example.test/search/photos'));
});
+
+test('giphy calls the configured api host with its key and safe rating', function () {
+ config()->set('services.giphy.api_key', 'key');
+ config()->set('trypost.media_sources.giphy.api', 'https://giphy.example.test/v1');
+ Http::fake(['giphy.example.test/*' => Http::response(['data' => [], 'pagination' => ['total_count' => 0, 'count' => 0, 'offset' => 0]])]);
+
+ (new GiphyService)->search('cats');
+
+ Http::assertSent(fn ($request) => Str::is('https://giphy.example.test/v1/gifs/search*', $request->url())
+ && $request['api_key'] === 'key'
+ && $request['q'] === 'cats'
+ && $request['rating'] === 'g');
+});
diff --git a/tests/Feature/Media/MediaUploadControllerTest.php b/tests/Feature/Media/MediaUploadControllerTest.php
index 15772a4db..0dbe63e0f 100644
--- a/tests/Feature/Media/MediaUploadControllerTest.php
+++ b/tests/Feature/Media/MediaUploadControllerTest.php
@@ -2,6 +2,7 @@
declare(strict_types=1);
+use App\Dto\ImportedFile;
use App\Enums\Media\Source;
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
@@ -13,6 +14,7 @@ use App\Models\User;
use App\Models\Workspace;
use App\Services\UnsplashService;
use App\Support\HeicConverter;
+use App\Support\MediaImportStatus;
use Illuminate\Http\Client\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
@@ -147,10 +149,7 @@ test('a user outside the workspace cannot upload', function () {
->assertForbidden();
test()->actingAs($outsider->fresh())
- ->postJson(route('app.media.store-from-url'), [
- 'url' => 'https://images.unsplash.com/photo-test',
- 'filename' => 'unsplash-test.jpg',
- ])
+ ->postJson(route('app.media.imports.store'), unsplashPick())
->assertForbidden();
test()->actingAs($outsider->fresh())
@@ -195,6 +194,7 @@ function unsplashPick(array $overrides = []): array
$website = config('trypost.media_sources.unsplash.website');
return [
+ 'source' => Source::Unsplash->value,
'url' => "https://{$images}/photo-test",
'filename' => 'unsplash-test.jpg',
'download_location' => config('trypost.media_sources.unsplash.api').'/photos/test/download',
@@ -210,7 +210,7 @@ function unsplashImagesPattern(): string
return Source::Unsplash->downloadHosts()[0].'/*';
}
-test('an unsplash photo imports through the importer as a temporary upload and sends the tracking hit', function () {
+test('an unsplash photo imports through the queue as a temporary upload and sends the tracking hit', function () {
config()->set('services.unsplash.access_key', 'unsplash-key');
$fake = UploadedFile::fake()->image('photo.jpg', 800, 600);
$image = file_get_contents($fake->getPathname());
@@ -220,14 +220,19 @@ test('an unsplash photo imports through the importer as a temporary upload and s
$download => Http::response(['url' => 'https://example.test']),
]);
- $response = test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertCreated()
- ->assertJsonPath('type', MediaType::Image->value);
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ $status = test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::DONE)
+ ->assertJsonPath('media.type', MediaType::Image->value);
$media = Media::query()->sole();
- expect($response->json('upload_token'))->toBe($media->upload_token)
+ expect($status->json('media.upload_token'))->toBe($media->upload_token)
->and(Str::isUuid($media->upload_token))->toBeTrue()
->and($media->collection)->toBe(Media::COLLECTION_UPLOADS)
->and($media->workspace_id)->toBe($this->workspace->id)
@@ -240,8 +245,9 @@ test('an unsplash photo imports through the importer as a temporary upload and s
'photo_id' => 'test',
'author_name' => 'Ana Photographer',
'author_url' => config('trypost.media_sources.unsplash.website').'/@ana?utm_source=trypost&utm_medium=referral',
+ 'download_location' => $download,
])
- ->and($response->json('meta.source_meta.author_name'))->toBe('Ana Photographer')
+ ->and($status->json('media.meta.source_meta.author_name'))->toBe('Ana Photographer')
->and(Storage::get($media->path))->toBe($image);
Http::assertSent(fn (Request $request) => $request->url() === $download
@@ -253,7 +259,7 @@ test('a url outside the configured download hosts is rejected before any request
Http::fake();
test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick(['url' => $url]))
+ ->postJson(route('app.media.imports.store'), unsplashPick(['url' => $url]))
->assertUnprocessable()
->assertJsonValidationErrors('url');
@@ -274,7 +280,7 @@ test('the configured download hosts decide what is accepted', function () {
Http::fake();
test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick(['url' => 'https://images.unsplash.com/photo-test']))
+ ->postJson(route('app.media.imports.store'), unsplashPick(['url' => 'https://images.unsplash.com/photo-test']))
->assertUnprocessable()
->assertJsonValidationErrors('url');
@@ -286,7 +292,7 @@ test('a download location on another host is rejected before any request', funct
Http::fake();
test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick(['download_location' => $downloadLocation]))
+ ->postJson(route('app.media.imports.store'), unsplashPick(['download_location' => $downloadLocation]))
->assertUnprocessable()
->assertJsonValidationErrors('download_location');
@@ -303,7 +309,7 @@ test('the attribution is required and the author link stays on the unsplash webs
Http::fake();
test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick(['author_url' => 'https://evil.test/@ana', 'author_name' => '', 'photo_id' => null]))
+ ->postJson(route('app.media.imports.store'), unsplashPick(['author_url' => 'https://evil.test/@ana', 'author_name' => '', 'photo_id' => null]))
->assertUnprocessable()
->assertJsonValidationErrors(['author_url', 'author_name', 'photo_id']);
@@ -315,15 +321,17 @@ test('unsplash picks are refused while unsplash is not configured', function ()
Http::fake();
test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
+ ->postJson(route('app.media.imports.store'), unsplashPick())
->assertUnprocessable()
- ->assertJsonValidationErrors(['url', 'download_location']);
+ ->assertJsonValidationErrors('source');
Http::assertNothingSent();
});
-test('the media library and giphy routes are gone while the upload routes remain', function () {
+test('the media library routes and the in-request imports are gone while the upload routes remain', function () {
foreach ([
+ 'app.media.store-from-url',
+ 'app.media.giphy.store',
'app.assets.index',
'app.assets.search',
'app.assets.store',
@@ -338,7 +346,7 @@ test('the media library and giphy routes are gone while the upload routes remain
}
expect(Route::has('app.media.store-chunked'))->toBeTrue()
- ->and(Route::has('app.media.store-from-url'))->toBeTrue()
+ ->and(Route::has('app.media.imports.store'))->toBeTrue()
->and(Route::has('app.media.unsplash.search'))->toBeTrue();
});
@@ -350,10 +358,15 @@ test('an allowed host that redirects is refused and nothing is tracked', functio
]);
$this->mock(UnsplashService::class)->shouldReceive('trackDownload')->never();
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertUnprocessable()
- ->assertJsonValidationErrors(['url' => __('posts.composer.media_sources.errors.import_failed')]);
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED)
+ ->assertJsonPath('reason', ImportedFile::HOST_NOT_ALLOWED);
Http::assertNotSent(fn (Request $request) => str_contains($request->url(), '127.0.0.1'));
expect(Media::query()->count())->toBe(0);
@@ -505,7 +518,7 @@ test('a user outside the workspace gets 403 before validation runs', function ()
->assertForbidden();
test()->actingAs($outsider->fresh())
- ->postJson(route('app.media.store-from-url'), ['url' => 'not a url'])
+ ->postJson(route('app.media.imports.store'), ['url' => 'not a url'])
->assertForbidden();
test()->actingAs($outsider->fresh())
@@ -513,15 +526,19 @@ test('a user outside the workspace gets 403 before validation runs', function ()
->assertForbidden();
});
-test('a from-url body that is not an image fails the import whatever its content type says', function () {
+test('an unsplash body that is not an image fails the import whatever its content type says', function () {
config()->set('services.unsplash.access_key', 'unsplash-key');
Http::fake([unsplashImagesPattern() => Http::response('<html>not an image</html>', 200, ['Content-Type' => 'image/png'])]);
$this->mock(UnsplashService::class)->shouldReceive('trackDownload')->never();
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertUnprocessable()
- ->assertJsonValidationErrors(['url' => __('posts.composer.media_sources.errors.import_failed')]);
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED);
expect(Media::query()->count())->toBe(0)
->and(Storage::allFiles())->toBe([]);
@@ -529,16 +546,20 @@ test('a from-url body that is not an image fails the import whatever its content
test('a gif body labelled jpeg is stored as a gif', function () {
config()->set('services.unsplash.access_key', 'unsplash-key');
- $gif = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
+ $gif = file_get_contents(base_path('tests/fixtures/1x1.gif'));
Http::fake([
unsplashImagesPattern() => Http::response($gif, 200, ['Content-Type' => 'image/jpeg']),
config('trypost.media_sources.unsplash.api').'/*' => Http::response([]),
]);
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertCreated()
- ->assertJsonPath('mime_type', 'image/gif');
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('media.mime_type', 'image/gif');
expect(Media::query()->sole())
->mime_type->toBe('image/gif')
@@ -552,10 +573,15 @@ test('an unsplash photo over the image cap is rejected and leaves no row or file
]);
$this->mock(UnsplashService::class)->shouldReceive('trackDownload')->never();
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertUnprocessable()
- ->assertJsonValidationErrors(['url' => __('posts.composer.media_sources.errors.import_failed')]);
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::FAILED)
+ ->assertJsonPath('reason', ImportedFile::TOO_LARGE);
expect(Media::query()->count())->toBe(0)
->and(Storage::allFiles())->toBe([]);
@@ -568,9 +594,14 @@ test('a failed tracking hit does not undo the pick', function () {
config('trypost.media_sources.unsplash.api').'/*' => Http::failedConnection(),
]);
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick())
- ->assertCreated();
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick())
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::DONE);
expect(Media::query()->count())->toBe(1);
});
@@ -613,10 +644,15 @@ test('a photo without a photographer link keeps a null author link', function ()
config('trypost.media_sources.unsplash.api').'/*' => Http::response([]),
]);
- test()->actingAs($this->user)
- ->postJson(route('app.media.store-from-url'), unsplashPick(['author_url' => null]))
- ->assertCreated()
- ->assertJsonPath('meta.source_meta.author_url', null);
+ $importId = test()->actingAs($this->user)
+ ->postJson(route('app.media.imports.store'), unsplashPick(['author_url' => null]))
+ ->assertAccepted()
+ ->json('import_id');
+
+ test()->getJson(route('app.media.imports.show', $importId))
+ ->assertOk()
+ ->assertJsonPath('status', MediaImportStatus::DONE)
+ ->assertJsonPath('media.meta.source_meta.author_url', null);
});
test('trending pages are cached and shared while failures are not', function () {
@@ -674,8 +710,8 @@ test('unsplash picks share the media imports throttle', function () {
config('trypost.media_sources.unsplash.api').'/*' => Http::response([]),
]);
- test()->actingAs($this->user)->postJson(route('app.media.store-from-url'), unsplashPick())->assertCreated();
- test()->actingAs($this->user)->postJson(route('app.media.store-from-url'), unsplashPick())->assertTooManyRequests();
+ test()->actingAs($this->user)->postJson(route('app.media.imports.store'), unsplashPick())->assertAccepted();
+ test()->actingAs($this->user)->postJson(route('app.media.imports.store'), unsplashPick())->assertTooManyRequests();
expect(Media::query()->count())->toBe(1);
});
diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.php
index 9cf17fb84..d2e238c95 100644
--- a/tests/Feature/Services/Social/LinkedInPublisherTest.php
+++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php
@@ -16,6 +16,7 @@ use App\Services\Social\LinkCard\LinkCardFetcher;
use App\Services\Social\LinkCard\LinkCardMetadata;
use App\Services\Social\LinkedInPublisher;
use App\Support\Social\ThreadProgress;
+use Illuminate\Http\Client\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
@@ -224,6 +225,77 @@ test('linkedin publisher can publish post with image', function () {
);
});
+test('linkedin publisher uploads an animated gif as it is, without re-encoding it', function () {
+ $gif = file_get_contents(base_path('tests/fixtures/1x1.gif'));
+ $this->post->update([
+ 'media' => [[
+ 'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/medias/loop.gif',
+ 'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif',
+ ]],
+ ]);
+
+ $this->mock(MediaOptimizer::class)->shouldNotReceive('optimizeImage');
+
+ $api = config('trypost.platforms.linkedin.api');
+ $uploadUrl = 'https://www.linkedin.com/dms/upload/v2/pic/0/gif-upload';
+ $uploaded = null;
+
+ Http::fake([
+ "{$api}/rest/images*" => Http::response(['value' => ['uploadUrl' => $uploadUrl, 'image' => 'urn:li:image:gifUrn']]),
+ "{$api}/rest/posts*" => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:gif']),
+ $uploadUrl => function (Request $request) use (&$uploaded) {
+ $uploaded = $request->body();
+
+ return Http::response(null, 201);
+ },
+ 'example.com/medias/loop.gif' => Http::response($gif, 200, ['Content-Type' => 'image/gif']),
+ ]);
+
+ $this->publisher->publish($this->post);
+
+ expect($uploaded)->toBe($gif);
+ Http::assertSent(fn (Request $request) => $request->url() === "{$api}/rest/posts"
+ && data_get($request->data(), 'content.media.id') === 'urn:li:image:gifUrn');
+});
+
+test('linkedin publisher sends an animated gif in a multi-image post next to a re-encoded jpeg', function () {
+ $gif = file_get_contents(base_path('tests/fixtures/1x1.gif'));
+ $this->post->update([
+ 'media' => [
+ ['id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/medias/loop.gif', 'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif'],
+ ['id' => 'jpg-1', 'path' => 'medias/photo.jpg', 'url' => 'https://example.com/medias/photo.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg'],
+ ],
+ ]);
+
+ $this->mock(MediaOptimizer::class)
+ ->shouldReceive('optimizeImage')
+ ->once()
+ ->andReturnUsing(fn () => tap(tempnam(sys_get_temp_dir(), 'li_jpg_'), fn ($path) => file_put_contents($path, 'jpeg-bytes')));
+
+ $api = config('trypost.platforms.linkedin.api');
+ $uploaded = [];
+
+ Http::fake([
+ "{$api}/rest/images*" => Http::sequence()
+ ->push(['value' => ['uploadUrl' => 'https://www.linkedin.com/dms/upload/1', 'image' => 'urn:li:image:img1']])
+ ->push(['value' => ['uploadUrl' => 'https://www.linkedin.com/dms/upload/2', 'image' => 'urn:li:image:img2']]),
+ "{$api}/rest/posts*" => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:multi']),
+ 'www.linkedin.com/dms/upload/*' => function (Request $request) use (&$uploaded) {
+ $uploaded[] = $request->body();
+
+ return Http::response(null, 201);
+ },
+ 'example.com/medias/loop.gif' => Http::response($gif, 200, ['Content-Type' => 'image/gif']),
+ 'example.com/medias/photo.jpg' => Http::response(linkedInJpegBytes(), 200, ['Content-Type' => 'image/jpeg']),
+ ]);
+
+ $this->publisher->publish($this->post);
+
+ expect($uploaded)->toBe([$gif, 'jpeg-bytes']);
+ Http::assertSent(fn (Request $request) => $request->url() === "{$api}/rest/posts"
+ && data_get($request->data(), 'content.multiImage.images.*.id') === ['urn:li:image:img1', 'urn:li:image:img2']);
+});
+
test('linkedin publisher sends the real alt text on a single image post', function () {
$this->post->update([
'media' => [
diff --git a/tests/Pest.php b/tests/Pest.php
index 858e04dbd..08a1e6a77 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -1140,6 +1140,40 @@ function clickWithoutPointer(mixed $page, string $selector): void
$page->script("document.querySelector({$selector}).click()");
}
+/**
+ * Plays a broadcast on the page as if Reverb delivered it: the event reaches
+ * the `useEcho` listeners of that private channel through the Pusher client
+ * Echo connects with (pusher-js keeps every client in `Pusher.instances`).
+ * Browser tests broadcast with the null driver, so a server event never
+ * arrives on its own. `$channel` is the name the app listens on
+ * (`workspace.{id}`), `$event` the event's `broadcastAs()` name.
+ *
+ * @param array<string, mixed> $payload
+ */
+function broadcastToPage(mixed $page, string $channel, string $event, array $payload): void
+{
+ $name = json_encode("private-{$channel}");
+ $eventName = json_encode($event);
+ $data = json_encode($payload);
+
+ waitForCondition($page, "Boolean(window.Pusher.instances[0]?.channel({$name}))");
+ $page->script("window.Pusher.instances[0].channel({$name}).emit({$eventName}, {$data})");
+}
+
+/**
+ * Plays the page's socket dropping and connecting again on the Pusher client
+ * Echo connects with, which Echo reports to `useConnectionStatus()`
+ * listeners. Each change is its own script, so the page sees the drop
+ * before the reconnection.
+ */
+function reconnectPageSocket(mixed $page): void
+{
+ foreach (['disconnected', 'connected'] as $state) {
+ $page->script("const connection = window.Pusher.instances[0].connection; connection.state = '{$state}'; connection.emit('state_change', { current: '{$state}' });");
+ waitForCondition($page, "window.Pusher.instances[0].connection.state === '{$state}'");
+ }
+}
+
/**
* Tells the page that the user's browser storage changed in another tab, as
* the browser does with a `storage` event: seed the change with
diff --git a/tests/Unit/Config/HorizonConfigTest.php b/tests/Unit/Config/HorizonConfigTest.php
index 0f82f1393..1ec4b2c9e 100644
--- a/tests/Unit/Config/HorizonConfigTest.php
+++ b/tests/Unit/Config/HorizonConfigTest.php
@@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Dto\RemoteFile;
+use App\Enums\Media\Type as MediaType;
use App\Jobs\Media\AdoptWorkspaceLibraryJob;
use App\Jobs\Media\ImportRemoteMedia;
use App\Jobs\RssFeed\FetchRssFeed;
@@ -50,7 +51,7 @@ test('media imports are worked only by their own supervisor', function () {
test('the media-imports supervisor outlives the import and redis never reserves it twice', function () {
config()->set('queue.default', 'redis');
- $job = new ImportRemoteMedia('import', 'workspace', 'user', new RemoteFile('https://example.com/a.png', 'a.png'));
+ $job = new ImportRemoteMedia('import', 'workspace', 'user', new RemoteFile('https://example.com/a.png', 'a.png'), MediaType::cases());
expect($job->queue)->toBe(ImportRemoteMedia::QUEUE)
->and($job->timeout)->toBe((int) config('trypost.media_sources.import_timeout_seconds'))
@@ -61,7 +62,7 @@ test('the media-imports supervisor outlives the import and redis never reserves
test('the import timeout stays below a short retry_after so the database queue never reserves it twice', function () {
config()->set(['queue.default' => 'database', 'queue.connections.database.retry_after' => 90]);
- $job = new ImportRemoteMedia('import', 'workspace', 'user', new RemoteFile('https://example.com/a.png', 'a.png'));
+ $job = new ImportRemoteMedia('import', 'workspace', 'user', new RemoteFile('https://example.com/a.png', 'a.png'), MediaType::cases());
expect($job->timeout)->toBe(60)
->and($job->timeout)->toBeLessThan(config('queue.connections.database.retry_after'));
diff --git a/tests/Unit/Enums/ContentTypeTest.php b/tests/Unit/Enums/ContentTypeTest.php
index 209efe6e6..1a9d61029 100644
--- a/tests/Unit/Enums/ContentTypeTest.php
+++ b/tests/Unit/Enums/ContentTypeTest.php
@@ -187,6 +187,8 @@ test('content type requires media correctly', function () {
test('media rules keep editor parity for gif and requires_media flags', function () {
expect(ContentType::DiscordMessage->acceptsGif())->toBeTrue();
expect(ContentType::TelegramPost->acceptsGif())->toBeTrue();
+ expect(ContentType::LinkedInPost->acceptsGif())->toBeTrue();
+ expect(ContentType::LinkedInPagePost->acceptsGif())->toBeTrue();
expect(ContentType::InstagramFeed->mediaRules()['requires_media'])->toBeTrue();
expect(ContentType::DiscordMessage->mediaRules()['accepts_gif'])->toBeTrue();
});
@@ -243,7 +245,7 @@ test('media rules preserve pre-centralization editor limits for mapped types', f
],
'linkedin_post' => [
'requires_media' => false,
- 'accepts_gif' => false,
+ 'accepts_gif' => true,
'max_files' => 10,
'max_document_bytes' => min(100 * $mb, $hardDocument),
'max_video_bytes' => $hardVideo,
diff --git a/tests/Unit/Enums/Media/SourceTest.php b/tests/Unit/Enums/Media/SourceTest.php
index da9b5fbf5..17d8524cd 100644
--- a/tests/Unit/Enums/Media/SourceTest.php
+++ b/tests/Unit/Enums/Media/SourceTest.php
@@ -8,6 +8,7 @@ function mediaSourceConfigure(array $overrides = []): void
{
config()->set(array_merge([
'services.unsplash.access_key' => null,
+ 'services.giphy.api_key' => null,
'services.google_media.client_id' => null,
'services.google_media.client_secret' => null,
'services.google_media.redirect' => null,
@@ -18,6 +19,7 @@ function mediaSourceConfigure(array $overrides = []): void
'trypost.media_sources.google_drive.enabled' => true,
'trypost.media_sources.google_photos.enabled' => true,
'trypost.media_sources.canva.enabled' => true,
+ 'trypost.media_sources.giphy.enabled' => true,
], $overrides));
}
@@ -27,7 +29,7 @@ function mediaSourceEnabled(): array
}
test('the picker sources are listed in menu order', function () {
- expect(Source::pickerSources())->toBe([Source::Canva, Source::GoogleDrive, Source::GooglePhotos, Source::Unsplash]);
+ expect(Source::pickerSources())->toBe([Source::Canva, Source::Giphy, Source::GoogleDrive, Source::GooglePhotos, Source::Unsplash]);
});
test('no picker source is enabled when every key is empty', function () {
@@ -49,6 +51,12 @@ test('each source needs its flag and every one of its keys', function () {
mediaSourceConfigure(['services.unsplash.access_key' => 'u']);
expect(mediaSourceEnabled())->toBe(['unsplash']);
+ mediaSourceConfigure(['services.giphy.api_key' => 'g']);
+ expect(mediaSourceEnabled())->toBe(['giphy']);
+
+ mediaSourceConfigure(['services.giphy.api_key' => 'g', 'trypost.media_sources.giphy.enabled' => false]);
+ expect(mediaSourceEnabled())->toBe([]);
+
mediaSourceConfigure(['services.google_media.client_id' => 'c']);
expect(mediaSourceEnabled())->toBe([]);
diff --git a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
index e64169918..27824184a 100644
--- a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
+++ b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
use App\Rules\ContentTypeCompatibleWithMedia;
+use Illuminate\Support\Number;
function runMediaRule(string $contentType, array $media): array
{
@@ -162,7 +163,7 @@ test('x still accepts a mov video', function () {
test('a gif is rejected on content types that do not accept gifs', function () {
$media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif']];
- foreach ([ContentType::InstagramFeed, ContentType::LinkedInPost, ContentType::PinterestPin, ContentType::FacebookPost, ContentType::GoogleBusinessPost] as $type) {
+ foreach ([ContentType::InstagramFeed, ContentType::PinterestPin, ContentType::FacebookPost, ContentType::GoogleBusinessPost] as $type) {
$errors = runMediaRule($type->value, $media);
expect($errors)->toHaveCount(1, $type->value);
@@ -189,15 +190,40 @@ test('an image over the content type cap is rejected by size', function () {
});
test('a kind violation is reported alone and is not overwritten by a size violation on the same item', function () {
- // A 6 MB GIF on LinkedIn breaks two rules; the root cause ("does not accept GIF") must be the one message.
+ // A 6 MB GIF on a Facebook post breaks two rules; the root cause ("does not accept GIF") must be the one message.
$media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif', 'size' => 6 * 1024 * 1024]];
- $errors = runMediaRule(ContentType::LinkedInPost->value, $media);
+ $errors = runMediaRule(ContentType::FacebookPost->value, $media);
expect($errors)->toHaveCount(1);
expect($errors[0])->toContain('GIF');
});
+dataset('linkedin content types', [
+ 'profile' => [ContentType::LinkedInPost],
+ 'page' => [ContentType::LinkedInPagePost],
+]);
+
+test('linkedin accepts an animated gif within its image cap', function (ContentType $type) {
+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif', 'size' => 2 * 1024 * 1024]];
+
+ expect(runMediaRule($type->value, $media))->toBe([]);
+})->with('linkedin content types');
+
+test('a linkedin gif over the 5 MB image cap is refused for its size, not for being a gif', function (ContentType $type) {
+ $media = [['type' => MediaType::Image->value, 'mime_type' => 'image/gif', 'size' => 6 * 1024 * 1024]];
+
+ expect(runMediaRule($type->value, $media))
+ ->toBe([__('posts.form.warnings.image_too_large', ['max' => Number::fileSize(5 * 1024 * 1024), 'current' => Number::fileSize(6 * 1024 * 1024, 1)])]);
+})->with('linkedin content types');
+
+test('linkedin takes a gif next to other images, but never next to a video', function (ContentType $type) {
+ $gif = ['type' => MediaType::Image->value, 'mime_type' => 'image/gif'];
+
+ expect(runMediaRule($type->value, [$gif, ['type' => MediaType::Image->value, 'mime_type' => 'image/jpeg']]))->toBe([])
+ ->and(runMediaRule($type->value, [$gif, ['type' => MediaType::Video->value, 'mime_type' => 'video/mp4']]))->toBe([__('posts.form.warnings.no_mixed_media')]);
+})->with('linkedin content types');
+
test('an item that cannot be classified is not measured against any cap', function () {
// An API `url`-only entry before download: no type, mime or filename, but a stray size.
$media = [['url' => 'https://example.com/asset', 'size' => 999_999_999]];
diff --git a/tests/fixtures/1x1.gif b/tests/fixtures/1x1.gif
new file mode 100644
index 000000000..f191b280c
Binary files /dev/null and b/tests/fixtures/1x1.gif differ