Skip to content

📨 The ultimate agentic social media scheduling tool 🤖

feat(media): opt-in adjust to platform limits on API, MCP and widget uploads

Gilad Resisief0c907d8441
diff --git a/apps/backend/src/api/routes/media.widget.controller.ts b/apps/backend/src/api/routes/media.widget.controller.ts
index c194d4d17..35c467884 100644
--- a/apps/backend/src/api/routes/media.widget.controller.ts
+++ b/apps/backend/src/api/routes/media.widget.controller.ts
@@ -1,5 +1,6 @@
import {
BadRequestException,
+ Body,
Controller,
Get,
Post,
@@ -25,7 +26,8 @@ export class MediaWidgetController {
async upload(
@GetOrgFromRequest() org: Organization,
@Req() req: Request,
- @UploadedFile() file: Express.Multer.File
+ @UploadedFile() file: Express.Multer.File,
+ @Body('adjust') adjust: string = 'false'
) {
if (!file) {
throw new BadRequestException('No file provided');
@@ -36,7 +38,8 @@ export class MediaWidgetController {
req.uploadSession,
file.filename,
file.path,
- file.originalname
+ file.originalname,
+ adjust === 'true'
);
}
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index dfb597282..6903e62de 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -81,13 +81,22 @@ export class PublicIntegrationsController {
@UseInterceptors(FileInterceptor('file', streamUploadOptions()))
async uploadSimple(
@GetOrgFromRequest() org: Organization,
- @UploadedFile('file') file: Express.Multer.File
+ @UploadedFile('file') file: Express.Multer.File,
+ @Body('adjust') adjust: string = 'false'
) {
Sentry.metrics.count('public_api-request', 1);
if (!file) {
throw new HttpException({ msg: 'No file provided' }, 400);
}
+ if (adjust === 'true') {
+ return this._mediaService.saveUploadedFile(
+ org.id,
+ file.filename,
+ file.path
+ );
+ }
+
return this._mediaService.saveFile(org.id, file.filename, file.path);
}
@@ -98,7 +107,11 @@ export class PublicIntegrationsController {
) {
Sentry.metrics.count('public_api-request', 1);
try {
- return await this._mediaService.uploadFromUrl(org.id, body.url);
+ return await this._mediaService.uploadFromUrl(
+ org.id,
+ body.url,
+ body.adjust
+ );
} catch (err) {
// Validation failures keep this route's { msg } error shape
if (err instanceof BadRequestException) {
@@ -266,6 +279,15 @@ export class PublicIntegrationsController {
};
}
+ @Get('/media/:id/status')
+ async getMediaStatus(
+ @GetOrgFromRequest() org: Organization,
+ @Param('id') id: string
+ ) {
+ Sentry.metrics.count('public_api-request', 1);
+ return this._mediaService.getMediaUploadStatus(org.id, id);
+ }
+
// `user` is only known for OAuth app tokens; an API key belongs to the
// whole organization
@Get('/me')
diff --git a/libraries/nestjs-libraries/src/chat/tools/media.status.tool.ts b/libraries/nestjs-libraries/src/chat/tools/media.status.tool.ts
new file mode 100644
index 000000000..de8e613b5
--- /dev/null
+++ b/libraries/nestjs-libraries/src/chat/tools/media.status.tool.ts
@@ -0,0 +1,56 @@
+import { AgentToolInterface } from '@gitroom/nestjs-libraries/chat/agent.tool.interface';
+import { createTool } from '@mastra/core/tools';
+import { z } from 'zod';
+import { Injectable } from '@nestjs/common';
+import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
+import { checkAuth } from '@gitroom/nestjs-libraries/chat/auth.context';
+
+@Injectable()
+export class MediaStatusTool implements AgentToolInterface {
+ constructor(private _mediaService: MediaService) {}
+ name = 'mediaStatusTool';
+
+ run() {
+ return createTool({
+ id: 'mediaStatusTool',
+ description: `Check whether a media uploaded with adjust set to true finished adjusting to the platforms' limits, using the media id returned by uploadFromUrlTool, the public API (POST /public/v1/upload or /public/v1/upload-from-url) or the Postiz CLI (postiz upload).
+Files the user uploaded through the upload widget (uploadWidgetTool) have no id until they are listed, so check those with uploadWidgetStatusTool and its sessionId instead.
+Only a media with the status "processing" needs checking: wait about 10 seconds and call again. Its path is already usable, a post published before the adjustment ends uses the original file.
+"ready" means the adjusted file is in place at the same path. "ready" with a warning means the adjustment failed and the original file was kept and will be used for publishing.`,
+ mcp: {
+ annotations: {
+ title: 'Media Status',
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+ },
+ },
+ inputSchema: z.object({
+ id: z.string().describe('The media id returned by the upload'),
+ }),
+ outputSchema: z.object({
+ id: z.string().optional(),
+ path: z.string().optional(),
+ status: z.string().optional(),
+ warning: z.string().optional(),
+ error: z.string().optional(),
+ }),
+ execute: async (inputData, context) => {
+ checkAuth(inputData, context);
+ try {
+ const org = JSON.parse(
+ (context?.requestContext as any)?.get('organization') as string
+ );
+ return await this._mediaService.getMediaUploadStatus(
+ org.id,
+ inputData.id
+ );
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return { error: `Media status lookup failed: ${message}` };
+ }
+ },
+ });
+ }
+}
diff --git a/libraries/nestjs-libraries/src/chat/tools/tool.list.ts b/libraries/nestjs-libraries/src/chat/tools/tool.list.ts
index 920d78730..0254fbac9 100644
--- a/libraries/nestjs-libraries/src/chat/tools/tool.list.ts
+++ b/libraries/nestjs-libraries/src/chat/tools/tool.list.ts
@@ -13,6 +13,7 @@ import { IntegrationListTool } from '@gitroom/nestjs-libraries/chat/tools/integr
import { GroupListTool } from '@gitroom/nestjs-libraries/chat/tools/group.list.tool';
import { UploadFromUrlTool } from '@gitroom/nestjs-libraries/chat/tools/upload.from.url.tool';
import { MediaListTool } from '@gitroom/nestjs-libraries/chat/tools/media.list.tool';
+import { MediaStatusTool } from '@gitroom/nestjs-libraries/chat/tools/media.status.tool';
import { PostsListTool } from '@gitroom/nestjs-libraries/chat/tools/posts.list.tool';
import { PostSettingsTool } from '@gitroom/nestjs-libraries/chat/tools/post.settings.tool';
import { DeletePostTool } from '@gitroom/nestjs-libraries/chat/tools/delete.post.tool';
@@ -39,6 +40,7 @@ export const toolList = [
GenerateImageTool,
UploadFromUrlTool,
MediaListTool,
+ MediaStatusTool,
UploadWidgetTool,
UploadWidgetTicketTool,
UploadWidgetStatusTool,
diff --git a/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts b/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
index c6778b7fa..ee1a8dd0b 100644
--- a/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
+++ b/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
@@ -16,7 +16,9 @@ export class UploadFromUrlTool implements AgentToolInterface {
description: `Upload a remote image or video into the media library from a public http(s) URL.
Local or private files cannot be fetched by this tool: upload them with the Postiz CLI (postiz upload, https://docs.postiz.com/cli/introduction) or the public API (POST /public/v1/upload with an API key, https://docs.postiz.com/public-api/introduction).
Use this before scheduling a post when the user provides an external media URL (not already hosted on our domain),
-so the attachment passes the upload-domain validation. Returns the hosted media { id, path } to use as an attachment (or as the src of an <img> in the content, when the channel rules say pictures go inside the content), or { error } on failure.`,
+so the attachment passes the upload-domain validation. Returns the hosted media { id, path, status } to use as an attachment (or as the src of an <img> in the content, when the channel rules say pictures go inside the content), or { error } on failure.
+Set adjust to true (off by default) to adjust the media to the platforms' limits after the upload, for media a platform may reject as too large, too small or in an unsupported encoding: videos get their short side scaled to 1080 px (up or down, long side at most 1920 px) and are re-encoded to H.264 MP4 with AAC audio at up to 60 fps; images are only scaled down (short side at most 1080 px, long side at most 1920 px) and keep their format. GIF, AVIF, BMP and TIFF files are stored as uploaded.
+The path is usable right away. Without adjust the status is "ready". With adjust it is "processing" until the adjusted file replaces the original at the same path, and a post published before that uses the original. To know when the adjusted file is in place, call mediaStatusTool with the returned id (not uploadWidgetStatusTool, which only covers the upload widget).`,
mcp: {
annotations: {
title: 'Upload Media From URL',
@@ -33,6 +35,12 @@ so the attachment passes the upload-domain validation. Returns the hosted media
.describe(
'The public http(s) URL of the image or video to upload. Local files and private hosts are not supported, use the Postiz CLI (postiz upload) or POST /public/v1/upload instead'
),
+ adjust: z
+ .boolean()
+ .optional()
+ .describe(
+ 'Adjust the media to the platforms\' limits (resize and re-encode) after the upload. Defaults to false'
+ ),
}),
// Mastra validates a tool's return against this schema, so it must also
// allow the graceful { error } shape. Fields are optional (rather than
@@ -42,6 +50,7 @@ so the attachment passes the upload-domain validation. Returns the hosted media
outputSchema: z.object({
id: z.string().optional(),
path: z.string().optional(),
+ status: z.string().optional(),
error: z.string().optional(),
}),
execute: async (inputData, context) => {
@@ -51,7 +60,11 @@ so the attachment passes the upload-domain validation. Returns the hosted media
(context?.requestContext as any)?.get('organization') as string
);
- return await this._mediaService.uploadFromUrl(org.id, inputData.url);
+ return await this._mediaService.uploadFromUrl(
+ org.id,
+ inputData.url,
+ inputData.adjust
+ );
} catch (err) {
// undici's fetch rejects with a generic TypeError('fetch failed')
// and hides the real reason (DNS, TLS, SSRF block, ...) in
diff --git a/libraries/nestjs-libraries/src/chat/tools/upload.widget.status.tool.ts b/libraries/nestjs-libraries/src/chat/tools/upload.widget.status.tool.ts
index 9b7584efd..3e2662d9a 100644
--- a/libraries/nestjs-libraries/src/chat/tools/upload.widget.status.tool.ts
+++ b/libraries/nestjs-libraries/src/chat/tools/upload.widget.status.tool.ts
@@ -15,9 +15,10 @@ export class UploadWidgetStatusTool implements AgentToolInterface {
return createTool({
id: 'uploadWidgetStatusTool',
description: `List the media the user uploaded with the upload widget, using the sessionId returned by uploadWidgetTool.
+Only for files uploaded through the upload widget (uploadWidgetTool, shown in apps that display MCP Apps). For a media id returned by uploadFromUrlTool, the public API or the Postiz CLI, use mediaStatusTool instead.
It lists only the files uploaded in that widget session, not the whole media library.
An empty list means the user did not upload anything yet. A media with the status "processing" is still being prepared: wait about 10 seconds and call again.
-A media with the status "ready" can be used as a post attachment with its { id, path }.`,
+A media with the status "ready" can be used as a post attachment with its { id, path }. "ready" with a warning means the adjustment failed and the original file was kept and will be used for publishing.`,
mcp: {
annotations: {
title: 'Upload Widget Status',
@@ -39,6 +40,7 @@ A media with the status "ready" can be used as a post attachment with its { id,
id: z.string(),
path: z.string(),
status: z.string(),
+ warning: z.string().optional(),
error: z.string().optional(),
})
)
@@ -56,12 +58,7 @@ A media with the status "ready" can be used as a post attachment with its { id,
inputData.sessionId
);
return {
- media: media.map((p) => ({
- id: p.id,
- path: p.path,
- status: p.status,
- ...(p.processingError ? { error: p.processingError } : {}),
- })),
+ media: media.map((p) => this._mediaService.toUploadStatus(p)),
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
diff --git a/libraries/nestjs-libraries/src/chat/ui/upload.widget.ts b/libraries/nestjs-libraries/src/chat/ui/upload.widget.ts
index b25e709c8..5704e28cc 100644
--- a/libraries/nestjs-libraries/src/chat/ui/upload.widget.ts
+++ b/libraries/nestjs-libraries/src/chat/ui/upload.widget.ts
@@ -26,6 +26,12 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
#drop.disabled { opacity: 0.5; pointer-events: none; }
#drop small { display: block; color: var(--muted); margin-top: 4px; }
input[type=file] { display: none; }
+ #options { display: flex; align-items: center; gap: 6px; margin-bottom: 12px; }
+ #options label { display: flex; align-items: center; gap: 8px; cursor: pointer; }
+ #options input { margin: 0; }
+ .info { position: relative; display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; border: 1px solid var(--muted); border-radius: 50%; color: var(--muted); font-size: 11px; font-style: normal; cursor: help; }
+ .info span { display: none; position: absolute; top: 22px; left: 50%; transform: translateX(-50%); width: 260px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg); font-size: 12px; line-height: 1.4; z-index: 1; }
+ .info:hover span, .info:focus span { display: block; }
#files { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 12px; margin-top: 12px; }
#files:empty { display: none; }
.tile { min-width: 0; }
@@ -43,11 +49,16 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
.name { margin-top: 4px; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.note { font-size: 11px; color: var(--bad); }
.note:empty { display: none; }
+ .tile.ok .note { color: var(--muted); }
#error { color: var(--bad); margin-top: 12px; }
#error:empty { display: none; }
</style>
</head>
<body>
+ <div id="options">
+ <label><input id="adjust" type="checkbox" /> Adjust media to platform limits</label>
+ <i class="info" tabindex="0" aria-label="About adjusting media">i<span>Platforms reject media that is too large, too small or in an unsupported format. When checked, videos are resized to 1080p and re-encoded to MP4, and oversized images are scaled down. If the adjustment fails, the original file is used. Check it before choosing files.</span></i>
+ </div>
<label id="drop" class="disabled">
Choose files or drop them here
<small>Images up to ${megabytes('image/png')} MB and videos up to ${megabytes('video/mp4')} MB</small>
@@ -122,8 +133,9 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
);
}
- function uploadFile(file, ticket) {
+ function uploadFile(file, ticket, adjust) {
var form = new FormData();
+ form.append('adjust', adjust ? 'true' : 'false');
form.append('file', file);
return fetch(BACKEND + '/media-widget/upload?ticket=' + encodeURIComponent(ticket), { method: 'POST', body: form }).then(function (res) {
if (!res.ok) return readError(res).then(function (err) { throw err; });
@@ -205,7 +217,7 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
tile.appendChild(note);
list.appendChild(tile);
preview(file, box, label);
- return function (kind, text, path) {
+ return function (kind, text, path, hint) {
if (path) {
var copy = document.createElement('button');
copy.type = 'button';
@@ -222,7 +234,7 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
tile.className = 'tile ' + kind;
state.textContent = kind === 'ok' ? '✓' : kind === 'bad' ? '✕' : text;
state.title = text;
- note.textContent = kind === 'bad' ? text : '';
+ note.textContent = kind === 'bad' ? text : hint || '';
resize();
};
}
@@ -256,23 +268,24 @@ export const uploadWidgetHtml = (backendUrl: string) => `<!DOCTYPE html>
drop.className = 'disabled';
fail('');
var done = [];
+ var adjust = document.getElementById('adjust').checked;
getTicket()
.then(function (ticket) {
return files.reduce(function (chain, file) {
var set = row(file);
return chain.then(function () {
set('', 'Uploading…');
- return uploadFile(file, ticket)
+ return uploadFile(file, ticket, adjust)
.then(function (media) {
if (media.status === 'processing') set('', 'Processing…');
return waitUntilReady(media, ticket);
})
.then(function (media) {
- if (media.status === 'failed') throw new Error(media.processingError || 'Processing failed');
+ // the upload only accepts formats the platforms take as-is, so a failed adjustment keeps a usable original
var item = { id: media.id, path: media.path, name: media.originalName || file.name };
uploaded.push(item);
done.push(item);
- set('ok', 'Uploaded', media.path);
+ set('ok', 'Uploaded', media.path, media.status === 'failed' ? 'Adjustment failed, original kept' : '');
})
.catch(function (err) { set('bad', err.message || 'Upload failed'); });
});
diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
index bdeaf1f8d..e93b02e43 100644
--- a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
@@ -129,7 +129,7 @@ export class MediaService {
// Streams the remote body straight into storage: only the sniffing prefix
// and a few upload parts are ever in memory, so a 1 GB video does not cost
// 1 GB of heap
- async uploadFromUrl(org: string, url: string) {
+ async uploadFromUrl(org: string, url: string, adjust?: boolean) {
let response: globalThis.Response;
try {
response = await fetch(url, {
@@ -160,7 +160,9 @@ export class MediaService {
response.body,
declaredSize
);
- return this.saveFile(org, uploaded.originalname, uploaded.path);
+ return adjust
+ ? this.saveUploadedFile(org, uploaded.originalname, uploaded.path)
+ : this.saveFile(org, uploaded.originalname, uploaded.path);
}
saveFile(
@@ -276,15 +278,13 @@ export class MediaService {
sessionId: string,
fileName: string,
filePath: string,
- originalName?: string
+ originalName?: string,
+ adjust?: boolean
) {
await this.checkUploadSession(org, sessionId);
- const media = await this.saveUploadedFile(
- org,
- fileName,
- filePath,
- originalName
- );
+ const media = adjust
+ ? await this.saveUploadedFile(org, fileName, filePath, originalName)
+ : await this.saveFile(org, fileName, filePath, originalName);
// a list, so parallel uploads of the same session can't overwrite each other
await ioRedis.rpush(`uploadSessionMedia:${sessionId}`, media.id);
await ioRedis.expire(`uploadSessionMedia:${sessionId}`, 3600);
@@ -310,6 +310,39 @@ export class MediaService {
return media;
}
+ // What API and MCP callers see: a failed adjustment of a file the
+ // platforms accept as-is is not a failed upload, the original stays in
+ // place and is what gets published
+ toUploadStatus(media: {
+ id: string;
+ name: string;
+ path: string;
+ status: string;
+ }) {
+ if (media.status !== 'failed') {
+ return { id: media.id, path: media.path, status: media.status };
+ }
+
+ return USABLE_AS_IS.has(extname(media.name).toLowerCase())
+ ? {
+ id: media.id,
+ path: media.path,
+ status: 'ready',
+ warning:
+ 'Adjustment failed, the original file was kept and will be used for publishing',
+ }
+ : {
+ id: media.id,
+ path: media.path,
+ status: 'failed',
+ error: 'Processing failed and the original file cannot be used',
+ };
+ }
+
+ async getMediaUploadStatus(org: string, id: string) {
+ return this.toUploadStatus(await this.getMediaStatus(org, id));
+ }
+
// The normalized file overwrites the original in place; only a container
// change (mov -> mp4, jpeg -> jpg) lands under a new key. Either way the
// polling side needs nothing but the media record to know where it is
diff --git a/libraries/nestjs-libraries/src/dtos/media/upload.dto.ts b/libraries/nestjs-libraries/src/dtos/media/upload.dto.ts
index 1acac9b0b..996ae51fe 100644
--- a/libraries/nestjs-libraries/src/dtos/media/upload.dto.ts
+++ b/libraries/nestjs-libraries/src/dtos/media/upload.dto.ts
@@ -1,4 +1,10 @@
-import { IsDefined, IsString, Validate } from 'class-validator';
+import {
+ IsBoolean,
+ IsDefined,
+ IsOptional,
+ IsString,
+ Validate,
+} from 'class-validator';
import { ValidUrlExtension } from '@gitroom/helpers/utils/valid.url.path';
import { IsSafeWebhookUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
@@ -11,4 +17,8 @@ export class UploadDto {
'URL must be a public HTTPS URL and cannot point to internal network addresses',
})
url: string;
+
+ @IsOptional()
+ @IsBoolean()
+ adjust?: boolean;
}