Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance uploadMediaChunked function to enable video tweet publishing.… #1227

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Aeknasd145
Copy link

Updated the uploadMediaChunked function to support video file handling and publishing on Twitter. This enhancement allows for efficient chunked upload of large video files and integrates the process with tweet publishing capabilities. Crucial for users who need to share video content directly via the API.

… Updated the uploadMediaChunked function to support video file handling and publishing on Twitter. This enhancement allows for efficient chunked upload of large video files and integrates the process with tweet publishing capabilities. Crucial for users who need to share video content directly via the API.
@ams-ryanolson
Copy link

ams-ryanolson commented Jun 18, 2024

What is the exact function of this change? I can see some QOL stuff in here but nothing that would specifically assist in helping with Video uploading outside of the existing chunks.

Also, there is an error on line 440 of TwitterOAuth.php

@Aeknasd145
Copy link
Author

Aeknasd145 commented Jun 23, 2024

What is the exact function of this change? I can see some QOL stuff in here but nothing that would specifically assist in helping with Video uploading outside of the existing chunks.

Also, there is an error on line 440 of TwitterOAuth.php

I was having problems uploading videos with API v2. That's why I made some changes, but I think I missed some steps when transferring my code from my real project to GitHub Lib. If this library works for you, there's no problem, but it didn't work for me, and to make it work, I had to downgrade to API v1.1, perform some operations, then upgrade back to v2 to complete the remaining tasks. The main reason was that since v2 does not support video uploading, I had to start the process in v2, upload in v1.1, and publish in v2. I couldn't find an alternative solution to this problem when I researched. If you want to adapt it, you can see the original code I actively use on my project. I think all the code I changed is as follows:

public function publishReelasOnTwitter(string $caption, string $filePath): object|false|array
	{
		if (!file_exists($filePath) || !is_readable($filePath)) {
			throw new Exception("File does not exist or cannot be read.");
		}

		$mediaType = 'video/mp4';
		$this->connection->setApiVersion('1.1'); // set version to V1.1 because media/upload is not available on V2 and there is no alternative
		$parameters = [
			'media' => $filePath,
			'media_type' => $mediaType
		];

		$mediaUpload = $this->connection->upload('media/upload', $parameters, true); // $this->connection is twitter oauth class

		$this->connection->setApiVersion('2');  // Set the version 2 back
		// if upload succeeded then post the reels
		if ($mediaUpload->processing_info->state === 'succeeded') { 
			return $this->tweetWithMedia($mediaUpload->media_id_string, $caption);
		}

		return false;
	}
	
	public function tweetWithMedia(string $mediaId, string $caption) {
		$content['media']['media_ids'][0] = $mediaId;
		$content['text'] = $caption;

		return $this->connection->post('tweets', $content, true);
	}


 /**
     * Private method to upload media (chunked) to upload.twitter.com.
     *
     * @param string $path
     * @param array  $parameters
     *
     * @return array|object
     */
    private function uploadMediaChunked(string $path, array $parameters)
    {
        $init = $this->http(
			'POST',
			self::UPLOAD_HOST,
			$path,
			$this->mediaInitParameters($parameters),
			false,
		);

        // Append
        $segmentIndex = 0;
        $media = fopen($parameters['media'], 'rb');
        while (!feof($media)) {
            $append = $this->http(
                'POST',
                self::UPLOAD_HOST,
                'media/upload',
                [
                    'command' => 'APPEND',
                    'media_id' => $init->media_id_string,
                    'segment_index' => $segmentIndex++,
                    'media_data' => base64_encode(
                        fread($media, $this->chunkSize),
                    ),
                ],
                false,
            );
        }
        fclose($media);

        // Finalize
        $finalize = $this->http(
            'POST',
            self::UPLOAD_HOST,
            'media/upload',
            [
                'command' => 'FINALIZE',
                'media_id' => $init->media_id_string,
            ],
            false,
        );

		do{
			$status = $this->mediaStatus($init->media_id_string);
			$this->returnLimit--;
			sleep($status->processing_info->check_after_secs ?? $this->defaultSleepTime);
		} while($status->processing_info->state != 'failed' && $status->processing_info->state != 'succeeded' && $this->returnLimit > 0);

		$finalize = $this->http(
			'POST',
			self::UPLOAD_HOST,
			'media/upload',
			[
				'command' => 'FINALIZE',
				'media_id' => $init->media_id_string,
			],
			false,
		);

        return $finalize;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants