public function testProcess()
 {
     // Test data *only* uploads.
     $params = array('data' => array('value' => 'foo'));
     $val = Google_MediaFileUpload::process(null, $params);
     $this->assertTrue(array_key_exists('postBody', $val));
     $this->assertEquals('foo', $val['postBody']);
     // Test only metadata.
     $params = array();
     $val = Google_MediaFileUpload::process(null, $params);
     $this->assertEquals(false, $val);
     // Test multipart (metadata & upload data).
     $params = array('data' => array('value' => 'foo'), 'boundary' => array('value' => 'a'));
     $val = Google_MediaFileUpload::process(array('a'), $params);
     $this->assertEquals('multipart/related; boundary=a', $val['content-type']);
     $expected = '--aContent-Type: application/json; charset=UTF-8' . '["a"]' . '--aContent-Type: Content-Transfer-Encoding: base64Zm9v--a--';
     $this->assertEquals($expected, str_replace("\r\n", '', $val['postBody']));
     // Multipart
     $params = array('data' => array('value' => 'foo'), 'boundary' => array('value' => 'a""'), 'mimeType' => array('value' => 'image/png'));
     $val = Google_MediaFileUpload::process(array('a'), $params);
     $this->assertEquals('multipart/related; boundary=a', $val['content-type']);
     $expected = '--aContent-Type: application/json; charset=UTF-8' . '["a"]' . '--aContent-Type: image/pngContent-Transfer-Encoding: base64Zm9v--a--';
     $this->assertEquals($expected, str_replace("\r\n", '', $val['postBody']));
 }
     $snippet->setTags(array("tag1", "tag2"));
     // Numeric video category. See
     // https://developers.google.com/youtube/v3/docs/videoCategories/list
     $snippet->setCategoryId("22");
     // Create a video status with privacy status. Options are "public", "private" and "unlisted".
     $status = new Google_VideoStatus();
     $status->privacyStatus = "public";
     // Create a YouTube video with snippet and status
     $video = new Google_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;
     // Create a MediaFileUpload with resumable uploads
     $media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
     $media->setFileSize(filesize($videoPath));
     // Create a video insert request
     $insertResponse = $youtube->videos->insert("status,snippet", $video, array('mediaUpload' => $media));
     $uploadStatus = false;
     // Read file and upload chunk by chunk
     $handle = fopen($videoPath, "rb");
     while (!$uploadStatus && !feof($handle)) {
         $chunk = fread($handle, $chunkSizeBytes);
         $uploadStatus = $media->nextChunk($insertResponse, $chunk);
     }
     fclose($handle);
     $htmlBody .= "<h3>Video Uploaded</h3><ul>";
     $htmlBody .= sprintf('<li>%s (%s)</li>', $uploadStatus['snippet']['title'], $uploadStatus['id']);
     $htmlBody .= '</ul>';
 } catch (Google_ServiceException $e) {
Exemplo n.º 3
0
 /**
  * @param $name
  * @param $arguments
  * @return Google_HttpRequest|array
  * @throws Google_Exception
  */
 public function __call($name, $arguments)
 {
     if (!isset($this->methods[$name])) {
         throw new Google_Exception("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()");
     }
     $method = $this->methods[$name];
     $parameters = $arguments[0];
     // postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it
     $postBody = null;
     if (isset($parameters['postBody'])) {
         if (is_object($parameters['postBody'])) {
             $this->stripNull($parameters['postBody']);
         }
         // Some APIs require the postBody to be set under the data key.
         if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) {
             if (!isset($parameters['postBody']['data'])) {
                 $rawBody = $parameters['postBody'];
                 unset($parameters['postBody']);
                 $parameters['postBody']['data'] = $rawBody;
             }
         }
         $postBody = is_array($parameters['postBody']) || is_object($parameters['postBody']) ? json_encode($parameters['postBody']) : $parameters['postBody'];
         unset($parameters['postBody']);
         if (isset($parameters['optParams'])) {
             $optParams = $parameters['optParams'];
             unset($parameters['optParams']);
             $parameters = array_merge($parameters, $optParams);
         }
     }
     if (!isset($method['parameters'])) {
         $method['parameters'] = array();
     }
     $method['parameters'] = array_merge($method['parameters'], $this->stackParameters);
     foreach ($parameters as $key => $val) {
         if ($key != 'postBody' && !isset($method['parameters'][$key])) {
             throw new Google_Exception("({$name}) unknown parameter: '{$key}'");
         }
     }
     if (isset($method['parameters'])) {
         foreach ($method['parameters'] as $paramName => $paramSpec) {
             if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) {
                 throw new Google_Exception("({$name}) missing required param: '{$paramName}'");
             }
             if (isset($parameters[$paramName])) {
                 $value = $parameters[$paramName];
                 $parameters[$paramName] = $paramSpec;
                 $parameters[$paramName]['value'] = $value;
                 unset($parameters[$paramName]['required']);
             } else {
                 unset($parameters[$paramName]);
             }
         }
     }
     // Discovery v1.0 puts the canonical method id under the 'id' field.
     if (!isset($method['id'])) {
         $method['id'] = $method['rpcMethod'];
     }
     // Discovery v1.0 puts the canonical path under the 'path' field.
     if (!isset($method['path'])) {
         $method['path'] = $method['restPath'];
     }
     $servicePath = $this->service->servicePath;
     // Process Media Request
     $contentType = false;
     if (isset($method['mediaUpload'])) {
         $media = Google_MediaFileUpload::process($postBody, $parameters);
         if ($media) {
             $contentType = isset($media['content-type']) ? $media['content-type'] : null;
             $postBody = isset($media['postBody']) ? $media['postBody'] : null;
             $servicePath = $method['mediaUpload']['protocols']['simple']['path'];
             $method['path'] = '';
         }
     }
     $url = Google_REST::createRequestUri($servicePath, $method['path'], $parameters);
     $httpRequest = new Google_HttpRequest($url, $method['httpMethod'], null, $postBody);
     if ($postBody) {
         $contentTypeHeader = array();
         if (isset($contentType) && $contentType) {
             $contentTypeHeader['content-type'] = $contentType;
         } else {
             $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8';
             $contentTypeHeader['content-length'] = Google_Utils::getStrLen($postBody);
         }
         $httpRequest->setRequestHeaders($contentTypeHeader);
     }
     $httpRequest = Google_Client::$auth->sign($httpRequest);
     if (Google_Client::$useBatch) {
         return $httpRequest;
     }
     // Terminate immediatly if this is a resumable request.
     if (isset($parameters['uploadType']['value']) && 'resumable' == $parameters['uploadType']['value']) {
         return $httpRequest;
     }
     return Google_REST::execute($httpRequest);
 }
}
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
// Check if access token successfully acquired
if ($client->getAccessToken()) {
    try {
        // REPLACE with the channel that you want to upload into
        $videoId = "VIDEO_ID";
        // REPLACE with the path to your file that you want to upload for thumbnail
        $imagePath = "/path/to/file.png";
        // 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;
        // Create a MediaFileUpload with resumable uploads
        $media = new Google_MediaFileUpload('image/png', null, true, $chunkSizeBytes);
        $media->setFileSize(filesize($imagePath));
        // List associated content owners to get content owner id
        $setResponse = $youtube->thumbnails->set($videoId, array('mediaUpload' => $media));
        $uploadStatus = false;
        // Read file and upload chunk by chunk
        $handle = fopen($imagePath, "rb");
        while (!$uploadStatus && !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);
            $uploadStatus = $media->nextChunk($setResponse, $chunk);
        }
        fclose($handle);
        $thumbnailUrl = $uploadStatus['items'][0]['default']['url'];
        $htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
        $htmlBody .= sprintf('<li>%s (%s)</li>', $videoId, $thumbnailUrl);
        $htmlBody .= sprintf('<img src="%s">', $thumbnailUrl);
Exemplo n.º 5
0
 public function createFileFromPath($path, $fileName, $description, Google_ParentReference $fileParent = null)
 {
     $mimeType = wp_check_filetype($fileName);
     $file = new Google_DriveFile();
     $file->setTitle($fileName);
     $file->setDescription($description);
     $file->setMimeType($mimeType['type']);
     if ($fileParent) {
         $file->setParents(array($fileParent));
     }
     $gdwpm_opsi_chunk = get_option('gdwpm_opsi_chunk');
     $chunks = $gdwpm_opsi_chunk['drive']['chunk'];
     $max_retries = (int) $gdwpm_opsi_chunk['drive']['retries'];
     $chunkSize = 1024 * 1024 * (int) $chunks;
     // 2mb chunk
     $fileupload = new Google_MediaFileUpload($mimeType['type'], null, true, $chunkSize);
     $fileupload->setFileSize(filesize($path));
     $mkFile = $this->_service->files->insert($file, array('mediaUpload' => $fileupload));
     $status = false;
     $handle = fopen($path, "rb");
     while (!$status && !feof($handle)) {
         $max = false;
         for ($i = 1; $i <= $max_retries; $i++) {
             $chunked = fread($handle, $chunkSize);
             if ($chunked) {
                 $createdFile = $fileupload->nextChunk($mkFile, $chunked);
                 break;
             } elseif ($i == $max_retries) {
                 $max = true;
             }
         }
         if ($max) {
             if ($createdFile) {
                 $this->_service->files->trash($createdFile['id']);
             }
             $createdFile = false;
             break;
         }
     }
     fclose($handle);
     if ($createdFile) {
         return $createdFile['id'];
     } else {
         return false;
     }
 }
Exemplo n.º 6
0
 public function putFileChunk($name, $file)
 {
     $file = realpath($file);
     if (!file_exists($file)) {
         $this->_throwExeption($this->_helper->__('File "%s" doesn\'t exist', strval($file)));
     }
     $handle = fopen($file, "rb");
     $filename = basename($name);
     $chunkSize = $this->getChunkSize();
     $fileObject = new Google_DriveFile();
     $fileObject->setTitle($filename);
     if (!($mimeType = $this->getRequestMimeType())) {
         if (substr(".tar.gz", -7)) {
             $mimeType = self::MIME_TYPE_TGZ;
         } else {
             if (substr(".gz", -3)) {
                 $mimeType = self::MIME_TYPE_GZIP;
             } else {
                 $mimeType = self::MIME_TYPE_GOOGLE_FILES;
             }
         }
         $this->setRequestMimeType($mimeType);
     }
     if (!($parentId = $this->getRequestParentId())) {
         $parentId = $this->getBackupFolder();
         $this->setRequestParentId($parentId);
     }
     if ($parentId != null) {
         $parent = new Google_ParentReference();
         $parent->setId($parentId);
         $fileObject->setParents(array($parent));
     }
     $media = new Google_MediaFileUpload($mimeType, null, true, $chunkSize);
     if (!($fileSize = $this->getRequestFileSize())) {
         $fileSize = $this->filesize($file);
     }
     $media->setFileSize($fileSize);
     $byte = $startByte = (double) $this->getRequestBytes();
     if ($byte > 0) {
         $this->fseek($handle, $byte);
         $media->resumeUri = $this->getRequestUrl();
         $media->progress = $byte;
     }
     /**
      * @var Google_HttpRequest $httpRequest
      * @see Google_FilesServiceResource::insert
      */
     $httpRequest = $this->getService(false)->files->insert($fileObject, array('mimeType' => $mimeType, 'mediaUpload' => $media));
     while (!feof($handle)) {
         if ($this->timeIsUp()) {
             $this->setRequestBytes($byte);
             $this->setRequestUrl($media->resumeUri);
             $nextChunk = true;
             break;
         }
         $chunk = fread($handle, $chunkSize);
         $uploadStatus = $media->nextChunk($httpRequest, $chunk);
         $byte += $chunkSize;
     }
     fclose($handle);
     $locale = Mage::app()->getLocale()->getLocale();
     if (isset($nextChunk)) {
         $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($byte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale))));
         return false;
     }
     $this->_addBackupProcessMessage($this->_helper->__('Bytes from %1$s to %2$s were added (total: %3$s)', Zend_Locale_Format::toNumber($startByte, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale)), Zend_Locale_Format::toNumber($fileSize, array('precision' => 0, 'locale' => $locale))));
     if (!isset($uploadStatus) || !is_array($uploadStatus) || empty($uploadStatus['id'])) {
         $this->_throwExeption($this->_helper->__('Error chunk upload response'));
     }
     $fileCloudPath = $this->getConfigValue(self::APP_PATH);
     $returnPath = $fileCloudPath . '/' . $filename;
     $this->_addAdditionalInfo($uploadStatus['id'], $returnPath);
     $this->clearRequestParams();
     return $returnPath;
 }