Example #1
0
 /**
  * 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 uploadVideo($season, $episode)
{
    global $youtube;
    // Check to ensure that the access token was successfully acquired.
    if ($client->getAccessToken()) {
        try {
            // XXX pick file name
            $videoPath = "/path/to/file.mp4";
            $snippet = new Google_Service_YouTube_VideoSnippet();
            $snippet->setTitle('SteamLUG Cast s03e00 ‐');
            // XXX capture from youtube description
            $snippet->setDescription('Test description');
            // TODO licence? comments? language? can we leave these as default?
            $snippet->setTags(array('linux', 'gaming', 'steam', 'steamlug', 'lug', 'podcast', 'steamlugcast', 'gaming on linux', 'steam for linux', 'linux steam', 'linux games', 'gaming on fedora', 'steam for fedora', 'fedora steam', 'fedora games', 'gaming on ubuntu', 'steam for ubuntu', 'ubuntu steam', 'ubuntu games', 'gaming on arch', 'steam for arch', 'arch steam', 'arch games'));
            // https://developers.google.com/youtube/v3/docs/videoCategories/list#try-it using ‘snippet’ and ‘GB’
            $snippet->setCategoryId('20');
            $status = new Google_Service_YouTube_VideoStatus();
            $status->privacyStatus = 'unlisted';
            $video = new Google_Service_YouTube_Video();
            $video->setSnippet($snippet);
            $video->setStatus($status);
            $chunkSizeBytes = 2 * 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));
            // 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);
            // good!
        } catch (Google_ServiceException $e) {
            // ' A service error occurred: '. htmlspecialchars( $e->getMessage( ) )
        } catch (Google_Exception $e) {
            // 'An client error occurred: ' . htmlspecialchars( $e->getMessage( ) )
        }
    } else {
        // 'We’re missing an access token'
        // TODO something here :^)
    }
}
/**
 *	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;
    }
}
Example #4
0
 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;
 }
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
// 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 = "/path/to/file.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("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;
 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;
 }
 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;
 }
 // submit the upload request
 try {
     // set video path
     $videoPath = $_FILES['videolocation']['tmp_name'];
     // set playlist ID
     $playlist_id = $_POST['video-playlist-setting'];
     // set video category
     $video_category = $_POST['video-category'];
     // 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($_POST['video-title']);
     $snippet->setDescription($_POST['video-details']);
     $snippet->setTags(explode(',', $_POST['video-tags']));
     $playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
     // Numeric video category. See
     // https://developers.google.com/youtube/v3/docs/videoCategories/list
     $snippet->setCategoryId($video_category);
     // Set the video's status.
     // Valid statuses are "public",
     // "private" and "unlisted".
     $status = new Google_Service_YouTube_VideoStatus();
     $status->privacyStatus = $_POST['video-privacy-settings'];
     // schedule the post at a given day and time! cool!
     // $status->publishAt = '2020-04-04T00:00:0.0Z';
     // Associate the snippet and status objects with a new video resource.
     $video = new Google_Service_YouTube_Video();
     $video->setSnippet($snippet);
     $video->setStatus($status);
        return $this->client;
    }
    public function getYt()
    {
        return $this->yt;
    }
}
$ytua = new XYoutubeUploaderYtapi();
$ytua->getFreshToken();
$client = $ytua->getClient();
$youtube = $ytua->getYt();
/* Sample code from https://developers.google.com/youtube/v3/code_samples/php?hl=en#resumable_uploads */
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle($title);
$snippet->setDescription($date . " Passage: " . $passage . " http://orpc.sg/node/" . $nodeid);
$snippet->setTags(array("orpc", "sermon"));
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "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));
/* Read the media file and upload it chunk by chunk. */
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
    $chunk = fread($handle, $chunkSizeBytes);
Example #11
0
 if ($client->getAccessToken()) {
     /*
      * 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 = $client->getAccessToken();
         $client->refreshToken($newToken->refresh_token);
         // file_put_contents('the_key.txt', $client->getAccessToken());
     }
     $youtube = new Google_Service_YouTube($client);
     // Create a snipet with title, description, tags and category id
     $snippet = new Google_Service_YouTube_VideoSnippet();
     $snippet->setTitle($name);
     $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('unlisted');
     // 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);
Example #12
0
 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);
 }
Example #13
0
 /**
  * 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();
 }
Example #14
0
 /**
  * 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);
 }
Example #15
0
 /**
  * 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'];
 }
 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;
 }
Example #17
0
 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();
     }
 }