📨 The ultimate agentic social media scheduling tool 🤖
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: inline picture
Nevo David2aae02fe034f
diff --git a/apps/frontend/src/app/global.scss b/apps/frontend/src/app/global.scssindex 0c6d5cc03..a6ea6d537 100644--- a/apps/frontend/src/app/global.scss+++ b/apps/frontend/src/app/global.scss@@ -604,6 +604,17 @@ html[dir='rtl'] [dir='ltr'] {color: #ae8afc;}+.ProseMirror img:not(.ProseMirror-separator) {+ max-height: 300px;+ margin: 16px 0;+ border-radius: 6px;+ cursor: grab;+}++.ProseMirror img.ProseMirror-selectednode {+ outline: 2px solid var(--new-btn-primary);+}+.ProseMirror ul,.preview ul {list-style: disc;@@ -637,6 +648,22 @@ html[dir='rtl'] [dir='ltr'] {font-weight: bold;}+// paragraphs stay tight, in most channels every line is a paragraph+.ProseMirror h1,+.ProseMirror h2,+.ProseMirror h3 {+ margin: 16px 0 8px;+ line-height: 1.3;+}++.ProseMirror ul {+ margin: 8px 0;+}++.ProseMirror li + li {+ margin-top: 4px;+}+.preview p {min-height: 24px;}diff --git a/apps/frontend/src/components/launches/helpers/dnd.provider.tsx b/apps/frontend/src/components/launches/helpers/dnd.provider.tsxindex 82ff70c99..2c5931f69 100644--- a/apps/frontend/src/components/launches/helpers/dnd.provider.tsx+++ b/apps/frontend/src/components/launches/helpers/dnd.provider.tsx@@ -3,8 +3,49 @@import { FC, ReactNode } from 'react';import { HTML5Backend } from 'react-dnd-html5-backend';import { DndProvider } from 'react-dnd';++const DRAG_HANDLERS = [+ 'handleTopDragStart',+ 'handleTopDragStartCapture',+ 'handleTopDragEndCapture',+ 'handleTopDragEnter',+ 'handleTopDragEnterCapture',+ 'handleTopDragLeaveCapture',+ 'handleTopDragOver',+ 'handleTopDragOverCapture',+ 'handleTopDrop',+ 'handleTopDropCapture',+];++// the path is kept from the start of the dispatch, the editor can re-render+// the target out of the page before the event bubbles up to the window+const isInsideEditor = (event: Event) =>+ event+ .composedPath()+ .some((node) => (node as HTMLElement).isContentEditable);++// the backend listens to every drag on the window and cancels the native drops+// it doesn't own, so dragging text or pictures inside the post editor did nothing+const CalendarBackend: typeof HTML5Backend = (manager, context, options) => {+ const backend = HTML5Backend(manager, context, options) as any;+ for (const name of DRAG_HANDLERS) {+ const handler = backend[name];+ if (typeof handler !== 'function') {+ continue;+ }++ backend[name] = (event: DragEvent) => {+ if (!isInsideEditor(event)) {+ handler(event);+ }+ };+ }++ return backend;+};+export const DNDProvider: FC<{children: ReactNode;}> = ({ children }) => {- return <DndProvider backend={HTML5Backend}>{children}</DndProvider>;+ return <DndProvider backend={CalendarBackend}>{children}</DndProvider>;};diff --git a/apps/frontend/src/components/media/media.component.tsx b/apps/frontend/src/components/media/media.component.tsxindex 4eadb0e84..eccfad834 100644--- a/apps/frontend/src/components/media/media.component.tsx+++ b/apps/frontend/src/components/media/media.component.tsx@@ -655,6 +655,7 @@ export const MultiMediaComponent: FC<{onClose?: () => void;toolBar?: React.ReactNode;information?: React.ReactNode;+ insertInContent?: (media: Array<{ id: string; path: string }>) => void;onChange: (event: {target: {name: string;@@ -679,6 +680,7 @@ export const MultiMediaComponent: FC<{toolBar,information,mediaNotAvailable,+ insertInContent,} = props;const user = useUser();const modals = useModals();@@ -704,6 +706,11 @@ export const MultiMediaComponent: FC<{}[]) => {const mediaArray = Array.isArray(m) ? m : [m];+ if (insertInContent) {+ insertInContent(mediaArray);+ return;+ }+const newMedia = [...(currentMedia || []), ...mediaArray];setCurrentMedia(newMedia);onChange({@@ -713,7 +720,7 @@ export const MultiMediaComponent: FC<{},});},- [currentMedia]+ [currentMedia, insertInContent]);const showModal = useCallback(() => {modals.openModal({@@ -724,10 +731,14 @@ export const MultiMediaComponent: FC<{size: 'calc(100% - 80px)',height: 'calc(100% - 80px)',children: (close) => (- <MediaBox setMedia={changeMedia} closeModal={close} />+ <MediaBox+ setMedia={changeMedia}+ closeModal={close}+ type={insertInContent ? 'image' : undefined}+ />),});- }, [changeMedia, t]);+ }, [changeMedia, insertInContent, t]);const clearMedia = useCallback((topIndex: number) => () => {@@ -857,12 +868,16 @@ export const MultiMediaComponent: FC<{</div></div>- <ThirdPartyMedia allData={allData} onChange={changeMedia} />+ {!insertInContent && (+ <ThirdPartyMedia allData={allData} onChange={changeMedia} />+ )}{!!user?.tier?.ai && (<><AiImage value={text} onChange={changeMedia} />- <AiVideo value={text} onChange={changeMedia} />+ {!insertInContent && (+ <AiVideo value={text} onChange={changeMedia} />+ )}</>)}</div>diff --git a/apps/frontend/src/components/new-launch/editor.tsx b/apps/frontend/src/components/new-launch/editor.tsxindex 83214e2a0..83a55a98a 100644--- a/apps/frontend/src/components/new-launch/editor.tsx+++ b/apps/frontend/src/components/new-launch/editor.tsx@@ -38,6 +38,7 @@ import {useEditor,EditorContent,Extension,+ Node,mergeAttributes,} from '@tiptap/react';import Document from '@tiptap/extension-document';@@ -50,12 +51,13 @@ import { History } from '@tiptap/extension-history';import { BulletList, ListItem } from '@tiptap/extension-list';import { Bullets } from '@gitroom/frontend/components/new-launch/bullets.component';import Heading from '@tiptap/extension-heading';+import { Slice } from '@tiptap/pm/model';import { HeadingComponent } from '@gitroom/frontend/components/new-launch/heading.component';import Mention from '@tiptap/extension-mention';import { suggestion } from '@gitroom/frontend/components/new-launch/mention.component';import { useFetch } from '@gitroom/helpers/utils/custom.fetch';import { AComponent } from '@gitroom/frontend/components/new-launch/a.component';-import { Placeholder } from '@tiptap/extensions';+import { Dropcursor, Placeholder, TrailingNode } from '@tiptap/extensions';import { useToaster } from '@gitroom/react/toaster/toaster';import { InformationComponent } from '@gitroom/frontend/components/launches/information.component';import {@@ -98,6 +100,48 @@ const InterceptUnderlineShortcut = Extension.create({},});+const EditorImage = Node.create({+ name: 'image',+ group: 'block',+ draggable: true,++ addAttributes() {+ return {+ src: { default: null },+ alt: { default: null },+ };+ },++ // same rule as the server sanitizer, any other source is dropped on save+ parseHTML() {+ return [{ tag: 'img[src^="https://"], img[src^="http://"]' }];+ },++ renderHTML({ HTMLAttributes }) {+ return ['img', HTMLAttributes];+ },+});++const insertImages = (+ editor: any,+ media: { path: string; alt?: string }[]+) => {+ if (!media.length) {+ return;+ }++ editor+ ?.chain()+ ?.focus()+ ?.insertContent(+ media.map((p) => ({+ type: 'image',+ attrs: { src: p.path, alt: p.alt },+ }))+ )+ ?.run();+};+export const EditorWrapper: FC<{totalPosts: number;value: string;@@ -130,6 +174,7 @@ export const EditorWrapper: FC<{postComment,dummy,editor,+ inlineImages,loadedState,setLoadedState,selectedIntegration,@@ -164,6 +209,7 @@ export const EditorWrapper: FC<{appendGlobalValueMedia: state.appendGlobalValueMedia,postComment: state.postComment,editor: state.editor,+ inlineImages: state.inlineImages,loadedState: state.loaded,setLoadedState: state.setLoaded,selectedIntegration: state.selectedIntegrations,@@ -436,6 +482,7 @@ export const EditorWrapper: FC<{<Editorcomments={comments}editorType={editor}+ inlineImages={editor === 'html' && inlineImages && index === 0}allValues={items}onChange={changeValue(index)}key={index}@@ -527,6 +574,7 @@ export const EditorWrapper: FC<{export const Editor: FC<{editorType?: 'none' | 'normal' | 'markdown' | 'html';+ inlineImages?: boolean;totalPosts: number;value: string;num?: number;@@ -547,6 +595,7 @@ export const Editor: FC<{}> = (props) => {const {editorType = 'normal',+ inlineImages = false,allValues,pictures,setImages,@@ -564,9 +613,18 @@ export const Editor: FC<{const toaster = useToaster();const editorRef = useRef<undefined | { editor: any }>(undefined);const [loading, setLoading] = useState(false);+ // the uploader is created once, so it reads the latest value from here+ const inlineImagesRef = useRef(inlineImages);+ inlineImagesRef.current = inlineImages;const uppy = useUppyUploader({onUploadSuccess: (result: any) => {+ const editor = editorRef?.current?.editor;+ if (inlineImagesRef.current && editor) {+ insertImages(editor, result);+ return;+ }+appendImages(result);},allowedFileTypes: 'image/*,video/mp4',@@ -574,8 +632,36 @@ export const Editor: FC<{onEnd: () => setLoading(false),});+ // inline images go into the content, which only holds pictures+ const filterFiles = useCallback(+ (files: File[]) => {+ if (!inlineImages) {+ return files;+ }++ const images = files.filter((file) => file.type.startsWith('image/'));+ if (images.length < files.length) {+ toaster.show(+ t(+ 'only_images_can_be_added_to_the_content',+ 'Only images can be added to the content'+ ),+ 'warning'+ );+ }++ return images;+ },+ [inlineImages, toaster, t]+ );+const onDrop = useCallback(- (acceptedFiles: File[]) => {+ (droppedFiles: File[]) => {+ const acceptedFiles = filterFiles(droppedFiles);+ if (!acceptedFiles.length) {+ return;+ }+const totalSize = acceptedFiles.reduce((acc, file) => acc + file.size, 0);if (totalSize > MAX_UPLOAD_SIZE) {@@ -595,31 +681,43 @@ export const Editor: FC<{uppy.addFile(file);}},- [uppy, toaster, t]+ [uppy, toaster, t, filterFiles]);const paste = useCallback(- async (event: ClipboardEvent | File[]) => {+ (event: ClipboardEvent | File[], slice?: Slice) => {if (num > 0 && comments === 'no-media') {- return;+ return false;}// @ts-ignoreconst clipboardItems = event.clipboardData?.items;if (!clipboardItems) {- return;+ return false;}- const files: File[] = [];+ const clipboardFiles: File[] = [];// @ts-ignorefor (const item of clipboardItems) {if (item.kind === 'file') {const file = item.getAsFile();if (file) {- files.push(file);+ clipboardFiles.push(file);}}}+ // a copied picture also comes as html linking to the site it was copied+ // from, so the file wins unless the html has text of its own+ // @ts-ignore+ const html = event.clipboardData.getData('text/html');+ const uploadInline =+ !!clipboardFiles.length &&+ (!html || !slice?.content.textBetween(0, slice.content.size).trim());+ if (inlineImages && !uploadInline) {+ return false;+ }++ const files = filterFiles(clipboardFiles);const totalSize = files.reduce((acc, file) => acc + file.size, 0);if (totalSize > MAX_UPLOAD_SIZE) {@@ -630,7 +728,7 @@ export const Editor: FC<{),'warning');- return;+ return false;}if (files.length > 0) {@@ -640,12 +738,41 @@ export const Editor: FC<{for (const file of files) {uppy.addFile(file);}++ // the uploaded pictures replace the pasted html+ return inlineImages;},- [uppy, num, comments, toaster, t]+ [uppy, num, comments, toaster, t, inlineImages, filterFiles]);+ // a drag that starts on the page (like moving a picture inside the editor)+ // is not an upload, but Chrome reports a dragged <img> as "Files"+ const [internalDrag, setInternalDrag] = useState(false);+ useEffect(() => {+ if (!inlineImages) {+ return;+ }++ const dragStart = (event: DragEvent) => {+ if (!event.defaultPrevented) {+ setInternalDrag(true);+ }+ };+ const dragEnd = () => setInternalDrag(false);++ window.addEventListener('dragstart', dragStart);+ window.addEventListener('dragend', dragEnd);+ window.addEventListener('drop', dragEnd);+ return () => {+ window.removeEventListener('dragstart', dragStart);+ window.removeEventListener('dragend', dragEnd);+ window.removeEventListener('drop', dragEnd);+ setInternalDrag(false);+ };+ }, [inlineImages]);+const { getRootProps, isDragActive } = useDropzone({- onDrop: (files) => {+ onDrop: (files, _, event) => {if (loading) {toaster.show('Upload current in progress, please wait and then try again.',@@ -653,9 +780,23 @@ export const Editor: FC<{);return;}++ if (inlineImages) {+ // uploads land at the cursor, move it to where the files were dropped+ const editor = editorRef?.current?.editor;+ const { clientX, clientY } = event as DragEvent;+ const position = editor?.view?.posAtCoords({+ left: clientX,+ top: clientY,+ });+ if (position) {+ editor.commands.focus(position.pos);+ }+ }+onDrop(files);},- noDrag: num > 0 && comments === 'no-media',+ noDrag: internalDrag || (num > 0 && comments === 'no-media'),});const valueWithoutHtml = useMemo(() => {@@ -670,15 +811,17 @@ export const Editor: FC<{[props.value, id]);- const [loadedEditor, setLoadedEditor] = useState(editorType);+ // the extensions are fixed once the editor is created, rebuild it when they change+ const editorKey = `${editorType}-${inlineImages}`;+ const [loadedEditor, setLoadedEditor] = useState(editorKey);const [showEditor, setShowEditor] = useState(true);useEffect(() => {- if (editorType === loadedEditor) {+ if (editorKey === loadedEditor) {return;}- setLoadedEditor(editorType);+ setLoadedEditor(editorKey);setShowEditor(false);- }, [editorType]);+ }, [editorKey]);useEffect(() => {if (showEditor) {@@ -716,6 +859,7 @@ export const Editor: FC<{<OnlyEditorvalue={props.value}editorType={editorType}+ inlineImages={inlineImages}onChange={props.onChange}paste={paste}ref={editorRef}@@ -765,6 +909,12 @@ export const Editor: FC<{value={props.pictures}dummy={dummy}name="image"+ insertInContent={+ inlineImages+ ? (media) =>+ insertImages(editorRef?.current?.editor, media)+ : undefined+ }information={<InformationComponentisPicture={pictures?.length > 0}@@ -859,11 +1009,12 @@ export const OnlyEditor = forwardRef<any,{editorType: 'none' | 'normal' | 'markdown' | 'html';+ inlineImages?: boolean;value: string;onChange: (value: string) => void;- paste?: (event: ClipboardEvent | File[]) => void;+ paste?: (event: ClipboardEvent | File[], slice?: Slice) => boolean;}->(({ editorType, value, onChange, paste }, ref) => {+>(({ editorType, inlineImages, value, onChange, paste }, ref) => {const t = useT();const fetch = useFetch();@@ -1023,6 +1174,21 @@ export const OnlyEditor = forwardRef<}),]: []),+ ...(inlineImages+ ? [+ EditorImage,+ Dropcursor.configure({+ color: 'var(--new-btn-primary)',+ width: 2,+ }),+ // a picture can't hold the cursor, keep a paragraph after a+ // trailing one so clicking below the content doesn't select it+ TrailingNode.configure({+ node: 'paragraph',+ notAfter: ['heading', 'bulletList'],+ }),+ ]+ : []),History.configure({depth: 100, // default is 100newGroupDelay: 100, // default is 500ms@@ -1031,8 +1197,9 @@ export const OnlyEditor = forwardRef<content: value || '',shouldRerenderOnTransaction: true,immediatelyRender: false,- // @ts-ignore- onPaste: paste,+ editorProps: {+ handlePaste: (view, event, slice) => !!paste?.(event as any, slice),+ },onUpdate: (innerProps) => {onChange?.(innerProps.editor.getHTML());},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 1d31a2aed..58087ce66 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@@ -8,7 +8,7 @@ import React, {useImperativeHandle,useMemo,} from 'react';-import { useForm, FormProvider } from 'react-hook-form';+import { useForm, useWatch, FormProvider } from 'react-hook-form';import { IsOptional } from 'class-validator';import { classValidatorResolver } from '@hookform/resolvers/class-validator';import { useLaunchStore } from '@gitroom/frontend/components/new-launch/store';@@ -49,6 +49,7 @@ export const withProvider = function <T extends object>(params: {}>;dto?: any;maximumCharacters?: number | ((settings: any) => number);+ inlineImages?: boolean | ((values: any) => boolean);}) {const {postComment,@@ -75,6 +76,7 @@ export const withProvider = function <T extends object>(params: {allIntegrations,setPostComment,setEditor,+ setInlineImages,dummy,setChars,setComments,@@ -97,6 +99,7 @@ export const withProvider = function <T extends object>(params: {setTotalChars: state.setTotalChars,setPostComment: state.setPostComment,setEditor: state.setEditor,+ setInlineImages: state.setInlineImages,setChars: state.setChars,selectedIntegration: state.selectedIntegrations.find((p) => p.integration.id === props.id@@ -125,6 +128,7 @@ export const withProvider = function <T extends object>(params: {setPostComment(PostComment.ALL);setTotalChars(0);setEditor('normal');+ setInlineImages(false);}if (current) {@@ -178,6 +182,21 @@ export const withProvider = function <T extends object>(params: {reValidateMode: 'onChange',});+ // the post settings can turn inline images on, like an X article+ const values = useWatch({+ control: form.control,+ disabled: typeof params.inlineImages !== 'function',+ });+ const inlineImages =+ typeof params.inlineImages === 'function'+ ? params.inlineImages(values)+ : !!params.inlineImages;+ useEffect(() => {+ if (current) {+ setInlineImages(inlineImages);+ }+ }, [current, inlineImages]);+useImperativeHandle(ref,() => ({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 05bb3fa90..462405b86 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@@ -30,4 +30,5 @@ export default withProvider({CustomPreviewComponent: undefined,dto: ListmonkDto,maximumCharacters: 300000,+ inlineImages: true,});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 7876038fc..7ad52173e 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@@ -50,4 +50,5 @@ export default withProvider({CustomPreviewComponent: undefined, // WordpressPreview,dto: WordpressDto,maximumCharacters: 100000,+ inlineImages: true,});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 11625b431..e98bd0c1c 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@@ -145,4 +145,5 @@ export default withProvider({}return 280;},+ inlineImages: (values) => values?.post_type === 'article',});diff --git a/apps/frontend/src/components/new-launch/store.ts b/apps/frontend/src/components/new-launch/store.tsindex 2ea620b82..1c0f51796 100644--- a/apps/frontend/src/components/new-launch/store.ts+++ b/apps/frontend/src/components/new-launch/store.ts@@ -27,6 +27,7 @@ export interface SelectedIntegrations {interface StoreState {editor: undefined | 'none' | 'normal' | 'markdown' | 'html';+ inlineImages: boolean;loaded: boolean;date: dayjs.Dayjs;postComment: PostComment;@@ -129,6 +130,7 @@ interface StoreState {setActivateExitButton?: (activateExitButton: boolean) => void;setDummy: (dummy: boolean) => void;setEditor: (editor: 'none' | 'normal' | 'markdown' | 'html') => void;+ setInlineImages: (inlineImages: boolean) => void;setLoaded?: (loaded: boolean) => void;setChars: (id: string, chars: number) => void;chars: Record<string, number>;@@ -137,6 +139,7 @@ interface StoreState {const initialState = {editor: undefined as undefined,+ inlineImages: false,loaded: true,dummy: false,comments: true,@@ -187,6 +190,7 @@ export const useLaunchStore = create<StoreState>()((set) => ({? {current: 'global',editor: 'normal',+ inlineImages: false,}: {}),};@@ -617,6 +621,10 @@ export const useLaunchStore = create<StoreState>()((set) => ({set((state) => ({editor,})),+ setInlineImages: (inlineImages: boolean) =>+ set((state) => ({+ inlineImages,+ })),setLoaded: (loaded: boolean) =>set((state) => ({loaded,diff --git a/apps/orchestrator/src/activities/post.activity.ts b/apps/orchestrator/src/activities/post.activity.tsindex 5c18c3475..ace280485 100644--- a/apps/orchestrator/src/activities/post.activity.ts+++ b/apps/orchestrator/src/activities/post.activity.ts@@ -361,7 +361,8 @@ export class PostActivity {true,false,!/<\/?[a-z][\s\S]*>/i.test(p.content),- getIntegration.mentionFormat+ getIntegration.mentionFormat,+ !!getIntegration.inlineImages?.(JSON.parse(p.settings || '{}'))),settings: JSON.parse(p.settings || '{}'),media: await this._postService.updateMedia(diff --git a/i18n.lock b/i18n.lockindex 1f9a81b9d..93a43fef5 100644--- a/i18n.lock+++ b/i18n.lock@@ -706,6 +706,7 @@ checksums:delete_post_tooltip: bcf081392c76d2f2a8522944ddd36b78drop_files_here_to_upload: a7971302d02a19a461c519cffedfa5e5insert_emoji: 6e2ab0e239c0ee87d385b1cd17185e00+ only_images_can_be_added_to_the_content: 39229242be2e514ce641c5edce713caawrite_something: bc9257cede62880c411001e61310ca43click_channel_to_add: 7dc67c45eba252d1fa931e5a101d568bconnect_your_channels: a8303310a9cc5f4e11510f8f55c0978ddiff --git a/libraries/helpers/src/utils/sanitize.post.content.ts b/libraries/helpers/src/utils/sanitize.post.content.tsindex 204fee139..d7a571069 100644--- a/libraries/helpers/src/utils/sanitize.post.content.ts+++ b/libraries/helpers/src/utils/sanitize.post.content.ts@@ -13,6 +13,7 @@ const ALLOWED_TAGS = ['h2','h3','span',+ 'img',];const ALLOWED_ATTR = [@@ -22,8 +23,21 @@ const ALLOWED_ATTR = ['class','data-mention-id','data-mention-label',+ 'src',+ 'alt',];+// <img> keeps data: URIs whatever ALLOWED_URI_REGEXP says, so a picture+// that doesn't point to a real file is dropped+DOMPurify.addHook('uponSanitizeElement', (node, data) => {+ if (+ data.tagName === 'img' &&+ !/^https?:\/\//i.test((node as Element).getAttribute('src') || '')+ ) {+ node.parentNode?.removeChild(node);+ }+});+export const sanitizePostContent = (value: unknown): string => {if (typeof value !== 'string' || !value) {return '';diff --git a/libraries/helpers/src/utils/strip.html.validation.ts b/libraries/helpers/src/utils/strip.html.validation.tsindex d780fc714..0b1c9eada 100644--- a/libraries/helpers/src/utils/strip.html.validation.ts+++ b/libraries/helpers/src/utils/strip.html.validation.ts@@ -137,7 +137,8 @@ export const stripHtmlValidation = (replaceBold = false,none = false,plain = false,- convertMentionFunction?: (idOrHandle: string, name: string) => string+ convertMentionFunction?: (idOrHandle: string, name: string) => string,+ inlineImages = false): string => {if (plain) {return val;@@ -156,7 +157,12 @@ export const stripHtmlValidation = (}if (type === 'html') {- return striptags(convertMention(value, convertMentionFunction), [+ return striptags(+ convertMention(+ inlineImages ? convertImages(value) : value,+ convertMentionFunction+ ),+ ['ul','li','h1',@@ -166,7 +172,9 @@ export const stripHtmlValidation = ('strong','u','a',- ])+ ...(inlineImages ? ['img'] : []),+ ]+ ).replace(/>/gi, '>').replace(/</gi, '<').replace(/&/gi, '&')@@ -268,6 +276,22 @@ export const stripHtmlValidation = (.replace(/</gi, '<');};+// keeps only an http(s) src and the alt of a picture, a value holding a quote+// is dropped since " is decoded afterwards and would close the attribute+export const convertImages = (value: string) => {+ return value.replace(/<img\b[^>]*>/gi, (match) => {+ const src = /\ssrc="(https?:\/\/[^"]*)"/i.exec(match)?.[1];+ const alt = /\salt="([^"]*)"/i.exec(match)?.[1];+ if (!src || src.includes('"')) {+ return '';+ }++ return `<img src="${src}"${+ alt && !alt.includes('"') ? ` alt="${alt}"` : ''+ }>`;+ });+};+export const convertMention = (value: string,process?: (idOrHandle: string, name: string) => stringdiff --git a/libraries/helpers/src/utils/valid.url.path.ts b/libraries/helpers/src/utils/valid.url.path.tsindex aeedbe415..c270c27c0 100644--- a/libraries/helpers/src/utils/valid.url.path.ts+++ b/libraries/helpers/src/utils/valid.url.path.ts@@ -25,16 +25,21 @@ export class ValidUrlExtension implements ValidatorConstraintInterface {}}+// also used for media urls that don't come through a DTO, like pictures in a post body+export const isAllowedUploadPath = (text: string) => {+ if (!process.env.RESTRICT_UPLOAD_DOMAINS) {+ return true;+ }++ return (+ (text || 'invalid url').indexOf(process.env.RESTRICT_UPLOAD_DOMAINS) > -1+ );+};+@ValidatorConstraint({ name: 'checkValidPath', async: false })export class ValidUrlPath implements ValidatorConstraintInterface {validate(text: string, args: ValidationArguments) {- if (!process.env.RESTRICT_UPLOAD_DOMAINS) {- return true;- }-- return (- (text || 'invalid url').indexOf(process.env.RESTRICT_UPLOAD_DOMAINS) > -1- );+ return isAllowedUploadPath(text);}defaultMessage(args: ValidationArguments) {diff --git a/libraries/nestjs-libraries/src/integrations/social/listmonk.provider.ts b/libraries/nestjs-libraries/src/integrations/social/listmonk.provider.tsindex 9366e5030..86d2ee20c 100644--- a/libraries/nestjs-libraries/src/integrations/social/listmonk.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/listmonk.provider.ts@@ -26,6 +26,10 @@ export class ListmonkProvider extends SocialAbstract implements SocialProvider {return 100000000;}+ inlineImages() {+ return true;+ }+async customFields() {return [{@@ -189,6 +193,10 @@ export class ListmonkProvider extends SocialAbstract implements SocialProvider {font-size: 15px;line-height: 1.6;}+.content img {+ max-width: 100%;+ height: auto;+}</style><div class="hidden-preheader"style="display:none !important; visibility:hidden; opacity:0; overflow:hidden;diff --git a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.tsindex 5b6a7a94a..52bf2fc43 100644--- a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts+++ b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts@@ -197,6 +197,7 @@ export interface SocialProviderisChromeExtension?: boolean;extensionCookies?: { name: string; domain: string }[];editor: 'none' | 'normal' | 'markdown' | 'html';+ inlineImages?: (settings?: any) => boolean;customFields?: () => Promise<{key: string;diff --git a/libraries/nestjs-libraries/src/integrations/social/wordpress.provider.ts b/libraries/nestjs-libraries/src/integrations/social/wordpress.provider.tsindex 8777a7c4b..80ba83cd6 100644--- a/libraries/nestjs-libraries/src/integrations/social/wordpress.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/wordpress.provider.ts@@ -32,6 +32,10 @@ export class WordpressProviderreturn 100000;}+ inlineImages() {+ return true;+ }+async generateAuthUrl() {const state = makeSecureId(6);return {diff --git a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts b/libraries/nestjs-libraries/src/integrations/social/x.provider.tsindex 782e8d872..bcab39263 100644--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts@@ -29,6 +29,7 @@ import { stripLinks as removeLinks } from '@gitroom/helpers/utils/strip.links';import { XDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/x.dto';import { Rules } from '@gitroom/nestjs-libraries/chat/rules.description.decorator';import { hasExtension } from '@gitroom/helpers/utils/has.extension';+import { isAllowedUploadPath } from '@gitroom/helpers/utils/valid.url.path';// Travels through the workflow history between postPending, checkPostStatus// and finalizePost - keep it small JSON (media ids and the tweet content).@@ -52,6 +53,8 @@ type XPendingData = {// Article cover selected in the settings, uploaded separately from the post// media (which is embedded in the article body).coverMediaId?: string;+ // Pictures placed inside the article body, by their src.+ inlineMediaIds?: Record<string, string>;// Media still transcoding on X's side, waiting for STATUS = succeeded.processingIds: string[];// Arm -> confirm -> publish handshake (same as the Facebook story flow):@@ -103,6 +106,11 @@ export class XProvider extends SocialAbstract implements SocialProvider {return isTwitterPremium ? 4000 : 280;}+ // Article bodies hold pictures, tweets only take attachments.+ inlineImages(settings?: any) {+ return settings?.post_type === 'article';+ }+// With `editor = 'html'` the activity hands the provider HTML (needed for// articles); everything that becomes a tweet has to be flattened back to the// plain text X expects - same output the old 'normal' editor produced.@@ -847,6 +855,19 @@ export class XProvider extends SocialAbstract implements SocialProvider {).media['article-cover']?.[0]: undefined;+ // Pictures placed in the article body are uploaded the same way and take+ // the place of their <img> in finalizeArticle.+ const inlineImages = isArticle+ ? [...new Set(this.articleImages(parseFragment(firstPost.message)))]+ : [];+ const { media: inlineMedia } = await this.uploadMediaEntries(+ client,+ inlineImages.map(+ (path, index) => ({ id: String(index), media: [{ path }] } as any)+ ),+ true+ );+return [{id: firstPost.id,@@ -870,6 +891,16 @@ export class XProvider extends SocialAbstract implements SocialProvider {},mediaIds: (media[firstPost.id] || []).filter((f) => f),...(coverMediaId ? { coverMediaId } : {}),+ ...(inlineImages.length+ ? {+ inlineMediaIds: Object.fromEntries(+ inlineImages.map((path, index) => [+ path,+ inlineMedia[String(index)]?.[0],+ ])+ ),+ }+ : {}),processingIds,} as XPendingData,},@@ -969,14 +1000,34 @@ export class XProvider extends SocialAbstract implements SocialProvider {};}+ // Pictures of the article body at any depth. Only http(s) files from where+ // uploads are allowed are kept: anything else would be read from the disk or+ // fetched from an arbitrary site when it's uploaded to X.+ private articleImages(node: any): string[] {+ if (node.nodeName === 'img') {+ const src =+ (node.attrs || []).find((a: any) => a.name === 'src')?.value || '';+ return /^https?:\/\//i.test(src) && isAllowedUploadPath(src) ? [src] : [];+ }++ return (node.childNodes || []).flatMap((child: any) =>+ this.articleImages(child)+ );+ }+// Converts the editor HTML (already sanitized by stripHtmlValidation's- // 'html' mode - only p, h1-h3, ul, li, strong, u and a survive) into the- // content_state the X Articles API expects, embedding the post media as- // atomic image blocks at the end (the cover travels separately).+ // 'html' mode - only p, h1-h3, ul, li, strong, u, a and img survive) into+ // the content_state the X Articles API expects. Pictures in the body become+ // atomic image blocks where they are, the post media is appended at the end+ // (the cover travels separately).// X's schema is a snake_case Draft.js dialect with additionalProperties// disallowed: blocks only accept key/text/type/data/entity_ranges/// inline_style_ranges (no depth).- private articleContentState(html: string, embeddedMediaIds: string[]) {+ private articleContentState(+ html: string,+ embeddedMediaIds: string[],+ inlineMediaIds: Record<string, string> = {}+ ) {const blocks: any[] = [];const entities: any[] = [];@@ -1037,10 +1088,38 @@ export class XProvider extends SocialAbstract implements SocialProvider {const pushBlock = (node: any, type: string) => {const ctx = { text: '', styles: [] as any[], entityRanges: [] as any[] };walkInline(node, ctx);- if (!ctx.text.trim()) {- return;+ if (ctx.text.trim()) {+ blocks.push(makeBlock(ctx.text, type, ctx.styles, ctx.entityRanges));+ }++ // pictures inside the node (a list item can hold one) follow its text+ for (const src of this.articleImages(node)) {+ if (inlineMediaIds[src]) {+ pushImage(inlineMediaIds[src]);+ }}- blocks.push(makeBlock(ctx.text, type, ctx.styles, ctx.entityRanges));+ };++ const pushImage = (mediaId: string) => {+ const key = entities.length;+ entities.push({+ key: String(key),+ value: {+ type: 'image',+ mutability: 'immutable',+ data: {+ media_items: [+ // Must match the category the media was uploaded with -+ // lowercase, like the upload endpoint (the uppercase+ // TWEET_IMAGE in the docs example is wrong).+ { media_category: 'tweet_image', media_id: mediaId },+ ],+ },+ },+ });+ blocks.push(+ makeBlock(' ', 'atomic', [], [{ offset: 0, length: 1, key }])+ );};const fragment = parseFragment(html) as any;@@ -1088,25 +1167,7 @@ export class XProvider extends SocialAbstract implements SocialProvider {}for (const mediaId of embeddedMediaIds) {- const key = entities.length;- entities.push({- key: String(key),- value: {- type: 'image',- mutability: 'immutable',- data: {- media_items: [- // Must match the category the media was uploaded with -- // lowercase, like the upload endpoint (the uppercase- // TWEET_IMAGE in the docs example is wrong).- { media_category: 'tweet_image', media_id: mediaId },- ],- },- },- });- blocks.push(- makeBlock(' ', 'atomic', [], [{ offset: 0, length: 1, key }])- );+ pushImage(mediaId);}return { blocks, entities };@@ -1140,7 +1201,8 @@ export class XProvider extends SocialAbstract implements SocialProvider {title: settings.article_title,content_state: this.articleContentState(pendingData.message,- embeddedMediaIds+ embeddedMediaIds,+ pendingData.inlineMediaIds),...(coverMediaId? {diff --git a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json b/libraries/react-shared-libraries/src/translation/locales/ar/translation.jsonindex b8a6dd6e2..a54763d0c 100644--- a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ar/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "حذف المنشور","drop_files_here_to_upload": "أسقط ملفاتك هنا للتحميل","insert_emoji": "إدراج رمز تعبيري",+ "only_images_can_be_added_to_the_content": "يمكن إضافة الصور فقط إلى المحتوى","write_something": "اكتب شيئًا …","click_channel_to_add": "انقر على قناة لإضافتها","connect_your_channels": "قم بتوصيل قنواتك",diff --git a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json b/libraries/react-shared-libraries/src/translation/locales/bn/translation.jsonindex 4f65a827a..31663d694 100644--- a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/bn/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "পোস্ট মুছুন","drop_files_here_to_upload": "আপলোড করতে আপনার ফাইলগুলো এখানে ছেড়ে দিন","insert_emoji": "ইমোজি যুক্ত করুন",+ "only_images_can_be_added_to_the_content": "কনটেন্টে শুধুমাত্র ছবি যোগ করা যায়","write_something": "কিছু লিখুন …","click_channel_to_add": "যোগ করার জন্য একটি চ্যানেলে ক্লিক করুন","connect_your_channels": "আপনার চ্যানেলগুলি সংযোগ করুন",diff --git a/libraries/react-shared-libraries/src/translation/locales/de/translation.json b/libraries/react-shared-libraries/src/translation/locales/de/translation.jsonindex 37a07c121..9f3c2ddb9 100644--- a/libraries/react-shared-libraries/src/translation/locales/de/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/de/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Beitrag löschen","drop_files_here_to_upload": "Dateien hierher ziehen, um sie hochzuladen","insert_emoji": "Emoji einfügen",+ "only_images_can_be_added_to_the_content": "Dem Inhalt können nur Bilder hinzugefügt werden","write_something": "Schreibe etwas …","click_channel_to_add": "Klicke auf einen Kanal, um ihn hinzuzufügen","connect_your_channels": "Verbinde deine Kanäle",diff --git a/libraries/react-shared-libraries/src/translation/locales/en/translation.json b/libraries/react-shared-libraries/src/translation/locales/en/translation.jsonindex 8c860883b..4ead7f9a5 100644--- a/libraries/react-shared-libraries/src/translation/locales/en/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/en/translation.json@@ -704,6 +704,7 @@"delete_post_tooltip": "Delete Post","drop_files_here_to_upload": "Drop your files here to upload","insert_emoji": "Insert Emoji",+ "only_images_can_be_added_to_the_content": "Only images can be added to the content","write_something": "Write something …","click_channel_to_add": "Click a channel to add it","connect_your_channels": "Connect Your Channels",diff --git a/libraries/react-shared-libraries/src/translation/locales/es/translation.json b/libraries/react-shared-libraries/src/translation/locales/es/translation.jsonindex 21f23c814..8e13f5293 100644--- a/libraries/react-shared-libraries/src/translation/locales/es/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/es/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Eliminar publicación","drop_files_here_to_upload": "Suelta tus archivos aquí para subirlos","insert_emoji": "Insertar emoji",+ "only_images_can_be_added_to_the_content": "Solo se pueden añadir imágenes al contenido","write_something": "Escribe algo…","click_channel_to_add": "Haz clic en un canal para agregarlo","connect_your_channels": "Conecta tus canales",diff --git a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json b/libraries/react-shared-libraries/src/translation/locales/fr/translation.jsonindex 330c69db2..328accd70 100644--- a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/fr/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Supprimer la publication","drop_files_here_to_upload": "Déposez vos fichiers ici pour les télécharger","insert_emoji": "Insérer un emoji",+ "only_images_can_be_added_to_the_content": "Seules les images peuvent être ajoutées au contenu","write_something": "Écrivez quelque chose…","click_channel_to_add": "Cliquez sur un canal pour l'ajouter","connect_your_channels": "Connectez vos canaux",diff --git a/libraries/react-shared-libraries/src/translation/locales/he/translation.json b/libraries/react-shared-libraries/src/translation/locales/he/translation.jsonindex ae20db6ce..e22a74063 100644--- a/libraries/react-shared-libraries/src/translation/locales/he/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/he/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "מחק פוסט","drop_files_here_to_upload": "גרור קבצים לכאן להעלאה","insert_emoji": "הוסף אימוג'י",+ "only_images_can_be_added_to_the_content": "ניתן להוסיף לתוכן רק תמונות","write_something": "כתוב משהו…","click_channel_to_add": "לחץ על ערוץ כדי להוסיף אותו","connect_your_channels": "חבר את הערוצים שלך",diff --git a/libraries/react-shared-libraries/src/translation/locales/it/translation.json b/libraries/react-shared-libraries/src/translation/locales/it/translation.jsonindex 5aa352e70..d917f7402 100644--- a/libraries/react-shared-libraries/src/translation/locales/it/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/it/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Elimina post","drop_files_here_to_upload": "Trascina qui i tuoi file per caricarli","insert_emoji": "Inserisci emoji",+ "only_images_can_be_added_to_the_content": "Al contenuto si possono aggiungere solo immagini","write_something": "Scrivi qualcosa…","click_channel_to_add": "Clicca su un canale per aggiungerlo","connect_your_channels": "Collega i tuoi canali",diff --git a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json b/libraries/react-shared-libraries/src/translation/locales/ja/translation.jsonindex 36c0534dc..f952bf02f 100644--- a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ja/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "投稿を削除","drop_files_here_to_upload": "ここにファイルをドロップしてアップロード","insert_emoji": "絵文字を挿入",+ "only_images_can_be_added_to_the_content": "コンテンツに追加できるのは画像のみです","write_something": "何かを書いてください…","click_channel_to_add": "追加するチャンネルをクリック","connect_your_channels": "チャンネルを接続する",diff --git a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json b/libraries/react-shared-libraries/src/translation/locales/ko/translation.jsonindex c88a6eb3c..47ab8a4e5 100644--- a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ko/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "게시물 삭제","drop_files_here_to_upload": "여기에 파일을 끌어다 놓아 업로드하세요","insert_emoji": "이모지 삽입",+ "only_images_can_be_added_to_the_content": "콘텐츠에는 이미지만 추가할 수 있습니다","write_something": "무엇인가를 작성하세요 …","click_channel_to_add": "채널을 추가하려면 클릭하세요","connect_your_channels": "채널 연결하기",diff --git a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json b/libraries/react-shared-libraries/src/translation/locales/pt/translation.jsonindex f259f7fa7..67dd663e1 100644--- a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/pt/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Excluir postagem","drop_files_here_to_upload": "Solte seus arquivos aqui para fazer upload","insert_emoji": "Inserir emoji",+ "only_images_can_be_added_to_the_content": "Apenas imagens podem ser adicionadas ao conteúdo","write_something": "Escreva algo…","click_channel_to_add": "Clique em um canal para adicionar","connect_your_channels": "Conecte seus canais",diff --git a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json b/libraries/react-shared-libraries/src/translation/locales/ru/translation.jsonindex f041fdf4b..36176fea6 100644--- a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ru/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Удалить публикацию","drop_files_here_to_upload": "Перетащите файлы сюда для загрузки","insert_emoji": "Вставить эмодзи",+ "only_images_can_be_added_to_the_content": "В контент можно добавлять только изображения","write_something": "Напишите что-нибудь …","click_channel_to_add": "Нажмите на канал, чтобы добавить его","connect_your_channels": "Подключите ваши каналы",diff --git a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json b/libraries/react-shared-libraries/src/translation/locales/tr/translation.jsonindex 813cc3925..889a89cb8 100644--- a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/tr/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Gönderiyi Sil","drop_files_here_to_upload": "Yüklemek için dosyalarınızı buraya bırakın","insert_emoji": "Emoji Ekle",+ "only_images_can_be_added_to_the_content": "İçeriğe yalnızca görseller eklenebilir","write_something": "Bir şeyler yazın …","click_channel_to_add": "Eklemek için bir kanal seçin","connect_your_channels": "Kanallarınızı Bağlayın",diff --git a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json b/libraries/react-shared-libraries/src/translation/locales/vi/translation.jsonindex 21a367798..3121edd33 100644--- a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/vi/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "Xóa bài đăng","drop_files_here_to_upload": "Kéo thả tệp vào đây để tải lên","insert_emoji": "Chèn biểu tượng cảm xúc",+ "only_images_can_be_added_to_the_content": "Chỉ có thể thêm hình ảnh vào nội dung","write_something": "Viết gì đó …","click_channel_to_add": "Nhấp vào kênh để thêm","connect_your_channels": "Kết nối các kênh của bạn",diff --git a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json b/libraries/react-shared-libraries/src/translation/locales/zh/translation.jsonindex 9b8d1b20d..46960af9f 100644--- a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/zh/translation.json@@ -702,6 +702,7 @@"delete_post_tooltip": "删除帖子","drop_files_here_to_upload": "将文件拖到此处以上传","insert_emoji": "插入表情",+ "only_images_can_be_added_to_the_content": "只能向内容中添加图片","write_something": "写点什么…","click_channel_to_add": "点击频道以添加","connect_your_channels": "连接你的频道",