π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat(x): stream video uploads in 1MB ranged chunks instead of buffering the whole file
Gilad Resisi5e82d4606dc8
diff --git a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts b/libraries/nestjs-libraries/src/integrations/social/x.provider.tsindex 22a85f73d..e3923d86a 100644--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts@@ -10,7 +10,11 @@ import {import { lookup } from 'mime-types';import sharp from 'sharp';import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';-import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import { createReadStream, statSync } from 'fs';+import {+ BadBody,+ SocialAbstract,+} from '@gitroom/nestjs-libraries/integrations/social.abstract';import { Plug } from '@gitroom/helpers/decorators/plug.decorator';import { Integration } from '@prisma/client';import { timer } from '@gitroom/helpers/utils/timer';@@ -417,6 +421,130 @@ export class XProvider extends SocialAbstract implements SocialProvider {);}+ // Same INIT / APPEND / FINALIZE flow as client.v2.uploadMedia, but the+ // video is never held in memory whole: total_bytes comes from a HEAD+ // request (statSync for local files) and each 1MB segment is fetched with+ // a ranged GET right before its APPEND. client.v2.uploadMedia only accepts+ // a Buffer, which is why the loop is replicated here.+ private async uploadVideoChunked(client: TwitterApi, path: string) {+ const size = await this.videoSize(path);+ const chunkSize = 1024 * 1024;++ const initResponse = await client.v2.post<{ data: { id: string } }>(+ 'media/upload/initialize',+ {+ media_type: lookup(path) || 'video/mp4',+ total_bytes: size,+ media_category: 'tweet_video',+ }+ );+ const mediaId = initResponse.data.id;++ for (let i = 0; i < size; i += chunkSize) {+ const end = Math.min(i + chunkSize, size) - 1;+ await client.v2.post(+ `media/upload/${mediaId}/append`,+ {+ segment_index: i / chunkSize,+ media: await this.videoChunk(path, i, end),+ },+ { forceBodyMode: 'form-data' }+ );+ }++ const finalizeResponse = await client.v2.post<{+ data: { processing_info?: object };+ }>(`media/upload/${mediaId}/finalize`);+ if (finalizeResponse.data.processing_info) {+ await this.waitForMediaProcessing(client, mediaId);+ }++ return mediaId;+ }++ // Mirrors the private client.v2.waitForMediaProcessing.+ private async waitForMediaProcessing(client: TwitterApi, mediaId: string) {+ const response = await client.v2.get<{+ data: {+ processing_info?: {+ state: string;+ check_after_secs?: number;+ error?: { message?: string };+ };+ };+ }>('media/upload', { command: 'STATUS', media_id: mediaId });++ const info = response.data.processing_info;+ if (!info || info.state === 'succeeded') {+ return;+ }+ if (info.state === 'failed') {+ throw new BadBody(+ 'x-error-upload',+ JSON.stringify(response.data),+ Buffer.from('{}'),+ `X media processing failed: ${info.error?.message || 'unknown error'}`+ );+ }+ await timer((info.check_after_secs || 1) * 1000);+ await this.waitForMediaProcessing(client, mediaId);+ }++ // Resolves the total byte size of the video without loading it into memory:+ // a HEAD request for remote URLs, statSync for local files.+ private async videoSize(path: string): Promise<number> {+ if (path.indexOf('http') === 0) {+ const head = await fetch(path, { method: 'HEAD' });+ const length = head.headers.get('content-length');+ if (!length) {+ throw new BadBody(+ 'x-error-upload',+ '{}',+ Buffer.from('{}'),+ 'Could not determine the video size for X upload'+ );+ }+ return Number(length);+ }++ return statSync(path).size;+ }++ // Returns only the [start, end] byte window of the video as a Buffer (a+ // ranged GET for remote URLs, a ranged read for local files), so memory is+ // bounded by the segment size.+ private async videoChunk(+ path: string,+ start: number,+ end: number+ ): Promise<Buffer> {+ if (path.indexOf('http') === 0) {+ const response = await fetch(path, {+ headers: { Range: `bytes=${start}-${end}` },+ });+ // A 200 means the origin ignored the Range header and is sending the+ // whole file: uploading it as this segment would silently corrupt the+ // video, so fail loudly instead.+ if (response.status !== 206) {+ throw new BadBody(+ 'x-error-upload',+ '{}',+ Buffer.from('{}'),+ `Media server ignored the ranged request (status ${response.status}); it must support HTTP Range requests for chunked X uploads`+ );+ }+ return Buffer.from(await response.arrayBuffer());+ }++ return new Promise((resolve, reject) => {+ const chunks: Buffer[] = [];+ createReadStream(path, { start, end })+ .on('data', (chunk) => chunks.push(chunk as Buffer))+ .on('end', () => resolve(Buffer.concat(chunks)))+ .on('error', reject);+ });+ }+private async uploadMedia(client: TwitterApi,postDetails: PostDetails<any>[]@@ -428,10 +556,10 @@ export class XProvider extends SocialAbstract implements SocialProvider {return {id: await this.runInConcurrent(async () =>- client.v2.uploadMedia(- hasExtension(m.path, 'mp4')- ? Buffer.from(await readOrFetch(m.path))- : await sharp(await readOrFetch(m.path), {+ hasExtension(m.path, 'mp4')+ ? this.uploadVideoChunked(client, m.path)+ : client.v2.uploadMedia(+ await sharp(await readOrFetch(m.path), {animated: lookup(m.path) === 'image/gif',}).resize({@@ -439,10 +567,10 @@ export class XProvider extends SocialAbstract implements SocialProvider {}).gif().toBuffer(),- {- media_type: (lookup(m.path) || '') as any,- }- ),+ {+ media_type: (lookup(m.path) || '') as any,+ }+ ),true),postId: p.id,