Anonymous
У меня проблемы с загрузкой видео в твиттер в laravel [закрыто]
Сообщение
Anonymous » 10 янв 2025, 13:14
В этом коде я получаю учетные данные приложения и токены пользователя и делаю запрос на загрузку видео, но когда я инициирую запрос
Код: Выделить всё
public function uploadVideo(Request $request)
{
// Increase the maximum execution time to 300 seconds (5 minutes)
set_time_limit(300);
// Set your access token details
$userFirst = User::find(auth()->user()->id);
if ($userFirst->social_type != "twitter") {
$account_id = $userFirst->account_id;
$user = User::where('account_id', $account_id)
->where('social_type', 'twitter')
->where('role', 0)
->first();
if (!$user) {
return response()->json(["message" => "No Twitter account found"], 404);
}
} else {
$user = User::find(auth()->user()->id);
}
$accessToken = $user->access_token;
$accessTokenSecret = $user->refresh_token;
// Initialize TwitterOAuth with your app credentials and the user's access token
$twitter = new TwitterOAuth(
config('services.twitter.client_id'),
config('services.twitter.client_secret'),
$accessToken,
$accessTokenSecret
);
// Increase the timeout settings
$twitter->setTimeouts(30, 300); // Set the connect timeout to 30 seconds and the request timeout to 300 seconds
// Tell the library we want to use the v1.1 API for media upload
$twitter->setApiVersion('1.1');
if ($request->hasFile('video')) {
$videoFile = $request->file('video');
$videoPath = $videoFile->getPathname();
$videoMimeType = $videoFile->getMimeType();
$videoExtension = $videoFile->getClientOriginalExtension();
$newVideoPath = $videoPath . '.' . $videoExtension;
// Rename the file with the correct extension
rename($videoPath, $newVideoPath);
$videoSize = filesize($newVideoPath);
// Initialize the upload
$initResponse = $twitter->upload('media/upload', [
'command' => 'INIT',
'media_type' => $videoMimeType,
'total_bytes' => $videoSize,
'media_category' => 'tweet_video'
]);
выдает эту ошибку
Код: Выделить всё
{
"message": "Undefined array key \"media\"",
"exception": "ErrorException",
"file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\abraham\\twitteroauth\\src\\TwitterOAuth.php",
"line": 358,
"trace": [
{
"file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\HandleExceptions.php",
"line": 256,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
{
"file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\abraham\\twitteroauth\\src\\TwitterOAuth.php",
"line": 358,
"function": "Illuminate\\Foundation\\Bootstrap\\{closure}",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
поэтому я не понимаю, что вызывает ошибку, поэтому, если кто-нибудь может мне помочь, пожалуйста,
и это остальная часть кода
Код: Выделить всё
if (!isset($initResponse->media_id_string)) {
return response()->json([
"message" => "Failed to initialize video upload",
"error" => $initResponse
], 500);
}
$mediaId = $initResponse->media_id_string;
// Append the media chunks
$segmentIndex = 0;
$chunkSize = 5 * 1024 * 1024; // 5MB per chunk
$handle = fopen($videoPath, 'rb');
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
$appendResponse = $twitter->upload('media/upload', [
'command' => 'APPEND',
'media_id' => $mediaId,
'segment_index' => $segmentIndex,
'media' => $chunk
],['chunkedUpload' => true]);
if ($appendResponse !== true) {
return response()->json([
"message" => "Failed to append video chunk",
"error" => $appendResponse
], 500);
}
$segmentIndex++;
}
fclose($handle);
// Finalize the upload
$finalizeResponse = $twitter->upload('media/upload', [
'command' => 'FINALIZE',
'media_id' => $mediaId
]);
if (isset($finalizeResponse->media_id_string)) {
return response()->json([
"message" => "Video uploaded successfully",
"media_id" => $finalizeResponse->media_id_string
], 200);
} else {
return response()->json([
"message" => "Failed to finalize video upload",
"error" => $finalizeResponse
], 500);
}
} else {
return response()->json(["message" => "No video file provided"], 400);
}
}
Я пытался загрузить видео в Твиттер, но при запуске запроса возникла ошибка
Подробнее здесь:
https://stackoverflow.com/questions/793 ... in-laravel
1736504085
Anonymous
В этом коде я получаю учетные данные приложения и токены пользователя и делаю запрос на загрузку видео, но когда я инициирую запрос [code]public function uploadVideo(Request $request) { // Increase the maximum execution time to 300 seconds (5 minutes) set_time_limit(300); // Set your access token details $userFirst = User::find(auth()->user()->id); if ($userFirst->social_type != "twitter") { $account_id = $userFirst->account_id; $user = User::where('account_id', $account_id) ->where('social_type', 'twitter') ->where('role', 0) ->first(); if (!$user) { return response()->json(["message" => "No Twitter account found"], 404); } } else { $user = User::find(auth()->user()->id); } $accessToken = $user->access_token; $accessTokenSecret = $user->refresh_token; // Initialize TwitterOAuth with your app credentials and the user's access token $twitter = new TwitterOAuth( config('services.twitter.client_id'), config('services.twitter.client_secret'), $accessToken, $accessTokenSecret ); // Increase the timeout settings $twitter->setTimeouts(30, 300); // Set the connect timeout to 30 seconds and the request timeout to 300 seconds // Tell the library we want to use the v1.1 API for media upload $twitter->setApiVersion('1.1'); if ($request->hasFile('video')) { $videoFile = $request->file('video'); $videoPath = $videoFile->getPathname(); $videoMimeType = $videoFile->getMimeType(); $videoExtension = $videoFile->getClientOriginalExtension(); $newVideoPath = $videoPath . '.' . $videoExtension; // Rename the file with the correct extension rename($videoPath, $newVideoPath); $videoSize = filesize($newVideoPath); // Initialize the upload $initResponse = $twitter->upload('media/upload', [ 'command' => 'INIT', 'media_type' => $videoMimeType, 'total_bytes' => $videoSize, 'media_category' => 'tweet_video' ]); [/code] выдает эту ошибку [code]{ "message": "Undefined array key \"media\"", "exception": "ErrorException", "file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\abraham\\twitteroauth\\src\\TwitterOAuth.php", "line": 358, "trace": [ { "file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Bootstrap\\HandleExceptions.php", "line": 256, "function": "handleError", "class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions", "type": "->" }, { "file": "C:\\xampp\\htdocs\\ThePostFlex\\vendor\\abraham\\twitteroauth\\src\\TwitterOAuth.php", "line": 358, "function": "Illuminate\\Foundation\\Bootstrap\\{closure}", "class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions", "type": "->" [/code] поэтому я не понимаю, что вызывает ошибку, поэтому, если кто-нибудь может мне помочь, пожалуйста, и это остальная часть кода [code] if (!isset($initResponse->media_id_string)) { return response()->json([ "message" => "Failed to initialize video upload", "error" => $initResponse ], 500); } $mediaId = $initResponse->media_id_string; // Append the media chunks $segmentIndex = 0; $chunkSize = 5 * 1024 * 1024; // 5MB per chunk $handle = fopen($videoPath, 'rb'); while (!feof($handle)) { $chunk = fread($handle, $chunkSize); $appendResponse = $twitter->upload('media/upload', [ 'command' => 'APPEND', 'media_id' => $mediaId, 'segment_index' => $segmentIndex, 'media' => $chunk ],['chunkedUpload' => true]); if ($appendResponse !== true) { return response()->json([ "message" => "Failed to append video chunk", "error" => $appendResponse ], 500); } $segmentIndex++; } fclose($handle); // Finalize the upload $finalizeResponse = $twitter->upload('media/upload', [ 'command' => 'FINALIZE', 'media_id' => $mediaId ]); if (isset($finalizeResponse->media_id_string)) { return response()->json([ "message" => "Video uploaded successfully", "media_id" => $finalizeResponse->media_id_string ], 200); } else { return response()->json([ "message" => "Failed to finalize video upload", "error" => $finalizeResponse ], 500); } } else { return response()->json(["message" => "No video file provided"], 400); } } [/code] Я пытался загрузить видео в Твиттер, но при запуске запроса возникла ошибка Подробнее здесь: [url]https://stackoverflow.com/questions/79342733/i-have-problems-with-video-uploading-to-twitter-in-laravel[/url]