Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions app/Casts/StoredMedia.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace App\Casts;

use App\Support\Media\MediaUrl;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

/** @implements CastsAttributes<array|null, array|null> */
final class StoredMedia implements CastsAttributes
{
public function get(Model $model, string $key, mixed $value, array $attributes): ?array
{
if ($value === null) {
return null;
}
$decoded = json_decode($value, true, flags: JSON_THROW_ON_ERROR);

return $key === 'meta' ? MediaUrl::meta($decoded) : MediaUrl::canonicalItems($decoded);
}

public function set(Model $model, string $key, mixed $value, array $attributes): ?string
{
return $value === null ? null : json_encode($key === 'meta' ? MediaUrl::meta($value) : MediaUrl::canonicalItems($value), JSON_THROW_ON_ERROR);
}
}
8 changes: 7 additions & 1 deletion app/Dto/MediaItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Enums\Media\Type;
use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Support\Media\MediaUrl;

class MediaItem
{
Expand Down Expand Up @@ -64,7 +65,7 @@ public function toArray(): array
return [
'id' => $this->id,
'path' => $this->path,
'url' => $this->url,
'url' => MediaUrl::verifiesStorage() ? MediaUrl::canonical($this->path, $this->id) : $this->url,
'type' => $this->type?->value,
'mime_type' => $this->mime_type,
'original_filename' => $this->original_filename,
Expand All @@ -82,6 +83,11 @@ public function isVideo(): bool
return $this->kind() === Type::Video;
}

public function publishUrl(): string
{
return MediaUrl::publishing($this->path, $this->url);
}

public function isImage(): bool
{
return $this->kind() === Type::Image;
Expand Down
13 changes: 13 additions & 0 deletions app/Http/Controllers/App/MediaFileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use App\Enums\Media\Type as MediaType;
use App\Http\Controllers\Controller;
use App\Models\Media;
use App\Support\Media\MediaUrl;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
Expand All @@ -19,6 +21,17 @@
*/
class MediaFileController extends Controller
{
public function view(Request $request, Media $media): RedirectResponse
{
abort_unless($media->workspace !== null, 404);
abort_unless($request->user()->can('view', $media->workspace), 404);

return redirect()->away(MediaUrl::temporary($media->path))->withHeaders([
'Cache-Control' => 'private, no-store',
'Referrer-Policy' => 'no-referrer',
]);
}

public function show(Request $request, Media $media): StreamedResponse
{
$workspace = $request->user()->currentWorkspace;
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Resources/Api/IdeaResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Http\Resources\Api;

use App\Models\Idea;
use App\Support\Media\MediaUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

Expand All @@ -24,7 +25,7 @@ public function toArray(Request $request): array
'title' => $this->title,
'body' => $this->body,
'position' => $this->position,
'media' => $this->media ?? [],
'media' => MediaUrl::apiItems($this->media ?? [], $this->workspace_id),
'labels' => LabelResource::collection($this->whenLoaded('labels')),
'created_at' => $this->created_at->format('Y-m-d H:i:s'),
'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
Expand Down
5 changes: 3 additions & 2 deletions app/Http/Resources/Api/PostResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Enums\Post\Status;
use App\Models\User;
use App\Support\Media\MediaUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

Expand All @@ -27,7 +28,7 @@ public function toArray(Request $request): array
'post_group_id' => $this->post_group_id,
'author' => $this->person($this->user),
'content' => $this->content,
'media' => $this->media,
'media' => MediaUrl::apiItems($this->media ?? [], $this->workspace_id),
'status' => $this->status?->value,
'schedule_mode' => $this->schedule_mode?->value,
'scheduled_at' => $this->scheduled_at?->format('Y-m-d H:i:s'),
Expand All @@ -45,7 +46,7 @@ public function toArray(Request $request): array
'publish_status' => $this->publish_status->value,
'platform' => $this->platform?->value,
'content_type' => $this->content_type?->value,
'meta' => $this->meta,
'meta' => $this->meta === null ? null : MediaUrl::meta($this->meta, true, $this->workspace_id),
'platform_url' => $this->platform_url,
'error_message' => $this->error_message,
'display_name' => $this->display_name,
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Resources/Api/UploadResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Http\Resources\Api;

use App\Models\Media;
use App\Support\Media\MediaUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

Expand All @@ -27,7 +28,7 @@ public function toArray(Request $request): array
'mime_type' => $this->mime_type,
'size' => $this->size,
'original_filename' => $this->original_filename,
'url' => $this->url,
'url' => MediaUrl::verifiesStorage() ? MediaUrl::temporary($this->path) : $this->url,
'expires_at' => $this->created_at->copy()->addHours((int) config('trypost.media.upload_retention_hours'))->toIso8601String(),
];
}
Expand Down
11 changes: 6 additions & 5 deletions app/Jobs/DispatchWebhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use App\Models\WebhookLog;
use App\Services\Http\SafeHttpFetcher;
use App\Services\WebhookService;
use App\Support\Media\RedactStorageCredentials;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
Expand Down Expand Up @@ -66,8 +67,6 @@ public function handle(SafeHttpFetcher $safeHttp, WebhookService $webhooks): voi
'created_at' => now()->toIso8601String(),
];

$signature = $webhooks->signature($body, $this->webhook->signing_secret);

$log = WebhookLog::query()->find($this->logId);

if ($log) {
Expand All @@ -91,6 +90,8 @@ public function handle(SafeHttpFetcher $safeHttp, WebhookService $webhooks): voi
}

try {
$deliveryBody = [...$body, 'data' => $webhooks->deliveryPayload($body['data'], $this->webhook->workspace_id)];
$signature = $webhooks->signature($deliveryBody, $this->webhook->signing_secret);
$response = $safeHttp->guardedRequest($this->webhook->endpoint, followRedirects: false)
->timeout(10)
->withUserAgent(config('trypost.user_agent'))
Expand All @@ -99,11 +100,11 @@ public function handle(SafeHttpFetcher $safeHttp, WebhookService $webhooks): voi
'X-Webhook-Signature' => $signature,
])
->withOptions(['stream' => true])
->post($this->webhook->endpoint, $body);
->post($this->webhook->endpoint, $deliveryBody);
} catch (ConnectionException|RuntimeException $e) {
$log->update([
'failed_at' => now(),
'response_body' => $e->getMessage(),
'response_body' => RedactStorageCredentials::clean($e->getMessage()),
]);

$log->refresh();
Expand All @@ -112,7 +113,7 @@ public function handle(SafeHttpFetcher $safeHttp, WebhookService $webhooks): voi
throw $e;
}

