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;
 }
示例#2
0
  * 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);
 // Create a MediaFileUpload object for resumable uploads.
 $media = new Google_Http_MediaFileUpload($client, $insertRequest, 'video/*', null, true, $chunkSizeBytes);
 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;
         }
     }
 }
 public function put()
 {
     $config = $this->uploadService->getConfig();
     //        $config = new UploadService_Config();
     $configConstraints = $config->getConstraints();
     //        $configConstraints = new UploadService_Config_Constraints();
     $response = ["success" => false, "message" => null, "file" => ["name" => null, "uri" => null, "isVideo" => false]];
     $path = file::cleanPath($config->getPath());
     //prepare file
     $file = $_FILES["file"];
     $fileError = $file["error"];
     $fileName = $file["name"];
     $fileSize = $file["size"];
     $fileTempName = $file["tmp_name"];
     $fileType = $file["type"];
     $fileName = file::cleanName($fileName);
     //get numerator
     $numerator = (int) numerador('archivoTemporal', 0, '');
     $newFileName = "{$numerator}-{$fileName}";
     //destinies
     $basePath = $_SERVER['DOCUMENT_ROOT'];
     $S3destiny = "{$path}/{$newFileName}";
     $destiny = "{$basePath}/{$S3destiny}";
     if ($fileError === UPLOAD_ERR_OK) {
         $videoControl = file::isVideo($fileName) && $config->getVideoPlatform();
         if ($videoControl) {
             //video control
             $response["success"] = move_uploaded_file($fileTempName, $destiny);
         } else {
             set_time_limit(600);
             //destiny file
             switch ($config->getToserver()) {
                 case UploadService::TO_S3:
                     $S3 = new S3(AWS_ACCES_KEY, AWS_SECRET_KEY);
                     $response["success"] = $S3->putObjectFile($fileTempName, "owlgroup", $S3destiny, S3::ACL_PUBLIC_READ);
                     break;
                 case UploadService::TO_SERVER:
                     $destinyFolder = str_replace("/{$newFileName}", '', $destiny);
                     !file_exists($destinyFolder) && !is_dir($destinyFolder) && creaCarpeta($destinyFolder);
                     $response["success"] = move_uploaded_file($fileTempName, $destiny);
                     break;
                 case UploadService::TO_BOTH:
                     $S3 = new S3(AWS_ACCES_KEY, AWS_SECRET_KEY);
                     $destinyFolder = str_replace("/{$newFileName}", '', $destiny);
                     !file_exists($destinyFolder) && !is_dir($destinyFolder) && creaCarpeta($destinyFolder);
                     $response["success"] = $S3->putObjectFile($fileTempName, "owlgroup", $S3destiny, S3::ACL_PUBLIC_READ) && move_uploaded_file($fileTempName, $destiny);
                     break;
             }
         }
         if ($response["success"]) {
             $response["file"]["name"] = $newFileName;
             //Insert register to file temporal table
             $formId = post("form");
             $field = post("field");
             $userId = $_SESSION["Persona"]["string"];
             $enterpriseUser = $_SESSION["enterprise_user"];
             addTempFile($numerator, $path, $newFileName, $fileName, $fileType, $formId, $userId, $enterpriseUser, $field);
             if ($videoControl) {
                 //video control
                 switch ($config->getVideoPlatform()) {
                     case UploadService::VIDEO_PLATFORM_OWL:
                         //NOTHING HERE
                         break;
                     case UploadService::VIDEO_PLATFORM_YOUTUBE:
                         set_time_limit(18000);
                         $systemGoogleClient = get_system_google_client();
                         if ($systemGoogleClient) {
                             $client = $systemGoogleClient->client;
                             //Define an object that will be used to make all API requests.
                             $youtube = new Google_Service_YouTube($client);
                             try {
                                 $fileSize = filesize($destiny);
                                 $videoSnippet = new Google_Service_YouTube_VideoSnippet();
                                 $videoSnippet->setTitle($fileName);
                                 $videoSnippet->setDescription("This video was upload in " . date("Y-m-d H:i:s"));
                                 $videoStatus = new Google_Service_YouTube_VideoStatus();
                                 $videoStatus->setPrivacyStatus("unlisted");
                                 //public | private | unlisted
                                 $video = new Google_Service_YouTube_Video();
                                 $video->setSnippet($videoSnippet);
                                 $video->setStatus($videoStatus);
                                 $chunkSizeBytes = 1 * 1024 * 1024;
                                 //1 megabyte
                                 $client->setDefer(true);
                                 //snippet,contentDetails,fileDetails,player,processingDetails,recordingDetails,statistics,status,suggestions,topicDetails
                                 $httpRequest = $youtube->videos->insert("status,snippet", $video);
                                 $mediaFileUpload = new Google_Http_MediaFileUpload($client, $httpRequest, 'video/*', null, true, $chunkSizeBytes);
                                 $mediaFileUpload->setFileSize($fileSize);
                                 $status = false;
                                 //open flow resource video file in binary mode
                                 $handle = fopen($destiny, "rb");
                                 while (!$status && !feof($handle)) {
                                     $chunk = fread($handle, $chunkSizeBytes);
                                     $status = $mediaFileUpload->nextChunk($chunk);
                                 }
                                 //close flow reource
                                 fclose($handle);
                                 $client->setDefer(false);
                                 $videoInserted = $status;
                                 //Google_Service_YouTube_Video class;
                                 $response["file"]["name"] = $videoInserted->getId();
                             } catch (Google_Service_Exception $e) {
                                 $response["success"] = false;
                                 $response["message"] = htmlspecialchars("A service error occurred: {$e->getMessage()}");
                             } catch (Google_Exception $e) {
                                 $response["success"] = false;
                                 $response["message"] = htmlspecialchars("An client error occurred: {$e->getMessage()}");
                             }
                         } else {
                             $response["success"] = false;
                             $response["message"] = "Ha ocurrido un error al establecer un medio para Google Services";
                         }
                         //delete file because it's not necesary save in the server when the file is a video
                         unlink($destiny);
                         break;
                 }
             } else {
                 if (file::isImage($fileName)) {
                     switch ($config->getToserver()) {
                         case UploadService::TO_S3:
                         case UploadService::TO_BOTH:
                             $response["file"]["uri"] = CONS_IPArchivos . "/{$S3destiny}";
                             break;
                         case UploadService::TO_SERVER:
                             $response["file"]["uri"] = getDomain() . "/{$S3destiny}";
                             break;
                     }
                 }
             }
         } else {
             $response["message"] = "Destiny directory don't exists or isn't writable, type to server is {$config->getToserver()}";
         }
     } else {
         $response["message"] = "Happened a error whit code {$fileError}";
     }
     return $response;
 }