I'm using the library tmhOAuth to post to Twitter in an app and I've already implemented uploading pictures but am having trouble implementing video upload.
This is the call I use to upload pictures and works perfectly with images.
$temp = '#upload/'.$name.';type='.$_FILES['img']['type'].';filename='.$name;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json', array('media' => $temp), true, true);
So I thought it might be the same for videos but I got the error
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
I believe I have to make 3 separate calls, as per the Twitter API, so I tried this
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&media_type=video/mp4&total_bytes='.$_FILES['img']['size'], array('media' => $temp), true, true);
$media_id = json_decode($tmhOAuth->response['response'])->media_id_string;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id='.$media_id.'&segment_index=0', array('media' => $temp), true, true);
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id='.$media_id, array('media' => $temp), true, true);
but I kept getting the same error for all 3 calls
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
Can anyone provide an example as to how to upload videos to twitter? I could find no examples online and it might just not be possible.
I had the same problem. Here's how I managed to solve it.
First you set up a var containing the filesystem full path to the media you want to upload.
$media_path = '/PATH/TO/THE/file.mp4';
Then instantiate $tmhOAuth and do the 3 steps :
$tmhOAuthUpload = new tmhOAuth();
INIT:
$code = $tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "INIT",
"total_bytes" => (int)filesize($media_path),
'media_type' => 'video/mp4',
)
);
Retrieve media id returned by Twitter
$results = json_decode($tmhOAuthUpload->response['response']);
$media_id = $results->media_id_string;
APPEND: Handle video/media upload with the Append loop
$fp = fopen($media_path, 'r');
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "APPEND",
"media_id" => $media_id,
'media_data' => base64_encode($chunk),
"segment_index" => $segment_id
)
);
$segment_id++;
}
FINALIZE:
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "FINALIZE",
"media_id" => $media_id,
)
);
By then I was able to to send my tweet:
$code = $tmhOAuth->request(
'POST',
$tmhOAuthUpload->url('1.1/statuses/update'),
array(
'media_ids' => $media_id,
'status' => $text,
),
true // use auth
);
Hope that helps
I've only been able to get video uploading working with CodeBird - a different PHP library.
The Twitter API calls for video are quite different from uploading images, as you've discovered.
Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks. You need to perform at least 3 calls to obtain your media_id for the video:
Send an INIT event to get a media_id draft.
Upload your chunks with APPEND events, each one up to 5MB in size.
Send a FINALIZE event to convert the draft to a ready-to-tweet media_id.
Post your tweet with video attached.
Remember, each APPEND must be 5MB or under.
If you are consistently getting "Media Type Unrecognised" errors, it might be that the video you are using is incompatible with Twitter. Can you test uploading the video via another service?
Thank you very much for that answer Pierre! I was however getting a “Not valid video” error if I tried to create the tweet too soon. The video wasn't done being processed by Twitter. In addition to Pierre's code, I needed something like this to check STATUS, after FINALIZE:
$videoCount = 0;
do
{
$tmhOAuth->request(
'GET',
$tmhOAuth->url('/1.1/media/upload.json'),
array(
"command" => "STATUS",
"media_id" => $mediaID,
)
);
$twitterResult = json_decode($tmhOAuth->response['response']);
if ($twitterResult->processing_info->state != 'succeeded')
{ sleep(5); }
$videoCount++;
}
while ($twitterResult->processing_info->state != 'succeeded' && $videoCount < 5);
Note: my variable names are different
Related
I work with Google cloud speech API. When I run my script there is a call to the API and a response. The operation info returns data, but the result is empty.
Here is my code (where file url, file name, key url, project name and bucket name I deleted the real data):
function __construct(){
$file_url='file path.mp3';
$filename='file name.mp3';
/** Create google client **/
$client = new Google_Client();
$key='path to google key';
putenv($key);
$client->useApplicationDefaultCredentials();
/** Create storage **/
$str_config = array(
'projectId' => 'project id'
);
$storage = new StorageClient($str_config);
$bucket_name='bucket name';
$bucket=$storage->bucket($bucket_name);
$object = $bucket->object($filename);
/** Create Speech **/
$config = array(
'projectId' => 'project id',
'languageCode' => 'en-US'
);
$options = array(
"encoding"=>'LINEAR16',
"languageCode"=>"en-US",
'sampleRateHertz' => 16000
)
;
$speech = new Google\Cloud\Speech\SpeechClient($config);
$operation = $speech->beginRecognizeOperation(
$object,
$options
);
$backoff = new ExponentialBackoff(100);
$backoff->execute(function () use ($operation) {
print('Waiting for operation to complete' . PHP_EOL);
$operation->reload();
if (!$operation->isComplete()) {
throw new Exception('Job has not yet completed', 500);
}
});
if ($operation->isComplete()) {
if (empty($results = $operation->results())) {
$results = $operation->info();
}
var_dump($results, $operatimon->results());
}
}
The result i get call:
Array
(
[0] => Array
(
[name] => some name
[metadata] => Array
(
[#type]=> type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata
[progressPercent] => 100
[startTime] => 2017-07-16T19:15:58.768490Z
[lastUpdateTime] => 2017-07-16T19:15:59.999625Z
)
[done] => 1
[response] => Array
(
[#type]=> type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse
[totalBilledTime] => 15s
)
)
[1] => Array
(
)
)
I tried several file type whit several encodings, can't find the right combination. Or maybe there is another problem. Pleas Help.
Solved it by using the ffmpeg library to encode the audio to flac whit mono channel.
For anyone else encountering this problem, the issue could lie in your audio file not matching the encoding you've entered in your option array.
Check this resource:
https://cloud.google.com/speech-to-text/docs/reference/rest/v1beta1/RecognitionConfig#AudioEncoding
Just like the accepted answer, by changing from "LINEAR16" to "FLAC" and converting my audio file to FLAC, it worked for me.
Testing the generateThumbnail call of the Azure Computer Vision API from PHP. I have been able to get it to operate, but the images being saved locally are very, very poor quality. Highly pixelated, very blurry, etc. They look nothing like the examples presented at https://www.microsoft.com/cognitive-services/en-us/computer-vision-api/documentation#Thumbnails
Is this an issue with the image processing on the server side, or possibly a degradation issue occurring locally during the file save process? I'm having trouble determining where to start on this one.
This seems to be the same follow-up question asked here:
Generate thumbnail in php, posting to Azure Computer Vision API
Source image dimensions are 542x1714. Trying to create 115x115 thumbnail.
Code at the moment. Have tried it with smartCropping set to both True and False.
$posturl = 'https://westus.api.cognitive.microsoft.com/vision/v1.0/generateThumbnail';
$posturl = add_query_arg( array( 'width' => $max_w, 'height' => $max_h, 'smartCropping' => true), $posturl);
$request = wp_remote_post( $posturl, array( 'headers' => array( 'Content-Type' => 'application/octet-stream', 'Ocp-Apim-Subscription-Key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ), 'body' => file_get_contents( $this->file ) ) );
if ( is_wp_error( $request ) ) {
return null;
} else {
$resized = #imagecreatefromstring( $request['body'] );
}
I'm trying to publish tweet on twitter with image and a link to my site
I get the following error:
{"errors": [{"code": 189, "message": ". Error creating status"}]}
I tried with twitter api:
with update.json
the tweet is published but no picture.
and
update_with_media.json
I get error
this is the code I use:
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'xxxxxxxxxx',
'consumer_secret' => 'xxxxxxxxxxxxx',
'user_token' => 'xxxxxxxxxxxxxxxxxxxx',
'user_secret' => 'xxxxxxxxxxxxxxxxxx',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image'] ['type']};filename={$_FILES['image']['name']}",
$picimg="img.jpg";
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$picimg}",
'status' => "status"
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I searched a lot on google but not served me anything.
I do not understand what's going on
It was poorly cast the image url and more stuff.
I have made an example of different api in my local.
I used APIs
https://github.com/themattharris/tmhOAuth
I've also installed composer for dependencies.
installing dependencies twitter api.
Well the most important thing is:
this piece of code:
$picimg="img.jpg";
array(
'media[]' => "#{$picimg}",
'status' => "status"
)
this is wrong.
but this above is good
$image = __DIR__.DIRECTORY_SEPARATOR .'..' . DIRECTORY_SEPARATOR . 'fotos'. DIRECTORY_SEPARATOR . 'foto1.jpg';
DIRECTORY_SEPARATOR is used instead of backslash, and this is very important if not the error response would be 189
$name = basename($image);
$status = "Picture time";
$media = "#{$image};type=image/jpg;filename={$name}";
media must be represented well in this format, not only url string.
// we set the type and filename are set here as well
$params = array(
'media[]' => $media,
'status' => $status
);
This is working AMIGOS
I'm having problems setting the "Metadata" option when uploading files to Amazon S3 using the AWS SDK PHP v2. The documentation that I'm reading for the upload() method states that the the 5th parameter is an array of options...
*$options Custom options used when executing commands: - params: Custom
parameters to use with the upload. The parameters must map to a
PutObject or InitiateMultipartUpload operation parameters. -
min_part_size: Minimum size to allow for each uploaded part when
performing a multipart upload. - concurrency: Maximum number of
concurrent multipart uploads. - before_upload: Callback to invoke
before each multipart upload. The callback will receive a
Guzzle\Common\Event object with context.*
My upload() code looks like this..
$upload = $client->upload(
'<BUCKETNAME>',
'metadatatest.upload.jpg',
fopen('metadatatest.jpg','r'),
'public-read',
array('Metadata' => array(
'SomeKeyString' => 'SomeValueString'
))
);
...and no meta data is set after upload.
If however I use putObject() as documented here, which I assume is a "lower level" method compared to upload()...
$putObject = $client->putObject(
array(
'Bucket' => '<BUCKETNAME>',
'Key' => 'metadatatest.putobject.jpg',
'Body' => file_get_contents('metadatatest.jpg'),
'ACL' => 'public-read',
'Metadata' => array(
'SomeKeyString' => 'SomeValueString'
)
)
);
The meta data is successfully returned when I call getObject() or view the file directly in my browser when uploaded using putObject()
$getObject = $client->getObject(
array(
'Bucket' => '<BUCKETNAME>',
'Key' => 'metadatatest.putobject.jpg'
)
);
I would prefer to use the $client->upload() method as the documentation states
Upload a file, stream, or string to a bucket. If the upload size exceeds the specified threshold, the upload will be performed using
parallel multipart uploads.
I'm not sure what I've missed?
There's really no difference in using upload() or putObject() if you don't do multipart uploads. You can have a look at the AWS PHP SDK source code but basically the upload method just calls putObject like this:
// Perform a simple PutObject operation
return $this->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
'ACL' => $acl
) + $options['params']);
This isn't very clear in the SDK documentation, but you need to send the last parameter as an array with the key params and its value being a second array with the Metadata key and value like this:
$upload = $client->upload(
'<BUCKETNAME>',
'metadatatest.upload.jpg',
fopen('metadatatest.jpg','r'),
'public-read',
array('params' => array(
'Metadata' => array(
'SomeKeyString' => 'SomeValueString'
)))
);
However, I you could just use the putObject call to achieve the same thing.
I'm trying to post a photo using the php-sdk - all was working for months successfully but all of the sudden no dice.
Other functions are still working with the same code base (ie: posting messages to wall) - its just the posting of photos that broke on my side.
try {
$data = $facebook->api('/me/photos', 'post', $args);
} catch (FacebookApiException $e) {
print_r($e);}
Is dumping:
FacebookApiException Object ( [result:protected] => Array ( [error_code] => 3 [error] => Array ( [message] => No URL set! [type] => CurlException ) ) [message:protected] => No URL set! [string:private] => [code:protected] => 3 [file:protected] => /locationofmy/base_facebook.php [line:protected] => 818 [trace:private] => Array ( [0] => Array [..............]
From the FB php-sdk lines 818:
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
This was working for a long time - has something changed on Facebooks side?
EDIT: php-sdk version: 3.1.1
EDIT 2:
$tag = array(
'tag_uid' => 'acct_num',
'x' => 0,
'y' => 0
);
$tags[] = $tag;
$args = array(
'message' => $item_description,
'image' => '#' . realpath($temp_path . $tempFile),
'tags' => $tags,
);
Probably that the file doesnt exist, or the file system can't serve it anymore. Can you confirm "$temp_path . $tempFile" - the error is no URL, usually that means no real path to image. I suspect, that the images are missing and/or your servers filled up and no local images are saving. (Yes, this has happened to me before!)
Try changing the image to source. I believe this should fix your issue.
The Facebook API requires a source field but I did not see anything about an image field.
You may also have to pass the actual file contents instead of the real_path (based on the example). Or, alternatively, pass an external URL (based on my understanding of the documentation).
Source: https://developers.facebook.com/docs/reference/api/photo/
Example: https://developers.facebook.com/blog/post/498/