π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: move validation of images / videos to the server
Nevo David1b53973e0280
diff --git a/apps/backend/src/api/routes/posts.controller.ts b/apps/backend/src/api/routes/posts.controller.tsindex 14756ce21..55e4b6d62 100644--- a/apps/backend/src/api/routes/posts.controller.ts+++ b/apps/backend/src/api/routes/posts.controller.ts@@ -28,6 +28,7 @@ import {AuthorizationActions,Sections,} from '@gitroom/backend/services/auth/permissions/permission.exception.class';+import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';@ApiTags('Posts')@Controller('/posts')@@ -167,13 +168,57 @@ export class PostsController {return this._postsService.getPost(org.id, id);}+ @Post('/valid')+ async validatePosts(+ @GetOrgFromRequest() org: Organization,+ @Body() rawBody: any+ ) {+ return this._postsService.validatePosts(org.id, rawBody?.posts || []);+ }+@Post('/')@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])async createPost(@GetOrgFromRequest() org: Organization,@Body() rawBody: any) {- console.log(JSON.stringify(rawBody, null, 2));+ // Server-side validation β never trust the client to have validated.+ const validation = await this._postsService.validatePosts(+ org.id,+ rawBody?.posts || []+ );++ const fail = (item: (typeof validation)[number], error: string) => {+ throw new PostValidationException({+ provider: item.identifier,+ name: item.name,+ error,+ });+ };++ for (const item of validation) {+ if (item.emptyContent) {+ fail(+ item,+ 'Your post should have at least one character or one image.'+ );+ }+ }++ if (rawBody?.type !== 'draft') {+ for (const item of validation) {+ if (!item.valid) {+ fail(item, item.settingsError || 'Please fix your settings');+ }+ if (item.errors !== true) {+ fail(item, item.errors as string);+ }+ if (item.tooLong) {+ fail(item, 'post is too long, please fix it');+ }+ }+ }+const body = await this._postsService.mapTypeToPost(rawBody, org.id);return this._postsService.createPost(org.id, body, 'WEB');}diff --git a/apps/backend/src/api/routes/posts.validation.exception.ts b/apps/backend/src/api/routes/posts.validation.exception.tsnew file mode 100644index 000000000..6e0820cad--- /dev/null+++ b/apps/backend/src/api/routes/posts.validation.exception.ts@@ -0,0 +1,40 @@+import {+ ArgumentsHost,+ Catch,+ ExceptionFilter,+ HttpException,+ HttpStatus,+} from '@nestjs/common';++export type PostValidationError = {+ /** Provider identifier, e.g. "x", "linkedin-page". */+ provider: string;+ /** Human readable provider name, e.g. "X", "LinkedIn Page". */+ name: string;+ /** The readable validation error. */+ error: string;+};++export class PostValidationException extends HttpException {+ constructor(message: PostValidationError) {+ super(message, HttpStatus.BAD_REQUEST);+ }+}++@Catch(PostValidationException)+export class PostValidationExceptionFilter implements ExceptionFilter {+ catch(exception: PostValidationException, host: ArgumentsHost) {+ const ctx = host.switchToHttp();+ const response = ctx.getResponse();+ const status = exception.getStatus();+ const { provider, name, error } =+ exception.getResponse() as PostValidationError;++ response.status(status).json({+ statusCode: status,+ provider,+ name,+ message: error,+ });+ }+}diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.tsindex 41230c686..703a06424 100644--- a/apps/backend/src/main.ts+++ b/apps/backend/src/main.ts@@ -15,6 +15,7 @@ import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';import { SubscriptionExceptionFilter } from '@gitroom/backend/services/auth/permissions/subscription.exception';+import { PostValidationExceptionFilter } from '@gitroom/backend/api/routes/posts.validation.exception';import { HttpExceptionFilter } from '@gitroom/nestjs-libraries/services/exception.filter';import { ConfigurationChecker } from '@gitroom/helpers/configuration/configuration.checker';import { startMcp } from '@gitroom/nestjs-libraries/chat/start.mcp';@@ -62,6 +63,7 @@ async function start() {app.use(cookieParser());app.use(compression());app.useGlobalFilters(new SubscriptionExceptionFilter());+ app.useGlobalFilters(new PostValidationExceptionFilter());app.useGlobalFilters(new HttpExceptionFilter());loadSwagger(app);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.tsindex 0b6d83386..48e9d163b 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@@ -56,6 +56,7 @@ import {import { getValidationSchemas } from '@gitroom/nestjs-libraries/chat/validation.schemas.helper';import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';import { timer } from '@gitroom/helpers/utils/timer';import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';@@ -188,6 +189,44 @@ export class PublicIntegrationsController {);}+ // Server-side validation β same rules as the dashboard, surfaced as a+ // readable 400 (see PostValidationExceptionFilter).+ const validation = await this._postsService.validatePosts(+ org.id,+ body.posts+ );++ const fail = (item: (typeof validation)[number], error: string) => {+ throw new PostValidationException({+ provider: item.identifier,+ name: item.name,+ error,+ });+ };++ for (const item of validation) {+ if (item.emptyContent) {+ fail(+ item,+ 'Your post should have at least one character or one image.'+ );+ }+ }++ if (body.type !== 'draft') {+ for (const item of validation) {+ if (!item.valid) {+ fail(item, item.settingsError || 'Please fix your settings');+ }+ if (item.errors !== true) {+ fail(item, item.errors as string);+ }+ if (item.tooLong) {+ fail(item, 'post is too long, please fix it');+ }+ }+ }+const allowedCreationMethods = ['CLI', 'API'] as const;const creationMethod = allowedCreationMethods.includes(rawBody.creationMethod@@ -195,7 +234,6 @@ export class PublicIntegrationsController {? (rawBody.creationMethod as 'CLI' | 'API'): 'API';- console.log(JSON.stringify(body, null, 2));return this._postsService.createPost(org.id, body, creationMethod);}diff --git a/apps/frontend/src/components/new-launch/manage.modal.tsx b/apps/frontend/src/components/new-launch/manage.modal.tsxindex 3b4cd4640..52393705e 100644--- a/apps/frontend/src/components/new-launch/manage.modal.tsx+++ b/apps/frontend/src/components/new-launch/manage.modal.tsx@@ -23,7 +23,6 @@ import { useShallow } from 'zustand/react/shallow';import { RepeatComponent } from '@gitroom/frontend/components/launches/repeat.component';import { TagsComponent } from '@gitroom/frontend/components/launches/tags.component';import { useToaster } from '@gitroom/react/toaster/toaster';-import { weightedLength } from '@gitroom/helpers/utils/count.length';import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';@@ -32,7 +31,6 @@ import { capitalize } from 'lodash';import { SelectCustomer } from '@gitroom/frontend/components/launches/select.customer';import { CopilotPopup } from '@copilotkit/react-ui';import { DummyCodeComponent } from '@gitroom/frontend/components/new-launch/dummy.code.component';-import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';import { CreationMethodBadge } from '@gitroom/frontend/components/launches/creation.method.badge';import {SettingsIcon,@@ -46,13 +44,6 @@ import { useShortlinkPreference } from '@gitroom/frontend/components/settings/shimport dayjs from 'dayjs';import { Button } from '@gitroom/react/form/button';-function countCharacters(text: string, type: string): number {- if (type !== 'x') {- return text.length;- }- return weightedLength(text);-}-export const ManageModal: FC<AddEditModalProps> = (props) => {const t = useT();const fetch = useFetch();@@ -246,91 +237,112 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {}setLoading(true);- const checkAllValid = await ref.current.checkAllValid();-- const notEnoughChars = checkAllValid.filter((p: any) => {- return p.values.some((a: any) => {- return (- countCharacters(- stripHtmlValidation('normal', a.content, true),- p?.integration?.identifier || ''- ) === 0 && a.media?.length === 0- );- });- });-- for (const item of notEnoughChars) {- toaster.show(- `${capitalize(item.integration.identifier.split('-')[0])} (${- item.integration.name- }):` +- ' ' +- t(- 'post_needs_content_or_image',- 'Your post should have at least one character or one image.'- ),- 'warning'- );- setLoading(false);- item.preview();- return;- }- if (type !== 'draft') {- for (const item of checkAllValid) {- if (item.valid === false) {- toaster.show(- `${capitalize(item.integration.identifier.split('-')[0])} (${- item.integration.name- }): ${t('please_fix_your_settings', 'Please fix your settings')}`,- 'warning'- );- item.fix();- setLoading(false);- setShowSettings(true);- return;- }+ // Pull the local values to build the payload, but rely on the server+ // (`/posts/valid`) for the actual validation β checkValidity now lives+ // server-side so it can't be bypassed.+ const allValues = await ref.current.getAllValues();- if (item.errors !== true) {- toaster.show(- `${capitalize(item.integration.identifier.split('-')[0])} (${- item.integration.name- }): ${item.errors}`,- 'warning'- );- item.preview();- setLoading(false);- setShowSettings(false);- return;- }- }+ const integrationById = (id: string) =>+ selectedIntegrations.find((p) => p.integration.id === id);- const sliceNeeded = checkAllValid.filter((p: any) => {- return p.values.some((a: any) => {- const strip = stripHtmlValidation('normal', a.content, true);- const weightedLength = countCharacters(- strip,- p?.integration?.identifier || ''- );- const totalCharacters =- weightedLength > strip.length ? weightedLength : strip.length;+ const group = existingData.group || makeId(10);- return totalCharacters > (p.maximumCharacters || 1000000);- });- });+ const posts = allValues.map((post: any) => ({+ integration: {+ id: post.id,+ },+ group,+ settings: { ...(post.settings || {}) },+ value: post.values.map((value: any) => ({+ ...(value.id ? { id: value.id } : {}),+ content: value.content,+ delay: value.delay || 0,+ image:+ (value?.media || []).map(+ ({ id, path, alt, thumbnail, thumbnailTimestamp }: any) => ({+ id,+ path,+ alt,+ thumbnail,+ thumbnailTimestamp,+ })+ ) || [],+ })),+ }));++ if (!dummy) {+ const checkAllValid = await (+ await fetch('/posts/valid', {+ method: 'POST',+ body: JSON.stringify({ type, posts }),+ })+ ).json();++ const focus = (id: string, where: 'fix' | 'preview') => {+ integrationById(id)?.ref?.current?.[where]?.();+ };++ const notEnoughChars = checkAllValid.filter((p: any) => p.emptyContent);- for (const item of sliceNeeded) {+ for (const item of notEnoughChars) {toaster.show(- `${item?.integration?.name} (${item?.integration?.identifier}) ${t(- 'post_is_too_long',- 'post is too long, please fix it'- )}`,+ `${capitalize(item.identifier.split('-')[0])} (${item.name}):` ++ ' ' ++ t(+ 'post_needs_content_or_image',+ 'Your post should have at least one character or one image.'+ ),'warning');- item.preview();setLoading(false);+ focus(item.id, 'preview');return;}++ if (type !== 'draft') {+ for (const item of checkAllValid) {+ if (item.valid === false) {+ toaster.show(+ `${capitalize(item.identifier.split('-')[0])} (${item.name}): ${+ item.settingsError ||+ t('please_fix_your_settings', 'Please fix your settings')+ }`,+ 'warning'+ );+ focus(item.id, 'fix');+ setLoading(false);+ setShowSettings(true);+ return;+ }++ if (item.errors !== true) {+ toaster.show(+ `${capitalize(item.identifier.split('-')[0])} (${item.name}): ${+ item.errors+ }`,+ 'warning'+ );+ focus(item.id, 'preview');+ setLoading(false);+ setShowSettings(false);+ return;+ }++ if (item.tooLong) {+ toaster.show(+ `${item.name} (${item.identifier}) ${t(+ 'post_is_too_long',+ 'post is too long, please fix it'+ )}`,+ 'warning'+ );+ focus(item.id, 'preview');+ setLoading(false);+ return;+ }+ }+ }}const shortlinkPreference = shortlinkPreferenceData?.shortlink || 'ASK';@@ -342,12 +354,12 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {await fetch('/posts/should-shortlink', {method: 'POST',body: JSON.stringify({- messages: checkAllValid+ messages: allValues// platforms that remove links won't keep shortlinks either- .filter((p: any) => !p?.integration?.stripLinks)- .flatMap((p: any) =>- p.values.flatMap((a: any) => a.content)- ),+ .filter(+ (p: any) => !integrationById(p.id)?.integration?.stripLinks+ )+ .flatMap((p: any) => p.values.flatMap((a: any) => a.content)),}),})).json();@@ -369,35 +381,13 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {}}- const group = existingData.group || makeId(10);const data = {type,...(repeater ? { inter: repeater } : {}),tags,shortLink,date: date.utc().format('YYYY-MM-DDTHH:mm:ss'),- posts: checkAllValid.map((post: any) => ({- integration: {- id: post.integration.id,- },- group,- settings: { ...(post.settings || {}) },- value: post.values.map((value: any) => ({- ...(value.id ? { id: value.id } : {}),- content: value.content,- delay: value.delay || 0,- image:- (value?.media || []).map(- ({ id, path, alt, thumbnail, thumbnailTimestamp }: any) => ({- id,- path,- alt,- thumbnail,- thumbnailTimestamp,- })- ) || [],- })),- })),+ posts,};if (dummy) {diff --git a/apps/frontend/src/components/new-launch/providers/bluesky/bluesky.provider.tsx b/apps/frontend/src/components/new-launch/providers/bluesky/bluesky.provider.tsxindex b34089700..8a19dc961 100644--- a/apps/frontend/src/components/new-launch/providers/bluesky/bluesky.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/bluesky/bluesky.provider.tsx@@ -16,19 +16,5 @@ export default withProvider({SettingsComponent: SettingsComponent,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async (posts) => {- if (- posts?.some(- (p) => p?.some((a) => (a?.path?.indexOf?.('mp4') ?? -1) > -1) && (p?.length ?? 0) > 1- )- ) {- return 'You can only upload one video per post.';- }-- if (posts?.some((p) => (p?.length ?? 0) > 4)) {- return 'There can be maximum 4 pictures in a post.';- }- return true;- },maximumCharacters: 300,});diff --git a/apps/frontend/src/components/new-launch/providers/devto/devto.provider.tsx b/apps/frontend/src/components/new-launch/providers/devto/devto.provider.tsxindex 66c7e5e75..42821fe42 100644--- a/apps/frontend/src/components/new-launch/providers/devto/devto.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/devto/devto.provider.tsx@@ -52,6 +52,5 @@ export default withProvider({SettingsComponent: DevtoSettings,CustomPreviewComponent: undefined, // DevtoPreview,dto: DevToSettingsDto,- checkValidity: undefined,maximumCharacters: 100000,});diff --git a/apps/frontend/src/components/new-launch/providers/discord/discord.provider.tsx b/apps/frontend/src/components/new-launch/providers/discord/discord.provider.tsxindex 467804a64..2494f0368 100644--- a/apps/frontend/src/components/new-launch/providers/discord/discord.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/discord/discord.provider.tsx@@ -22,6 +22,5 @@ export default withProvider({SettingsComponent: DiscordComponent,CustomPreviewComponent: undefined,dto: DiscordDto,- checkValidity: undefined,maximumCharacters: 1980,});diff --git a/apps/frontend/src/components/new-launch/providers/dribbble/dribbble.provider.tsx b/apps/frontend/src/components/new-launch/providers/dribbble/dribbble.provider.tsxindex 741aaa1f7..4b9c092ce 100644--- a/apps/frontend/src/components/new-launch/providers/dribbble/dribbble.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/dribbble/dribbble.provider.tsx@@ -24,32 +24,5 @@ export default withProvider({SettingsComponent: DribbbleSettings,CustomPreviewComponent: undefined,dto: DribbbleDto,- checkValidity: async ([firstItem, ...otherItems] = []) => {- const isMp4 = firstItem?.find((item) => (item?.path?.indexOf?.('mp4') ?? -1) > -1);- if (firstItem?.length !== 1) {- return 'Requires one item';- }- if (isMp4) {- return 'Does not support mp4 files';- }- const details = await new Promise<{- width: number;- height: number;- }>((resolve, reject) => {- const url = new Image();- url.onload = function () {- // @ts-ignore- resolve({ width: this.width, height: this.height });- };- url.src = firstItem?.[0]?.path;- });- if (- (details?.width === 400 && details?.height === 300) ||- (details?.width === 800 && details?.height === 600)- ) {- return true;- }- return 'Invalid image size. Requires 400x300 or 800x600 px images.';- },maximumCharacters: 40000,});diff --git a/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx b/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsxindex a3bbb70e9..acd309256 100644--- a/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/facebook/facebook.provider.tsx@@ -59,13 +59,5 @@ export default withProvider<FacebookDto>({SettingsComponent: FacebookSettings,CustomPreviewComponent: FacebookPreview,dto: FacebookDto,- checkValidity: async ([firstPost, ...otherPosts] = [], settings) => {- if (settings?.post_type === 'story') {- if (!firstPost?.length) {- return 'Story should have at least one media';- }- }- return true;- },maximumCharacters: 63206,});diff --git a/apps/frontend/src/components/new-launch/providers/gmb/gmb.provider.tsx b/apps/frontend/src/components/new-launch/providers/gmb/gmb.provider.tsxindex ba008a1a2..c63066d80 100644--- a/apps/frontend/src/components/new-launch/providers/gmb/gmb.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/gmb/gmb.provider.tsx@@ -165,26 +165,5 @@ export default withProvider({SettingsComponent: GmbSettings,CustomPreviewComponent: undefined,dto: GmbSettingsDto,- checkValidity: async (items, settings: any) => {- // GMB posts can have text only, or text with one image- if ((items?.length ?? 0) > 0 && (items?.[0]?.length ?? 0) > 1) {- return 'Google My Business posts can only have one image';- }-- // Check for video - GMB doesn't support video in local posts- if ((items?.length ?? 0) > 0 && (items?.[0]?.length ?? 0) > 0) {- const media = items?.[0]?.[0];- if ((media?.path?.indexOf?.('mp4') ?? -1) > -1) {- return 'Google My Business posts do not support video attachments';- }- }-- // Event posts require a title- if (settings?.topicType === 'EVENT' && !settings?.eventTitle) {- return 'Event posts require an event title';- }-- return true;- },maximumCharacters: 1500,});diff --git a/apps/frontend/src/components/new-launch/providers/hashnode/hashnode.provider.tsx b/apps/frontend/src/components/new-launch/providers/hashnode/hashnode.provider.tsxindex b4793ff24..ffa62fbc9 100644--- a/apps/frontend/src/components/new-launch/providers/hashnode/hashnode.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/hashnode/hashnode.provider.tsx@@ -48,6 +48,5 @@ export default withProvider({SettingsComponent: HashnodeSettings,CustomPreviewComponent: undefined, // HashnodePreview,dto: HashnodeSettingsDto,- checkValidity: undefined,maximumCharacters: 10000,});diff --git a/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx b/apps/frontend/src/components/new-launch/providers/high.order.provider.tsxindex b1f57b0e8..1d31a2aed 100644--- a/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx@@ -48,16 +48,6 @@ export const withProvider = function <T extends object>(params: {maximumCharacters?: number;}>;dto?: any;- checkValidity?: (- value: Array<- Array<{- path: string;- thumbnail?: string;- }>- >,- settings: T,- additionalSettings: any- ) => Promise<string | true>;maximumCharacters?: number | ((settings: any) => number);}) {const {@@ -65,7 +55,6 @@ export const withProvider = function <T extends object>(params: {SettingsComponent,CustomPreviewComponent,dto,- checkValidity,maximumCharacters,} = params;@@ -200,15 +189,6 @@ export const withProvider = function <T extends object>(params: {integration: selectedIntegration.integration,valid: await form.trigger(),err: form.formState.errors,- errors: checkValidity- ? await checkValidity(- value.map((p) => p.media || []),- settings,- JSON.parse(- selectedIntegration.integration.additionalSettings || '[]'- )- )- : true,settings,values: value,maximumCharacters:@@ -363,7 +343,6 @@ export const withProvider = function <T extends object>(params: {dto,postComment,maximumCharacters,- checkValidity,};return Wrapped;@@ -378,11 +357,6 @@ export const getProviderSettingsMeta = (component: unknown) => {dto?: any;postComment: PostComment;maximumCharacters?: number | ((settings: any) => number);- checkValidity?: (- value: Array<Array<{ path: string; thumbnail?: string }>>,- settings: any,- additionalSettings: any- ) => Promise<string | true>;}| undefined;};diff --git a/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx b/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsxindex aa3cf7452..b16fb3cf9 100644--- a/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx+++ b/apps/frontend/src/components/new-launch/providers/instagram/instagram.collaborators.tsx@@ -99,46 +99,6 @@ export default withProvider<InstagramDto>({SettingsComponent: InstagramCollaborators,CustomPreviewComponent: InstagramPreview,dto: InstagramDto,- checkValidity: async ([firstPost, ...otherPosts] = [], settings) => {- if (!firstPost?.length) {- return 'Should have at least one media';- }- if (settings?.is_trial_reel) {- if ((firstPost?.length ?? 0) > 1) {- return 'Trial Reels can only have one video';- }- const hasVideo = firstPost?.some(- (f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1- );- if (!hasVideo) {- return 'Trial Reels must be a video';- }- }- const checkVideosLength = await Promise.all(- firstPost- ?.filter((f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1)- ?.flatMap((p) => p?.path)- ?.map((p) => {- return new Promise<number>((res) => {- const video = document.createElement('video');- video.preload = 'metadata';- video.src = p;- video.addEventListener('loadedmetadata', () => {- res(video.duration);- });- });- }) ?? []- );- for (const video of checkVideosLength) {- if (video > 60 && settings?.post_type === 'story') {- return 'Stories should be maximum 60 seconds';- }- if (video > 180 && settings?.post_type === 'post') {- return 'Reel should be maximum 180 seconds';- }- }- return true;- },maximumCharacters: 2200,comments: 'no-media'});diff --git a/apps/frontend/src/components/new-launch/providers/kick/kick.provider.tsx b/apps/frontend/src/components/new-launch/providers/kick/kick.provider.tsxindex a18a7ea7e..7c2ef9663 100644--- a/apps/frontend/src/components/new-launch/providers/kick/kick.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/kick/kick.provider.tsx@@ -12,6 +12,5 @@ export default withProvider({SettingsComponent: undefined,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: undefined,maximumCharacters: 500,});diff --git a/apps/frontend/src/components/new-launch/providers/lemmy/lemmy.provider.tsx b/apps/frontend/src/components/new-launch/providers/lemmy/lemmy.provider.tsxindex 74bbb2946..db120180c 100644--- a/apps/frontend/src/components/new-launch/providers/lemmy/lemmy.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/lemmy/lemmy.provider.tsx@@ -72,18 +72,5 @@ export default withProvider({SettingsComponent: LemmySettings,CustomPreviewComponent: undefined,dto: LemmySettingsDto,- checkValidity: async (items) => {- const [firstItems] = items ?? [];- if (- firstItems?.length &&- (firstItems?.[0]?.path?.indexOf?.('png') ?? -1) === -1 &&- (firstItems?.[0]?.path?.indexOf?.('jpg') ?? -1) === -1 &&- (firstItems?.[0]?.path?.indexOf?.('jpef') ?? -1) === -1 &&- (firstItems?.[0]?.path?.indexOf?.('gif') ?? -1) === -1- ) {- return 'You can set only one picture for a cover';- }- return true;- },maximumCharacters: 10000,});diff --git a/apps/frontend/src/components/new-launch/providers/linkedin/linkedin.provider.tsx b/apps/frontend/src/components/new-launch/providers/linkedin/linkedin.provider.tsxindex 47818da81..fe6c770f0 100644--- a/apps/frontend/src/components/new-launch/providers/linkedin/linkedin.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/linkedin/linkedin.provider.tsx@@ -43,27 +43,5 @@ export default withProvider<LinkedinDto>({SettingsComponent: LinkedInSettings,CustomPreviewComponent: LinkedinPreview,dto: LinkedinDto,- checkValidity: async (posts, vals) => {- const [firstPost, ...restPosts] = posts ?? [];-- if (- vals?.post_as_images_carousel &&- ((firstPost?.length ?? 0) < 2 ||- firstPost?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1))- ) {- return 'Carousel can only be created with 2 or more images and no videos.';- }-- if (- (firstPost?.length ?? 0) > 1 &&- firstPost?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1)- ) {- return 'Can have maximum 1 media when selecting a video.';- }- if (restPosts?.some((p) => (p?.length ?? 0) > 0)) {- return 'Comments can only contain text.';- }- return true;- },maximumCharacters: 3000,});diff --git a/apps/frontend/src/components/new-launch/providers/listmonk/listmonk.provider.tsx b/apps/frontend/src/components/new-launch/providers/listmonk/listmonk.provider.tsxindex 7e7a1bcfa..05bb3fa90 100644--- a/apps/frontend/src/components/new-launch/providers/listmonk/listmonk.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/listmonk/listmonk.provider.tsx@@ -29,6 +29,5 @@ export default withProvider({SettingsComponent: SettingsComponent,CustomPreviewComponent: undefined,dto: ListmonkDto,- checkValidity: undefined,maximumCharacters: 300000,});diff --git a/apps/frontend/src/components/new-launch/providers/mastodon/mastodon.provider.tsx b/apps/frontend/src/components/new-launch/providers/mastodon/mastodon.provider.tsxindex 73613ef9c..6c0653605 100644--- a/apps/frontend/src/components/new-launch/providers/mastodon/mastodon.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/mastodon/mastodon.provider.tsx@@ -10,6 +10,5 @@ export default withProvider({SettingsComponent: null,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: undefined,maximumCharacters: 500,});diff --git a/apps/frontend/src/components/new-launch/providers/medium/medium.provider.tsx b/apps/frontend/src/components/new-launch/providers/medium/medium.provider.tsxindex ee29ac516..c35755bff 100644--- a/apps/frontend/src/components/new-launch/providers/medium/medium.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/medium/medium.provider.tsx@@ -40,6 +40,5 @@ export default withProvider({SettingsComponent: MediumSettings,CustomPreviewComponent: undefined, //MediumPreview,dto: MediumSettingsDto,- checkValidity: undefined,maximumCharacters: 100000,});diff --git a/apps/frontend/src/components/new-launch/providers/mewe/mewe.provider.tsx b/apps/frontend/src/components/new-launch/providers/mewe/mewe.provider.tsxindex 82e27c38a..fc65cb7c7 100644--- a/apps/frontend/src/components/new-launch/providers/mewe/mewe.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/mewe/mewe.provider.tsx@@ -38,6 +38,5 @@ export default withProvider({SettingsComponent: MeweComponent,CustomPreviewComponent: undefined,dto: MeweDto,- checkValidity: undefined,maximumCharacters: 63206,});diff --git a/apps/frontend/src/components/new-launch/providers/nostr/nostr.provider.tsx b/apps/frontend/src/components/new-launch/providers/nostr/nostr.provider.tsxindex b7417d0ec..2ee14568d 100644--- a/apps/frontend/src/components/new-launch/providers/nostr/nostr.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/nostr/nostr.provider.tsx@@ -10,8 +10,5 @@ export default withProvider({SettingsComponent: null,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async () => {- return true;- },maximumCharacters: 100000,});diff --git a/apps/frontend/src/components/new-launch/providers/pinterest/pinterest.provider.tsx b/apps/frontend/src/components/new-launch/providers/pinterest/pinterest.provider.tsxindex 9e7320ba3..9b9f2e849 100644--- a/apps/frontend/src/components/new-launch/providers/pinterest/pinterest.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/pinterest/pinterest.provider.tsx@@ -34,53 +34,5 @@ export default withProvider({SettingsComponent: PinterestSettings,CustomPreviewComponent: PinterestPreview,dto: PinterestSettingsDto,- checkValidity: async ([firstItem, ...otherItems] = []) => {- const isMp4 = firstItem?.find(- (item) => (item?.path?.indexOf?.('mp4') ?? -1) > -1- );- const isPicture = firstItem?.find(- (item) => (item?.path?.indexOf?.('mp4') ?? -1) === -1- );- if ((firstItem?.length ?? 0) === 0) {- return 'Requires at least one media';- }- if ((firstItem?.length ?? 0) > 5) {- return 'You can only have up to 5 media items';- }- if (isMp4 && firstItem?.length !== 2 && !isPicture) {- return 'If posting a video you have to also include a cover image as second media';- }- if (isMp4 && (firstItem?.length ?? 0) > 2) {- return 'If posting a video you can only have two media items';- }-- if (- (firstItem?.length ?? 0) > 1 &&- firstItem?.every((p) => (p?.path?.indexOf?.('mp4') ?? -1) == -1)- ) {- const loadAll: Array<{- width: number;- height: number;- }> = (await Promise.all(- firstItem?.map((p) => {- return new Promise((resolve, reject) => {- const url = new Image();- url.onload = function () {- // @ts-ignore- resolve({ width: this.width, height: this.height });- };- url.src = p?.path;- });- }) ?? []- )) as any;- const checkAllTheSameWidthHeight = loadAll?.every((p, i, arr) => {- return p?.width === arr?.[0]?.width && p?.height === arr?.[0]?.height;- });- if (!checkAllTheSameWidthHeight) {- return 'Requires all images to have the same width and height';- }- }- return true;- },maximumCharacters: 500,});diff --git a/apps/frontend/src/components/new-launch/providers/reddit/reddit.provider.tsx b/apps/frontend/src/components/new-launch/providers/reddit/reddit.provider.tsxindex d4e6abe3a..e09cae29d 100644--- a/apps/frontend/src/components/new-launch/providers/reddit/reddit.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/reddit/reddit.provider.tsx@@ -214,25 +214,5 @@ export default withProvider({SettingsComponent: RedditSettings,CustomPreviewComponent: undefined,dto: RedditSettingsDto,- checkValidity: async (posts, settings: any) => {- if (- settings?.subreddit?.some(- (p: any, index: number) =>- p?.value?.type === 'media' && posts?.[0]?.length !== 1- )- ) {- return 'When posting a media post, you must attached exactly one media file.';- }-- if (- posts?.some((p) =>- p?.some((a) => !a?.thumbnail && (a?.path?.indexOf?.('mp4') ?? -1) > -1)- )- ) {- return 'You must attach a thumbnail to your video post.';- }-- return true;- },maximumCharacters: 10000,});diff --git a/apps/frontend/src/components/new-launch/providers/skool/skool.provider.tsx b/apps/frontend/src/components/new-launch/providers/skool/skool.provider.tsxindex f6b2b43a6..ebc2191de 100644--- a/apps/frontend/src/components/new-launch/providers/skool/skool.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/skool/skool.provider.tsx@@ -32,7 +32,6 @@ export default withProvider({SettingsComponent: SkoolComponent,CustomPreviewComponent: undefined,dto: SkoolDto,- checkValidity: undefined,maximumCharacters: 50000,postComment: PostComment.ALL,});diff --git a/apps/frontend/src/components/new-launch/providers/slack/slack.provider.tsx b/apps/frontend/src/components/new-launch/providers/slack/slack.provider.tsxindex 6e4130939..b8b3e6731 100644--- a/apps/frontend/src/components/new-launch/providers/slack/slack.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/slack/slack.provider.tsx@@ -22,6 +22,5 @@ export default withProvider({SettingsComponent: SlackComponent,CustomPreviewComponent: undefined,dto: SlackDto,- checkValidity: undefined,maximumCharacters: 400000,});diff --git a/apps/frontend/src/components/new-launch/providers/telegram/telegram.provider.tsx b/apps/frontend/src/components/new-launch/providers/telegram/telegram.provider.tsxindex 2b4a1ce9a..ec93f83d2 100644--- a/apps/frontend/src/components/new-launch/providers/telegram/telegram.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/telegram/telegram.provider.tsx@@ -10,8 +10,5 @@ export default withProvider({SettingsComponent: null,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async () => {- return true;- },maximumCharacters: 4096,});diff --git a/apps/frontend/src/components/new-launch/providers/threads/threads.provider.tsx b/apps/frontend/src/components/new-launch/providers/threads/threads.provider.tsxindex 7b930d26d..7bc370c8d 100644--- a/apps/frontend/src/components/new-launch/providers/threads/threads.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/threads/threads.provider.tsx@@ -15,30 +15,5 @@ export default withProvider({SettingsComponent: SettingsComponent,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async ([firstPost, ...otherPosts] = [], settings) => {- const checkVideosLength = await Promise.all(- firstPost- ?.filter((f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1)- ?.flatMap((p) => p?.path)- ?.map((p) => {- return new Promise<number>((res) => {- const video = document.createElement('video');- video.preload = 'metadata';- video.src = p;- video.addEventListener('loadedmetadata', () => {- res(video.duration);- });- });- }) ?? []- );-- for (const video of checkVideosLength) {- if (video > 300) {- return 'Video should be maximum 300 seconds (5 minutes)';- }- }-- return true;- },maximumCharacters: 500,});diff --git a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsxindex edd5e5e43..5d824c5ad 100644--- a/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/tiktok/tiktok.provider.tsx@@ -336,23 +336,5 @@ export default withProvider({comments: false,CustomPreviewComponent: TiktokPreview,dto: TikTokDto,- checkValidity: async (items) => {- const [firstItems] = items ?? [];- if ((firstItems?.length ?? 0) === 0) {- return 'No video / images selected';- }- if (- (firstItems?.length ?? 0) > 1 &&- firstItems?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1)- ) {- return 'Only pictures are supported when selecting multiple items';- } else if (- firstItems?.length !== 1 &&- (firstItems?.[0]?.path?.indexOf?.('mp4') ?? -1) > -1- ) {- return 'You need one media';- }- return true;- },maximumCharacters: 2000,});diff --git a/apps/frontend/src/components/new-launch/providers/twitch/twitch.provider.tsx b/apps/frontend/src/components/new-launch/providers/twitch/twitch.provider.tsxindex 6ddccf885..9cce148f8 100644--- a/apps/frontend/src/components/new-launch/providers/twitch/twitch.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/twitch/twitch.provider.tsx@@ -90,6 +90,5 @@ export default withProvider({SettingsComponent: TwitchSettings,CustomPreviewComponent: undefined,dto: TwitchDto,- checkValidity: undefined,maximumCharacters: 500,});diff --git a/apps/frontend/src/components/new-launch/providers/vk/vk.provider.tsx b/apps/frontend/src/components/new-launch/providers/vk/vk.provider.tsxindex c1421c18c..36e4ce8b3 100644--- a/apps/frontend/src/components/new-launch/providers/vk/vk.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/vk/vk.provider.tsx@@ -11,8 +11,5 @@ export default withProvider({SettingsComponent: null,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async (posts) => {- return true;- },maximumCharacters: 2048,});diff --git a/apps/frontend/src/components/new-launch/providers/warpcast/warpcast.provider.tsx b/apps/frontend/src/components/new-launch/providers/warpcast/warpcast.provider.tsxindex efb372c5d..f8775c5d2 100644--- a/apps/frontend/src/components/new-launch/providers/warpcast/warpcast.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/warpcast/warpcast.provider.tsx@@ -63,13 +63,5 @@ export default withProvider({SettingsComponent: WrapcastProvider,CustomPreviewComponent: undefined,dto: undefined,- checkValidity: async (list) => {- if (- list?.some((item) => item?.some((field) => (field?.path?.indexOf?.('mp4') ?? -1) > -1))- ) {- return 'Can only accept images';- }- return true;- },maximumCharacters: 800,});diff --git a/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsx b/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsxindex 3c08938e6..222dfb49b 100644--- a/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsx@@ -42,6 +42,5 @@ export default withProvider({SettingsComponent: WhopSettings,CustomPreviewComponent: undefined,dto: WhopDto,- checkValidity: undefined,maximumCharacters: 50000,});diff --git a/apps/frontend/src/components/new-launch/providers/wordpress/wordpress.provider.tsx b/apps/frontend/src/components/new-launch/providers/wordpress/wordpress.provider.tsxindex fe3e993d4..b830f4e95 100644--- a/apps/frontend/src/components/new-launch/providers/wordpress/wordpress.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/wordpress/wordpress.provider.tsx@@ -31,6 +31,5 @@ export default withProvider({SettingsComponent: WordpressSettings,CustomPreviewComponent: undefined, // WordpressPreview,dto: WordpressDto,- checkValidity: undefined,maximumCharacters: 100000,});diff --git a/apps/frontend/src/components/new-launch/providers/x/x.provider.tsx b/apps/frontend/src/components/new-launch/providers/x/x.provider.tsxindex 7b5efca01..2d9b9d129 100644--- a/apps/frontend/src/components/new-launch/providers/x/x.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/x/x.provider.tsx@@ -88,23 +88,6 @@ export default withProvider({SettingsComponent: SettingsComponent,CustomPreviewComponent: undefined,dto: XDto,- checkValidity: async (posts, settings, additionalSettings: any) => {- const premium =- additionalSettings?.find((p: any) => p?.title === 'Verified')?.value ||- false;- // if (posts?.some((p) => (p?.length ?? 0) > 4)) {- // return 'There can be maximum 4 pictures in a post.';- // }- for (const load of posts?.flatMap((p) => p?.flatMap((a) => a?.path)) ?? []) {- if ((load?.indexOf?.('mp4') ?? -1) > -1) {- const isValid = await checkVideoDuration(load, premium);- if (!isValid) {- return 'Video duration must be less than or equal to 140 seconds.';- }- }- }- return true;- },maximumCharacters: (settings) => {if (settings?.[0]?.value) {return 4000;@@ -112,25 +95,3 @@ export default withProvider({return 280;},});-const checkVideoDuration = async (- url: string,- isPremium = false-): Promise<boolean> => {- return new Promise((resolve, reject) => {- const video = document.createElement('video');- video.src = url;- video.preload = 'metadata';- video.onloadedmetadata = () => {- // Check if the duration is less than or equal to 140 seconds- const duration = video.duration;- if ((!isPremium && duration <= 140) || isPremium) {- resolve(true); // Video duration is acceptable- } else {- resolve(false); // Video duration exceeds 140 seconds- }- };- video.onerror = () => {- reject(new Error('Failed to load video metadata.'));- };- });-};diff --git a/apps/frontend/src/components/new-launch/providers/youtube/youtube.provider.tsx b/apps/frontend/src/components/new-launch/providers/youtube/youtube.provider.tsxindex 9509d1efc..d3009fb24 100644--- a/apps/frontend/src/components/new-launch/providers/youtube/youtube.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/youtube/youtube.provider.tsx@@ -87,15 +87,5 @@ export default withProvider({SettingsComponent: YoutubeSettings,CustomPreviewComponent: YoutubePreview,dto: YoutubeSettingsDto,- checkValidity: async (items) => {- const [firstItems] = items ?? [];- if (items?.[0]?.length !== 1) {- return 'You need one media';- }- if ((firstItems?.[0]?.path?.indexOf?.('mp4') ?? -1) === -1) {- return 'Item must be a video';- }- return true;- },maximumCharacters: 5000,});diff --git a/apps/frontend/src/components/provider-preview/preview.provider.component.tsx b/apps/frontend/src/components/provider-preview/preview.provider.component.tsxindex 96a94735d..40b6d2978 100644--- a/apps/frontend/src/components/provider-preview/preview.provider.component.tsx+++ b/apps/frontend/src/components/provider-preview/preview.provider.component.tsx@@ -173,27 +173,15 @@ export const ProviderPreviewComponent: FC<ProviderPreviewProps> = ({validate: async () => {const formValid = await form.trigger(undefined, { shouldFocus: false });const errs = flattenFormErrors(form.formState.errors);- let customError: string | true = true;- if (meta?.checkValidity) {- try {- customError = await meta.checkValidity(- posts ?? [],- form.getValues(),- resolveAdditionalSettings(),- );- } catch (e: any) {- customError = e?.message ?? 'checkValidity threw';- }- }- const checkValidityError =- customError === true ? null : customError;- if (checkValidityError) errs.push(checkValidityError);+ // Media validation (`checkValidity`) now runs server-side at create+ // time (`/posts/valid` + `/posts`), so the preview only does the+ // local DTO/form validation here.return {- isValid: formValid && checkValidityError === null,+ isValid: formValid,value: form.getValues() as Record<string, unknown>,errors: errs,formValid,- checkValidityError,+ checkValidityError: null,};},};diff --git a/libraries/nestjs-libraries/src/chat/tools/integration.schedule.post.ts b/libraries/nestjs-libraries/src/chat/tools/integration.schedule.post.tsindex b2983de7d..e6a657941 100644--- a/libraries/nestjs-libraries/src/chat/tools/integration.schedule.post.ts+++ b/libraries/nestjs-libraries/src/chat/tools/integration.schedule.post.ts@@ -2,23 +2,12 @@ import { AgentToolInterface } from '@gitroom/nestjs-libraries/chat/agent.tool.inimport { createTool } from '@mastra/core/tools';import { z } from 'zod';import { Injectable } from '@nestjs/common';-import { socialIntegrationList } from '@gitroom/nestjs-libraries/integrations/integration.manager';import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import { AllProvidersSettings } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/all.providers.settings';-import { validate } from 'class-validator';import { Integration } from '@prisma/client';import { checkAuth } from '@gitroom/nestjs-libraries/chat/auth.context';-import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';-import { weightedLength } from '@gitroom/helpers/utils/count.length';--function countCharacters(text: string, type: string): number {- if (type !== 'x') {- return text.length;- }- return weightedLength(text);-}@Injectable()export class IntegrationSchedulePostTool implements AgentToolInterface {@@ -138,50 +127,56 @@ If the tools return errors, you would need to rerun it with the right parametersplatform.integrationId);- const { dto, maxLength, identifier } = socialIntegrationList.find(- (p) =>- p.identifier ===- integrations[platform.integrationId].providerIdentifier- )!;-- if (dto) {- const newDTO = new dto();- const obj = Object.assign(- newDTO,- platform.settings.reduce(- (acc: AllProvidersSettings, s: { key: string; value: any }) => ({- ...acc,- [s.key]: s.value,- }),- {} as AllProvidersSettings- )- );- const errors = await validate(obj);- if (errors.length) {+ // Same server-side validation as the dashboard / public API+ // (settings DTO + media checkValidity + empty / too-long content).+ const settings = platform.settings.reduce(+ (acc: AllProvidersSettings, s: { key: string; value: any }) => ({+ ...acc,+ [s.key]: s.value,+ }),+ {} as AllProvidersSettings+ );++ const [validation] = await this._postsService.validatePosts(+ organizationId,+ [+ {+ integration: { id: platform.integrationId },+ settings,+ value: platform.postsAndComments.map((p: any) => ({+ content: p.content,+ image: (p.attachments || []).map((path: string) => ({+ path,+ })),+ })),+ },+ ]+ );++ if (validation.emptyContent) {+ return {+ errors: `${validation.name}: Your post should have at least one character or one image.`,+ };+ }++ if (platform.type !== 'draft') {+ if (!validation.valid) {return {- errors: JSON.stringify(errors),+ errors: `${validation.name}: ${+ validation.settingsError || 'Please fix your settings'+ }, please fix it, and try integrationSchedulePostTool again.`,};}- const errorsLength = [];- for (const post of platform.postsAndComments) {- const maximumCharacters = maxLength(platform.isPremium);- const strip = stripHtmlValidation('normal', post.content, true);- const weightedLength = countCharacters(strip, identifier || '');- const totalCharacters =- weightedLength > strip.length ? weightedLength : strip.length;-- if (totalCharacters > (maximumCharacters || 1000000)) {- errorsLength.push({- value: post.content,- error: `The maximum characters is ${maximumCharacters}, we got ${totalCharacters}, please fix it, and try integrationSchedulePostTool again.`,- });- }+ if (validation.errors !== true) {+ return {+ errors: `${validation.name}: ${validation.errors}, please fix it, and try integrationSchedulePostTool again.`,+ };}- if (errorsLength.length) {+ if (validation.tooLong) {return {- errors: JSON.stringify(errorsLength),+ errors: `${validation.name}: The maximum characters is ${validation.maximumCharacters}, please fix it, and try integrationSchedulePostTool again.`,};}}diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 0e8100efc..a3dfdb5c1 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -49,6 +49,10 @@ import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstimport { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';import { hasExtension } from '@gitroom/helpers/utils/has.extension';import { stripLinks } from '@gitroom/helpers/utils/strip.links';+import { validate } from 'class-validator';+import { plainToInstance } from 'class-transformer';+import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';+import { weightedLength } from '@gitroom/helpers/utils/count.length';type PostWithConditionals = Post & {integration?: Integration;@@ -747,6 +751,126 @@ export class PostsService {} catch (err) {}}+ /**+ * Server-side validation that used to live on the client (`checkValidity` ++ * the manage modal loop). Runs the provider's settings DTO validation, the+ * provider `checkValidity` (media rules) and the empty-content / too-long+ * character checks. Returns one result per post so the frontend can show the+ * same toasts it did before β and so `/posts` can refuse to create invalid+ * posts.+ */+ async validatePosts(+ orgId: string,+ posts: Array<{+ integration: { id: string };+ value: Array<{+ content?: string;+ image?: Array<{ path: string; thumbnail?: string }>;+ }>;+ settings?: any;+ }>+ ) {+ return Promise.all(+ (posts || []).map(async (post) => {+ const integration = await this._integrationService.getIntegrationById(+ orgId,+ post?.integration?.id+ );++ if (!integration) {+ throw new BadRequestException(+ `Integration with id ${post?.integration?.id} not found`+ );+ }++ const provider = this._integrationManager.getSocialIntegration(+ integration.providerIdentifier+ );++ let additionalSettings: any[] = [];+ try {+ additionalSettings = JSON.parse(integration.additionalSettings || '[]');+ } catch {+ additionalSettings = [];+ }++ const settings = post.settings || {};+ const media = (post.value || []).map((p) => p.image || []);++ // Settings DTO validation β mirrors the client `form.trigger()`.+ let valid = true;+ let settingsError = '';+ if (provider?.dto) {+ const instance = plainToInstance(provider.dto, settings, {+ enableImplicitConversion: true,+ });+ const validationErrors = await validate(instance as object, {+ skipMissingProperties: false,+ });+ settingsError = this.firstValidationError(validationErrors);+ valid = validationErrors.length === 0;+ }++ // Provider-specific media validation (the old client `checkValidity`).+ let errors: string | true = true;+ try {+ errors = await provider.checkValidity(+ media,+ settings,+ additionalSettings+ );+ } catch (err: any) {+ errors = err?.message || 'Invalid media';+ }++ const maximumCharacters = provider.maxLength(additionalSettings);+ const isX = integration.providerIdentifier === 'x';++ const emptyContent = (post.value || []).some((a) => {+ const strip = stripHtmlValidation('normal', a.content || '', true);+ const length = isX ? weightedLength(strip) : strip.length;+ return length === 0 && (a.image || []).length === 0;+ });++ const tooLong = (post.value || []).some((a) => {+ const strip = stripHtmlValidation('normal', a.content || '', true);+ const weighted = isX ? weightedLength(strip) : strip.length;+ const totalCharacters =+ weighted > strip.length ? weighted : strip.length;+ return totalCharacters > (maximumCharacters || 1000000);+ });++ return {+ id: integration.id,+ identifier: integration.providerIdentifier,+ name: integration.name,+ valid,+ settingsError,+ errors,+ emptyContent,+ tooLong,+ maximumCharacters,+ };+ })+ );+ }++ /** Returns the first class-validator message (incl. nested children), or ''. */+ private firstValidationError(errors: any[]): string {+ for (const e of errors || []) {+ if (e?.constraints) {+ return Object.values(e.constraints as Record<string, string>)[0] || '';+ }+ const child = e?.children?.length+ ? this.firstValidationError(e.children)+ : '';+ if (child) {+ return child;+ }+ }+ return '';+ }+async createPost(orgId: string,body: CreatePostDto,diff --git a/libraries/nestjs-libraries/src/integrations/social.abstract.ts b/libraries/nestjs-libraries/src/integrations/social.abstract.tsindex c52cf107d..9c5cad807 100644--- a/libraries/nestjs-libraries/src/integrations/social.abstract.ts+++ b/libraries/nestjs-libraries/src/integrations/social.abstract.ts@@ -1,6 +1,13 @@import { timer } from '@gitroom/helpers/utils/timer';import { Integration } from '@prisma/client';import { ApplicationFailure } from '@temporalio/activity';+import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';+import sharp from 'sharp';++export type ValidityMedia = {+ path: string;+ thumbnail?: string;+};export class RefreshToken extends ApplicationFailure {constructor(identifier: string, json: string, body: BodyInit, message = '') {@@ -59,6 +66,41 @@ export abstract class SocialAbstract {return undefined;}+ /**+ * Server-side replacement for the old client-side `checkValidity`.+ * Validates the media attached to a post (and its comments) against the+ * provider rules. Returns `true` when valid, or an error message string.+ *+ * `posts` mirrors the client shape: the outer array is the main post followed+ * by each comment, the inner array is the media items for that entry.+ *+ * Note: video-duration validations that used to run in the browser are not+ * re-implemented here (no ffmpeg dependency). Image-dimension checks use sharp.+ */+ async checkValidity(+ posts: Array<ValidityMedia[]>,+ settings: any,+ additionalSettings: any[]+ ): Promise<string | true> {+ return true;+ }++ /** Reads the pixel dimensions of an image via sharp (works for http or local paths). */+ protected async getImageDimensions(+ path: string+ ): Promise<{ width: number; height: number }> {+ // Stored media paths are relative (e.g. "uploads/x.png"); resolve them to a+ // fetchable URL the same way posts.service.updateMedia does.+ const url =+ path?.indexOf('http') === -1+ ? `${process.env.FRONTEND_URL}/${path}`+ : path;+ const { width = 0, height = 0 } = await sharp(+ await readOrFetch(url)+ ).metadata();+ return { width, height };+ }+public async mention(token: string,d: { query: string },diff --git a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.tsindex 206f14585..057fb850d 100644--- a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts@@ -9,6 +9,7 @@ import {BadBody,RefreshToken,SocialAbstract,+ ValidityMedia,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import {BskyAgent,@@ -158,6 +159,25 @@ export class BlueskyProvider extends SocialAbstract implements SocialProvider {return 300;}+ override async checkValidity(+ posts: Array<ValidityMedia[]>+ ): Promise<string | true> {+ if (+ posts?.some(+ (p) =>+ p?.some((a) => (a?.path?.indexOf?.('mp4') ?? -1) > -1) &&+ (p?.length ?? 0) > 1+ )+ ) {+ return 'You can only upload one video per post.';+ }++ if (posts?.some((p) => (p?.length ?? 0) > 4)) {+ return 'There can be maximum 4 pictures in a post.';+ }+ return true;+ }+async customFields() {return [{diff --git a/libraries/nestjs-libraries/src/integrations/social/dribbble.provider.ts b/libraries/nestjs-libraries/src/integrations/social/dribbble.provider.tsindex ba5968ea6..7b93eae45 100644--- a/libraries/nestjs-libraries/src/integrations/social/dribbble.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/dribbble.provider.ts@@ -8,7 +8,10 @@ import {import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import axios from 'axios';import FormData from 'form-data';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { DribbbleDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/dribbble.dto';import mime from 'mime-types';import { DiscordDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/discord.dto';@@ -26,6 +29,28 @@ export class DribbbleProvider extends SocialAbstract implements SocialProvider {}dto = DribbbleDto;+ override async checkValidity(+ [firstItem]: Array<ValidityMedia[]>+ ): Promise<string | true> {+ const isMp4 = firstItem?.find(+ (item) => (item?.path?.indexOf?.('mp4') ?? -1) > -1+ );+ if (firstItem?.length !== 1) {+ return 'Requires one item';+ }+ if (isMp4) {+ return 'Does not support mp4 files';+ }+ const details = await this.getImageDimensions(firstItem?.[0]?.path);+ if (+ (details?.width === 400 && details?.height === 300) ||+ (details?.width === 800 && details?.height === 600)+ ) {+ return true;+ }+ return 'Invalid image size. Requires 400x300 or 800x600 px images.';+ }+async refreshToken(refreshToken: string): Promise<AuthTokenDetails> {const { access_token, expires_in } = await (await this.fetch('https://api-sandbox.pinterest.com/v5/oauth/token', {diff --git a/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts b/libraries/nestjs-libraries/src/integrations/social/facebook.provider.tsindex 96e43c9f9..fe9552aaa 100644--- a/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/facebook.provider.ts@@ -7,7 +7,10 @@ import {} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import dayjs from 'dayjs';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { FacebookDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';import { DribbbleDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/dribbble.dto';import { Integration } from '@prisma/client';@@ -37,6 +40,18 @@ export class FacebookProvider extends SocialAbstract implements SocialProvider {}dto = FacebookDto;+ override async checkValidity(+ [firstPost]: Array<ValidityMedia[]>,+ settings: any+ ): Promise<string | true> {+ if (settings?.post_type === 'story') {+ if (!firstPost?.length) {+ return 'Story should have at least one media';+ }+ }+ return true;+ }+override handleErrors(body: string,status: numberdiff --git a/libraries/nestjs-libraries/src/integrations/social/farcaster.provider.ts b/libraries/nestjs-libraries/src/integrations/social/farcaster.provider.tsindex fbadbeecf..0e237c401 100644--- a/libraries/nestjs-libraries/src/integrations/social/farcaster.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/farcaster.provider.ts@@ -6,7 +6,10 @@ import {} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import dayjs from 'dayjs';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { NeynarAPIClient } from '@neynar/nodejs-sdk';import { Integration } from '@prisma/client';import { FarcasterDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/farcaster.dto';@@ -36,6 +39,19 @@ export class FarcasterProvider}dto = FarcasterDto;+ override async checkValidity(+ list: Array<ValidityMedia[]>+ ): Promise<string | true> {+ if (+ list?.some((item) =>+ item?.some((field) => (field?.path?.indexOf?.('mp4') ?? -1) > -1)+ )+ ) {+ return 'Can only accept images';+ }+ return true;+ }+async refreshToken(refresh_token: string): Promise<AuthTokenDetails> {return {refreshToken: '',diff --git a/libraries/nestjs-libraries/src/integrations/social/gmb.provider.ts b/libraries/nestjs-libraries/src/integrations/social/gmb.provider.tsindex 797c54415..9d3bdc6e1 100644--- a/libraries/nestjs-libraries/src/integrations/social/gmb.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/gmb.provider.ts@@ -8,7 +8,10 @@ import {import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import { google } from 'googleapis';import { OAuth2Client } from 'google-auth-library/build/src/auth/oauth2client';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import * as process from 'node:process';import dayjs from 'dayjs';import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';@@ -51,6 +54,31 @@ export class GmbProvider extends SocialAbstract implements SocialProvider {return 1500;}+ override async checkValidity(+ items: Array<ValidityMedia[]>,+ settings: any+ ): Promise<string | true> {+ // GMB posts can have text only, or text with one image+ if ((items?.length ?? 0) > 0 && (items?.[0]?.length ?? 0) > 1) {+ return 'Google My Business posts can only have one image';+ }++ // Check for video - GMB doesn't support video in local posts+ if ((items?.length ?? 0) > 0 && (items?.[0]?.length ?? 0) > 0) {+ const media = items?.[0]?.[0];+ if ((media?.path?.indexOf?.('mp4') ?? -1) > -1) {+ return 'Google My Business posts do not support video attachments';+ }+ }++ // Event posts require a title+ if (settings?.topicType === 'EVENT' && !settings?.eventTitle) {+ return 'Event posts require an event title';+ }++ return true;+ }+override handleErrors(body: string):| {type: 'refresh-token' | 'bad-body';diff --git a/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts b/libraries/nestjs-libraries/src/integrations/social/instagram.provider.tsindex eb10f0c67..9efe65fb9 100644--- a/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/instagram.provider.ts@@ -8,7 +8,10 @@ import {import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import { timer } from '@gitroom/helpers/utils/timer';import dayjs from 'dayjs';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { InstagramDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/instagram.dto';import { Integration } from '@prisma/client';import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';@@ -41,6 +44,27 @@ export class InstagramProviderreturn 2200;}+ override async checkValidity(+ [firstPost]: Array<ValidityMedia[]>,+ settings: any+ ): Promise<string | true> {+ if (!firstPost?.length) {+ return 'Should have at least one media';+ }+ if (settings?.is_trial_reel) {+ if ((firstPost?.length ?? 0) > 1) {+ return 'Trial Reels can only have one video';+ }+ const hasVideo = firstPost?.some(+ (f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1+ );+ if (!hasVideo) {+ return 'Trial Reels must be a video';+ }+ }+ return true;+ }+async refreshToken(refresh_token: string): Promise<AuthTokenDetails> {return {refreshToken: '',diff --git a/libraries/nestjs-libraries/src/integrations/social/instagram.standalone.provider.ts b/libraries/nestjs-libraries/src/integrations/social/instagram.standalone.provider.tsindex 6051e4034..c1e649f72 100644--- a/libraries/nestjs-libraries/src/integrations/social/instagram.standalone.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/instagram.standalone.provider.ts@@ -6,7 +6,10 @@ import {} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import dayjs from 'dayjs';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { InstagramDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/instagram.dto';import { InstagramProvider } from '@gitroom/nestjs-libraries/integrations/social/instagram.provider';import { Integration } from '@prisma/client';@@ -39,6 +42,27 @@ export class InstagramStandaloneProviderreturn 2200;}+ override async checkValidity(+ [firstPost]: Array<ValidityMedia[]>,+ settings: any+ ): Promise<string | true> {+ if (!firstPost?.length) {+ return 'Should have at least one media';+ }+ if (settings?.is_trial_reel) {+ if ((firstPost?.length ?? 0) > 1) {+ return 'Trial Reels can only have one video';+ }+ const hasVideo = firstPost?.some(+ (f) => (f?.path?.indexOf?.('mp4') ?? -1) > -1+ );+ if (!hasVideo) {+ return 'Trial Reels must be a video';+ }+ }+ return true;+ }+public override handleErrors(body: string,status: numberdiff --git a/libraries/nestjs-libraries/src/integrations/social/lemmy.provider.ts b/libraries/nestjs-libraries/src/integrations/social/lemmy.provider.tsindex 53d230d91..1d52c9c09 100644--- a/libraries/nestjs-libraries/src/integrations/social/lemmy.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/lemmy.provider.ts@@ -5,7 +5,10 @@ import {SocialProvider,} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import dayjs from 'dayjs';import { Integration } from '@prisma/client';import { AuthService } from '@gitroom/helpers/auth/auth.service';@@ -24,6 +27,22 @@ export class LemmyProvider extends SocialAbstract implements SocialProvider {}dto = LemmySettingsDto;+ override async checkValidity(+ items: Array<ValidityMedia[]>+ ): Promise<string | true> {+ const [firstItems] = items ?? [];+ if (+ firstItems?.length &&+ (firstItems?.[0]?.path?.indexOf?.('png') ?? -1) === -1 &&+ (firstItems?.[0]?.path?.indexOf?.('jpg') ?? -1) === -1 &&+ (firstItems?.[0]?.path?.indexOf?.('jpef') ?? -1) === -1 &&+ (firstItems?.[0]?.path?.indexOf?.('gif') ?? -1) === -1+ ) {+ return 'You can set only one picture for a cover';+ }+ return true;+ }+async customFields() {return [{diff --git a/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts b/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.tsindex b74f9868b..331ebceeb 100644--- a/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts@@ -9,7 +9,10 @@ import sharp from 'sharp';import { lookup } from 'mime-types';import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';import { hasExtension } from '@gitroom/helpers/utils/has.extension';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { Integration } from '@prisma/client';import { PostPlug } from '@gitroom/helpers/decorators/post.plug';import { LinkedinDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/linkedin.dto';@@ -42,6 +45,32 @@ export class LinkedinProvider extends SocialAbstract implements SocialProvider {return 3000;}+ override async checkValidity(+ posts: Array<ValidityMedia[]>,+ vals: any+ ): Promise<string | true> {+ const [firstPost, ...restPosts] = posts ?? [];++ if (+ vals?.post_as_images_carousel &&+ ((firstPost?.length ?? 0) < 2 ||+ firstPost?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1))+ ) {+ return 'Carousel can only be created with 2 or more images and no videos.';+ }++ if (+ (firstPost?.length ?? 0) > 1 &&+ firstPost?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1)+ ) {+ return 'Can have maximum 1 media when selecting a video.';+ }+ if (restPosts?.some((p) => (p?.length ?? 0) > 0)) {+ return 'Comments can only contain text.';+ }+ return true;+ }+override handleErrors(body: string):diff --git a/libraries/nestjs-libraries/src/integrations/social/pinterest.provider.ts b/libraries/nestjs-libraries/src/integrations/social/pinterest.provider.tsindex 0b15ec1a0..649042f4b 100644--- a/libraries/nestjs-libraries/src/integrations/social/pinterest.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/pinterest.provider.ts@@ -13,6 +13,7 @@ import { timer } from '@gitroom/helpers/utils/timer';import {BadBody,SocialAbstract,+ ValidityMedia,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import dayjs from 'dayjs';import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';@@ -43,6 +44,45 @@ export class PinterestProviderdto = PinterestSettingsDto;+ override async checkValidity(+ [firstItem]: Array<ValidityMedia[]>+ ): Promise<string | true> {+ const isMp4 = firstItem?.find(+ (item) => (item?.path?.indexOf?.('mp4') ?? -1) > -1+ );+ const isPicture = firstItem?.find(+ (item) => (item?.path?.indexOf?.('mp4') ?? -1) === -1+ );+ if ((firstItem?.length ?? 0) === 0) {+ return 'Requires at least one media';+ }+ if ((firstItem?.length ?? 0) > 5) {+ return 'You can only have up to 5 media items';+ }+ if (isMp4 && firstItem?.length !== 2 && !isPicture) {+ return 'If posting a video you have to also include a cover image as second media';+ }+ if (isMp4 && (firstItem?.length ?? 0) > 2) {+ return 'If posting a video you can only have two media items';+ }++ if (+ (firstItem?.length ?? 0) > 1 &&+ firstItem?.every((p) => (p?.path?.indexOf?.('mp4') ?? -1) === -1)+ ) {+ const loadAll = await Promise.all(+ firstItem?.map((p) => this.getImageDimensions(p?.path)) ?? []+ );+ const checkAllTheSameWidthHeight = loadAll?.every((p, i, arr) => {+ return p?.width === arr?.[0]?.width && p?.height === arr?.[0]?.height;+ });+ if (!checkAllTheSameWidthHeight) {+ return 'Requires all images to have the same width and height';+ }+ }+ return true;+ }+editor = 'normal' as const;public override handleErrors(body: string):diff --git a/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts b/libraries/nestjs-libraries/src/integrations/social/reddit.provider.tsindex bfd4d666d..8f98245d4 100644--- a/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/reddit.provider.ts@@ -8,7 +8,10 @@ import { makeId } from '@gitroom/nestjs-libraries/services/make.is';import { RedditSettingsDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/reddit.dto';import { timer } from '@gitroom/helpers/utils/timer';import { groupBy } from 'lodash';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import {+ SocialAbstract,+ ValidityMedia,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { lookup } from 'mime-types';import axios from 'axios';import WebSocket from 'ws';@@ -32,6 +35,29 @@ export class RedditProvider extends SocialAbstract implements SocialProvider {return 10000;}+ override async checkValidity(+ posts: Array<ValidityMedia[]>,+ settings: any+ ): Promise<string | true> {+ if (+ settings?.subreddit?.some(+ (p: any) => p?.value?.type === 'media' && posts?.[0]?.length !== 1+ )+ ) {+ return 'When posting a media post, you must attached exactly one media file.';+ }++ if (+ posts?.some((p) =>+ p?.some((a) => !a?.thumbnail && (a?.path?.indexOf?.('mp4') ?? -1) > -1)+ )+ ) {+ return 'You must attach a thumbnail to your video post.';+ }++ return true;+ }+async refreshToken(refreshToken: string): Promise<AuthTokenDetails> {const { access_token: accessToken, expires_in: expiresIn } = await (await this.fetch('https://www.reddit.com/api/v1/access_token', {diff --git a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.tsindex a48598a8d..f8b706d3d 100644--- a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts+++ b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts@@ -145,6 +145,11 @@ export interface SocialProviderrefreshCron?: boolean;dto?: any;maxLength: (additionalSettings?: any) => number;+ checkValidity(+ posts: Array<{ path: string; thumbnail?: string }[]>,+ settings: any,+ additionalSettings: any[]+ ): Promise<string | true>;isWeb3?: boolean;isChromeExtension?: boolean;extensionCookies?: { name: string; domain: string }[];diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.tsindex 7cc068bc9..9100540db 100644--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts@@ -9,6 +9,7 @@ import dayjs from 'dayjs';import {BadBody,SocialAbstract,+ ValidityMedia,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { TikTokDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/tiktok.dto';import { timer } from '@gitroom/helpers/utils/timer';@@ -39,6 +40,27 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {return 2000;}+ override async checkValidity(+ items: Array<ValidityMedia[]>+ ): Promise<string | true> {+ const [firstItems] = items ?? [];+ if ((firstItems?.length ?? 0) === 0) {+ return 'No video / images selected';+ }+ if (+ (firstItems?.length ?? 0) > 1 &&+ firstItems?.some((p) => (p?.path?.indexOf?.('mp4') ?? -1) > -1)+ ) {+ return 'Only pictures are supported when selecting multiple items';+ } else if (+ firstItems?.length !== 1 &&+ (firstItems?.[0]?.path?.indexOf?.('mp4') ?? -1) > -1+ ) {+ return 'You need one media';+ }+ return true;+ }+override handleErrors(body: string):| {type: 'refresh-token' | 'bad-body';diff --git a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts b/libraries/nestjs-libraries/src/integrations/social/x.provider.tsindex 5181635dd..e7b972ec1 100644--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts@@ -39,8 +39,13 @@ export class XProvider extends SocialAbstract implements SocialProvider {editor = 'normal' as const;dto = XDto;- maxLength(isTwitterPremium: boolean) {- return isTwitterPremium ? 4000 : 200;+ maxLength(additionalSettings?: any) {+ // Accepts either the parsed additionalSettings array (from validation) or a+ // plain boolean (legacy callers). "Verified" => premium => higher limit.+ const isTwitterPremium = Array.isArray(additionalSettings)+ ? !!additionalSettings.find((p: any) => p?.title === 'Verified')?.value+ : !!additionalSettings;+ return isTwitterPremium ? 4000 : 280;}override handleErrors(body: string):diff --git a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.tsindex 1a7f33fad..7674a23e7 100644--- a/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/youtube.provider.ts@@ -13,6 +13,7 @@ import { YoutubeSettingsDto } from '@gitroom/nestjs-libraries/dtos/posts/provideimport {BadBody,SocialAbstract,+ ValidityMedia,} from '@gitroom/nestjs-libraries/integrations/social.abstract';import * as process from 'node:process';import dayjs from 'dayjs';@@ -71,6 +72,19 @@ export class YoutubeProvider extends SocialAbstract implements SocialProvider {return 5000;}+ override async checkValidity(+ items: Array<ValidityMedia[]>+ ): Promise<string | true> {+ const [firstItems] = items ?? [];+ if (items?.[0]?.length !== 1) {+ return 'You need one media';+ }+ if ((firstItems?.[0]?.path?.indexOf?.('mp4') ?? -1) === -1) {+ return 'Item must be a video';+ }+ return true;+ }+override handleErrors(body: string):| {type: 'refresh-token' | 'bad-body';