node-twitter-api-v2 icon indicating copy to clipboard operation
node-twitter-api-v2 copied to clipboard

[bug] V2 uploadMedia (documentation, not working?)

Open aavmurphy opened this issue 1 year ago • 13 comments

Describe the bug

1) Documentation with example missing

e.g.

image_buffer = fs.readFileSync( filename );
api.v2.uploadMedia( image_buffer, { media_type : 'image/jpeg' } )

2) Can't get it to work

I got the interface from the v2 media upload test. Either it not working, or I misunderstood something :)

Request failed with code 400, data: { code: 38, message: 'media parameter is missing.' }

[POST api.x.com/2/media/upload] {
  method: 'POST',
  headers: {
    'x-user-agent': 'Node.twitter-api-v2',
    Authorization: 'OAuth oauth_consumer_key="d...u",oauth_signature="...",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1739809660",oauth_token="....",oauth_version="1.0"',
    'content-type': 'application/json;charset=UTF-8',
    'content-length': 65,
    'accept-encoding': 'br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1'
  },
  timeout: undefined,
  agent: undefined
}
Request body: {"command":"INIT","media_type":"image/jpeg","total_bytes":247818}
Request failed with code 400, data: { code: 38, message: 'media parameter is missing.' }
Response headers: {
  date: 'Mon, 17 Feb 2025 16:27:40 GMT',
  perf: '7402827104',
  vary: 'Origin',
  server: 'tsa_f',
  'set-cookie': [
    'guest_id=....; Max-Age=34214400; Expires=Fri, 20 Mar 2026 16:27:41 GMT; Path=/; Domain=.x.com; Secure; SameSite=None'
  ],
  'content-type': 'application/json; charset=utf-8',
  'cache-control': 'no-cache, no-store, max-age=0',
  'content-length': '75',
  'x-frame-options': 'SAMEORIGIN',
  'content-encoding': 'gzip',
  'x-transaction-id': '....',
  'x-xss-protection': '1; mode=block',
  'x-rate-limit-limit': '40000',
  'x-rate-limit-reset': '1739810389',
  'x-content-type-options': 'nosniff',
  'x-rate-limit-remaining': '39997',
  'strict-transport-security': 'max-age=631138519',
  'x-response-time': '143',
  'x-connection-hash': '.....'
}

Version

  • Node.js version 23.7
  • node twitter api 1.20.1
  • linux (ubuntu)

Thanks for looking at this. Its appreciated !

aavmurphy avatar Feb 17 '25 16:02 aavmurphy

Any idea @leeran7?

plhery avatar Feb 17 '25 17:02 plhery

I got same issue

Mnigos avatar Feb 18 '25 12:02 Mnigos

Any idea @leeran7?

Definitely looks like bad implementation on my part, apologies about that. Looking like I missed the most important part of the implementation somehow and not providing the media in the INIT request. Along with making this a form-data request.

Working on the fix, rate limited at the moment from twitter.

leeran7 avatar Feb 18 '25 18:02 leeran7

@leeran7 any ETA on this?

anshuman-singh1 avatar Feb 21 '25 12:02 anshuman-singh1

if someone looking to find a workaround then here is the working code

const axios = require('axios');
const OAuth = require('oauth-1.0a');
const crypto = require('crypto');
const FormData = require('form-data');

class XMediaUploader {
    constructor(oauthConfig) {
        this.baseUrl = 'https://api.x.com/2/media/upload';
        this.oauth = new OAuth({
            consumer: {
                key: oauthConfig.consumerKey,
                secret: oauthConfig.consumerSecret
            },
            signature_method: 'HMAC-SHA1',
            hash_function(baseString, key) {
                return crypto
                    .createHmac('sha1', key)
                    .update(baseString)
                    .digest('base64');
            }
        });
        this.token = {
            key: oauthConfig.accessToken,
            secret: oauthConfig.accessTokenSecret
        };
    }

    async getAuthHeaders(method, url) {
        const requestData = {
            url,
            method
        };
        return this.oauth.toHeader(this.oauth.authorize(requestData, this.token));
    }

    async downloadFile(url) {
        const response = await axios.get(url, { responseType: 'arraybuffer' });
        return response.data;
    }

    async uploadMedia(mediaUrl, mediaType, target) {
        try {
            // Download the file first
            console.log('Downloading media from URL...');
            const fileData = await this.downloadFile(mediaUrl);
            const fileSize = fileData.length;


            // Step 1: Initialize upload
            console.log('Initializing upload...');
            const mediaId = await this.initUpload(fileSize, mediaType, target);

            // Step 2: Upload chunks
            console.log('Uploading media...');
            const chunkSize = 1024 * 1024; // 1MB chunks
            let offset = 0;
            let segmentIndex = 0;

            while (offset < fileData.length) {
                const chunk = fileData.slice(offset, offset + chunkSize);
                await this.appendChunk(mediaId, chunk, segmentIndex);
                offset += chunkSize;
                segmentIndex++;
                console.log(`Uploaded chunk ${segmentIndex}`);
            }

            // Step 3: Finalize upload
            console.log('Finalizing upload...');
            const finalizeResult = await this.finalizeUpload(mediaId);

            // Step 4: Check processing status if needed
            if (finalizeResult.processing_info) {
                console.log('Waiting for processing...');
                await this.waitForProcessing(mediaId);
            }

            return mediaId;
        } catch (error) {
            console.error('Upload failed:', error);
            throw error;
        }
    }

