API списка Youtube V3 возвращает пустые элементы, если загрузка видео не удаласьPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 API списка Youtube V3 возвращает пустые элементы, если загрузка видео не удалась

Сообщение Anonymous »

Я использую PHP API Youtube v3 для загрузки видео на YouTube. После загрузки я проверяю статус загруженного видео с помощью API списка. API списка, используемый для предоставления видео в массиве элементов в ответ, независимо от статуса загрузки/обработки видео. Но через 4 дня он внезапно перестал отправлять информацию о видео, если загрузка видео не удалась по какой-либо причине, например, при дублирующей загрузке. Как мне это исправить?

public static function uploadVideo_($file, $filename, $target_dir, $params = []){
try {
if (is_array($file)) {
$ret = self::uploadToLocalFromArray_($file, $filename, $target_dir);
} else {
$ret = self::uploadToLocal_($file, $filename, $target_dir);
}
if(!$ret){
throw Exception("Failed to upload video on local");
}
$client = Yii::$app->google->getService();
$youtube = new Google_Service_YouTube($client);

$videoPath = $target_dir.$filename;

$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle(@$params['title']);
$snippet->setDescription(@$params['description']);
$snippet->setTags(@$params['tags']);
$snippet->setCategoryId(@$params['category_id']);

// Set the video's status to "public". Valid statuses are "public",
// "private" and "unlisted".
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "public";

// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);

$chunkSizeBytes = 1 * 1024 * 1024;

// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(true);

// Create a request for the API's videos.insert method to create and upload the video.
$insertRequest = $youtube->videos->insert("status,snippet", $video);

// Create a MediaFileUpload object for resumable uploads.
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));

// Read the media file and upload it chunk by chunk.
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}

fclose($handle);
$videoId = $status['id'];
// If you want to make other calls after the file upload, set setDefer back to false
// Get Video uploaded or not - alternate
$client->setDefer(false);

while(true){
sleep(1);
# Call the videos.list method to retrieve processingDetails for each video.
$videosResponse = $youtube->videos->listVideos('status, processingDetails', array(
'id' => $videoId,
));
if(empty($videosResponse['items'][0])){
continue;
}
$videoResult = $videosResponse['items'][0];
if($videoResult['processingDetails']['processingStatus'] == "processing") {
continue;
}
if($videoResult['status']['uploadStatus'] == "processed" || $videoResult['status']['uploadStatus'] == "uploaded") {
break;
} else if($videoResult['status']['uploadStatus'] == "deleted") {
throw new Exception("Video has been deleted.");
} else if($videoResult['status']['uploadStatus'] == "failed") {
throw new Exception("Video upload failed: ".$videoResult['status']['failureReason']);
} else if($videoResult['status']['uploadStatus'] == "rejected") {
throw new Exception("Video Rejected: ".$videoResult['status']['rejectionReason']);
}
/*
if($videoResult['processingDetails']['processingStatus'] == "failed") {
throw new Exception("");
} else if($videoResult['processingDetails']['processingStatus'] == "succeeded") {
break;
} else if($videoResult['processingDetails']['processingStatus'] == "terminated") {
return ['status'=>false, 'message'=>$e->getMessage()];
}*/
$client->setDefer(false);
}

unlink($videoPath);
$thumb_high = $status->getSnippet()->getThumbnails()->getHigh();
$thumb_url = str_replace("hq", "sd", $thumb_high->getUrl());
try {
$dim = getimagesize($thumb_url);
$thumb_width = $dim[0];
$thumb_height = $dim[1];
} catch(Exception $e) {
$thumb_url = $thumb_high->getUrl();
$thumb_width = $thumb_high->getWidth();
$thumb_height = $thumb_high->getHeight();
}
return ['status'=>true, 'videoId'=>$videoId, 'thumbnail'=>$thumb_url, 'width'=>$thumb_width, 'height'=>$thumb_height];
} catch (Exception $e) {
return ['status'=>false, 'message'=>$e->getMessage()];
}
return ['status'=>false, 'message'=>'Unknown Reason'];
}


Подробнее здесь: https://stackoverflow.com/questions/522 ... -is-failed
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»