π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: runpod
Nevo Davide2d5b9c59269
diff --git a/.env.example b/.env.exampleindex dd83c15a5..b5d0cd21e 100644--- a/.env.example+++ b/.env.example@@ -19,6 +19,11 @@ CLOUDFLARE_SECRET_ACCESS_KEY="your-secret-access-key"CLOUDFLARE_BUCKETNAME="your-bucket-name"CLOUDFLARE_BUCKET_URL="https://your-bucket-url.r2.cloudflarestorage.com/"CLOUDFLARE_REGION="auto"+## Optional media normalization (postiz-uploader on RunPod Serverless). Requires STORAGE_PROVIDER="cloudflare".+## When set, web uploads are transcoded to 1080p h264 mp4 / downsized images in the background;+## the media record reports status "processing" until the normalized file replaces the original.+#RUNPOD_API_KEY=""+#RUNPOD_ENDPOINT_ID=""# === Common optional Settingsdiff --git a/apps/backend/src/api/routes/media.controller.ts b/apps/backend/src/api/routes/media.controller.tsindex 6d5b557a1..f942c10f3 100644--- a/apps/backend/src/api/routes/media.controller.ts+++ b/apps/backend/src/api/routes/media.controller.ts@@ -167,7 +167,7 @@ export class MediaController {const name = upload.Location.split('/').pop();const originalName = req.body?.file?.name;- const saveFile = await this._mediaService.saveFile(+ const saveFile = await this._mediaService.saveUploadedFile(org.id,name,// @ts-ignore@@ -178,6 +178,14 @@ export class MediaController {res.status(200).json({ ...upload, saved: saveFile });}+ @Get('/:id/status')+ getMediaStatus(+ @GetOrgFromRequest() org: Organization,+ @Param('id') id: string+ ) {+ return this._mediaService.getMediaStatus(org.id, id);+ }+@Get('/')getMedia(@GetOrgFromRequest() org: Organization,diff --git a/apps/frontend/src/app/(app)/layout.tsx b/apps/frontend/src/app/(app)/layout.tsxindex ae83325be..cc1cc4ff8 100644--- a/apps/frontend/src/app/(app)/layout.tsx+++ b/apps/frontend/src/app/(app)/layout.tsx@@ -87,6 +87,11 @@ export default async function AppLayout({ children }: { children: ReactNode }) {googleAdsId={process.env.NEXT_PUBLIC_GTM_ID}googleAdsTrialTracking={process.env.NEXT_PUBLIC_TRACKING_TRIAL}language={language}+ mediaProcessing={+ process.env.STORAGE_PROVIDER === 'cloudflare' &&+ !!process.env.RUNPOD_API_KEY &&+ !!process.env.RUNPOD_ENDPOINT_ID+ }transloadit={process.env.TRANSLOADIT_AUTH && process.env.TRANSLOADIT_TEMPLATE? [diff --git a/apps/frontend/src/app/(extension)/layout.tsx b/apps/frontend/src/app/(extension)/layout.tsxindex b5990cb47..db1fe6d7e 100644--- a/apps/frontend/src/app/(extension)/layout.tsx+++ b/apps/frontend/src/app/(extension)/layout.tsx@@ -55,6 +55,11 @@ export default async function AppLayout({ children }: { children: ReactNode }) {disableXAnalytics={!!process.env.DISABLE_X_ANALYTICS}sentryDsn={process.env.NEXT_PUBLIC_SENTRY_DSN!}extensionId={process.env.EXTENSION_ID || ''}+ mediaProcessing={+ process.env.STORAGE_PROVIDER === 'cloudflare' &&+ !!process.env.RUNPOD_API_KEY &&+ !!process.env.RUNPOD_ENDPOINT_ID+ }transloadit={process.env.TRANSLOADIT_AUTH && process.env.TRANSLOADIT_TEMPLATE? [diff --git a/apps/frontend/src/app/(provider)/layout.tsx b/apps/frontend/src/app/(provider)/layout.tsxindex 80f161f8a..149f45b28 100644--- a/apps/frontend/src/app/(provider)/layout.tsx+++ b/apps/frontend/src/app/(provider)/layout.tsx@@ -57,6 +57,11 @@ export default async function AppLayout({ children }: { children: ReactNode }) {disableXAnalytics={!!process.env.DISABLE_X_ANALYTICS}sentryDsn={process.env.NEXT_PUBLIC_SENTRY_DSN!}extensionId={process.env.EXTENSION_ID || ''}+ mediaProcessing={+ process.env.STORAGE_PROVIDER === 'cloudflare' &&+ !!process.env.RUNPOD_API_KEY &&+ !!process.env.RUNPOD_ENDPOINT_ID+ }transloadit={process.env.TRANSLOADIT_AUTH && process.env.TRANSLOADIT_TEMPLATE? [diff --git a/apps/frontend/src/components/media/new.uploader.tsx b/apps/frontend/src/components/media/new.uploader.tsxindex cde95e738..532dc0132 100644--- a/apps/frontend/src/components/media/new.uploader.tsx+++ b/apps/frontend/src/components/media/new.uploader.tsx@@ -3,7 +3,10 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';import Uppy, { BasePlugin, UploadResult, UppyFile } from '@uppy/core';// @ts-ignoreimport { useFetch } from '@gitroom/helpers/utils/custom.fetch';-import { getUppyUploadPlugin } from '@gitroom/react/helpers/uppy.upload';+import {+ getUppyUploadPlugin,+ WaitForMediaProcessing,+} from '@gitroom/react/helpers/uppy.upload';import { Dashboard, FileInput, ProgressBar } from '@uppy/react';// Uppy styles@@ -44,8 +47,14 @@ export function useUppyUploader(props: {}) {const setLocked = useLaunchStore((state) => state.setLocked);const toast = useToaster();- const { storageProvider, backendUrl, disableImageCompression, transloadit } =- useVariables();+ const t = useT();+ const {+ storageProvider,+ backendUrl,+ disableImageCompression,+ transloadit,+ mediaProcessing,+ } = useVariables();const { onUploadSuccess, allowedFileTypes } = props;const fetch = useFetch();return useMemo(() => {@@ -84,6 +93,10 @@ export function useUppyUploader(props: {if (type === 'video/*') {return ['video/mp4', 'video/mpeg', 'video/quicktime'];}+ // the normalizer turns QuickTime into mp4, nothing else is accepted by the bucket+ if (type === 'video/mp4' && mediaProcessing) {+ return ['video/mp4', 'video/quicktime'];+ }if (type === 'video/mp4' && transloadit && transloadit.length > 0) {return ['video/mp4', 'video/mpeg', 'video/quicktime'];}@@ -167,15 +180,31 @@ export function useUppyUploader(props: {});});+ // The normalizer takes precedence over Transloadit, so both can stay+ // configured and turning the normalizer off falls back to Transloadit+ const useTransloadit = !mediaProcessing && transloadit.length > 0;const { plugin, options } = getUppyUploadPlugin(- transloadit.length > 0 ? 'transloadit' : storageProvider,+ useTransloadit ? 'transloadit' : storageProvider,fetch,backendUrl,transloadit);uppy2.use(plugin, options);- if (!disableImageCompression) {+ // installed whenever the record can come back "processing", so the backend+ // decides; it passes files through untouched when the row is already ready+ if (storageProvider === 'cloudflare' && !useTransloadit) {+ uppy2.use(WaitForMediaProcessing, {+ fetch,+ processingMessage: t('processing', 'Processing...'),+ fallbackMessage: t(+ 'could_not_optimize_file',+ 'Could not optimize the file, the original will be used'+ ),+ });+ }+ // the normalizer resizes on the server, shrinking first would only make it upscale a blurry copy+ if (!disableImageCompression && !mediaProcessing) {uppy2.use(CompressionWrapper, {convertTypes: ['image/jpeg', 'image/png', 'image/webp'],maxWidth: 1000,@@ -222,7 +251,7 @@ export function useUppyUploader(props: {return;}- if (transloadit.length > 0) {+ if (useTransloadit) {// @ts-ignoreconst allRes = result.transloadit[0].results;const toSave = uniqBy<{ name: string; originalName: string; order: number }>(diff --git a/apps/orchestrator/src/activities/media.activity.ts b/apps/orchestrator/src/activities/media.activity.tsnew file mode 100644index 000000000..beff47318--- /dev/null+++ b/apps/orchestrator/src/activities/media.activity.ts@@ -0,0 +1,26 @@+import { Injectable } from '@nestjs/common';+import { Activity, ActivityMethod } from 'nestjs-temporal-core';+import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';++@Injectable()+@Activity()+export class MediaActivity {+ constructor(private _mediaService: MediaService) {}++ // Returns the processor job id, or null when there is nothing to process+ @ActivityMethod()+ async submitMediaProcessing(mediaId: string) {+ return this._mediaService.submitProcessing(mediaId);+ }++ // Returns true once the media record is final (ready or failed)+ @ActivityMethod()+ async checkMediaProcessing(mediaId: string, jobId: string) {+ return this._mediaService.checkProcessing(mediaId, jobId);+ }++ @ActivityMethod()+ async failMediaProcessing(mediaId: string, error: string) {+ return this._mediaService.failProcessing(mediaId, error);+ }+}diff --git a/apps/orchestrator/src/app.module.ts b/apps/orchestrator/src/app.module.tsindex e2707b93c..4c0af35bc 100644--- a/apps/orchestrator/src/app.module.ts+++ b/apps/orchestrator/src/app.module.ts@@ -6,6 +6,7 @@ import { AutopostService } from '@gitroom/nestjs-libraries/database/prisma/autopimport { EmailActivity } from '@gitroom/orchestrator/activities/email.activity';import { IntegrationsActivity } from '@gitroom/orchestrator/activities/integrations.activity';import { VideoActivity } from '@gitroom/orchestrator/activities/video.activity';+import { MediaActivity } from '@gitroom/orchestrator/activities/media.activity';import { VideoModule } from '@gitroom/nestjs-libraries/videos/video.module';import { HealthController } from '@gitroom/orchestrator/health.controller';@@ -15,6 +16,7 @@ const activities = [EmailActivity,IntegrationsActivity,VideoActivity,+ MediaActivity,];@Module({imports: [diff --git a/apps/orchestrator/src/workflows/index.ts b/apps/orchestrator/src/workflows/index.tsindex a949c9893..4d902a017 100644--- a/apps/orchestrator/src/workflows/index.ts+++ b/apps/orchestrator/src/workflows/index.ts@@ -17,3 +17,4 @@ export * from './send.email.workflow';export * from './refresh.token.workflow';export * from './streak.workflow';export * from './generate.video.workflow';+export * from './process.media.workflow';diff --git a/apps/orchestrator/src/workflows/process.media.workflow.ts b/apps/orchestrator/src/workflows/process.media.workflow.tsnew file mode 100644index 000000000..7b6b30614--- /dev/null+++ b/apps/orchestrator/src/workflows/process.media.workflow.ts@@ -0,0 +1,66 @@+import { ActivityFailure, proxyActivities, sleep } from '@temporalio/workflow';+import { MediaActivity } from '@gitroom/orchestrator/activities/media.activity';++// Submitting is a plain POST with no idempotency key, so a retry after the+// queue accepted the job would run it twice; one attempt, and a failure+// releases the media instead+const { submitMediaProcessing } = proxyActivities<MediaActivity>({+ startToCloseTimeout: '2 minute',+ taskQueue: 'main',+ retry: {+ maximumAttempts: 1,+ },+});++// Polling is idempotent: ride out a queue API outage of a few minutes.+// Terminal answers are recorded by the activity itself and never throw+const { checkMediaProcessing, failMediaProcessing } =+ proxyActivities<MediaActivity>({+ startToCloseTimeout: '2 minute',+ taskQueue: 'main',+ retry: {+ maximumAttempts: 10,+ backoffCoefficient: 2,+ initialInterval: '10 seconds',+ maximumInterval: '2 minutes',+ },+ });++// the workflow only sees the activity failure wrapper; the reason is its cause+const reason = (err: any, fallback: string) =>+ (err instanceof ActivityFailure ? err.cause?.message : err?.message) ||+ fallback;++// Polls a job on the media normalization service; the service has no callbacks,+// and the RunPod job TTL is one hour so polling past it is pointless+const POLL_INTERVAL = 5000;+const MAX_POLLS = (60 * 60 * 1000) / POLL_INTERVAL;++export async function processMediaWorkflow({ mediaId }: { mediaId: string }) {+ let jobId: string | null;+ try {+ jobId = await submitMediaProcessing(mediaId);+ } catch (err: any) {+ await failMediaProcessing(mediaId, reason(err, 'Could not submit job'));+ return;+ }++ // nothing to run: the activity already released the media as ready+ if (!jobId) {+ return;+ }++ for (let i = 0; i < MAX_POLLS; i++) {+ await sleep(POLL_INTERVAL);+ try {+ if (await checkMediaProcessing(mediaId, jobId)) {+ return;+ }+ } catch (err: any) {+ await failMediaProcessing(mediaId, reason(err, 'Could not check job'));+ return;+ }+ }++ await failMediaProcessing(mediaId, 'Processing timed out');+}diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.repository.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.repository.tsindex 208def20f..7f05d20b3 100644--- a/libraries/nestjs-libraries/src/database/prisma/media/media.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.repository.ts@@ -25,6 +25,53 @@ export class MediaRepository {path: true,thumbnail: true,alt: true,+ status: true,+ },+ });+ }++ startProcessing(org: string, id: string) {+ return this._media.model.media.update({+ where: { id, organizationId: org },+ data: { status: 'processing', processingError: null },+ select: { id: true, status: true },+ });+ }++ finishProcessing(+ org: string,+ id: string,+ data: { name?: string; path?: string; fileSize?: number; error?: string }+ ) {+ return this._media.model.media.update({+ where: { id, organizationId: org },+ data: {+ ...(data.name ? { name: data.name } : {}),+ ...(data.path ? { path: data.path } : {}),+ ...(data.fileSize ? { fileSize: data.fileSize } : {}),+ status: data.error ? 'failed' : 'ready',+ processingError: data.error || null,+ },+ select: { id: true, status: true },+ });+ }++ getMediaStatus(org: string, id: string) {+ return this._media.model.media.findFirst({+ where: {+ id,+ organizationId: org,+ deletedAt: null,+ },+ select: {+ id: true,+ name: true,+ originalName: true,+ path: true,+ thumbnail: true,+ alt: true,+ status: true,+ processingError: true,},});}@@ -89,6 +136,7 @@ export class MediaRepository {id: org,},deletedAt: null,+ status: { not: 'processing' },...searchFilter,},};@@ -97,6 +145,8 @@ export class MediaRepository {where: {organizationId: org,deletedAt: null,+ // still being normalized: it shows up once the workflow releases it+ status: { not: 'processing' },...searchFilter,},orderBy: {diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.service.tsindex c56534b85..307f70c64 100644--- a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts@@ -17,10 +17,57 @@ import { TemporalService } from 'nestjs-temporal-core';import { TypedSearchAttributes } from '@temporalio/common';import { organizationId } from '@gitroom/nestjs-libraries/temporal/temporal.search.attribute';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { MediaProcessorJob } from '@gitroom/nestjs-libraries/upload/media.processor.interface';+import { extname } from 'path';++// What every upload is normalized to before a provider ever sees it. The+// service applies exactly these, so a platform-specific need belongs in the+// provider, not here.+const VIDEO_RULES: MediaProcessorJob['rules'] = {+ short_side_min: 1080,+ short_side_max: 1080,+ long_side_max: 1920,+ video: {+ container: 'mp4',+ video_codec: 'h264',+ profile: 'high',+ pixel_format: 'yuv420p',+ fps_max: 60,+ quality: 23,+ audio_codec: 'aac',+ audio_bitrate_kbps: 128,+ audio_sample_rate: 48000,+ faststart: true,+ },+};+const IMAGE_RULES: MediaProcessorJob['rules'] = {+ short_side_min: 1,+ short_side_max: 1080,+ long_side_max: 1920,+ image: { jpeg_quality: 90, keep_format: true },+};+const LIMITS: MediaProcessorJob['limits'] = {+ max_input_bytes: 1073741824,+ max_duration_seconds: 900,+ timeout_seconds: 1200,+};+// Extension of the normalized file and the content type the presigned PUT is+// minted for; anything else (gif, avif, ...) is stored as uploaded+const PROCESSABLE: Record<string, { type: 'video' | 'image'; ext: string; contentType: string }> = {+ '.mp4': { type: 'video', ext: 'mp4', contentType: 'video/mp4' },+ '.mov': { type: 'video', ext: 'mp4', contentType: 'video/mp4' },+ '.jpg': { type: 'image', ext: 'jpg', contentType: 'image/jpeg' },+ '.jpeg': { type: 'image', ext: 'jpg', contentType: 'image/jpeg' },+ '.png': { type: 'image', ext: 'png', contentType: 'image/png' },+ '.webp': { type: 'image', ext: 'webp', contentType: 'image/webp' },+};+// Formats a post can carry without normalization; anything else only exists to be converted+const USABLE_AS_IS = new Set(['.mp4', '.jpg', '.jpeg', '.png', '.webp', '.gif']);@Injectable()export class MediaService {private storage = UploadFactory.createStorage();+ private processor = UploadFactory.createProcessor();constructor(private _mediaRepository: MediaRepository,@@ -66,6 +113,185 @@ export class MediaService {return this._mediaRepository.saveFile(org, fileName, filePath, originalName);}+ // Saves an upload and, when a normalizer is configured, hands it to the+ // processing workflow; the caller polls getMediaStatus until it is ready+ async saveUploadedFile(+ org: string,+ fileName: string,+ filePath: string,+ originalName?: string+ ) {+ const media = await this.saveFile(org, fileName, filePath, originalName);+ const client = this._temporalService.client.getRawClient();+ if (!this.processor || !PROCESSABLE[extname(fileName).toLowerCase()] || !client) {+ return media;+ }++ await this._mediaRepository.startProcessing(org, media.id);+ try {+ await client.workflow.start('processMediaWorkflow', {+ workflowId: `media_${media.id}`,+ taskQueue: 'main',+ args: [{ mediaId: media.id }],+ typedSearchAttributes: new TypedSearchAttributes([+ {+ key: organizationId,+ value: org,+ },+ ]),+ });+ } catch (err) {+ // no workflow means nothing will ever flip the status+ return this.releaseUnprocessed(org, media.id, media.name);+ }++ return { ...media, status: 'processing' };+ }++ // Lets go of a media the normalizer will not touch. A source the platforms+ // accept as-is (mp4, png, ...) becomes ready; one that only exists to be+ // converted (mov) is failed, since nothing downstream can use it+ private async releaseUnprocessed(org: string, id: string, name: string) {+ const convertOnly = !USABLE_AS_IS.has(extname(name).toLowerCase());+ await this._mediaRepository.finishProcessing(org, id, {+ ...(convertOnly+ ? { error: 'No media processor is available to convert this file' }+ : {}),+ });+ return this._mediaRepository.getMediaStatus(org, id);+ }++ async getMediaStatus(org: string, id: string) {+ const media = await this._mediaRepository.getMediaStatus(org, id);+ if (!media) {+ throw new HttpException('Media not found', 404);+ }++ return media;+ }++ // The normalized file sits next to the original under a derived key, so the+ // polling side needs nothing but the media record to know where it landed+ private normalizedName(name: string) {+ const ext = extname(name).toLowerCase();+ return `${name.slice(0, -ext.length)}-n.${PROCESSABLE[ext].ext}`;+ }++ // Returns the processor job id; when this process has nothing to run the+ // media (already marked processing by the upload) is released as ready, so+ // a worker without the processor configured never leaves an upload hanging+ async submitProcessing(mediaId: string) {+ const media = await this._mediaRepository.getMediaById(mediaId);+ if (!media) {+ return null;+ }++ const processable = PROCESSABLE[extname(media.name).toLowerCase()];+ if (+ !this.processor ||+ !processable ||+ !this.storage.signDownloadUrl ||+ !this.storage.signUploadUrl+ ) {+ await this.releaseUnprocessed(media.organizationId, media.id, media.name);+ return null;+ }++ const outputName = this.normalizedName(media.name);+ return this.processor.submit({+ version: 1,+ type: processable.type,+ reference: media.id,+ source: { url: await this.storage.signDownloadUrl(media.name) },+ output: {+ url: await this.storage.signUploadUrl(outputName, processable.contentType),+ content_type: processable.contentType,+ },+ rules: processable.type === 'video' ? VIDEO_RULES : IMAGE_RULES,+ limits: LIMITS,+ });+ }++ // Returns true once the record is final. A transport error throws so the+ // activity retries the poll; a terminal answer from the queue or the service+ // marks the media failed and keeps the original usable+ async checkProcessing(mediaId: string, jobId: string) {+ const media = await this._mediaRepository.getMediaById(mediaId);+ if (!media) {+ return true;+ }++ // a retried activity after the record was already finalized must not+ // derive the output key a second time from the rewritten name+ if (media.status !== 'processing') {+ return true;+ }++ const org = media.organizationId;+ if (!this.processor) {+ await this.releaseUnprocessed(org, mediaId, media.name);+ return true;+ }++ const job = await this.processor.status(jobId);+ if (job.status === 'pending') {+ return false;+ }++ if (job.status === 'failed') {+ await this._mediaRepository.finishProcessing(org, mediaId, {+ error: job.error,+ });+ return true;+ }++ const { result } = job;+ if (!result || !['completed', 'unchanged', 'failed'].includes(result.status)) {+ await this._mediaRepository.finishProcessing(org, mediaId, {+ error: `Unexpected processor result: ${JSON.stringify(result).slice(0, 500)}`,+ });+ return true;+ }++ if (result.status === 'failed') {+ // the stderr tail is the only way to know what ffmpeg objected to+ await this._mediaRepository.finishProcessing(org, mediaId, {+ error: [+ `${result.failure?.code || 'FAILED'}: ${result.failure?.message || ''}`,+ result.failure?.stderr_tail,+ ]+ .filter(Boolean)+ .join('\n')+ .slice(0, 4000),+ });+ return true;+ }++ if (result.status === 'unchanged') {+ await this._mediaRepository.finishProcessing(org, mediaId, {});+ return true;+ }++ const outputName = this.normalizedName(media.name);+ await this._mediaRepository.finishProcessing(org, mediaId, {+ name: outputName,+ path: media.path.slice(0, media.path.lastIndexOf('/') + 1) + outputName,+ fileSize: result.output?.bytes,+ });+ return true;+ }++ async failProcessing(mediaId: string, error: string) {+ const media = await this._mediaRepository.getMediaById(mediaId);+ if (!media) {+ return;+ }++ return this._mediaRepository.finishProcessing(media.organizationId, mediaId, {+ error,+ });+ }+getMedia(org: string, page: number, search?: string) {return this._mediaRepository.getMedia(org, page, search);}diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 13e684f81..592ebde93 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -349,11 +349,23 @@ export class PostsService {(await Promise.all((imagesList || []).map(async (p: any) => {- if (!p.path && p.id) {+ if (!p.id) {+ return p;+ }++ if (!p.path) {imageUpdateNeeded = true;return this._mediaService.getMediaById(p.id);}+ // the normalizer may have replaced the file after the post was+ // composed; a record still processing publishes the original+ const fresh = await this._mediaService.getMediaById(p.id);+ if (fresh?.status === 'ready' && fresh.path !== p.path) {+ imageUpdateNeeded = true;+ return { ...p, name: fresh.name, path: fresh.path };+ }+return p;}))diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex 623bc0c68..941e27a8d 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -224,6 +224,8 @@ model Media {thumbnail String?alt String?thumbnailTimestamp Int?+ status String @default("ready")+ processingError String?organization Organization @relation(fields: [organizationId], references: [id])agencies SocialMediaAgency[]userPicture User[]diff --git a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts b/libraries/nestjs-libraries/src/upload/cloudflare.storage.tsindex e01438aad..e26d10079 100644--- a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts+++ b/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts@@ -1,4 +1,5 @@-import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';+import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';+import { getSignedUrl } from '@aws-sdk/s3-request-presigner';import 'multer';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import mime from 'mime-types';@@ -154,6 +155,26 @@ class CloudflareStorage implements IUploadProvider {}}+ async signDownloadUrl(fileName: string) {+ return getSignedUrl(+ this._client,+ new GetObjectCommand({ Bucket: this._bucketName, Key: fileName }),+ { expiresIn: 3 * 3600 }+ );+ }++ async signUploadUrl(fileName: string, contentType: string) {+ return getSignedUrl(+ this._client,+ new PutObjectCommand({+ Bucket: this._bucketName,+ Key: fileName,+ ContentType: contentType,+ }),+ { expiresIn: 3 * 3600 }+ );+ }+// Implement the removeFile method from IUploadProviderasync removeFile(filePath: string): Promise<void> {// const fileName = filePath.split('/').pop(); // Extract the filename from the pathdiff --git a/libraries/nestjs-libraries/src/upload/media.processor.interface.ts b/libraries/nestjs-libraries/src/upload/media.processor.interface.tsnew file mode 100644index 000000000..1d705b600--- /dev/null+++ b/libraries/nestjs-libraries/src/upload/media.processor.interface.ts@@ -0,0 +1,69 @@+// Contract of the media normalization service (postiz-uploader schema/v1).+// The service knows nothing about Postiz: URLs in, metadata out.+export interface MediaProcessorJob {+ version: 1;+ type: 'video' | 'image';+ reference: string;+ source: { url: string; content_type?: string };+ output: { url: string; content_type: string };+ thumbnail?: {+ url: string;+ timestamp_seconds?: number;+ content_type?: 'image/jpeg';+ };+ rules: {+ short_side_min: number;+ short_side_max: number;+ long_side_max: number;+ video?: {+ container?: 'mp4';+ video_codec?: 'h264';+ profile?: string;+ pixel_format?: string;+ fps_max?: number;+ quality?: number;+ audio_codec?: string;+ audio_bitrate_kbps?: number;+ audio_sample_rate?: number;+ faststart?: boolean;+ };+ image?: { jpeg_quality?: number; keep_format?: boolean };+ };+ limits?: {+ max_input_bytes?: number;+ max_duration_seconds?: number;+ timeout_seconds?: number;+ };+}++export interface MediaProcessorResult {+ version: 1;+ reference: string;+ status: 'completed' | 'unchanged' | 'failed';+ actions: string[];+ output?: {+ width: number;+ height: number;+ duration_seconds?: number;+ bytes: number;+ content_type: string;+ };+ thumbnail?: { width: number; height: number; bytes: number } | null;+ failure?: {+ code: string;+ message: string;+ retryable: boolean;+ stderr_tail?: string;+ } | null;+}++export type MediaProcessorStatus =+ | { status: 'pending' }+ | { status: 'completed'; result: MediaProcessorResult }+ // the queue itself failed (crash, expired job); retryable by the caller+ | { status: 'failed'; error: string };++export interface IMediaProcessor {+ submit(job: MediaProcessorJob): Promise<string>;+ status(jobId: string): Promise<MediaProcessorStatus>;+}diff --git a/libraries/nestjs-libraries/src/upload/r2.uploader.ts b/libraries/nestjs-libraries/src/upload/r2.uploader.tsindex ef2ed4fb5..3164d5ed8 100644--- a/libraries/nestjs-libraries/src/upload/r2.uploader.ts+++ b/libraries/nestjs-libraries/src/upload/r2.uploader.ts@@ -14,6 +14,7 @@ import { Request, Response } from 'express';import crypto from 'crypto';import path from 'path';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';// eslint-disable-next-line @typescript-eslint/no-var-requiresconst { fileTypeFromBuffer } = require('file-type');@@ -30,9 +31,18 @@ const ALLOWED_EXT_TO_MIME: Record<string, string> = {'.mp4': 'video/mp4',};+// Multipart uploads go through the normalizer, so they may also carry+// QuickTime, which it turns into an mp4; simple uploads never do+function multipartExtToMime(): Record<string, string> {+ return {+ ...ALLOWED_EXT_TO_MIME,+ ...(UploadFactory.processorEnabled() ? { '.mov': 'video/quicktime' } : {}),+ };+}+function normalizeExtension(filename: string): string | null {const ext = path.extname(filename || '').toLowerCase();- return ALLOWED_EXT_TO_MIME[ext] ? ext : null;+ return multipartExtToMime()[ext] ? ext : null;}const {@@ -111,7 +121,7 @@ export async function createMultipartUpload(req: Request, res: Response) {if (!safeExt) {return res.status(400).json({ message: 'Unsupported file type.' });}- const safeContentType = ALLOWED_EXT_TO_MIME[safeExt];+ const safeContentType = multipartExtToMime()[safeExt];const randomFilename = generateRandomString() + safeExt;try {@@ -205,7 +215,7 @@ export async function completeMultipartUpload(req: Request, res: Response) {);return res.status(400).json({ message: 'Unsupported file type.' });}- const expectedMime = ALLOWED_EXT_TO_MIME[safeExt];+ const expectedMime = multipartExtToMime()[safeExt];const head = await R2.send(new GetObjectCommand({@@ -222,7 +232,10 @@ export async function completeMultipartUpload(req: Request, res: Response) {const prefix = Buffer.concat(chunks);const detected = await fileTypeFromBuffer(prefix);- if (!detected || detected.mime !== expectedMime) {+ // a .mov with an ISO brand sniffs as video/mp4; the normalizer reads both+ const acceptedMimes =+ safeExt === '.mov' ? ['video/quicktime', 'video/mp4'] : [expectedMime];+ if (!detected || !acceptedMimes.includes(detected.mime)) {await R2.send(new DeleteObjectCommand({ Bucket: CLOUDFLARE_BUCKETNAME, Key: key }));diff --git a/libraries/nestjs-libraries/src/upload/runpod.media.processor.ts b/libraries/nestjs-libraries/src/upload/runpod.media.processor.tsnew file mode 100644index 000000000..236695772--- /dev/null+++ b/libraries/nestjs-libraries/src/upload/runpod.media.processor.ts@@ -0,0 +1,66 @@+import {+ IMediaProcessor,+ MediaProcessorJob,+ MediaProcessorStatus,+} from './media.processor.interface';++// RunPod Serverless wraps every request as { input } and every result as+// { id, status, output }. The worker returns failures as a normal result with+// status "failed" inside, so a RunPod-level FAILED is only an unhandled crash.+export class RunPodMediaProcessor implements IMediaProcessor {+ private _baseUrl: string;++ constructor(private _apiKey: string, endpointId: string) {+ this._baseUrl = `https://api.runpod.ai/v2/${endpointId}`;+ }++ private async request(path: string, init?: RequestInit) {+ const response = await fetch(`${this._baseUrl}${path}`, {+ ...init,+ headers: {+ Authorization: `Bearer ${this._apiKey}`,+ 'Content-Type': 'application/json',+ ...(init?.headers || {}),+ },+ signal: AbortSignal.timeout(30000),+ });++ if (!response.ok) {+ throw new Error(+ `RunPod ${response.status}: ${(await response.text()).slice(0, 500)}`+ );+ }++ return response.json();+ }++ async submit(job: MediaProcessorJob): Promise<string> {+ const { id } = await this.request('/run', {+ method: 'POST',+ body: JSON.stringify({ input: job }),+ });++ if (!id) {+ throw new Error('RunPod accepted the job without returning an id');+ }++ return id;+ }++ async status(jobId: string): Promise<MediaProcessorStatus> {+ const { status, output, error } = await this.request(`/status/${jobId}`, {+ method: 'GET',+ });++ switch (status) {+ case 'COMPLETED':+ return { status: 'completed', result: output };+ case 'FAILED':+ case 'CANCELLED':+ case 'TIMED_OUT':+ return { status: 'failed', error: error || status };+ default:+ return { status: 'pending' };+ }+ }+}diff --git a/libraries/nestjs-libraries/src/upload/upload.factory.ts b/libraries/nestjs-libraries/src/upload/upload.factory.tsindex f89d310a8..a66332110 100644--- a/libraries/nestjs-libraries/src/upload/upload.factory.ts+++ b/libraries/nestjs-libraries/src/upload/upload.factory.ts@@ -1,6 +1,8 @@import { CloudflareStorage } from './cloudflare.storage';import { IUploadProvider } from './upload.interface';import { LocalStorage } from './local.storage';+import { IMediaProcessor } from './media.processor.interface';+import { RunPodMediaProcessor } from './runpod.media.processor';export class UploadFactory {static createStorage(): IUploadProvider {@@ -22,4 +24,24 @@ export class UploadFactory {throw new Error(`Invalid storage type ${storageProvider}`);}}++ // Normalization needs presigned URLs, so it is only available on cloud storage+ static processorEnabled() {+ return (+ process.env.STORAGE_PROVIDER === 'cloudflare' &&+ !!process.env.RUNPOD_API_KEY &&+ !!process.env.RUNPOD_ENDPOINT_ID+ );+ }++ static createProcessor(): IMediaProcessor | null {+ if (!UploadFactory.processorEnabled()) {+ return null;+ }++ return new RunPodMediaProcessor(+ process.env.RUNPOD_API_KEY!,+ process.env.RUNPOD_ENDPOINT_ID!+ );+ }}diff --git a/libraries/nestjs-libraries/src/upload/upload.interface.ts b/libraries/nestjs-libraries/src/upload/upload.interface.tsindex 52c2f030f..73230f110 100644--- a/libraries/nestjs-libraries/src/upload/upload.interface.ts+++ b/libraries/nestjs-libraries/src/upload/upload.interface.ts@@ -2,4 +2,8 @@ export interface IUploadProvider {uploadSimple(path: string): Promise<string>;uploadFile(file: Express.Multer.File): Promise<any>;removeFile(filePath: string): Promise<void>;+ // Presigned URLs handed to the media processor, which has no storage+ // credentials; only cloud storage can mint them+ signDownloadUrl?(fileName: string): Promise<string>;+ signUploadUrl?(fileName: string, contentType: string): Promise<string>;}diff --git a/libraries/react-shared-libraries/src/helpers/uppy.upload.ts b/libraries/react-shared-libraries/src/helpers/uppy.upload.tsindex 12af1cd57..acece4e7d 100644--- a/libraries/react-shared-libraries/src/helpers/uppy.upload.ts+++ b/libraries/react-shared-libraries/src/helpers/uppy.upload.ts@@ -2,6 +2,110 @@ import XHRUpload from '@uppy/xhr-upload';import AwsS3Multipart from '@uppy/aws-s3';import sha256 from 'sha256';import Transloadit from '@uppy/transloadit';+import { BasePlugin } from '@uppy/core';++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++// Keeps a file in the "processing" state after it reached the bucket until the+// media normalization workflow marks the record ready, the same way+// Transloadit's waitForEncoding holds the dashboard until the assembly is done.+// Files whose record is already ready (no normalizer, gif, ...) pass through.+// The bytes are already stored, so giving up never fails the upload: the+// original file is used instead.+export class WaitForMediaProcessing extends BasePlugin<any, any, any> {+ constructor(+ uppy: any,+ opts: {+ fetch: any;+ processingMessage: string;+ fallbackMessage: string;+ interval?: number;+ maxWait?: number;+ }+ ) {+ super(uppy, opts);+ this.id = 'WaitForMediaProcessing';+ this.type = 'modifier';+ }++ install() {+ this.uppy.addPostProcessor(this.process);+ }++ uninstall() {+ this.uppy.removePostProcessor(this.process);+ }++ process = async (fileIDs: string[]) => {+ await Promise.all(fileIDs.map((id) => this.waitForFile(id)));+ };++ waitForFile = async (id: string) => {+ const file: any = this.uppy.getFile(id);+ const saved = file?.response?.body?.saved;+ if (saved?.status !== 'processing') {+ return;+ }++ this.uppy.emit('postprocess-progress', file, {+ mode: 'indeterminate',+ message: this.opts.processingMessage,+ });++ const interval = this.opts.interval || 2000;+ const deadline = Date.now() + (this.opts.maxWait || 20 * 60 * 1000);+ let failures = 0;+ let media: any = saved;+ // the file disappears when the user cancels, so stop polling with it+ while (this.uppy.getFile(id) && Date.now() < deadline && failures < 5) {+ await sleep(interval);++ try {+ const response = await (+ await this.opts.fetch(`/media/${saved.id}/status`)+ ).json();+ // a 4xx body has no status; treat it like a failed poll+ if (!response?.status) {+ throw new Error(response?.message || 'Media not found');+ }+ media = response;+ failures = 0;+ } catch (err) {+ failures++;+ continue;+ }++ if (media.status !== 'processing') {+ break;+ }+ }++ const current: any = this.uppy.getFile(id);+ if (!current) {+ return;+ }++ if (media.status !== 'ready') {+ // a file that only existed to be converted has nothing to fall back to+ const usable = /\.(png|jpe?g|gif|webp|mp4)$/i.test(media.name || '');+ if (!usable) {+ this.uppy.info(media.processingError || this.opts.fallbackMessage, 'error', 5000);+ this.uppy.setFileState(id, { error: media.processingError || 'failed' } as any);+ this.uppy.emit('postprocess-complete', this.uppy.getFile(id));+ return;+ }+ this.uppy.info(this.opts.fallbackMessage, 'warning', 5000);+ }++ this.uppy.setFileState(id, {+ response: {+ ...current.response,+ body: { ...current.response.body, saved: media },+ },+ } as any);+ this.uppy.emit('postprocess-complete', this.uppy.getFile(id));+ };+}const fetchUploadApiEndpoint = async (fetch: any,endpoint: string,diff --git a/libraries/react-shared-libraries/src/helpers/variable.context.tsx b/libraries/react-shared-libraries/src/helpers/variable.context.tsxindex 67e3b4007..4bf3870df 100644--- a/libraries/react-shared-libraries/src/helpers/variable.context.tsx+++ b/libraries/react-shared-libraries/src/helpers/variable.context.tsx@@ -29,6 +29,7 @@ interface VariableContextInterface {language: string;dub: boolean;transloadit: string[];+ mediaProcessing: boolean;sentryDsn: string;extensionId: string;googleAdsId?: string;@@ -63,6 +64,7 @@ const VariableContext = createContext({language: '',dub: false,transloadit: [],+ mediaProcessing: false,sentryDsn: '',extensionId: '',} as VariableContextInterface);