$responseBody = mb_scrub(str_replace("\0", '', $safeHttp->bodyPrefix($response, self::RESPONSE_BODY_BYTES)), 'UTF-8');
$responseBody = RedactStorageCredentials::clean(mb_scrub(str_replace("\0", '', $safeHttp->bodyPrefix($response, self::RESPONSE_BODY_BYTES)), 'UTF-8'));

if ($response->successful()) {
$log->update([
Expand Down
53 changes: 51 additions & 2 deletions app/Jobs/PublishToSocialPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
use App\Services\Social\TikTokPublisher;
use App\Services\Social\XPublisher;
use App\Services\Social\YouTubePublisher;
use App\Support\Media\MediaUrl;
use App\Support\Media\RedactStorageCredentials;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use App\Support\Social\LimitRetryPolicy;
use App\Support\Social\PublishCheckpoint;
Expand Down Expand Up @@ -115,6 +117,10 @@ public function handle(): void
return;
}

if ($this->failForMissingStoredMedia()) {
return;
}

if ($this->failForInvalidMedia()) {
return;
}
Expand Down Expand Up @@ -251,6 +257,48 @@ private function failForMissingScopes(): bool
return true;
}

private function failForMissingStoredMedia(): bool
{
if (! MediaUrl::verifiesStorage()) {
return false;
}

$context = $this->post->error_context;
if (PublishCheckpoint::instagramWorkflow($context) !== null || PublishCheckpoint::tiktokPublishId($context) !== null) {
return false;
}

$items = [...($this->post->media ?? [])];
foreach (ThreadReplies::of($this->post->meta) as $reply) {
array_push($items, ...$reply['media']);
}

try {
foreach ($items as $item) {
$path = data_get($item, 'path');
if (is_string($path) && $path !== '' && ! MediaUrl::exists($path)) {
$this->failAndFinalize('A media attachment is unavailable.', $this->failureContext([
'reason' => 'media_missing',
'category' => ErrorCategory::MediaFormat->value,
]));

return true;
}
}
} catch (Throwable) {
$this->rescheduleForRetry(new PlatformUnavailableException(
'Media storage is unavailable.',
context: ['reason' => 'media_unavailable'],
));
$this->updatePostStatus();
$this->broadcastStatus();

return true;
}

return false;
}

/**
* Media can become invalid after scheduling (bounds changed in a release,
* an edit through another path): recheck it against the same rule every
Expand Down Expand Up @@ -310,6 +358,7 @@ private function rescheduleForRetry(PlatformUnavailableException $e): void
...($hasOwnPolicy ? ['max_retries' => $maxRetries, 'retry_delay_seconds' => $retryDelaySeconds] : []),
'detail' => $e->getMessage(),
];
$context = RedactStorageCredentials::clean($context);

if ($retryCount > $maxRetries) {
$this->reportCaughtPublishFailure($e, [
Expand Down Expand Up @@ -513,8 +562,8 @@ private function markPlatformAsFailed(string $message, ?array $context = null):
$failureContext = [...$previousContext, ...($context ?? [])];

$this->post->markPublicationFailed(
ThreadProgress::failureMessage($this->post, $message, $failureContext),
$failureContext === [] ? null : $failureContext,
RedactStorageCredentials::clean(ThreadProgress::failureMessage($this->post, $message, $failureContext)),
$failureContext === [] ? null : RedactStorageCredentials::clean($failureContext),
);
}

Expand Down
3 changes: 2 additions & 1 deletion app/Models/Idea.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Models;

use App\Casts\StoredMedia;
use App\Dto\MediaItem;
use Database\Factories\IdeaFactory;
use Illuminate\Database\Eloquent\Builder;
Expand Down Expand Up @@ -40,7 +41,7 @@ class Idea extends Model
protected function casts(): array
{
return [
'media' => 'array',
'media' => StoredMedia::class,
'position' => 'integer',
];
}
Expand Down
3 changes: 2 additions & 1 deletion app/Models/Media.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Enums\Media\Type as MediaType;
use App\Exceptions\MediaOwnershipViolation;
use App\Jobs\Media\DeleteMediaFiles;
use App\Support\Media\MediaUrl;
use Database\Factories\MediaFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
Expand Down Expand Up @@ -164,7 +165,7 @@ public function issueUploadToken(): void
protected function url(): Attribute
{
return Attribute::make(
get: fn () => Storage::url($this->path),
get: fn () => MediaUrl::browser($this),
);
}

Expand Down
9 changes: 5 additions & 4 deletions app/Models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Models;

use App\Actions\Media\SyncOwnedMedia;
use App\Casts\StoredMedia;
use App\Dto\MediaItem;
use App\Enums\Media\Type;
use App\Enums\Post\CreatedVia;
Expand All @@ -19,6 +20,7 @@
use App\Enums\TikTok\PrivacyLevel;
use App\Observers\PostObserver;
use App\Support\Media\MediaCopyBatch;
use App\Support\Media\MediaUrl;
use Carbon\CarbonInterface;
use Database\Factories\PostFactory;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
Expand All @@ -33,7 +35,6 @@
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

#[ObservedBy([PostObserver::class])]
class Post extends Model
Expand Down Expand Up @@ -115,7 +116,7 @@ protected function casts(): array
'recurrence_origin_at' => 'datetime',
'created_via' => CreatedVia::class,
'origin' => Origin::class,
'media' => 'array',
'media' => StoredMedia::class,
'scheduled_at' => 'datetime',
'published_at' => 'datetime',
'approval_requested_at' => 'datetime',
Expand All @@ -124,7 +125,7 @@ protected function casts(): array
'publish_status' => PublishStatus::class,
'platform' => Platform::class,
'content_type' => ContentType::class,
'meta' => 'array',
'meta' => StoredMedia::class,
'error_context' => 'array',
'thread_reply_ids' => 'array',
'submitted_at' => 'datetime',
Expand Down Expand Up @@ -460,7 +461,7 @@ protected function displayAvatar(): Attribute
{
return Attribute::make(
get: fn (): ?string => $this->socialAccount?->avatar_url
?: ($this->platform_avatar ? Storage::url($this->platform_avatar) : null),
?: MediaUrl::avatar($this->platform_avatar),
);
}

Expand Down
4 changes: 2 additions & 2 deletions app/Models/SocialAccount.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use App\Observers\ComposerVersionObserver;
use App\Observers\SocialAccountObserver;
use App\Support\GoogleBusinessResourceName;
use App\Support\Media\MediaUrl;
use Database\Factories\SocialAccountFactory;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
Expand All @@ -33,7 +34,6 @@
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

#[ObservedBy([SocialAccountObserver::class, ComposerVersionObserver::class])]
#[ScopedBy(SocialAccountOrderScope::class)]
Expand Down Expand Up @@ -322,7 +322,7 @@ public function needsProactiveTokenRefresh(): bool
protected function avatarUrl(): Attribute
{
return Attribute::make(
get: fn (?string $value) => $value ? Storage::url($value) : null,
get: fn (?string $value) => MediaUrl::avatar($value),
);
}

Expand Down
Loading
Loading