/** * Upload Video. * * @param \Userdesk\Submission\Classes\SubmissionVideoItem $item; * * @return \Userdesk\Submission\Classes\SubmissionResult; */ public function uploadVideo(SubmissionVideoItem $item) { $google = $this->providerFromToken($this->token); try { $youtube = new \Google_Service_YouTube($google); $videoPath = $item->getVideo(); if (!empty($videoPath)) { // Create a snipet with title, description, tags and category id $snippet = new \Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($item->getTitle()); $snippet->setDescription($item->getDescription()); $snippet->setTags(explode(',', $item->getKeywords())); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); $status = new \Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "public"; // Create a YouTube video with snippet and status $video = new \Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks, // for reliable connections). Setting it lower leads better recovery (fine-grained chunks) $chunkSizeBytes = 1 * 1024 * 1024; $google->setDefer(true); $insertRequest = $youtube->videos->insert("status,snippet", $video); // Create a MediaFileUpload with resumable uploads $media = new \Google_Http_MediaFileUpload($google, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); // Create a video insert request $uploadStatus = false; // Read file and upload chunk by chunk $handle = fopen($videoPath, "rb"); while (!$uploadStatus && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $uploadStatus = $media->nextChunk($chunk); } fclose($handle); $google->setDefer(false); if (!empty($uploadStatus) && !empty($uploadStatus->id)) { $url = "http://www.youtube.com/watch?v=" . $uploadStatus->id; return new SubmissionResult(true, '', $url); } return new SubmissionResult(false, 'Video Upload Failed'); } } catch (\Google_ServiceException $e) { throw new InvalidUploadException($e->getMessage()); } catch (\Google_Exception $e) { throw new InvalidUploadException($e->getMessage()); } catch (Exception $e) { throw new InvalidUploadException($e->getMessage()); } }
function publishVideo($season, $episode) { // XXX copy try block from above // XXX fetch cast header global $youtube; $reply = $youtube->videos->listVideos('snippet,status', array('id' => '')); $videoList = $reply['items']; $video = $videoList[0]; $videoStatus = $video['status']; $updateStatus = new Google_Service_YouTube_VideoStatus($videoStatus); $updateStatus->privacyStatus = 'public'; $updateVideo = new Google_Service_YouTube_Video($video); $updateVideo->setStatus($updateStatus); $update_response = $youtube->videos->update('snippet,status', $updateVideo); // TODO playlist support! // XXX debug // print_r( $update_response ); return true; }
// Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle("Test title"); $snippet->setDescription("Test description"); $snippet->setTags(array("tag1", "tag2")); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // 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); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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.
/** * @param \Google_Service_YouTube_Video $source * * @return \C2iS\SocialWall\YouTube\Model\SocialItem */ protected function createSocialItem($source) { $item = new SocialItem(); /** @var \Google_Service_YouTube_VideoSnippet $snippet */ $snippet = $source->getSnippet(); $item->setId($source->getId()); $item->setTitle($snippet->getTitle()); $item->setVideoId($source->getId()); $item->setPublishedAt(new \DateTime($snippet->getPublishedAt())); $item->setContent($snippet->getDescription()); $item->setUrl($this->createUrl($source->getId())); /** @var \Google_Service_YouTube_VideoStatistics $statistics */ $statistics = $source->getStatistics(); $item->setViews($statistics->getViewCount()); $item->setLikes($statistics->getLikeCount()); $item->setDislikes($statistics->getDislikeCount()); $item->setComments($statistics->getCommentCount()); $item->setFavorites($statistics->getFavoriteCount()); $item->setThumbnails($this->createThumbnailCollection($snippet->getThumbnails())); return $item; }
public function google_access($flag) { include_once APPPATH . "third_party/Google/autoload.php"; //include_once APPPATH . "libraries/Google/Client.php"; //include_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php"; //include_once APPPATH . "libraries/Google/Service/Youtube.php"; $scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtubepartner'); $client = new Google_Client(); $client->setClientId($this->client_id); $client->setClientSecret($this->client_secret); //$client->setScopes('https://www.googleapis.com/auth/youtube'); $client->setScopes($scope); $client->setRedirectUri($this->redirect_uri); $client->setApplicationName($this->application_name); $client->setAccessType('offline'); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); } if ($flag == '') { if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); $client->getAccessToken(); $_SESSION['token'] = $client->getAccessToken(); //unset($_SESSION['token']); var_dump($_SESSION); return 1; } else { $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } } if ($flag) { if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); $client->getAccessToken(); $_SESSION['token'] = $client->getAccessToken(); try { /*if($client->isAccessTokenExpired()) { $newToken = json_decode($client->getAccessToken()); $client->refreshToken($newToken->access_token); }*/ $video_det = explode(',', $flag); // $video_det[0], $video_det[1]; $videoPath = $video_det[0]; $videoTitle = $video_det[1]; $videoDescription = "A video tutorial on how to upload to YouTube"; $videoCategory = "22"; $videoTags = array("youtube", "tutorial"); $youtube = new Google_Service_YouTube($client); // Create a snipet with title, description, tags and category id $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($videoTitle); $snippet->setDescription($videoDescription); $snippet->setCategoryId($videoCategory); $snippet->setTags($videoTags); // Create a video status with privacy status. Options are "public", "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->setPrivacyStatus('private'); // Create a YouTube video with snippet and status $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks, // for reliable connections). Setting it lower leads better recovery (fine-grained chunks) $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)); //var_dump(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); // Video has successfully been upload, now lets perform some cleanup functions for this video if ($status->status['uploadStatus'] == 'uploaded') { // Actions to perform for a successful upload redirect('home', 'refresh'); } // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); } catch (Google_Service_Exception $e) { print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage(); print "Stack trace is " . $e->getTraceAsString(); } catch (Exception $e) { print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage(); print "Stack trace is " . $e->getTraceAsString(); } } else { $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . 'assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } if ($client->getAccessToken()) { try { // Call the channels.list method to retrieve information about the // currently authenticated user's channel. $channelsResponse = $youtube->channels->listChannels('contentDetails', array('mine' => 'true')); $htmlBody = ''; foreach ($channelsResponse['items'] as $channel) { // Extract the unique playlist ID that identifies the list of videos // uploaded to the channel, and then call the playlistItems.list method // to retrieve that list. $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array('playlistId' => $uploadsListId, 'maxResults' => 50)); $htmlBody .= "<h3>Videos in list {$uploadsListId}</h3><ul>"; foreach ($playlistItemsResponse['items'] as $playlistItem) { $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']); } $htmlBody .= '</ul>'; } } catch (Google_ServiceException $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $string = '<script src="' . base_url() . '"assets/jquery-1.10.2.js"></script><a id="load_page" href="' . $authUrl . '">Connect Me!!</a><script>window.location = $("#load_page"").attr(""href");</script>'; return $string; } } }
function google($video_temp = '', $video_name = '', $video_desc = '') { $OAUTH2_CLIENT_ID = '353001433162-42vrona3fi8msfve7akh857t6fk0di9v.apps.googleusercontent.com'; $OAUTH2_CLIENT_SECRET = 'cEcHT7CkTK5GYUDmC7dgYa8r'; $redirect = 'http://localhost/multitvfinal/index.php/video/google'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($this->session->userdata('state')) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $this->session->set_userdata('token', $client->getAccessToken()); header('Location: ' . $redirect); } $session_token = $this->session->userdata('token'); if ($session_token) { $client->setAccessToken($this->session->userdata('token')); } if ($client->getAccessToken()) { if (isset($video_temp) && $video_temp != '') { // REPLACE this value with the path to the file you are uploading. $videoPath = $video_temp; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($video_name); $snippet->setDescription($video_desc); $snippet->setTags(array("globalPunjab", "Video")); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); $snippet->setChannelTitle("GlobalPunjab"); // 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); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); $htmlBody = $status['id']; //echo "<pre>"; print_r($status); } $htmlBody = false; } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $this->session->set_userdata('state', $state); //echo $this->session->userdata('state'); $authUrl = $client->createAuthUrl(); $htmlBody = $authUrl; } return $htmlBody; //spl_autoload_register('google_api_php_client_autoload'); die; }
protected function _getFlashPlayerUrl(Google_Service_YouTube_Video $entry) { return 'https://www.youtube.com/embed/' . $entry->getId(); }
protected function doSubmit(KalturaDistributionSubmitJobData $data, KalturaYoutubeApiDistributionProfile $distributionProfile) { $client = $this->initClient($distributionProfile); $youtube = new Google_Service_YouTube($client); if ($data->entryDistribution->remoteId) { $data->remoteId = $data->entryDistribution->remoteId; } else { $videoPath = $data->providerData->videoAssetFilePath; if (!$videoPath) { throw new KalturaException('No video asset to distribute, the job will fail'); } if (!file_exists($videoPath)) { throw new KalturaDistributionException("The file [{$videoPath}] was not found (probably not synced yet), the job will retry"); } $needDel = false; if (strstr($videoPath, ".") === false) { $videoPathNew = $this->tempXmlPath . "/" . uniqid() . ".dme"; if (!file_exists($videoPathNew)) { copy($videoPath, $videoPathNew); $needDel = true; } $videoPath = $videoPathNew; } $this->fieldValues = unserialize($data->providerData->fieldValues); // $props['start_date'] = $this->getValueForField(KalturaYouTubeApiDistributionField::START_DATE); // $props['end_date'] = $this->getValueForField(KalturaYouTubeApiDistributionField::END_DATE); $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($this->getValueForField(KalturaYouTubeApiDistributionField::MEDIA_TITLE)); $snippet->setDescription($this->getValueForField(KalturaYouTubeApiDistributionField::MEDIA_DESCRIPTION)); $snippet->setTags(explode(',', $this->getValueForField(KalturaYouTubeApiDistributionField::MEDIA_KEYWORDS))); $snippet->setCategoryId($this->translateCategory($youtube, $distributionProfile, $this->getValueForField(KalturaYouTubeApiDistributionField::MEDIA_CATEGORY))); $status = new Google_Service_YouTube_VideoStatus(); $status->setPrivacyStatus('private'); $status->setEmbeddable(false); if ($data->entryDistribution->sunStatus == KalturaEntryDistributionSunStatus::AFTER_SUNRISE) { $status->setPrivacyStatus('public'); } if ($this->getValueForField(KalturaYouTubeApiDistributionField::ALLOW_EMBEDDING) == 'allowed') { $status->setEmbeddable(true); } $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $client->setDefer(true); $request = $youtube->videos->insert("status,snippet", $video); $chunkSizeBytes = 1 * 1024 * 1024; $media = new Google_Http_MediaFileUpload($client, $request, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); $ingestedVideo = false; $handle = fopen($videoPath, "rb"); while (!$ingestedVideo && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $ingestedVideo = $media->nextChunk($chunk); } /* @var $ingestedVideo Google_Service_YouTube_Video */ fclose($handle); $client->setDefer(false); $data->remoteId = $ingestedVideo->getId(); if ($needDel == true) { unlink($videoPath); } } foreach ($data->providerData->captionsInfo as $captionInfo) { /* @var $captionInfo KalturaYouTubeApiCaptionDistributionInfo */ if ($captionInfo->action == KalturaYouTubeApiDistributionCaptionAction::SUBMIT_ACTION) { $data->mediaFiles[] = $this->submitCaption($youtube, $captionInfo, $data->remoteId); } } $playlistIds = explode(',', $this->getValueForField(KalturaYouTubeApiDistributionField::MEDIA_PLAYLIST_IDS)); $this->syncPlaylistIds($youtube, $data->remoteId, $playlistIds); return $distributionProfile->assumeSuccess; }
/** * Upload the video files to youtube * No matter success or fail, the result will be logged in logStatus() * @param String $videoPath Local video path (./1.mp4) * @param String $videoTitle Video Title * @param String $videoDescription Video Description, allow \n characters and links * @param int $videoCategory Video Category ID, Please refer to the list - https://gist.github.com/dgp/1b24bf2961521bd75d6c * @param String[] $videoTags Keyword Tags array */ function uploadYoutube($videoPath, $videoTitle, $videoDescription, $videoCategory, $videoTags) { $OAUTH2_CLIENT_ID = 'XXX.apps.googleusercontent.com'; //TODO: UPDATE YOUR CLIENT ID $OAUTH2_CLIENT_SECRET = 'XXX'; //TODO:UPDATE YOUR CLIENT SECRET $RESULT = array('refreshToken' => 'XXXXXXXXXXXXX'); //TODO:UPDATE YOUR PROPOSED ACCOUNT REFRESH ID $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://localhost/authorize/'); $client->setRedirectUri($redirect); $youtube = new Google_Service_YouTube($client); $client->refreshToken($RESULT['refreshToken']); $RESULT['accessToken'] = $client->getAccessToken()['access_token']; $client->authenticate($RESULT['accessToken']); if ($client->getAccessToken()) { try { logStatus('Video Start Upload - ' . $videoTitle); $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($videoTitle); $snippet->setDescription($videoDescription); $snippet->setTags(${$videoTags}); $snippet->setCategoryId($videoCategory); $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "private"; //TODO: UPDATE YOUR UPLOAD VIDEO STATUS , (private/public) $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $chunkSizeBytes = 1 * 1024 * 1024; $client->setDefer(true); $insertRequest = $youtube->videos->insert("status,snippet", $video); $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize(filesize($videoPath)); $status = false; $handle = fopen($videoPath, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $media->nextChunk($chunk); } fclose($handle); $client->setDefer(false); logStatus('Video Uploaded -' . $status['snippet']['title'] . ' ' . $status['id']); saveYoutubePath($status['id']); } catch (Google_Service_Exception $e) { logStatus($e->getMessage()); exit; } catch (Google_Exception $e) { logStatus($e->getMessage()); exit; } } else { $state = mt_rand(); $client->setState($state); $authUrl = $client->createAuthUrl(); logStatus($authUrl); exit; } }
public function actionUpload() { $this->checkAccess("upload"); if (empty($_FILES) || !isset($_FILES['video'])) { return ApiHelper::errorResponse("Video file missing", 422); } $client = new \Google_Client(); $client->setClientId(Yii::$app->params['OAUTH2_CLIENT_ID']); $client->setClientSecret(Yii::$app->params['OAUTH2_CLIENT_SECRET']); $client->setScopes('https://www.googleapis.com/auth/youtube'); $client->setRedirectUri(Yii::$app->params['redirectVideo']); // Define an object that will be used to make all API requests. $youtube = new \Google_Service_YouTube($client); if ($this->checkToken()) { $token = $this->getToken(); } else { $oldToken = $this->getToken(); $token = $this->updateToken($oldToken->refresh_token); if (is_array($token)) { return ApiHelper::errorResponse($token, 500); } } $client->setAccessToken($token->toJson()); // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { try { // REPLACE this value with the path to the file you are uploading. $videoPath = $this->saveToLocal($_FILES['video']); // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new \Google_Service_YouTube_VideoSnippet(); $snippet->setTitle(Yii::$app->request->post('title')); $snippet->setDescription(Yii::$app->request->post('description')); $snippet->setTags(explode(",", Yii::$app->request->post('tags'))); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // 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); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(true); //$status['snippet']['title'] return ApiHelper::successResponse(["link" => "https://www.youtube.com/watch?v=" . $status['id']]); } catch (\Google_Service_Exception $e) { return ApiHelper::errorResponse(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())), 500); } catch (\Google_Exception $e) { return ApiHelper::errorResponse(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())), 500); } } return ApiHelper::errorResponse("No authorizied", 401); }
/** * displayYouTubeUploadSubmitPage * * Upload the video to youtube. * * @return void */ function displayYouTubeUploadSubmitPage() { $videoTitle = ''; $videoDescription = ''; $videoPath = $_FILES['video']['tmp_name']; if (isset($_POST['title'])) { $videoTitle = strip_tags($_POST['title']); } if (isset($_POST['description'])) { $videoDescription = strip_tags($_POST['description']); } $videoCategory = isset($_POST['category']) ? $_POST['category'] : ''; $videoPrivacy = isset($_POST['unlisted']) ? 'unlisted' : 'public'; // Create fcms video - we update after the youtube video is created $sql = "INSERT INTO `fcms_video` (\n `source_id`, \n `title`, \n `description`, \n `source`, \n `created`, \n `created_id`, \n `updated`, \n `updated_id`\n )\n VALUES\n ('0', ?, ?, 'youtube', NOW(), ?, NOW(), ?)"; $params = array($videoTitle, $videoDescription, $this->fcmsUser->id, $this->fcmsUser->id); $videoId = $this->fcmsDatabase->insert($sql, $params); if ($videoId === false) { $this->displayHeader(); $this->fcmsError->displayError(); $this->displayFooter(); return; } try { $googleClient = getAuthedGoogleClient($this->fcmsUser->id); $youtube = new Google_Service_YouTube($googleClient); $snippet = new Google_Service_YouTube_VideoSnippet(); $status = new Google_Service_YouTube_VideoStatus(); $video = new Google_Service_YouTube_Video(); // Save the video title, desc and category $snippet->setTitle($videoTitle); $snippet->setDescription($videoDescription); $snippet->setCategoryId('22'); // Save privacy (public, private or unlisted) $status->privacyStatus = $videoPrivacy; // Associate the snippet and status objects with the new video $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chuck in bytes. // Note: higher value faster uploads, lower for better recovery $chunkSizeBytes = 1 * 1024 * 1024; // Defer - tells the client to return a request which can be called // with ->execute() instead of making API call immediately $googleClient->setDefer(true); $insertRequest = $youtube->videos->insert('status,snippet', $video); // Create a MediaFileUpload for resumable uploads $media = new Google_Http_MediaFileUpload($googleClient, $insertRequest, 'video/*', null, true, $chunkSizeBytes); $media->setFileSize($_FILES['video']['size']); // 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); $sourceId = $status['id']; // Update fcms video $sql = "UPDATE `fcms_video`\n SET `source_id` = ?,\n `updated` = NOW()\n WHERE `id` = ?"; $params = array($sourceId, $videoId); if (!$this->fcmsDatabase->update($sql, $params)) { $this->displayHeader(); $this->fcmsError->displayError(); $this->displayFooter(); return; } header("Location: video.php?u=" . $this->fcmsUser->id . "&id={$videoId}"); } catch (Exception $e) { $this->displayHeader(); $this->fcmsError->add(array('type' => 'operation', 'message' => 'Could not upload video to YouTube.', 'error' => $e, 'file' => __FILE__, 'line' => __LINE__)); $this->fcmsError->displayError(); $this->displayFooter(); return; } }
/** * Uploads the passed video to the YouTube account identified by the access token in the DB and returns the * uploaded video's YouTube Video ID. Attempts to automatically refresh the token if it's expired. * * @param array $data As is returned from \Input::all() given a form as per the one in views/example.blade.php * @return string The ID of the uploaded video * @throws \Exception */ public function upload(array $data) { $accessToken = $this->client->getAccessToken(); if (is_null($accessToken)) { throw new \Exception('You need an access token to upload'); } // Attempt to refresh the access token if it's expired and save the new one in the database if ($this->client->isAccessTokenExpired()) { $accessToken = json_decode($accessToken); $refreshToken = $accessToken->refresh_token; $this->client->refreshToken($refreshToken); $newAccessToken = $this->client->getAccessToken(); $this->saveAccessTokenToDB($newAccessToken); } $snippet = new \Google_Service_YouTube_VideoSnippet(); if (array_key_exists('title', $data)) { $snippet->setTitle($data['title']); } if (array_key_exists('description', $data)) { $snippet->setDescription($data['description']); } if (array_key_exists('tags', $data)) { $snippet->setTags($data['tags']); } if (array_key_exists('category_id', $data)) { $snippet->setCategoryId($data['category_id']); } $status = new \Google_Service_YouTube_VideoStatus(); if (array_key_exists('status', $data)) { $status->privacyStatus = $data['status']; } $video = new \Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $result = $this->youtube->videos->insert('status,snippet', $video, array('data' => file_get_contents($data['video']->getRealPath()), 'mimeType' => $data['video']->getMimeType(), 'uploadType' => 'multipart')); if (!$result instanceof \Google_Service_YouTube_Video) { throw new \Exception('Expecting instance of Google_Service_YouTube_Video, got:' . $result); } return $result->getId(); }
/** * Uploads a single video to YouTube * * @param string $filepath Movie id * @param int $id Movie id * @param string $title Movie id * @param string $description Movie id * @param array $tags Movie id * @param boolean $share Movie options * @param boolean $html Movie options * */ public function uploadVideoToYouTube($filepath, $id, $title, $description, $tags, $share, $html) { // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($title); $snippet->setDescription($description); $snippet->setTags($tags); //$snippet->setPublishedAt(array('Helioviewer.org')); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("28"); // 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); //Proceed to upload $this->_uploadVideoToYouTube($video, $filepath, $id, $title, $description, $tags, $share, $html); }
public function put() { $config = $this->uploadService->getConfig(); // $config = new UploadService_Config(); $configConstraints = $config->getConstraints(); // $configConstraints = new UploadService_Config_Constraints(); $response = ["success" => false, "message" => null, "file" => ["name" => null, "uri" => null, "isVideo" => false]]; $path = file::cleanPath($config->getPath()); //prepare file $file = $_FILES["file"]; $fileError = $file["error"]; $fileName = $file["name"]; $fileSize = $file["size"]; $fileTempName = $file["tmp_name"]; $fileType = $file["type"]; $fileName = file::cleanName($fileName); //get numerator $numerator = (int) numerador('archivoTemporal', 0, ''); $newFileName = "{$numerator}-{$fileName}"; //destinies $basePath = $_SERVER['DOCUMENT_ROOT']; $S3destiny = "{$path}/{$newFileName}"; $destiny = "{$basePath}/{$S3destiny}"; if ($fileError === UPLOAD_ERR_OK) { $videoControl = file::isVideo($fileName) && $config->getVideoPlatform(); if ($videoControl) { //video control $response["success"] = move_uploaded_file($fileTempName, $destiny); } else { set_time_limit(600); //destiny file switch ($config->getToserver()) { case UploadService::TO_S3: $S3 = new S3(AWS_ACCES_KEY, AWS_SECRET_KEY); $response["success"] = $S3->putObjectFile($fileTempName, "owlgroup", $S3destiny, S3::ACL_PUBLIC_READ); break; case UploadService::TO_SERVER: $destinyFolder = str_replace("/{$newFileName}", '', $destiny); !file_exists($destinyFolder) && !is_dir($destinyFolder) && creaCarpeta($destinyFolder); $response["success"] = move_uploaded_file($fileTempName, $destiny); break; case UploadService::TO_BOTH: $S3 = new S3(AWS_ACCES_KEY, AWS_SECRET_KEY); $destinyFolder = str_replace("/{$newFileName}", '', $destiny); !file_exists($destinyFolder) && !is_dir($destinyFolder) && creaCarpeta($destinyFolder); $response["success"] = $S3->putObjectFile($fileTempName, "owlgroup", $S3destiny, S3::ACL_PUBLIC_READ) && move_uploaded_file($fileTempName, $destiny); break; } } if ($response["success"]) { $response["file"]["name"] = $newFileName; //Insert register to file temporal table $formId = post("form"); $field = post("field"); $userId = $_SESSION["Persona"]["string"]; $enterpriseUser = $_SESSION["enterprise_user"]; addTempFile($numerator, $path, $newFileName, $fileName, $fileType, $formId, $userId, $enterpriseUser, $field); if ($videoControl) { //video control switch ($config->getVideoPlatform()) { case UploadService::VIDEO_PLATFORM_OWL: //NOTHING HERE break; case UploadService::VIDEO_PLATFORM_YOUTUBE: set_time_limit(18000); $systemGoogleClient = get_system_google_client(); if ($systemGoogleClient) { $client = $systemGoogleClient->client; //Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); try { $fileSize = filesize($destiny); $videoSnippet = new Google_Service_YouTube_VideoSnippet(); $videoSnippet->setTitle($fileName); $videoSnippet->setDescription("This video was upload in " . date("Y-m-d H:i:s")); $videoStatus = new Google_Service_YouTube_VideoStatus(); $videoStatus->setPrivacyStatus("unlisted"); //public | private | unlisted $video = new Google_Service_YouTube_Video(); $video->setSnippet($videoSnippet); $video->setStatus($videoStatus); $chunkSizeBytes = 1 * 1024 * 1024; //1 megabyte $client->setDefer(true); //snippet,contentDetails,fileDetails,player,processingDetails,recordingDetails,statistics,status,suggestions,topicDetails $httpRequest = $youtube->videos->insert("status,snippet", $video); $mediaFileUpload = new Google_Http_MediaFileUpload($client, $httpRequest, 'video/*', null, true, $chunkSizeBytes); $mediaFileUpload->setFileSize($fileSize); $status = false; //open flow resource video file in binary mode $handle = fopen($destiny, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSizeBytes); $status = $mediaFileUpload->nextChunk($chunk); } //close flow reource fclose($handle); $client->setDefer(false); $videoInserted = $status; //Google_Service_YouTube_Video class; $response["file"]["name"] = $videoInserted->getId(); } catch (Google_Service_Exception $e) { $response["success"] = false; $response["message"] = htmlspecialchars("A service error occurred: {$e->getMessage()}"); } catch (Google_Exception $e) { $response["success"] = false; $response["message"] = htmlspecialchars("An client error occurred: {$e->getMessage()}"); } } else { $response["success"] = false; $response["message"] = "Ha ocurrido un error al establecer un medio para Google Services"; } //delete file because it's not necesary save in the server when the file is a video unlink($destiny); break; } } else { if (file::isImage($fileName)) { switch ($config->getToserver()) { case UploadService::TO_S3: case UploadService::TO_BOTH: $response["file"]["uri"] = CONS_IPArchivos . "/{$S3destiny}"; break; case UploadService::TO_SERVER: $response["file"]["uri"] = getDomain() . "/{$S3destiny}"; break; } } } } else { $response["message"] = "Destiny directory don't exists or isn't writable, type to server is {$config->getToserver()}"; } } else { $response["message"] = "Happened a error whit code {$fileError}"; } return $response; }
public function connect_google($in_upload_state = "") { set_include_path(get_include_path() . PATH_SEPARATOR . BASEPATH . '../assets/google_api/src'); require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; $this->load->library('session'); $client = new Google_Client(); $client->setApplicationName("Zeepro youtube upload"); $client->setClientId("652807238221-vrc4no9o0t9mdb48ltc69v215henenm4.apps.googleusercontent.com"); $client->setClientSecret("PPww8vp8cOVcqeHioL7HbCFx"); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('https://sso.zeepro.com/redirect.ashx', FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); $client->setAccessType('offline'); $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($this->session->userdata('state')) !== strval($_GET['state'])) { var_dump($this->session->all_userdata()); die('The session state did not match.'); } $client->authenticate($_GET['code']); $this->session->set_userdata('token', $client->getAccessToken()); $this->session->set_userdata('code', $_GET['code']); } if ($this->session->userdata('token') !== FALSE) { $client->setAccessToken($this->session->userdata('token')); if ($client->isAccessTokenExpired()) { $currentTokenData = json_decode($this->session->userdata('token')); if (isset($currentTokenData->refresh_token)) { $client->refreshToken($tokenData->refresh_token); } } } if ($client->getAccessToken() && $in_upload_state != "") { $this->load->helper('zimapi'); try { $videoPath = ZIMAPI_FILEPATH_TIMELAPSE; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($this->session->userdata('yt_title')); $snippet->setDescription($this->session->userdata("yt_desc")); $snippet->setTags($this->session->userdata("yt_tags")); // Numeric video category. See https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = $this->session->userdata('yt_privacy'); // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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/mp4', 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); $client->setDefer(false); $this->session->unset_userdata(array('yt_title', 'yt_desc', 'yt_tags', 'yt_privacy')); echo "<h3>Video Uploaded</h3><ul>"; echo sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']); echo '</ul>'; //stats info $this->load->helper('printerlog'); PrinterLog_statsShareVideo(PRINTERLOG_STATS_LABEL_YOUTUBE); } catch (Google_ServiceException $e) { $this->_exitWithError500(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } catch (Google_Exception $e) { $this->_exitWithError500(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } $this->session->set_userdata('token', $client->getAccessToken()); } else { $this->load->helper(array('zimapi', 'corestatus')); $prefix = CoreStatus_checkTromboning() ? 'https://' : 'http://'; $data = array('printersn' => ZimAPI_getSerial(), 'URL' => $prefix . $_SERVER['HTTP_HOST'] . '/share/video_upload'); $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data))); $context = stream_context_create($options); @file_get_contents('https://sso.zeepro.com/url.ashx', false, $context); $result = substr($http_response_header[0], 9, 3); if ($result == 200) { //echo 'ca marche'; } $state = ZimAPI_getSerial(); $client->setState($state); $this->session->set_userdata('state', $state); $authUrl = $client->createAuthUrl(); $this->output->set_header("Location: " . $authUrl); } return; }
public function uploadVideosChannel() { // Call set_include_path() as needed to point to your client library. set_time_limit(0); require_once 'Google/autoload.php'; require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; session_start(); $htmlBody = ""; /* * You can acquire an OAuth 2.0 client ID and client secret from the * Google Developers Console <https://console.developers.google.com/> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ $settings = Engine_Api::_()->getApi('settings', 'core'); $user_youtube_allow = $settings->getSetting('user_youtube_allow'); if (!$user_youtube_allow) { return false; } $token = $settings->getSetting('user_youtube_token', ""); $OAUTH2_CLIENT_ID = $settings->getSetting('user_youtube_clientid', ""); $OAUTH2_CLIENT_SECRET = $settings->getSetting('user_youtube_secret', ""); if (empty($token) || empty($token) || empty($token)) { return fasle; } //getting videos $videoTable = Engine_Api::_()->getItemTable('video'); $select = $videoTable->select()->where('file_id <> ?', '0')->limit(2); $videos = $videoTable->fetchAll($select); foreach ($videos as $videoLoop) { $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setAccessType('offline'); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL); $redirect = str_replace("index.php", "admin/user/youtube/token", $redirect); $client->setRedirectUri($redirect); $client->setAccessToken($token); /** * Check to see if our access token has expired. If so, get a new one and save it to file for future use. */ if ($client->isAccessTokenExpired()) { $newToken = json_decode($client->getAccessToken()); $client->refreshToken($newToken->refresh_token); $settings->setSetting('user_youtube_token', $client->getAccessToken()); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { try { // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); //get info of files $file = Engine_Api::_()->getItem('storage_file', $videoLoop->file_id); if (!file) { continue; } // REPLACE this value with the path to the file you are uploading. $videoPath = $file->storage_path; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($videoLoop->getTitle()); $snippet->setDescription($videoLoop->getDescription()); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // 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); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); //update video data $videoLoop->code = $status['id']; $videoLoop->file_id = 0; $videoLoop->type = 1; $videoLoop->status = 1; $videoLoop->save(); //delete old video $file->delete(); //echo $status['id']; //$htmlBody .= "<h3>Video Uploaded</h3><ul>"; //$htmlBody .= sprintf('<li>%s (%s)</li>', // $status['snippet']['title'], // $status['id']); $htmlBody .= '</ul>'; } catch (Google_Service_Exception $e) { //$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', // htmlspecialchars($e->getMessage())); continue; } catch (Google_Exception $e) { //$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', // htmlspecialchars($e->getMessage())); continue; } } } //echo $htmlBody; }
private function youtube_oauth2_upload_video($attachment_data) { //Init vars $file_type = NULL; $path_info = NULL; $myVideoEntry = NULL; $uploadUrl = NULL; $filesource = NULL; $newEntry = NULL; $output = NULL; //Cache plugin options $plugin_options = get_option(PRSOGFORMSADVUPLOADER__OPTIONS_NAME); //cache client object from youtube api $client = $this->data['YouTubeClass']['client']; $youtube = $this->data['YouTubeClass']['youtube']; //Check for required data if (isset($attachment_data['file_path'], $attachment_data['mime_type'], $attachment_data['title'], $attachment_data['description'])) { try { // REPLACE this value with the path to the file you are uploading. $videoPath = $attachment_data['file_path']; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($attachment_data['title']); $snippet->setDescription($attachment_data['description']); //$snippet->setTags(array("tag1", "tag2")); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list //$snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", // "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); if ($plugin_options['video_is_private']) { $status->privacyStatus = "private"; } else { $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); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $chunkSizeBytes = 10 * 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); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); $this->plugin_error_log($status); return $status; } catch (Google_Service_Exception $e) { $this->plugin_error_log(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } catch (Google_Exception $e) { $this->plugin_error_log(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } } }
/** * Upload the video to YouTube * @param string $path The path to the file you wish to upload. * @param array $snippet An array of data. * @param string $status The status of the uploaded video, set to 'public' by default. * @return mixed */ public function upload($path, array $data, $privacyStatus = 'public') { $this->handleAccessToken(); /* ------------------------------------ #. Setup the Snippet ------------------------------------ */ $snippet = new \Google_Service_YouTube_VideoSnippet(); if (array_key_exists('title', $data)) { $snippet->setTitle($data['title']); } if (array_key_exists('description', $data)) { $snippet->setDescription($data['description']); } if (array_key_exists('tags', $data)) { $snippet->setTags($data['tags']); } if (array_key_exists('category_id', $data)) { $snippet->setCategoryId($data['category_id']); } /* ------------------------------------ #. Set the Privacy Status ------------------------------------ */ $status = new \Google_Service_YouTube_VideoStatus(); $status->privacyStatus = $privacyStatus; /* ------------------------------------ #. Set the Snippet & Status ------------------------------------ */ $video = new \Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); /* ------------------------------------ #. Set the Chunk Size ------------------------------------ */ $chunkSize = 1 * 1024 * 1024; /* ------------------------------------ #. Set the defer to true ------------------------------------ */ $this->client->setDefer(true); /* ------------------------------------ #. Build the request ------------------------------------ */ $insert = $this->youtube->videos->insert('status,snippet', $video); /* ------------------------------------ #. Upload ------------------------------------ */ $media = new \Google_Http_MediaFileUpload($this->client, $insert, 'video/*', null, true, $chunkSize); /* ------------------------------------ #. Set the Filesize ------------------------------------ */ $media->setFileSize(filesize($path)); /* ------------------------------------ #. Read the file and upload in chunks ------------------------------------ */ $status = false; $handle = fopen($path, "rb"); while (!$status && !feof($handle)) { $chunk = fread($handle, $chunkSize); $status = $media->nextChunk($chunk); } fclose($handle); /* ------------------------------------ #. Set the defer to false again ------------------------------------ */ $this->client->setDefer(true); /* ------------------------------------ #. Return the Uploaded Video ID ------------------------------------ */ return $status['id']; }
public function youtube_upload($video = "linkedin.mp4", $title = "tvn rahul youtube api v3", $desc = "tvn rahul youtube api v3 for php", $tags = ["rahultvn", "youtubeapi3"], $privacy_status = "public") { $result = []; $htmlBody = ""; $OAUTH2_CLIENT_ID = $this->ci->config->item('OAUTH2_CLIENT_ID'); //'980811603180-qlbtavji7o0ekejgerqifous319d2he2.apps.googleusercontent.com'; $OAUTH2_CLIENT_SECRET = $this->ci->config->item('OAUTH2_CLIENT_SECRET'); //'sbzALHg38sB9aXEo0a9GG4ZA'; $client = new Google_Client(); $client->setClientId($OAUTH2_CLIENT_ID); $client->setClientSecret($OAUTH2_CLIENT_SECRET); $client->setScopes('https://www.googleapis.com/auth/youtube'); $redirect = $this->ci->config->item('REDIRECT_URI'); //filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], //FILTER_SANITIZE_URL); $client->setRedirectUri($redirect); // Define an object that will be used to make all API requests. $youtube = new Google_Service_YouTube($client); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { //echo $client->getAccessToken(); try { // REPLACE this value with the path to the file you are uploading. $videoPath = realpath(APPPATH . '../videos/' . $video); //$videoPath = "videos/linkedin.mp4"; // Create a snippet with title, description, tags and category ID // Create an asset resource and set its snippet metadata and type. // This example sets the video's title, description, keyword tags, and // video category. $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($title); $snippet->setDescription($desc); $snippet->setTags($tags); // Numeric video category. See // https://developers.google.com/youtube/v3/docs/videoCategories/list $snippet->setCategoryId("22"); // Set the video's status to "public". Valid statuses are "public", // "private" and "unlisted". $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = $privacy_status; // Associate the snippet and status objects with a new video resource. $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); // Specify the size of each chunk of data, in bytes. Set a higher value for // reliable connection as fewer chunks lead to faster uploads. Set a lower // value for better recovery on less reliable connections. $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); // If you want to make other calls after the file upload, set setDefer back to false $client->setDefer(false); $htmlBody .= "<h3>Video Uploaded</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $status['snippet']['title'], $status['id']); $htmlBody .= '</ul>'; $result['id'] = $status['id']; $result['title'] = $status['snippet']['title']; } catch (Google_Service_Exception $e) { $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } $_SESSION['token'] = $client->getAccessToken(); } else { // If the user hasn't authorized the app, initiate the OAuth flow $state = mt_rand(); $client->setState($state); $_SESSION['state'] = $state; $authUrl = $client->createAuthUrl(); $htmlBody .= "<h3>Authorization Required</h3>"; $htmlBody .= "<p>You need to <a href=" . $authUrl . ">authorize access</a> before proceeding.<p>"; $result['authUrl'] = $authUrl; } $result['message'] = $htmlBody; return $result; }
/** * Associate the snippet and status objects with a new video resource. * * @param \Google_Service_YouTube_VideoSnippet $snippet * @param \Google_Service_YouTube_VideoStatus $status * * @return \Google_Service_YouTube_Video */ protected function createVideoResource(\Google_Service_YouTube_VideoSnippet $snippet, \Google_Service_YouTube_VideoStatus $status) { $video = new \Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); return $video; }
public function post_video($title, $description, $video_name) { require_once __DIR__ . '/../../../../vendor/google/apiclient/src/Google/Service/YouTube.php'; $token = Access_token::inst()->get_youtube_token($this->_user_id); $this->_google->setApplicationName("Google keywords"); $this->_google->setAccessToken($token->data); $youTubeService = new Google_Service_YouTube($this->_google); $snippet = new Google_Service_YouTube_VideoSnippet(); $snippet->setTitle($title); $snippet->setDescription($description); $snippet->setTags(array("video")); $snippet->setCategoryId("22"); $status = new Google_Service_YouTube_VideoStatus(); $status->privacyStatus = "public"; $video = new Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $error = true; $i = 0; $video_path = FCPATH . 'public/uploads/' . $this->_user_id . '/' . $video_name; if (function_exists('mime_content_type')) { $mime_type = mime_content_type($video_path); } else { $mime_type = $this->_get_mime_content_type($video_name); } try { $obj = $youTubeService->videos->insert("status,snippet", $video, array("data" => file_get_contents($video_path), "mimeType" => $mime_type)); return $obj; } catch (Google_ServiceException $e) { print "Caught Google service Exception " . $e->getCode() . " message is " . $e->getMessage() . " <br>"; print "Stack trace is " . $e->getTraceAsString(); } }