Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
<?php
declare(strict_types=1);
namespace App\Models\Traits;
use App\Enums\Media\Type;
use App\Models\Media;
use App\Models\User;
use App\Models\Workspace;
use App\Support\HeicConverter;
use App\Support\Media\ImageDimensions;
use App\Support\VideoDurationProbe;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\ImageManager;
use InvalidArgumentException;
use RuntimeException;
use Throwable;
trait HasMedia
{
/**
* Media collections configuration.
* 'single' = only one media per collection (replaces existing)
* 'multiple' = unlimited media per collection
*/
protected static array $mediaCollections = [
Workspace::class => [
'logo' => 'single',
],
User::class => [
'avatar' => 'single',
],
];
public function media(): MorphMany
{
return $this->morphMany(Media::class, 'mediable')->orderBy('order');
}
public function getMedia(string $collection = 'default'): MorphMany
{
return $this->media()->where('collection', $collection);
}
public function getFirstMedia(string $collection = 'default'): ?Media
{
return $this->getMedia($collection)->first();
}
public function getFirstMediaUrl(string $collection = 'default', ?string $default = null): ?string
{
$media = $this->getFirstMedia($collection);
return $media?->url ?? $default;
}
/**
* Generate a DiceBear fallback URL using initials.
*/
public function getFallbackAvatarUrl(string $seed): string
{
return 'https://api.dicebear.com/9.x/initials/svg?backgroundColor=777777&fontFamily=Verdana&fontSize=40&seed='.urlencode($seed);
}
/**
* Add media to a collection.
* If the collection is configured as 'single', it will clear existing media first.
*/
public function addMedia(UploadedFile $file, string $collection = 'default', array $meta = [], ?string $groupId = null): Media
{
if ($this->isSingleMediaCollection($collection)) {
$this->clearMediaCollection($collection);
}
$mimeType = $file->getMimeType();
$type = $this->getMediaType($mimeType);
// Normalize non-JPEG still images to JPEG q100 for universal platform compatibility.
// GIF is preserved (animation kept for X/Bluesky/Mastodon).
[$normalizedBytes, $normalizedMime, $normalizedExt] = $this->normalizeImageFormat(
$file->getPathname(),
$mimeType,
$type,
$file->getClientOriginalExtension(),
);
$filename = Str::uuid().'.'.$normalizedExt;
$path = "medias/{$filename}";
$meta = $this->withVideoDuration($meta, $type, $file->getPathname());
Storage::put($path, $normalizedBytes);
return $this->media()->create([
'group_id' => $groupId ?? Str::uuid()->toString(),
'collection' => $collection,
'type' => $type,
'path' => $path,
'original_filename' => $this->sanitizeOriginalFilename(HeicConverter::convertedFilename($file->getClientOriginalName(), $mimeType)),
'mime_type' => $normalizedMime,
'size' => strlen($normalizedBytes),
'order' => 0,
'meta' => [...$meta, ...$this->imageDimensions($normalizedBytes, $type)],
]);
}
/**
* Add media from a file path (used for chunked uploads).
* Images are normalized in memory; videos/PDFs are streamed to storage.
*/
public function addMediaFromPath(string $filePath, string $originalFilename, string $collection = 'default', array $meta = [], ?string $groupId = null, ?string $mimeType = null): Media
{
if ($this->isSingleMediaCollection($collection)) {
$this->clearMediaCollection($collection);
}
// Prefer an explicit MIME (e.g. from UploadedFile after FormRequest
// validation) — sniffing misclassifies empty test fakes and some
// freshly written temps as application/x-empty.
$mimeType ??= File::mimeType($filePath) ?: null;
if ($mimeType === null) {
throw new InvalidArgumentException("Unable to determine MIME type for media file: {$filePath}");
}
$type = $this->getMediaType($mimeType);
$extension = File::extension($originalFilename);
$meta = $this->withVideoDuration($meta, $type, $filePath);
$stored = $type === Type::Image
? $this->storeImageFromPath($filePath, $mimeType, $type, $extension, $meta)
: $this->streamFileToStorage($filePath, $mimeType, $extension, $meta);
return $this->media()->create([
'group_id' => $groupId ?? Str::uuid()->toString(),
'collection' => $collection,
'type' => $type,
'path' => $stored['path'],
'original_filename' => $this->sanitizeOriginalFilename(HeicConverter::convertedFilename($originalFilename, $mimeType)),
'mime_type' => $stored['mime_type'],
'size' => $stored['size'],
'order' => 0,
'meta' => $stored['meta'],
]);
}
/**
* Register media that is already stored on the default disk (e.g. after a
* multipart cloud upload).
*/
public function addMediaFromStoredPath(
string $storagePath,
string $originalFilename,
string $mimeType,
int $size,
string $collection = 'default',
array $meta = [],
?string $groupId = null,
): Media {
if ($this->isSingleMediaCollection($collection)) {
$this->clearMediaCollection($collection);
}
$type = $this->getMediaType($mimeType);
return $this->media()->create([
'group_id' => $groupId ?? Str::uuid()->toString(),
'collection' => $collection,
'type' => $type,
'path' => $storagePath,
'original_filename' => $this->sanitizeOriginalFilename($originalFilename),
'mime_type' => $mimeType,
'size' => $size,
'order' => 0,
'meta' => $meta,
]);
}
public function clearMediaCollection(string $collection = 'default'): void
{
$this->getMedia($collection)->each(fn (Media $media) => $media->delete());
}
public function isSingleMediaCollection(string $collection): bool
{
$modelClass = static::class;
$config = self::$mediaCollections[$modelClass][$collection] ?? 'multiple';
return $config === 'single';
}
/**
* @param array<string, mixed> $meta
* @return array{path: string, mime_type: string, size: int, meta: array<string, mixed>}
*/
private function storeImageFromPath(string $filePath, string $mimeType, Type $type, string $extension, array $meta): array
{
[$bytes, $storedMime, $storedExt] = $this->normalizeImageFormat(
$filePath,
$mimeType,
$type,
$extension,
);
$filename = Str::uuid().".{$storedExt}";
$path = "medias/{$filename}";
Storage::put($path, $bytes);
return [
'path' => $path,
'mime_type' => $storedMime,
'size' => strlen($bytes),
'meta' => [...$meta, ...$this->imageDimensions($bytes, $type)],
];
}
/**
* @param array<string, mixed> $meta
* @return array{path: string, mime_type: string, size: int, meta: array<string, mixed>}
*/
private function streamFileToStorage(string $filePath, string $mimeType, string $extension, array $meta): array
{
$filename = Str::uuid().".{$extension}";
$path = "medias/{$filename}";
$stream = fopen($filePath, 'rb');
if ($stream === false) {
throw new RuntimeException("Unable to open media file for reading: {$filePath}");
}
try {
Storage::writeStream($path, $stream);
} finally {
if (is_resource($stream)) {
fclose($stream);
}
}
return [
'path' => $path,
'mime_type' => $mimeType,
'size' => (int) filesize($filePath),
'meta' => $meta,
];
}
/**
* HEIC passes through to its own checks, which explain an unavailable
* converter or a multi-photo file instead of an unsupported type.
*/
private function getMediaType(string $mimeType): Type
{
if (HeicConverter::isHeicMime($mimeType) || HeicConverter::isSequenceMime($mimeType)) {
return Type::Image;
}
return Type::fromMime($mimeType)
?? throw ValidationException::withMessages(['media' => __('posts.composer.upload_errors.unsupported_type')]);
}
/**
* Reads the declared size from the header, so an image that would not fit
* in memory once decoded is refused before anything decodes it.
*/
private function assertWithinPixelLimit(string $filePath): void
{
$size = @getimagesize($filePath);
if (is_array($size) && (int) config('trypost.media.image_max_pixels') < $size[0] * $size[1]) {
throw ValidationException::withMessages(['media' => __('posts.composer.upload_errors.image_too_large')]);
}
}
/**
* Client-supplied filenames may contain byte sequences that aren't valid
* UTF-8 (e.g. a raw Windows-1252 byte for an em dash). Postgres rejects
* those outright on insert, so replace invalid sequences before storing.
*/
private function sanitizeOriginalFilename(string $filename): string
{
return mb_scrub($filename, 'UTF-8');
}
/**
* @param array<string, mixed> $meta
* @return array<string, mixed>
*/
private function withVideoDuration(array $meta, Type $type, string $filePath): array
{
return $type === Type::Video
? VideoDurationProbe::mergeInto($meta, VideoDurationProbe::fromFile($filePath))
: $meta;
}
/**
* Pixel width / height of raw image bytes as displayed (EXIF orientation
* applied), read after format normalization, when the original file path is
* gone; nothing for other types.
*
* @return array<string, int>
*/
private function imageDimensions(string $bytes, Type $type): array
{
return $type === Type::Image ? (ImageDimensions::fromBytes($bytes) ?? []) : [];
}
/**
* Convert PNG/WebP/HEIC/AVIF to JPEG at q100 (keeps dimensions). GIF and
* JPEG are returned untouched. Non-image types are passed through.
*
* @return array{0: string, 1: string, 2: string} [bytes, mime_type, extension]
*/
private function normalizeImageFormat(string $filePath, string $mimeType, Type $type, string $originalExtension): array
{
if ($type !== Type::Image) {
return [file_get_contents($filePath), $mimeType, $originalExtension];
}
if (HeicConverter::isSequenceMime($mimeType)) {
throw ValidationException::withMessages(['media' => __('posts.composer.upload_errors.heic_invalid')]);
}
if (HeicConverter::isHeicMime($mimeType)) {
return $this->convertHeicToJpeg($filePath);
}
$this->assertWithinPixelLimit($filePath);
// Formats that publish safely everywhere (JPEG is universal, GIF needed for X/Bluesky/Mastodon).
if (in_array($mimeType, ['image/jpeg', 'image/jpg', 'image/gif'], true)) {
return [file_get_contents($filePath), $mimeType, $originalExtension];
}
try {
$manager = new ImageManager(new Driver);
$encoded = (string) $manager->decodePath($filePath)->encode(new JpegEncoder(quality: 100));
return [$encoded, 'image/jpeg', 'jpg'];
} catch (Throwable $e) {
Log::warning('HasMedia: image normalization failed, storing original', [
'mime' => $mimeType,
'error' => $e->getMessage(),
]);
return [file_get_contents($filePath), $mimeType, $originalExtension];
}
}
/**
* @return array{0: string, 1: string, 2: string} [bytes, mime_type, extension]
*/
private function convertHeicToJpeg(string $filePath): array
{
if (! HeicConverter::available()) {
throw ValidationException::withMessages(['media' => __('posts.composer.upload_errors.heic_unavailable')]);
}
try {
return [HeicConverter::toJpeg($filePath), 'image/jpeg', 'jpg'];
} catch (Throwable $e) {
Log::warning('HasMedia: HEIC conversion failed', ['error' => $e->getMessage()]);
throw ValidationException::withMessages(['media' => __('posts.composer.upload_errors.heic_invalid')]);
}
}
}