Search code examples
c#.nettwittertweetinvi

TweetInvi Video Upload Failing With "The tweet cannot be published as some of the medias could not be published!"


I'm having an issue with TweetInvi 0.9.9.7 failing to upload a video. The video is a 9MB MP4 video and I am able to upload it to twitter just fine by using the web interface. The error message I get is:

The tweet cannot be published as some of the medias could not be published!

I used fiddler an can see this error message is coming back from the API:

error=segment size must be <= 1.

According to one of the developers, that error occurs when a video over 5MB is trying to be uploaded to Twitter and is not being sent up in chunks. https://twittercommunity.com/t/append-call-in-video-upload-api-giving-error/49067

Here is my code, am I doing something wrong? Uploading a file under 5MB works fine but the official API spec supports video up to 15MB

Auth.ApplicationCredentials = new TwitterCredentials("blahblahblah", "censoring private key", "***private, keep out***", "***beware of dog***");
var binary = File.ReadAllBytes(VideoPath);
Tweet.PublishTweetWithVideo("Here is some tweet text", binary);

Solution

  • Ultimately, I found this undocumented beauty: Upload.CreateChunkedUploader();

    Which exposes exactly the functionality I needed to upload this larger file. Here is my new working code for anyone else who may encounter this problem.

            var chunk = Upload.CreateChunkedUploader(); //Create an instance of the ChunkedUploader class (I believe this is the only way to get this object)
    
            using(FileStream fs = File.OpenRead(VideoPath))
            {
                chunk.Init("video/mp4", (int)fs.Length); //Important! When initialized correctly, your "chunk" object will now have a type long "MediaId"
                byte[] buffer = new byte[4900000]; //Your chunk MUST be 5MB or less or else the Append function will fail silently.
                int bytesRead = 0;
    
                while((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    byte[] copy = new byte[bytesRead];
                    Buffer.BlockCopy(buffer, 0, copy, 0, bytesRead);
                    chunk.Append(copy, chunk.NextSegmentIndex); //The library says the NextSegment Parameter is optional, however I wasn't able to get it to work if I left it out. 
                }
            }
    
            var video = chunk.Complete(); //This tells the API that we are done uploading.
            Tweet.PublishTweet("Tweet text:", new PublishTweetOptionalParameters()
            {
                Medias = new List<IMedia>() { video }
            });
    

    Important take-aways from this:

    Note: You’ll be prompted if the selected video is not in a supported format. Maximum file size is 512MB. See here for more details about formats.