    getMediaType(url) {
        const extension = url.split('.').pop().toLowerCase();
        const mediaTypes = {
            'mp4': 'video/mp4',
            'jpg': 'JPG',
            'jpeg': 'JPG',
            'png': 'PNG',
            'gif': 'GIF'
        };
        return mediaTypes[extension] || 'video/mp4';
    }

    async initUpload(totalBytes, mediaType, target) {
        const headers = await this.getAuthHeaders('POST', this.baseUrl);
        const formData = new FormData();
        formData.append('command', 'INIT');
        formData.append('total_bytes', totalBytes);

        if (target === 'tweet') {
            if (mediaType === 'IMAGE') {
                formData.append('media_category', 'tweet_image');
            } else if (mediaType === 'VIDEO') {
                formData.append('media_category', 'tweet_video');
            } else if (mediaType === 'GIF') {
                formData.append('media_category', 'tweet_gif');
            }
        } else if (target === 'dm') {
            if (mediaType === 'IMAGE') {
                formData.append('media_category', 'dm_image');
            } else if (mediaType === 'VIDEO') {
                formData.append('media_category', 'dm_video');
            } else if (mediaType === 'GIF') {
                formData.append('media_category', 'dm_gif');
            }
        }

        const urlParams = new URLSearchParams(headers).toString();
        const f = {
            ...headers,
            ...formData.getHeaders()
        }


        const response = await axios.post(this.baseUrl, formData, {
            headers: {
                ...headers,
                ...formData.getHeaders()
            }
        });

        return response.data.data.id;
    }

    isVideo(mediaType) {
        return mediaType.includes('video') || mediaType.includes('VIDEO');
    }

    async appendChunk(mediaId, chunk, segmentIndex) {
        const headers = await this.getAuthHeaders('POST', this.baseUrl);
        const formData = new FormData();
        formData.append('command', 'APPEND');
        formData.append('media_id', mediaId);
        formData.append('segment_index', segmentIndex);
        formData.append('media', Buffer.from(chunk), {
            filename: 'media_chunk',
            contentType: 'application/octet-stream'
        });

        await axios.post(this.baseUrl, formData, {
            headers: {
                ...headers,
                ...formData.getHeaders()
            },
            maxContentLength: Infinity,
            maxBodyLength: Infinity
        });
    }

    async finalizeUpload(mediaId) {
        const headers = await this.getAuthHeaders('POST', this.baseUrl);
        const formData = new FormData();
        formData.append('command', 'FINALIZE');
        formData.append('media_id', mediaId);

        const response = await axios.post(this.baseUrl, formData, {
            headers: {
                ...headers,
                ...formData.getHeaders()
            }
        });

        return response.data.data;
    }

    async waitForProcessing(mediaId) {
        const checkStatus = async () => {
            try {
                const url = `${this.baseUrl}?command=STATUS&media_id=${mediaId}`;
                const headers = await this.getAuthHeaders('GET', url);
                const response = await axios.get(`${url}`, {
                    headers
                });

                return response.data.data.processing_info.state;
            } catch (error) {
                console.error(error)
                throw error
            }

        };

        while (true) {
            const state = await checkStatus();
            if (state === 'succeeded') break;
            if (state === 'failed') throw new Error('Media processing failed');
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
    }
}





module.exports = XMediaUploader

usage

  const config = {
      consumerKey,
      consumerSecret,
      accessToken,
      accessTokenSecret
    }

    const media_id = await new XMediaUploader(config).uploadMedia(
      media_url,
      media_type,
      target) , target could be dm,tweet

anshuman-singh-93 avatar Feb 21 '25 15:02 anshuman-singh-93

@leeran7 any ETA on this?

Will have a draft PR up today or tomorrow. Just want to be confident this time its working properly.

leeran7 avatar Feb 24 '25 15:02 leeran7

https://github.com/PLhery/node-twitter-api-v2/pull/570

Pushed up the fix.

leeran7 avatar Feb 24 '25 16:02 leeran7

any idea when will this be released?

jmforj avatar Feb 25 '25 12:02 jmforj

Hello, I'll do it in a few hours!

plhery avatar Feb 25 '25 14:02 plhery

Released in 1.20.2

plhery avatar Feb 25 '25 21:02 plhery

Documentation released in 1.21.0

Can see it here https://github.com/PLhery/node-twitter-api-v2/blob/master/doc/v2.md#upload-medias

francistogram avatar Mar 20 '25 21:03 francistogram

Apparently they are removing the command query parameter and introducing new endpoints to upload media, as described here.

It seems easy to adapt the current code here to remove the command query parameter and use the new endpoints. I propose https://github.com/PLhery/node-twitter-api-v2/pull/584.

avillegasn avatar May 02 '25 08:05 avillegasn

Fix publised in 1.23.0!

plhery avatar May 05 '25 21:05 plhery