/**
  * Create a resumable video upload to YouTube.
  *
  * @param AssetFileModel                $asset
  * @param \Google_Service_YouTube_Video $video
  *
  * @throws Exception
  *
  * @return bool|string
  */
 protected function uploadVideo(AssetFileModel $asset, \Google_Service_YouTube_Video $video)
 {
     // Get file by asset
     $file = $this->getAssetFile($asset);
     // 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;
     // Verify the client
     if ($this->client instanceof \Google_Client) {
         // 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.
         $this->client->setDefer(true);
         // Create a request for the API's videos.insert method to create and upload the video.
         $insertRequest = $this->youtube->videos->insert('status,snippet', $video);
         // Create a MediaFileUpload object for resumable uploads.
         $media = new \Google_Http_MediaFileUpload($this->client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
         $media->setFileSize(IOHelper::getFileSize($file));
         // Read the media file and upload it chunk by chunk.
         $status = $this->uploadChunks($file, $media, $chunkSizeBytes);
         // If you want to make other calls after the file upload, set setDefer back to false
         $this->client->setDefer(false);
         // Return the status
         return $status;
     }
     // Or die
     throw new Exception(Craft::t('Unable to authenticate the YouTube API client'));
 }
function doResumableUpload(Google_Client $client)
{
    // Drive service
    $driveService = new Google_Service_Drive($client);
    $gs_basepath = 'gs://' . CloudStorageTools::getDefaultGoogleStorageBucketName();
    $fileName = UPLOAD_FILENAME;
    // 82.52MB file
    $fileToUploadPath = $gs_basepath . "/{$fileName}";
    $uploadFilesize = filesize($fileToUploadPath);
    $options = array('gs' => array('enable_cache' => false, 'acl' => 'public-read'));
    $ctx = stream_context_create($options);
    if (($handle = fopen($fileToUploadPath, 'r', false, $ctx)) === false) {
        throw new Exception('fopen failed.');
    }
    $mimeType = CloudStorageTools::getContentType($handle);
    // prepare a drive file
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($fileName);
    $file->setMimeType($mimeType);
    $file->setFileSize($uploadFilesize);
    // You can also set the parent folder:
    // @see https://developers.google.com/drive/v2/reference/files/insert
    $chunkSizeBytes = 256 * 1024 * 4 * 1;
    // upload in multiples of 256K (1M * n)
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $request = $driveService->files->insert($file);
    // Create a media file upload to represent our upload process.
    $media = new Google_Http_MediaFileUpload($client, $request, $mimeType, null, true, $chunkSizeBytes);
    // set the media filesize to the actual filesize.
    $media->setFileSize($uploadFilesize);
    // Upload the various chunks. $status will be false until the process is complete.
    $status = false;
    while (!$status && !feof($handle)) {
        $chunk = readChunk($handle, $chunkSizeBytes);
        $status = $media->nextChunk($chunk);
    }
    fclose($handle);
    // Reset to the client to execute requests immediately in the future.
    $client->setDefer(false);
    var_dump($status);
}
Example #3
0
}
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
    try {
        // REPLACE with the path to your file that you want to upload for thumbnail
        $imagePath = "/path/to/file.jpg";
        // 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);
        $chan = new Google_Service_YouTube_ChannelBannerResource();
        // Create a request for the API's channelBanners.insert method to upload the banner.
        $insertRequest = $youtube->channelBanners->insert($chan);
        // Create a MediaFileUpload object for resumable uploads.
        $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'image/jpeg', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($imagePath));
        // 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
 function uploadFile()
 {
     $cachedfolder = $this->cache->isCached($this->_requestedEntry);
     if ($cachedfolder === false) {
         $cachedfolder = $this->getEntry($this->_requestedEntry);
         if ($cachedfolder === false) {
             return new WP_Error('broke', __("Root folder not found ", 'useyourdrive'));
             die;
         }
     }
     /* Check if user is allowed to upload to this dir */
     if (!$cachedfolder->isInFolder($this->_rootFolder)) {
         return new WP_Error('broke', __("You are not authorized to upload files to this directory", 'useyourdrive'));
         die;
     }
     /* Upload File to server */
     require 'jquery-file-upload/server/UploadHandler.php';
     $accept_file_types = '/.(' . $this->options['upload_ext'] . ')$/i';
     $max_file_size = $this->options['maxfilesize'];
     $uploadir = wp_upload_dir();
     $options = array('upload_dir' => $uploadir['path'] . '/', 'upload_url' => $uploadir['url'] . '/', 'access_control_allow_methods' => array('POST', 'PUT'), 'accept_file_types' => $accept_file_types, 'inline_file_types' => '/\\.____$/i', 'orient_image' => false, 'image_versions' => array(), 'max_file_size' => $max_file_size, 'print_response' => false);
     if ($this->options['demo'] === '1') {
         $options['accept_file_types'] = '/\\.____$/i';
     }
     $error_messages = array(1 => __('The uploaded file exceeds the upload_max_filesize directive in php.ini', 'useyourdrive'), 2 => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 'useyourdrive'), 3 => __('The uploaded file was only partially uploaded', 'useyourdrive'), 4 => __('No file was uploaded', 'useyourdrive'), 6 => __('Missing a temporary folder', 'useyourdrive'), 7 => __('Failed to write file to disk', 'useyourdrive'), 8 => __('A PHP extension stopped the file upload', 'useyourdrive'), 'post_max_size' => __('The uploaded file exceeds the post_max_size directive in php.ini', 'useyourdrive'), 'max_file_size' => __('File is too big', 'useyourdrive'), 'min_file_size' => __('File is too small', 'useyourdrive'), 'accept_file_types' => __('Filetype not allowed', 'useyourdrive'), 'max_number_of_files' => __('Maximum number of files exceeded', 'useyourdrive'), 'max_width' => __('Image exceeds maximum width', 'useyourdrive'), 'min_width' => __('Image requires a minimum width', 'useyourdrive'), 'max_height' => __('Image exceeds maximum height', 'useyourdrive'), 'min_height' => __('Image requires a minimum height', 'useyourdrive'));
     $this->upload_handler = new UploadHandler($options, false, $error_messages);
     $response = @$this->upload_handler->post(false);
     /* Upload files to Google Drive */
     foreach ($response['files'] as &$file) {
         /* Check user permission */
         $userrole = $cachedfolder->getItem()->getUserPermission()->getRole();
         if (in_array($userrole, array('reader', 'commenter'))) {
             $file->error = __("You are not authorized to upload files to this directory", 'useyourdrive');
         }
         if (!isset($file->error)) {
             /* Write file */
             $filePath = $file->tmp_path;
             $chunkSizeBytes = 1 * 1024 * 1024;
             /* Update Mime-type if needed (for IE8 and lower?) */
             include_once 'mime-types/mime-types.php';
             $fileExtension = pathinfo($file->name, PATHINFO_EXTENSION);
             $file->type = getMimeType($fileExtension);
             try {
                 /* Create new Google File */
                 $googledrive_file = new Google_Service_Drive_DriveFile();
                 $googledrive_file->setTitle($file->name);
                 $googledrive_file->setMimeType($file->type);
                 /* Add Parent to Google File */
                 if ($this->_lastFolder != null) {
                     $parent = new Google_Service_Drive_ParentReference();
                     $parent->setId($this->_lastFolder);
                     $googledrive_file->setParents(array($parent));
                 }
                 /* Call the API with the media upload, defer so it doesn't immediately return. */
                 $this->client->setDefer(true);
                 $convert = $this->options['convert'] === '1' ? true : false;
                 $request = $this->googleDriveService->files->insert($googledrive_file, array('convert' => $convert));
                 $request->disableGzip();
                 /* Create a media file upload to represent our upload process. */
                 $media = new Google_Http_MediaFileUpload($this->client, $request, $file->type, null, true, $chunkSizeBytes);
                 $media->setFileSize(filesize($filePath));
                 /* Start partialy upload 
                    Upload the various chunks. $status will be false until the process is
                    complete. */
                 $status = false;
                 $handle = fopen($filePath, "rb");
                 while (!$status && !feof($handle)) {
                     set_time_limit(60);
                     $chunk = fread($handle, $chunkSizeBytes);
                     $uploadStatus = $media->nextChunk($chunk);
                 }
                 fclose($handle);
             } catch (Exception $ex) {
                 $file->error = __('Not uploaded to Google Drive', 'useyourdrive') . ': ' . $ex->getMessage();
             }
             $this->client->setDefer(false);
             if (!empty($uploadStatus)) {
                 /* check if uploaded file has size */
                 $newentry = $this->googleDriveService->files->get($uploadStatus['id'], array("userIp" => $this->userip));
                 if ($newentry->getFileSize() === 0 && strpos($newentry->getMimeType(), 'google-apps') === false) {
                     $deletedentry = $this->googleDriveService->files->delete($newentry->getId(), array("userIp" => $this->userip));
                     $file->error = __('Not succesfully uploaded to Google Drive', 'useyourdrive');
                 } else {
                     /* Add new file to our Cache */
                     $cachedentry = $this->cache->addToCache($newentry);
                     $file->completepath = $cachedentry->getPath($this->_rootFolder);
                     $file->fileid = $newentry->getId();
                     $file->filesize = UseyourDrive_bytesToSize1024($file->size);
                     $file->link = urlencode($newentry->getAlternateLink());
                 }
             }
         } else {
             if ($this->options['debug'] === '1') {
                 $file->error = __('Uploading failed', 'useyourdrive') . ': ' . $file->error;
             } else {
                 $file->error = __('Uploading failed', 'useyourdrive');
             }
         }
     }
     /* Send email if needed */
     if ($this->options['notificationupload'] === '1') {
         $this->sendNotificationEmail('upload', $response['files']);
     }
     /* Create response */
     $this->upload_handler->generate_response($response);
     die;
 }
Example #5
0
    if ($client->isAccessTokenExpired()) {
        unset($_SESSION['upload_token']);
    }
} else {
    $authUrl = $client->createAuthUrl();
}
/************************************************
  If we're signed in then lets try to upload our
  file.
 ************************************************/
if ($client->getAccessToken()) {
    $file = new Google_Service_Drive_DriveFile();
    $file->title = "Big File";
    $chunkSizeBytes = 1 * 1024 * 1024;
    // Call the API with the media upload, defer so it doesn't immediately return.
    $client->setDefer(true);
    $request = $service->files->insert($file);
    // Create a media file upload to represent our upload process.
    $media = new Google_Http_MediaFileUpload($client, $request, 'text/plain', null, true, $chunkSizeBytes);
    $media->setFileSize(filesize(TESTFILE));
    // Upload the various chunks. $status will be false until the process is
    // complete.
    $status = false;
    $handle = fopen(TESTFILE, "rb");
    while (!$status && !feof($handle)) {
        $chunk = fread($handle, $chunkSizeBytes);
        $status = $media->nextChunk($chunk);
    }
    // The final value of $status will be the data from the API for the object
    // that has been uploaded.
    $result = false;
Example #6
0
/**
 * Updates a caption track's draft status to publish it.
 * Updates the track with a new binary file as well if it is present.  (captions.update)
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param Google_Client $client Google client.
 * @param string $captionId The id parameter specifies the caption ID for the resource
 * that is being updated. In a caption resource, the id property specifies the
 * caption track's ID.
 * @param $htmlBody - html body.
 * @param $captionFile caption track binary file.
 */
function updateCaption(Google_Service_YouTube $youtube, Google_Client $client, $captionId, &$htmlBody, $captionFile)
{
    // Modify caption's isDraft property to unpublish a caption track.
    $updateCaptionSnippet = new Google_Service_YouTube_CaptionSnippet();
    $updateCaptionSnippet->setIsDraft(true);
    # Create a caption with snippet.
    $updateCaption = new Google_Service_YouTube_Caption();
    $updateCaption->setSnippet($updateCaptionSnippet);
    $updateCaption->setId($captionId);
    if ($captionFile == '') {
        // Call the YouTube Data API's captions.update method to update an existing caption track.
        $captionUpdateResponse = $youtube->captions->update("snippet", $updateCaption);
        $htmlBody .= "<h2>Updated caption track</h2><ul>";
        $htmlBody .= sprintf('<li>%s(%s) draft status: %s</li>', $captionUpdateResponse['snippet']['name'], $captionUpdateResponse['id'], $captionUpdateResponse['snippet']['isDraft']);
        $htmlBody .= '</ul>';
    } else {
        // 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 YouTube Data API's captions.update method to update
        // an existing caption track.
        $captionUpdateRequest = $youtube->captions->update("snippet", $updateCaption);
        // Create a MediaFileUpload object for resumable uploads.
        $media = new Google_Http_MediaFileUpload($client, $captionUpdateRequest, '*/*', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($captionFile));
        // Read the caption file and upload it chunk by chunk.
        $status = false;
        $handle = fopen($captionFile, "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 .= "<h2>Updated caption track</h2><ul>";
        $htmlBody .= sprintf('<li>%s(%s) draft status: %s and updated the track with
          the new uploaded file.</li>', $status['snippet']['name'], $status['id'], $status['snippet']['isDraft']);
        $htmlBody .= '</ul>';
    }
}
/**
 *	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 #8
0
 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;
 }
Example #9
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;
 }
 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;
         }
     }
 }
Example #11
0
 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;
 }
 function UploadFile()
 {
     if (version_compare(WPDM_Version, '4.0.0', '<')) {
         return;
     }
     $missingapi = "Missing Google Drive API Credentials! <a href='edit.php?post_type=wpdmpro&page=settings&tab=cloud-storage' target='_blank'>Configure Here</a>";
     $expired = "Session Expired!";
     if (!isset($_FILES['gdrive_upload'])) {
         die('error!');
     }
     if (is_uploaded_file($_FILES['gdrive_upload']['tmp_name']) && current_user_can('manage_options')) {
         $tempFile = $_FILES['gdrive_upload']['tmp_name'];
         $wpdm_google_drive = maybe_unserialize(get_option('__wpdm_google_drive', array()));
         if (!isset($wpdm_google_drive['api_key']) || $wpdm_google_drive['api_key'] == '') {
             die($missingapi);
         }
         $client = new Google_Client();
         $client->setClientId($wpdm_google_drive['client_id']);
         $client->setClientSecret($wpdm_google_drive['client_secret']);
         $client->addScope(Google_Service_Drive::DRIVE);
         $client->addScope(Google_Service_Drive::DRIVE_FILE);
         $client->addScope(Google_Service_Drive::DRIVE_READONLY);
         $client->addScope(Google_Service_Drive::DRIVE_APPDATA);
         $client->addScope(Google_Service_Drive::DRIVE_APPS_READONLY);
         $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
         $client->setRedirectUri(admin_url('/?page=wpdm-google-drive'));
         $access_token = isset($_SESSION['wpdmgd_access_token']) ? $_SESSION['wpdmgd_access_token'] : '';
         if ($access_token == '') {
             die($expired);
         } else {
             $client->setAccessToken($access_token);
         }
         if ($client->isAccessTokenExpired()) {
             $access_token = '';
             unset($_SESSION['wpdmgd_access_token']);
             try {
                 $code = isset($_SESSION['gacode']) ? $_SESSION['gacode'] : '';
                 $client->authenticate($code);
                 $NewAccessToken = json_decode($client->getAccessToken());
                 $client->refreshToken($NewAccessToken->refresh_token);
             } catch (Exception $e) {
                 die($expired);
             }
         }
         $service = new Google_Service_Drive($client);
         $filetype = wp_check_filetype($_FILES['gdrive_upload']['name']);
         $file = new Google_Service_Drive_DriveFile();
         $file->title = $_FILES['gdrive_upload']['name'];
         $chunkSizeBytes = 1 * 1024 * 1024;
         // Call the API with the media upload, defer so it doesn't immediately return.
         $client->setDefer(true);
         $request = $service->files->insert($file);
         // Create a media file upload to represent our upload process.
         $media = new Google_Http_MediaFileUpload($client, $request, $filetype['type'], null, true, $chunkSizeBytes);
         $media->setFileSize($_FILES['gdrive_upload']['size']);
         // Upload the various chunks. $status will be false until the process is
         // complete.
         $status = false;
         $handle = fopen($_FILES['gdrive_upload']['tmp_name'], "rb");
         while (!$status && !feof($handle)) {
             $chunk = fread($handle, $chunkSizeBytes);
             $status = $media->nextChunk($chunk);
         }
         // The final value of $status will be the data from the API for the object
         // that has been uploaded.
         $result = false;
         if ($status != false) {
             $result = $status;
         }
         fclose($handle);
         @unlink($_FILES['gdrive_upload']['tmp_name']);
         //$this->InsertFile($service, $_FILES['gdrive_upload']['name'],'', 0, $filetype['type'], $_FILES['gdrive_upload']['tmp_name']);
     }
     if (isset($result)) {
         echo "<span class='text-success'><i class='fa fa-check'></i> Success</span>";
     } else {
         echo "<span class='text-danger'><i class='fa fa-times'></i> Failed!</span>";
     }
     die;
 }
Example #14
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 #15
-1
 public function testPrepareService()
 {
     $client = new Google_Client();
     $client->setScopes(array("scope1", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("scope1 scope2", $scopes);
     $client->setScopes(array("", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals(" scope2", $scopes);
     $client->setScopes("scope2");
     $client->addScope("scope3");
     $client->addScope(array("scope4", "scope5"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("scope2 scope3 scope4 scope5", $scopes);
     $client->setClientId('test1');
     $client->setRedirectUri('http://localhost/');
     $client->setScopes(array("http://test.com", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("http://test.com scope2", $scopes);
     $this->assertEquals('' . 'https://accounts.google.com/o/oauth2/auth' . '?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F' . '&client_id=test1' . '&scope=http%3A%2F%2Ftest.com+scope2&access_type=online' . '&approval_prompt=auto', $client->createAuthUrl());
     // This should not trigger a request.
     $client->setDefer(true);
     $dr_service = new Google_Service_Drive($client);
     $this->assertInstanceOf('Google_Http_Request', $dr_service->files->listFiles());
 }