public function execute() { $this->forceSystemAuthentication(); myDbHelper::$use_alternative_con = null; //myDbHelper::DB_HELPER_CONN_PROPEL2 $uiConfId = $this->getRequestParameter("id"); $uiConf = uiConfPeer::retrieveByPK($uiConfId); $subTypes = array(uiconf::FILE_SYNC_UICONF_SUB_TYPE_DATA, uiconf::FILE_SYNC_UICONF_SUB_TYPE_FEATURES); foreach ($subTypes as $subType) { if ($subType == uiconf::FILE_SYNC_UICONF_SUB_TYPE_DATA) { echo "Data:" . PHP_EOL; } else { if ($subType == uiconf::FILE_SYNC_UICONF_SUB_TYPE_FEATURES) { echo "Features:" . PHP_EOL; } } $syncKey = $uiConf->getSyncKey($subType); if (kFileSyncUtils::file_exists($syncKey)) { echo "File sync already exists." . PHP_EOL; } else { list($rootPath, $filePath) = $uiConf->generateFilePathArr($subType); $fullPath = $rootPath . $filePath; if (file_exists($fullPath)) { kFileSyncUtils::createSyncFileForKey($syncKey); echo "Created successfully." . PHP_EOL; } else { echo "File not found:" . PHP_EOL; echo $fullPath . PHP_EOL; echo "Not creating file sync." . PHP_EOL; } } echo PHP_EOL; } die; }
public function execute() { $jobId = $this->getRequestParameter("id"); $partnerId = $this->getRequestParameter("pid"); $type = $this->getRequestParameter("type"); $c = new Criteria(); $c->addAnd(BatchJobPeer::ID, $jobId); $c->addAnd(BatchJobPeer::PARTNER_ID, $partnerId); $c->addAnd(BatchJobPeer::JOB_TYPE, BatchJobType::BULKUPLOAD); $batchJob = BatchJobPeer::doSelectOne($c); if (!$batchJob) { die("File not found"); } header("Content-Type: text/plain; charset=UTF-8"); if ($type == "log") { $bulkUploadResults = BulkUploadResultPeer::retrieveByBulkUploadId($jobId); if (!count($bulkUploadResults)) { $syncKey = $batchJob->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOADLOG); if (kFileSyncUtils::file_exists($syncKey, true)) { $content = kFileSyncUtils::file_get_contents($syncKey, true); echo $content; die; } die("Log file is not ready"); } $STDOUT = fopen('php://output', 'w'); $data = $batchJob->getData(); foreach ($bulkUploadResults as $bulkUploadResult) { $values = array($bulkUploadResult->getTitle(), $bulkUploadResult->getDescription(), $bulkUploadResult->getTags(), $bulkUploadResult->getUrl(), $bulkUploadResult->getContentType()); if ($data instanceof kBulkUploadJobData && $data->getCsvVersion() > kBulkUploadJobData::BULK_UPLOAD_CSV_VERSION_V1) { $values[] = $bulkUploadResult->getConversionProfileId(); $values[] = $bulkUploadResult->getAccessControlProfileId(); $values[] = $bulkUploadResult->getCategory(); $values[] = $bulkUploadResult->getScheduleStartDate('Y-m-d\\TH:i:s'); $values[] = $bulkUploadResult->getScheduleEndDate('Y-m-d\\TH:i:s'); $values[] = $bulkUploadResult->getThumbnailUrl(); $values[] = $bulkUploadResult->getPartnerData(); } $values[] = $bulkUploadResult->getEntryId(); $values[] = $bulkUploadResult->getEntryStatus(); $values[] = $bulkUploadResult->getErrorDescription(); fputcsv($STDOUT, $values); } fclose($STDOUT); } else { $syncKey = $batchJob->getSyncKey(BatchJob::FILE_SYNC_BATCHJOB_SUB_TYPE_BULKUPLOADCSV); if (kFileSyncUtils::file_exists($syncKey, true)) { $content = kFileSyncUtils::file_get_contents($syncKey, true); echo $content; die; } else { die("File not found"); } } die; // no template needed }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { // where file is {entryId/flavorId}.{ism,ismc,ismv} $objectId = $type = null; $objectIdStr = $this->getRequestParameter("objectId"); if ($objectIdStr) { list($objectId, $type) = @explode(".", $objectIdStr); } if (!$type || !$objectId) { KExternalErrors::dieError(KExternalErrors::MISSING_PARAMETER); } $ks = $this->getRequestParameter("ks"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $syncKey = $this->getFileSyncKey($objectId, $type); KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveIsm', $this->entry->getPartnerId()); myPartnerUtils::enforceDelivery($this->entry, $this->flavorAsset); if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for type [{$type}] objectId [{$objectId}]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); if ($type == 'ism') { $fileData = $this->fixIsmManifestForReplacedEntry($path); $renderer = new kRendererString($fileData, 'image/ism'); $renderer->output(); KExternalErrors::dieGracefully(); } else { kFileUtils::dumpFile($path); } }
public function copyToEntry($entryId = null, $partnerId = null) { $newFlavorAsset = $this->copy(); if ($partnerId) { $newFlavorAsset->setPartnerId($partnerId); } if ($entryId) { $newFlavorAsset->setEntryId($entryId); } $newFlavorAsset->save(); $flavorParamsOutput = flavorParamsOutputPeer::retrieveByFlavorAssetId($this->getId()); if ($flavorParamsOutput) { $newFlavorParamsOutput = $flavorParamsOutput->copy(); $newFlavorParamsOutput->setPartnerId($newFlavorAsset->getPartnerId()); $newFlavorParamsOutput->setEntryId($newFlavorAsset->getEntryId()); $newFlavorParamsOutput->setFlavorAssetId($newFlavorAsset->getId()); $newFlavorParamsOutput->save(); } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($this->getId()); if ($mediaInfo) { $newMediaInfo = $mediaInfo->copy(); $newMediaInfo->setFlavorAssetId($newFlavorAsset->getId()); $newMediaInfo->save(); } $assetSyncKey = $this->getSyncKey(self::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $convertLogSyncKey = $this->getSyncKey(self::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG); $newAssetSyncKey = $newFlavorAsset->getSyncKey(self::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $newConvertLogSyncKey = $newFlavorAsset->getSyncKey(self::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_CONVERT_LOG); if (kFileSyncUtils::file_exists($assetSyncKey, true)) { kFileSyncUtils::softCopy($assetSyncKey, $newAssetSyncKey); } if (kFileSyncUtils::file_exists($convertLogSyncKey, true)) { kFileSyncUtils::softCopy($convertLogSyncKey, $newConvertLogSyncKey); } return $newFlavorAsset; }
public function execute() { requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $ks = $this->getRequestParameter("ks"); $fileParam = $this->getRequestParameter("file"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = flavorAssetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId()); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($flavorAsset->getPartnerId()); //disabled enforce cdn because of rtmp delivery //requestUtils::enforceCdnDelivery($flavorAsset->getPartnerId()); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFile::dumpUrl($remoteUrl, true, true); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds $clipTo = $this->getRequestParameter("clipTo", 2147483647); // milliseconds if ($clipTo == 0) { $clipTo = 2147483647; } if (is_dir($path) && $fileParam) { $path .= "/{$fileParam}"; //echo "path($path),file($fileParam)"; kFile::dumpFile($path, null, null); die; } else { if (!$isFlv) { $limit_file_size = 0; if ($clipTo != 2147483647) { $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@filesize($path) * ($clipTo / $duration)); } } kFile::dumpFile($path, null, null, $limit_file_size); die; } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } header('Content-Disposition: attachment; filename="video.flv"'); // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); die; }
public function execute() { //entitlement should be disabled to serveFlavor action as we do not get ks on this action. KalturaCriterion::disableTag(KalturaCriterion::TAG_ENTITLEMENT_CATEGORY); requestUtils::handleConditionalGet(); $flavorId = $this->getRequestParameter("flavorId"); $shouldProxy = $this->getRequestParameter("forceproxy", false); $fileName = $this->getRequestParameter("fileName"); $fileParam = $this->getRequestParameter("file"); $fileParam = basename($fileParam); $pathOnly = $this->getRequestParameter("pathOnly", false); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } $flavorAsset = assetPeer::retrieveById($flavorId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entryId = $this->getRequestParameter("entryId"); if (!is_null($entryId) && $flavorAsset->getEntryId() != $entryId) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } if ($fileName) { header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Type: application/force-download"); header("Content-Description: File Transfer"); } $clipTo = null; $entry = $flavorAsset->getentry(); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } KalturaMonitorClient::initApiMonitor(false, 'extwidget.serveFlavor', $flavorAsset->getPartnerId()); myPartnerUtils::enforceDelivery($entry, $flavorAsset); $version = $this->getRequestParameter("v"); if (!$version) { $version = $flavorAsset->getVersion(); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); if ($pathOnly && kIpAddressUtils::isInternalIp($_SERVER['REMOTE_ADDR'])) { $path = null; list($file_sync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, false, false); if ($file_sync) { $parent_file_sync = kFileSyncUtils::resolve($file_sync); $path = $parent_file_sync->getFullPath(); if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; } } $renderer = new kRendererString('{"sequences":[{"clips":[{"type":"source","path":"' . $path . '"}]}]}', 'application/json'); if ($path) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } if (kConf::hasParam('serve_flavor_allowed_partners') && !in_array($flavorAsset->getPartnerId(), kConf::get('serve_flavor_allowed_partners'))) { KExternalErrors::dieError(KExternalErrors::ACTION_BLOCKED); } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } // always dump remote urls so they will be cached by the cdn transparently $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFileUtils::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); $isFlv = false; if (!$shouldProxy) { $flvWrapper = new myFlvHandler($path); $isFlv = $flvWrapper->isFlv(); } $clipFrom = $this->getRequestParameter("clipFrom", 0); // milliseconds if (is_null($clipTo)) { $clipTo = $this->getRequestParameter("clipTo", self::NO_CLIP_TO); } // milliseconds if ($clipTo == 0) { $clipTo = self::NO_CLIP_TO; } if (!is_numeric($clipTo) || $clipTo < 0) { KExternalErrors::dieError(KExternalErrors::BAD_QUERY, 'clipTo must be a positive number'); } $seekFrom = $this->getRequestParameter("seekFrom", -1); if ($seekFrom <= 0) { $seekFrom = -1; } $seekFromBytes = $this->getRequestParameter("seekFromBytes", -1); if ($seekFromBytes <= 0) { $seekFromBytes = -1; } if ($fileParam && is_dir($path)) { $path .= "/{$fileParam}"; kFileUtils::dumpFile($path, null, null); KExternalErrors::dieGracefully(); } else { if (!$isFlv || $clipTo == self::NO_CLIP_TO && $seekFrom < 0 && $seekFromBytes < 0) { $limit_file_size = 0; if ($clipTo != self::NO_CLIP_TO) { if (strtolower($flavorAsset->getFileExt()) == 'mp4' && PermissionPeer::isValidForPartner(PermissionName::FEATURE_ACCURATE_SERVE_CLIPPING, $flavorAsset->getPartnerId())) { $contentPath = myContentStorage::getFSContentRootPath(); $tempClipName = $version . '_' . $clipTo . '.mp4'; $tempClipPath = $contentPath . myContentStorage::getGeneralEntityPath("entry/tempclip", $flavorAsset->getIntId(), $flavorAsset->getId(), $tempClipName); if (!file_exists($tempClipPath)) { kFile::fullMkdir($tempClipPath); $clipToSec = round($clipTo / 1000, 3); $cmdLine = kConf::get("bin_path_ffmpeg") . " -i {$path} -vcodec copy -acodec copy -f mp4 -t {$clipToSec} -y {$tempClipPath} 2>&1"; KalturaLog::log("Executing {$cmdLine}"); $output = array(); $return_value = ""; exec($cmdLine, $output, $return_value); KalturaLog::log("ffmpeg returned {$return_value}, output:" . implode("\n", $output)); } if (file_exists($tempClipPath)) { KalturaLog::log("Dumping {$tempClipPath}"); kFileUtils::dumpFile($tempClipPath); } else { KalturaLog::err('Failed to clip the file using ffmpeg, falling back to rough clipping'); } } $mediaInfo = mediaInfoPeer::retrieveByFlavorAssetId($flavorAsset->getId()); if ($mediaInfo && ($mediaInfo->getVideoDuration() || $mediaInfo->getAudioDuration() || $mediaInfo->getContainerDuration())) { $duration = $mediaInfo->getVideoDuration() ? $mediaInfo->getVideoDuration() : ($mediaInfo->getAudioDuration() ? $mediaInfo->getAudioDuration() : $mediaInfo->getContainerDuration()); $limit_file_size = floor(@kFile::fileSize($path) * ($clipTo / $duration) * 1.2); } } $renderer = kFileUtils::getDumpFileRenderer($path, null, null, $limit_file_size); if (!$fileName) { $this->storeCache($renderer, $flavorAsset->getPartnerId()); } $renderer->output(); KExternalErrors::dieGracefully(); } } $audioOnly = $this->getRequestParameter("audioOnly"); // milliseconds if ($audioOnly === '0') { // audioOnly was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flvWrapper->getFirstVideoTimestamp() < 0) { $audioOnly = true; } $bytes = 0; if ($seekFrom !== -1 && $seekFrom !== 0) { list($bytes, $duration, $firstTagByte, $toByte) = $flvWrapper->clip(0, -1, $audioOnly); list($bytes, $duration, $fromByte, $toByte, $seekFromTimestamp) = $flvWrapper->clip($seekFrom, -1, $audioOnly); $seekFromBytes = myFlvHandler::FLV_HEADER_SIZE + $flvWrapper->getMetadataSize($audioOnly) + $fromByte - $firstTagByte; } else { list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); } $metadataSize = $flvWrapper->getMetadataSize($audioOnly); $dataOffset = $metadataSize + myFlvHandler::getHeaderSize(); $totalLength = $dataOffset + $bytes; list($bytes, $duration, $fromByte, $toByte, $fromTs, $cuepointPos) = myFlvStaticHandler::clip($path, $clipFrom, $clipTo, $audioOnly); list($rangeFrom, $rangeTo, $rangeLength) = requestUtils::handleRangeRequest($totalLength); if ($totalLength < 1000) { // (actually $total_length is probably 13 or 143 - header + empty metadata tag) probably a bad flv maybe only the header - dont cache requestUtils::sendCdnHeaders("flv", $rangeLength, 0); } else { requestUtils::sendCdnHeaders("flv", $rangeLength); } // dont inject cuepoint into the stream $cuepointTime = 0; $cuepointPos = 0; try { Propel::close(); } catch (Exception $e) { $this->logMessage("serveFlavor: error closing db {$e}"); } header("Content-Type: video/x-flv"); $flvWrapper->dump(self::CHUNK_SIZE, $fromByte, $toByte, $audioOnly, $seekFromBytes, $rangeFrom, $rangeTo, $cuepointTime, $cuepointPos); KExternalErrors::dieGracefully(); }
private function handleEntry($onlyExtractThumb, $prefix, $type, $entry_id, $name = null, $tags = null, $entry = null) { KalturaLog::debug("handleEntry({$type}, {$entry_id}, {$name})"); $this->clear($prefix, $entry_id); $kuser_id = $this->kuser_id; $entry_data_prefix = $kuser_id . '_' . ($prefix == '' ? 'data' : rtrim($prefix, '_')); $uploads = myContentStorage::getFSUploadsPath(); $content = myContentStorage::getFSContentRootPath(); $media_source = $this->getParam('entry_media_source'); $media_type = $this->getParam('entry_media_type'); $entry_url = $this->getParam('entry_url'); $entry_source_link = $this->getParam('entry_source_link'); $entry_fileName = $this->getParam('entry_data'); $entry_thumbNum = $this->getParam('entry_thumb_num', 0); $entry_thumbUrl = $this->getParam('entry_thumb_url', ''); $should_copy = $this->getParam('should_copy', false); $skip_conversion = $this->getParam('skip_conversion', false); $webcam_suffix = $this->getParam('webcam_suffix', ''); $duration = $this->getParam('duration', null); $entry_fullPath = ""; $ext = null; $entry = null; if ($entry_id) { $entry = entryPeer::retrieveByPK($entry_id); } else { $entry = new entry(); } $this->entry = $entry; $entry_status = $entry->getStatus(); if (is_null($entry_status)) { $entry_status = entryStatus::READY; } // by the end of this block of code $entry_fullPath will point to the location of the entry // the entry status will be set (IMPORT / PRECONVERT / READY) // a background image is always previewed by the user no matter what source he used // so the entry is already in the /uploads directory // continue tracking the file upload $te = new TrackEntry(); $te->setEntryId($entry_id); $te->setTrackEventTypeId(TrackEntry::TRACK_ENTRY_EVENT_TYPE_ADD_ENTRY); KalturaLog::debug("handleEntry: media_source: {$media_source}, prefix: {$prefix}"); if ($media_source == entry::ENTRY_MEDIA_SOURCE_FILE || $prefix == 'bg_') { $full_path = $this->getParam('entry_full_path'); if ($full_path) { $entry_fullPath = $full_path; } else { $entry_fullPath = $uploads . $entry_data_prefix . strrchr($entry_fileName, '.'); } if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) { $entry_status = entryStatus::PRECONVERT; } $te->setParam3Str($entry_fullPath); $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_FILE"); } else { if ($media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { // set $entry_fileName to webcam output file and flag that conversion is not needed $webcam_basePath = $content . '/content/webcam/' . ($webcam_suffix ? $webcam_suffix : 'my_recorded_stream_' . $kuser_id); $entry_fullPath = $webcam_basePath . '.' . kWAMSWebcam::OUTPUT_FILE_EXT; $ext = kWAMSWebcam::OUTPUT_FILE_EXT; if (file_exists($entry_fullPath)) { // continue tracking the webcam $te->setParam3Str($entry_fullPath); $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_WEBCAM"); } else { KalturaLog::err("File [{$entry_fullPath}] does not exist"); $entry_status = entryStatus::ERROR_IMPORTING; } } else { // if the url ends with .ext, we'll extract it this way $urlext = strrchr($entry_url, '.'); // TODO: fix this patch if (strlen($urlext) > 4) { $urlext = '.jpg'; } // if we got something wierd, assume we're downloading a jpg $entry_fileName = $entry_data_prefix . $urlext; KalturaLog::debug("handleEntry: media_type: {$media_type}"); if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) { $duration = 0; $entry_fullPath = $uploads . $entry_fileName; if (!kFile::downloadUrlToFile($entry_url, $entry_fullPath)) { KalturaLog::debug("Failed downloading file[{$entry_url}]"); $entry_status = entryStatus::ERROR_IMPORTING; } // track images $te->setParam3Str($entry_fullPath); $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_URL:ENTRY_MEDIA_TYPE_IMAGE"); } else { if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO) { //fixme - we can extract during import $ext = "flv"; } else { $ext = "mp3"; } $entry_status = entryStatus::IMPORT; // track images $te->setParam3Str($ext); $te->setDescription(__METHOD__ . ":" . __LINE__ . "::ENTRY_MEDIA_SOURCE_URL:ENTRY_MEDIA_TYPE_VIDEO"); } } } if ($ext == null) { $entry_fullPathTmp = $entry_fullPath; $qpos = strpos($entry_fullPathTmp, "?"); if ($qpos !== false) { $entry_fullPathTmp = substr($entry_fullPathTmp, 0, $qpos); } $ext = strtolower(pathinfo($entry_fullPathTmp, PATHINFO_EXTENSION)); } // save the Trackentry TrackEntry::addTrackEntry($te); KalturaLog::debug("handleEntry: ext: {$ext}"); // We don't want to reject entries based on file extentions anumore // Remarked by Tan-Tan // // if ($entry_status == entryStatus::PRECONVERT && !myContentStorage::fileExtNeedConversion($ext)) // { // // $this->errorMsg = "insertEntryAction Error - PRECONVERT file type not acceptable ($ext)"; // KalturaLog::debug("handleEntry: err: $this->errorMsg"); // if(is_null($entry) && $this->entry_id) // { // $entry = entryPeer::retrieveByPK($this->entry_id); // } // if($entry) // { // $entry->setStatus(entryStatus::ERROR_CONVERTING); // $entry->save(); // } // return false; // } $media_date = null; // We don't want to reject entries based on file extentions anumore // Remarked by Tan-Tan // // // if entry is ready, validate file type (webcam is an exception since we control the file type - flv) // if ($entry_status == entryStatus::READY && // $media_source != entry::ENTRY_MEDIA_SOURCE_WEBCAM && !myContentStorage::fileExtAccepted($ext)) // { // $this->errorMsg = "insertEntryAction Error - READY file type not acceptable ($ext)"; // KalturaLog::debug("handleEntry: err: $this->errorMsg"); // if(is_null($entry) && $this->entry_id) // { // $entry = entryPeer::retrieveByPK($this->entry_id); // } // if($entry) // { // $entry->setStatus(entryStatus::ERROR_CONVERTING); // $entry->save(); // } // return false; // } if ($entry_status == entryStatus::ERROR_IMPORTING) { $need_thumb = false; // we wont be needing a thumb for an errornous entry KalturaLog::debug("handleEntry: error importing, thumb not needed"); } else { // thumbs are created by one of the following ways: // 1. Image - images are already on disk for every selection method, so we can just create a thumb // 2. Audio - no thumb is needed // 3. Video - // a. uploaded (file / webcam) - file is on disk and the user already selected a thumb // b. imported - the source site had a thumbnail and we'll use it $thumbTempPrefix = $uploads . $entry_data_prefix . '_thumbnail_'; $thumbBigFullPath = null; $need_thumb = $type == entryType::MEDIA_CLIP; KalturaLog::debug("handleEntry: handling media {$media_type}"); if ($media_type == entry::ENTRY_MEDIA_TYPE_IMAGE) { // fetch media creation date $exif_image_type = @exif_imagetype($entry_fullPath); if ($exif_image_type == IMAGETYPE_JPEG || $exif_image_type == IMAGETYPE_TIFF_II || $exif_image_type == IMAGETYPE_TIFF_MM || $exif_image_type == IMAGETYPE_IFF || $exif_image_type == IMAGETYPE_PNG) { $exif_data = @exif_read_data($entry_fullPath); if ($exif_data && isset($exif_data["DateTimeOriginal"]) && $exif_data["DateTimeOriginal"]) { $media_date = $exif_data["DateTimeOriginal"]; $ts = strtotime($media_date); // handle invalid dates either due to bad format or out of range if ($ts === -1 || $ts === false || $ts < strtotime('2000-01-01') || $ts > strtotime('2015-01-01')) { $media_date = null; } } } // create thumb $thumbFullPath = $thumbTempPrefix . '1.jpg'; $entry_thumbNum = 1; $need_thumb = true; //copy($entry_fullPath, $thumbFullPath); myFileConverter::createImageThumbnail($entry_fullPath, $thumbFullPath, "image2"); //$thumbBigFullPath = $thumbFullPath; // no filesync for thumbnail of image } else { if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO) { if ($entry_status == entryStatus::IMPORT || $media_source == entry::ENTRY_MEDIA_SOURCE_URL) { // import thumb and convert to our size $thumbFullPath = $thumbTempPrefix . '1.jpg'; $entry_thumbNum = 1; $importedThumbPath = $uploads . $entry_data_prefix . '_temp_thumb' . strrchr($entry_thumbUrl, '.'); if (kFile::downloadUrlToFile($entry_thumbUrl, $importedThumbPath)) { myFileConverter::createImageThumbnail($importedThumbPath, $thumbFullPath, "image2"); // set thumb as big thumb so fileSync will be created. $thumbBigFullPath = $thumbFullPath; } else { $need_thumb = false; } } else { if ($entry_thumbNum == 0) { $entry_thumbNum = 1; $thumbTime = 3; if ($duration && $duration < $thumbTime * 1000) { $thumbTime = floor($duration / 1000); } // for videos - thumbail should be created in post convert // otherwise this code will fail if the thumbanil wasn't created successfully (roman) //myFileConverter::autoCaptureFrame($entry_fullPath, $thumbTempPrefix."big_", $thumbTime, -1, -1); $need_thumb = false; $thumbBigFullPath = $thumbTempPrefix . "big_" . $entry_thumbNum . '.jpg'; } } //else select existing thumb ($entry_thumbNum already points to the right thumbnail) } } $thumbFullPath = $thumbTempPrefix . $entry_thumbNum . '.jpg'; // if we arrived here both entry and thumbnail are valid we can now update the db // in order to have the final entry_id and move its data to its final destination if ($onlyExtractThumb) { return $thumbFullPath; } } $entry->setkshowId($this->kshow_id); $entry->setKuserId($kuser_id); $entry->setCreatorKuserId($kuser_id); if ($this->partner_id != null) { $entry->setPartnerId($this->partner_id); $entry->setSubpId($this->subp_id); } $entry->setName($name ? $name : $this->getParam('entry_name')); // $entry->setDescription('');//$this->getParam('entry_description')); $entry->setType($type); $entry->setMediaType($media_type); $entry->setTags($tags ? $tags : $this->getParam('entry_tags')); $entry->setSource($media_source); $entry->setSourceId($this->getParam('entry_media_id')); if ($media_date) { $entry->setMediaDate($media_date); } // if source_link wasnt given use the entry_url HOWEVER, use it only if id doesnt contain @ which suggests the use of a password $entry->setSourceLink($entry_source_link ? $entry_source_link : (strstr($entry_url, '@') ? "" : $entry_url)); if ($media_source == entry::ENTRY_MEDIA_SOURCE_FILE) { $entry->setSourceLink("file:{$entry_fullPath}"); } $entry->setLicenseType($this->getParam('entry_license')); $entry->setCredit($this->getParam('entry_credit')); $entry->setStatus($entry_status); if ($duration !== null) { $entry->setLengthInMsecs($duration); } if ($this->entry_id == 0) { $entry->save(); $this->entry_id = $entry->getId(); } // move thumb to final destination and set db entry if ($media_type != entry::ENTRY_MEDIA_TYPE_AUDIO && $entry_thumbNum && $need_thumb) { KalturaLog::debug("handleEntry: saving none audio thumb [{$thumbBigFullPath}]"); $entry->setThumbnail('.jpg'); if ($thumbBigFullPath) { if ($media_type != entry::ENTRY_MEDIA_TYPE_IMAGE) { myFileConverter::convertImage($thumbBigFullPath, $thumbFullPath); } /*$thumbBigFinalPath = $content.$entry->getBigThumbnailPath(); myContentStorage::moveFile($thumbBigFullPath, $thumbBigFinalPath, true , $should_copy ); */ $entryThumbKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); try { if (!$should_copy) { kFileSyncUtils::moveFromFile($thumbBigFullPath, $entryThumbKey); } else { kFileSyncUtils::copyFromFile($thumbBigFullPath, $entryThumbKey); } } catch (Exception $e) { $entry->setStatus(entryStatus::ERROR_CONVERTING); $entry->save(); throw $e; } } } // after extracting the thumb we can move the entry to its next destination KalturaLog::debug("handleEntry: current status [" . $entry->getStatus() . "]"); // if needed a job will be submitted for importing external media sources if ($entry->getStatus() == entryStatus::IMPORT) { KalturaLog::debug("handleEntry: creating import job"); // changed by Tan-Tan, Nov 09 to support the new batch mechanism kJobsManager::addImportJob(null, $this->entry_id, $this->partner_id, $entry_url); // remarked by Tan-Tan // $entry_fullPath = $content.'/content/imports/data/'.$this->entry_id.".".$ext; // myContentStorage::fullMkdir($entry_fullPath); // // $batchClient = new myBatchUrlImportClient(); // $batchClient->addJob($this->entry_id, $entry_url, $entry_fullPath); } else { if ($entry->getStatus() == entryStatus::PRECONVERT) { if (!$skip_conversion) { // changed by Tan-Tan, Dec 09 to support the new batch mechanism KalturaLog::debug("handleEntry: creating original flavor asset for pre convert"); $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id); if ($flavorAsset) { $flavorAsset->setFileExt($ext); $flavorAsset->save(); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); try { kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey); } catch (Exception $e) { $entry->setStatus(entryStatus::ERROR_CONVERTING); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $entry->save(); $flavorAsset->save(); throw $e; } kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset)); } else { $entry->setStatus(entryStatus::ERROR_CONVERTING); } // Remarked by Tan-Tan // $targetFileName = $this->entry_id.".".$ext; // if ( false /* old conversion */) // { // // if we need to convert move entry to conversion directory // $preConvPath = $content.'/content/preconvert/'; // myContentStorage::moveFile($entry_fullPath, $preConvPath."data/".$targetFileName, true , $should_copy ); // // $signalFilePath = $preConvPath."files/".$targetFileName; // myContentStorage::fullMkdir($signalFilePath); // touch($signalFilePath); // } // else // { // $preConvPath = myContentStorage::getFSContentRootPath (). "/content/new_preconvert"; // $to_data = $preConvPath . "/$targetFileName" ; // myContentStorage::moveFile($entry_fullPath, $to_data , true); // touch ( $to_data . ".indicator" ); // } } } else { if ($entry->getStatus() == entryStatus::PENDING || $media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { $entry->setData($entry_fullPath); $entry->save(); if ($media_type == entry::ENTRY_MEDIA_TYPE_VIDEO || $media_type == entry::ENTRY_MEDIA_TYPE_AUDIO) { KalturaLog::debug("handleEntry: creating original flavor asset for ready entry"); $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id); if ($flavorAsset) { $ext = pathinfo($entry_fullPath, PATHINFO_EXTENSION); $flavorAsset->setFileExt($ext); $flavorAsset->save(); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); try { if (!$should_copy) { kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey); } else { // copy & create file sync from $entry_fullPath kFileSyncUtils::copyFromFile($entry_fullPath, $syncKey); } } catch (Exception $e) { $entry->setStatus(entryStatus::ERROR_CONVERTING); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $entry->save(); $flavorAsset->save(); throw $e; } // // bypass to conversion // kBusinessPreConvertDL::bypassConversion($flavorAsset, $entry); /** * if this is webcam entry, create mediaInfo for the source flavor asset synchronously * since entry is ready right at the beginning */ if ($media_source == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "api_v3" . DIRECTORY_SEPARATOR . "bootstrap.php"; // extract file path $sourceFileKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); $sourceFilePath = kFileSyncUtils::getLocalFilePathForKey($sourceFileKey); // call mediaInfo for file $mediaInfo = new mediaInfo(); try { $mediaInfoParser = new KMediaInfoMediaParser($sourceFilePath, kConf::get('bin_path_mediainfo')); $KalturaMediaInfo = new KalturaMediaInfo(); $KalturaMediaInfo = $mediaInfoParser->getMediaInfo(); $mediaInfo = $KalturaMediaInfo->toInsertableObject($mediaInfo); $mediaInfo->setFlavorAssetId($flavorAsset->getId()); $mediaInfo->save(); } catch (Exception $e) { KalturaLog::err("Getting media info: " . $e->getMessage()); $mediaInfo = null; } // fix flavor asset according to mediainfo if ($mediaInfo) { KDLWrap::ConvertMediainfoCdl2FlavorAsset($mediaInfo, $flavorAsset); $flavorTags = KDLWrap::CDLMediaInfo2Tags($mediaInfo, array(flavorParams::TAG_WEB, flavorParams::TAG_MBR)); $flavorAsset->setTags(implode(',', $flavorTags)); } $flavorAsset->save(); } kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset)); $flavorAsset->setStatusLocalReady(); $flavorAsset->save(); } else { $entry->setStatus(entryStatus::ERROR_IMPORTING); } } else { if ($entry->getType() == entryType::DOCUMENT) { //TODO: document should be handled by the plugin manager) KalturaLog::debug("handleEntry: creating original flavor asset for ready entry"); $flavorAsset = kFlowHelper::createOriginalFlavorAsset($this->partner_id, $this->entry_id); if ($flavorAsset) { $ext = pathinfo($entry_fullPath, PATHINFO_EXTENSION); $flavorAsset->setFileExt($ext); $flavorAsset->save(); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); try { if (!$should_copy) { kFileSyncUtils::moveFromFile($entry_fullPath, $syncKey); } else { // copy & create file sync from $entry_fullPath kFileSyncUtils::copyFromFile($entry_fullPath, $syncKey); } } catch (Exception $e) { $entry->setStatus(entryStatus::ERROR_CONVERTING); $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR); $entry->save(); $flavorAsset->save(); throw $e; } kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset)); } } else { KalturaLog::debug("handleEntry: creating data file sync for file [{$entry_fullPath}]"); $entryDataKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); if (!kFileSyncUtils::file_exists($entryDataKey)) { try { if (!$should_copy) { kFileSyncUtils::moveFromFile($entry_fullPath, $entryDataKey); } else { // copy & create file sync from $entry_fullPath kFileSyncUtils::copyFromFile($entry_fullPath, $entryDataKey); } } catch (Exception $e) { $entry->setStatus(entryStatus::ERROR_CONVERTING); $entry->save(); throw $e; } } $entry->setStatus(entryStatus::READY); $entry->save(); } } // Remarked by Tan-Tan, the flavor asset should be synced instead of the entry // // $entryDataKey = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // if(!$should_copy) // { // kFileSyncUtils::moveFromFile($entry_fullPath, $entryDataKey); // } // else // { // // copy & create file sync from $entry_fullPath // kFileSyncUtils::copyFromFile($entry_fullPath, $entryDataKey); // } } } } if ($entry->getStatus() == entryStatus::READY) { $entry->updateDimensions(); } $entry->save(); return true; }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser) { KalturaLog::log("adddownloadAction: executeImpl ( {$partner_id} , {$subp_id} , {$puser_id} , {$partner_prefix} , {$puser_kuser})"); $entry_id = $this->getPM("entry_id"); $version = $this->getP("version"); $file_format = strtolower($this->getPM("file_format")); $conversion_quality = $this->getP("conversion_quality", null); $force_download = $this->getP("force_download", null); $entry = entryPeer::retrieveByPK($entry_id); if (!$entry) { KalturaLog::log("add download Action entry not found"); $this->addError(APIErrors::INVALID_ENTRY_ID, $this->getObjectPrefix(), $entry_id); return; } KalturaLog::log("adddownloadAction: entry found [{$entry_id}]"); /* $content_path = myContentStorage::getFSContentRootPath(); $file_name = $content_path . $entry->getDataPath( $version ); // replaced__getDataPath if (!file_exists($file_name)) */ $sync_key = null; $originalFlavorAsset = assetPeer::retrieveOriginalByEntryId($entry->getId()); if ($originalFlavorAsset) { $sync_key = $originalFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); } if (!$sync_key) { $sync_key = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version); } if (!kFileSyncUtils::file_exists($sync_key)) { // if not found local file - perhaps wasn't created here and wasn't synced yet // try to see if remote exists - and proxy the request if it is. list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, true); if (!$local) { // take input params and add to URL $queryArr = array('entry_id' => $entry_id, 'version' => $version, 'file_format' => $file_format, 'conversion_quality' => $conversion_quality, 'force_download' => $force_download, 'ks' => $this->ks->toSecureString(), 'partner_id' => $partner_id, 'subp_id' => $subp_id, 'format' => $this->response_type); $get_query = http_build_query($queryArr, '', '&'); $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync, $_SERVER['REQUEST_URI']); $url = strpos($remote_url, '?') === FALSE ? $remote_url . '?' . $get_query : $remote_url . '&' . $get_query; // prxoy request to other DC KalturaLog::log(__METHOD__ . ": redirecting to [{$url}]"); kFileUtils::dumpUrl($url); } KalturaLog::log("add download Action sync key doesn't exists"); $this->addError(APIErrors::INVALID_ENTRY_VERSION, $this->getObjectPrefix(), $entry_id, $version); return; } if ($entry->getType() == entryType::MIX) { KalturaLog::log("The Batch job for flattening a mix is no longer supported"); $this->addError(APIErrors::INVALID_ENTRY_TYPE, $this->getObjectPrefix(), $entry_id, $version); return; } $flavorParamsId = 0; if ($file_format != "original") { if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) { $file_format = "flv"; } // Backward compatebility if (!$file_format && $entry->getType() == entryType::DOCUMENT) { $file_format = "swf"; } $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($partner_id, $file_format); $flavorParamsId = $flavorParams->getId(); } $jobs = kJobsManager::addBulkDownloadJob($partner_id, $puser_id, $entry->getId(), $flavorParamsId); $job = $jobs[0]; // remove kConvertJobData object from batchJob.data $job->setData(null); $jobWrapperClass = objectWrapperBase::getWrapperClass($job, objectWrapperBase::DETAIL_LEVEL_DETAILED); $this->addMsg("download", $jobWrapperClass); // Backwards compatebilty for document entries if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_DOCUMENT || $entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_PDF) { $this->addMsg("OOconvert", $jobWrapperClass); $download_path = $entry->getDownloadUrl(); //TODO: once api_v3 will support parameters with '/' instead of '?', we can change this to war with api_v3 $download_path .= '/direct_serve/true/type/download/forceproxy/true/format/' . $file_format; $this->addMsg('downloadUrl', $download_path); } }
/** * @param BatchJob $dbBatchJob * @param kImportJobData $data * @param BatchJob $twinJob * @return BatchJob */ public static function handleImportFinished(BatchJob $dbBatchJob, kImportJobData $data, BatchJob $twinJob = null) { KalturaLog::debug("Import finished, with file: " . $data->getDestFileLocalPath()); if ($dbBatchJob->getAbort()) { return $dbBatchJob; } if (!$twinJob) { if (!file_exists($data->getDestFileLocalPath())) { throw new APIException(APIErrors::INVALID_FILE_NAME, $data->getDestFileLocalPath()); } } $msg = null; $flavorAsset = kFlowHelper::createOriginalFlavorAsset($dbBatchJob->getPartnerId(), $dbBatchJob->getEntryId(), $msg); if (!$flavorAsset) { KalturaLog::err("Flavor asset not created for entry [" . $dbBatchJob->getEntryId() . "]"); kBatchManager::updateEntry($dbBatchJob, entryStatus::ERROR_CONVERTING); $dbBatchJob->setMessage($msg); $dbBatchJob->setDescription($dbBatchJob->getDescription() . "\n" . $msg); return $dbBatchJob; } $syncKey = null; if ($twinJob) { $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); // copy file sync $twinData = $twinJob->getData(); if ($twinData instanceof kImportJobData) { $twinFlavorAsset = flavorAssetPeer::retrieveById($twinData->getFlavorAssetId()); if ($twinFlavorAsset) { $twinSyncKey = $twinFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if ($twinSyncKey && kFileSyncUtils::file_exists($twinSyncKey)) { kFileSyncUtils::softCopy($twinSyncKey, $syncKey); } } } } else { $ext = pathinfo($data->getDestFileLocalPath(), PATHINFO_EXTENSION); KalturaLog::info("Imported file extension: {$ext}"); $flavorAsset->setFileExt($ext); $flavorAsset->save(); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); kFileSyncUtils::moveFromFile($data->getDestFileLocalPath(), $syncKey); } // set the path in the job data $data->setDestFileLocalPath(kFileSyncUtils::getLocalFilePathForKey($syncKey)); $data->setFlavorAssetId($flavorAsset->getId()); $dbBatchJob->setData($data); $dbBatchJob->save(); kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset)); return $dbBatchJob; }
public static function copyEntryData(entry $entry, entry $targetEntry) { // for any type that does not require assets: $shouldCopyDataForNonClip = true; if ($entry->getType() == entryType::MEDIA_CLIP) { $shouldCopyDataForNonClip = false; } if ($entry->getType() == entryType::PLAYLIST) { $shouldCopyDataForNonClip = false; } $shouldCopyDataForClip = false; // only images get their data copied if ($entry->getType() == entryType::MEDIA_CLIP) { if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_AUDIO) { $shouldCopyDataForClip = true; } } if ($shouldCopyDataForNonClip || $shouldCopyDataForClip) { // copy the data $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath $to = $targetEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath KalturaLog::log("copyEntriesByType - copying entry data [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } $ismFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); if (kFileSyncUtils::fileSync_exists($ismFrom)) { $ismTo = $targetEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); KalturaLog::log("copying entry ism [" . $ismFrom . "] to [" . $ismTo . "]"); kFileSyncUtils::softCopy($ismFrom, $ismTo); } $ismcFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); if (kFileSyncUtils::fileSync_exists($ismcFrom)) { $ismcTo = $targetEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); KalturaLog::log("copying entry ism [" . $ismcFrom . "] to [" . $ismcTo . "]"); kFileSyncUtils::softCopy($ismcFrom, $ismcTo); } $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath $considerCopyThumb = true; // if entry is image - data is thumbnail, and it was copied if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $considerCopyThumb = false; } // if entry is not clip, and there is no file in both DCs - nothing to copy if ($entry->getType() != entryType::MEDIA_CLIP && !kFileSyncUtils::file_exists($from, true)) { $considerCopyThumb = false; } if ($considerCopyThumb) { $skipThumb = false; // don't attempt to copy a thumbnail for images - it's the same as the data which was just created if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) { // check if audio entry has real thumb, if not - don't copy thumb. $originalFileSync = kFileSyncUtils::getOriginFileSyncForKey($from, false); if (!$originalFileSync) { $skipThumb = true; } } if (!$skipThumb) { $to = $targetEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath KalturaLog::log("copyEntriesByType - copying entry thumbnail [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } } // added by Tan-Tan 12/01/2010 to support falvors copy $sourceAssets = assetPeer::retrieveByEntryId($entry->getId()); foreach ($sourceAssets as $sourceAsset) { $sourceAsset->copyToEntry($targetEntry->getId(), $targetEntry->getPartnerId()); } }
public function execute() { requestUtils::handleConditionalGet(); $entry_id = $this->getRequestParameter("entry_id"); $ks_str = $this->getRequestParameter("ks"); $base64_referrer = $this->getRequestParameter("referrer"); $referrer = base64_decode($base64_referrer); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ""; } $clip_from = $this->getRequestParameter("clip_from", 0); // milliseconds $clip_to = $this->getRequestParameter("clip_to", 2147483647); // milliseconds if ($clip_to == 0) { $clip_to = 2147483647; } $request = $_SERVER["REQUEST_URI"]; // remove dynamic fields from the url so we'll request a single url from the cdn $request = str_replace("/referrer/{$base64_referrer}", "", $request); $request = str_replace("/ks/{$ks_str}", "", $request); // workaround the filter which hides all the deleted entries - // now that deleted entries are part of xmls (they simply point to the 'deleted' templates), we should allow them here $entry = entryPeer::retrieveByPKNoFilter($entry_id); if (!$entry) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } myPartnerUtils::blockInactivePartner($entry->getPartnerId()); // set the memory size to be able to serve big files in a single chunk ini_set("memory_limit", "64M"); // set the execution time to be able to serve big files in a single chunk ini_set("max_execution_time", 240); if ($entry->getType() == entryType::MIX && $entry->getStatus() == entryStatus::DELETED) { // because the fiter was turned off - a manual check for deleted entries must be done. die; } else { if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $version = $this->getRequestParameter("version", null); $width = $this->getRequestParameter("width", -1); $height = $this->getRequestParameter("height", -1); $crop_provider = $this->getRequestParameter("crop_provider", null); $bgcolor = $this->getRequestParameter("bgcolor", "ffffff"); $type = $this->getRequestParameter("type", 1); $quality = $this->getRequestParameter("quality", 0); $src_x = $this->getRequestParameter("src_x", 0); $src_y = $this->getRequestParameter("src_y", 0); $src_w = $this->getRequestParameter("src_w", 0); $src_h = $this->getRequestParameter("src_h", 0); $vid_sec = $this->getRequestParameter("vid_sec", -1); $vid_slice = $this->getRequestParameter("vid_slice", -1); $vid_slices = $this->getRequestParameter("vid_slices", -1); if ($width == -1 && $height == -1) { $width = 640; $height = 480; } else { if ($width == -1) { // if only either width or height is missing reset them to zero, and convertImage will handle them $width = 0; } else { if ($height == -1) { $height = 0; } } } $tempThumbPath = myEntryUtils::resizeEntryImage($entry, $version, $width, $height, $type, $bgcolor, $crop_provider, $quality, $src_x, $src_y, $src_w, $src_h, $vid_sec, $vid_slice, $vid_slices); kFile::dumpFile($tempThumbPath, null, strpos($tempThumbPath, "_NOCACHE_") === false ? null : 0); } } $audio_only = $this->getRequestParameter("audio_only"); // milliseconds $flavor = $this->getRequestParameter("flavor", 1); // $flavor_param_id = $this->getRequestParameter("flavor_param_id", null); // $streamer = $this->getRequestParameter("streamer"); // if (substr($streamer, 0, 4) == "rtmp") { // the fms may add .mp4 to the end of the url $streamer = "rtmp"; } // grab seek_from_bytes parameter and normalize url $seek_from_bytes = $this->getRequestParameter("seek_from_bytes", -1); $request = str_replace("/seek_from_bytes/{$seek_from_bytes}", "", $request); if ($seek_from_bytes <= 0) { $seek_from_bytes = -1; } // grab seek_from parameter and normalize url $seek_from = $this->getRequestParameter("seek_from", -1); $request = str_replace("/seek_from/{$seek_from}", "", $request); if ($seek_from <= 0) { $seek_from = -1; } $this->dump_from_byte = 0; // reset accurate seek from timestamp $seek_from_timestamp = -1; // backward compatibility if ($flavor === "0") { // for edit version $flavor = "edit"; } if ($flavor === "1" || $flavor === 1) { // for play version $flavor = null; } // when flavor is null, we will get a default flavor if ($flavor == "edit") { $flavorAsset = flavorAssetPeer::retrieveBestEditByEntryId($entry->getId()); } elseif (!is_null($flavor)) { $flavorAsset = flavorAssetPeer::retrieveById($flavor); // when specific asset was request, we don't validate its tags if ($flavorAsset && ($flavorAsset->getEntryId() != $entry->getId() || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY)) { $flavorAsset = null; } // we will throw an error later } elseif (is_null($flavor) && !is_null($flavor_param_id)) { $flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entry->getId(), $flavor_param_id); if ($flavorAsset && $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { $flavorAsset = null; } // we will throw an error later } else { if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { $flavorAsset = flavorAssetPeer::retrieveOriginalByEntryId($entry->getId()); } else { $flavorAsset = flavorAssetPeer::retrieveBestPlayByEntryId($entry->getId()); } if (!$flavorAsset) { $flavorAssets = flavorAssetPeer::retreiveReadyByEntryIdAndTag($entry->getId(), flavorParams::TAG_WEB); if (count($flavorAssets) > 0) { $flavorAsset = $flavorAssets[0]; } } } if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (kFileSyncUtils::file_exists($syncKey, false)) { $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); } else { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for flavor [" . $flavorAsset->getId() . "]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); $this->redirect($remoteUrl); } $flv_wrapper = new myFlvHandler($path); $isFlv = $flv_wrapper->isFlv(); // scrubbing is not allowed within mp4 files if (!$isFlv) { $seek_from = $seek_from_bytes = -1; } if ($seek_from !== -1 && $seek_from !== 0) { if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } list($bytes, $duration, $first_tag_byte, $to_byte) = $flv_wrapper->clip(0, -1, $audio_only); list($bytes, $duration, $from_byte, $to_byte, $seek_from_timestamp) = $flv_wrapper->clip($seek_from, -1, $audio_only); $seek_from_bytes = myFlvHandler::FLV_HEADER_SIZE + $flv_wrapper->getMetadataSize($audio_only) + $from_byte - $first_tag_byte; } // the direct path without a cdn is "http://s3kaltura.s3.amazonaws.com".$entry->getDataPath(); $extStorageUrl = $entry->getExtStorageUrl(); if ($extStorageUrl && substr_count($extStorageUrl, 's3kaltura')) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $request_host = parse_url($extStorageUrl, PHP_URL_HOST); $akamai_url = str_replace($request_host, "cdns3akmi.kaltura.com", $extStorageUrl); $akamai_url .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); die; } elseif ($extStorageUrl) { // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $extStorageUrl .= $seek_from_bytes == -1 ? "" : "?aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$extStorageUrl}"); die; } // use headers to detect cdn $cdn_name = ""; $via_header = @$_SERVER["HTTP_VIA"]; if (strpos($via_header, "llnw.net") !== false) { $cdn_name = "limelight"; } else { if (strpos($via_header, "akamai") !== false) { $cdn_name = "akamai"; } else { if (strpos($via_header, "Level3") !== false) { $cdn_name = "level3"; } } } // setting file extension - first trying frrom flavor asset $ext = $flavorAsset->getFileExt(); // if failed, set extension according to file type (isFlv) if (!$ext) { $ext = $isFlv ? "flv" : "mp4"; } $flv_extension = $streamer == "rtmp" ? "?" : "/a.{$ext}?novar=0"; // dont check for rtmp / and for an already redirect url if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // check security using ks $securyEntryHelper = new KSecureEntryHelper($entry, $ks_str, $referrer); if ($securyEntryHelper->shouldPreview()) { $this->checkForPreview($securyEntryHelper, $clip_to); } else { $securyEntryHelper->validateForPlay($entry, $ks_str); } } else { // if needs security check using cdn authentication mechanism // for now assume this is a cdn request and don't check for security } // use limelight mediavault if either security policy requires it or if we're trying to seek within the video if ($entry->getSecurityPolicy() || $seek_from_bytes !== -1) { // we have three options: // arrived through limelight mediavault url - the url is secured // arrived directly through limelight (not secured through mediavault) - enforce ks and redirect to mediavault url // didnt use limelight - enforce ks // the cdns are configured to authenticate request for /s/.... // check if we're already in a redirected secure link using the "/s/" prefix $secure_request = substr($request, 0, 3) == "/s/"; if ($secure_request && ($cdn_name == "limelight" || $cdn_name == "level3")) { // request was validated by cdn let it through } else { // extract ks $ks_str = $this->getRequestParameter("ks", ""); if ($entry->getSecurityPolicy()) { if (!$ks_str) { $this->logMessage("flvclipper - no KS"); die; } $ks = kSessionUtils::crackKs($ks_str); if (!$ks) { $this->logMessage("flvclipper - invalid ks [{$ks_str}]"); die; } $matched_privs = $ks->verifyPrivileges("sview", $entry_id); $this->logMessage("flvclipper - verifyPrivileges name [sview], priv [{$entry_id}] [{$matched_privs}]"); if (!$matched_privs) { $this->logMessage("flvclipper - doesnt not match required privlieges [{$ks_str}]"); die; } } if ($cdn_name == "limelight") { $ll_url = requestUtils::getCdnHost() . "/s{$request}" . $flv_extension; $secret = kConf::get("limelight_madiavault_password"); $expire = "&e=" . (time() + 120); $ll_url .= $expire; $fs = $seek_from_bytes == -1 ? "" : "&fs={$seek_from_bytes}"; $ll_url .= "&h=" . md5("{$secret}{$ll_url}") . $fs; //header("Location: $ll_url"); $this->redirect($ll_url); } else { if ($cdn_name == "level3") { $level3_url = $request . $flv_extension; if ($entry->getSecurityPolicy()) { $level3_url = "/s{$level3_url}"; // set expire time in GMT hence the date("Z") offset $expire = "&nva=" . strftime("%Y%m%d%H%M%S", time() - date("Z") + 30); $level3_url .= $expire; $secret = kConf::get("level3_authentication_key"); $hash = "0" . substr(self::hmac('sha1', $secret, $level3_url), 0, 20); $level3_url .= "&h={$hash}"; } $level3_url .= $seek_from_bytes == -1 ? "" : "&start={$seek_from_bytes}"; header("Location: {$level3_url}"); die; } else { if ($cdn_name == "akamai") { $akamai_url = $request . $flv_extension; // if for some reason we didnt set our accurate $seek_from_timestamp reset it to the requested seek_from if ($seek_from_timestamp == -1) { $seek_from_timestamp = $seek_from; } $akamai_url .= $seek_from_bytes == -1 ? "" : "&aktimeoffset=" . floor($seek_from_timestamp / 1000); header("Location: {$akamai_url}"); die; } } } // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $this->dump_from_byte = $seek_from_bytes; } } } // always add the file suffix to the request (needed for scrubbing by some cdns, // and also breaks without extension on some corporate antivirus). // we add the the novar paramter since a leaving a trailing "?" will be trimmed // and then the /seek_from request will result in another url which level3 // will try to refetch from the origin // note that for streamer we dont add the file extension if ($streamer != "rtmp" && strpos($request, $flv_extension) === false) { // a seek request without a supporting cdn - we need to send the answer from our server if ($seek_from_bytes !== -1 && $via_header === null) { $request .= "/seek_from_bytes/{$seek_from_bytes}"; } requestUtils::sendCdnHeaders("flv", 0); header("Location: {$request}" . $flv_extension); die; } // mp4 if (!$isFlv) { kFile::dumpFile($path); } $this->logMessage("flvclipperAction: serving file [{$path}] entry_id [{$entry_id}] clip_from [{$clip_from}] clip_to [{$clip_to}]", "warning"); if ($audio_only === '0') { // audio_only was explicitly set to 0 - don't attempt to make further automatic investigations } elseif ($flv_wrapper->getFirstVideoTimestamp() < 0) { $audio_only = true; } //$start = microtime(true); list($bytes, $duration, $from_byte, $to_byte, $from_ts, $cuepoint_pos) = myFlvStaticHandler::clip($path, $clip_from, $clip_to, $audio_only); $metadata_size = $flv_wrapper->getMetadataSize($audio_only); $this->from_byte = $from_byte; $this->to_byte = $to_byte; //$end1 = microtime(true); //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); //$this->logMessage( "flvclipperAction: serving file [$path] t1 [" . ( $end1-$start) . "]"); $data_offset = $metadata_size + myFlvHandler::getHeaderSize(); // if we're returning a partial file adjust the total size: // substract the metadata and bytes which are not delivered if ($this->dump_from_byte >= $data_offset && !$audio_only) { $bytes -= $metadata_size + max(0, $this->dump_from_byte - $data_offset); } $this->total_length = $data_offset + $bytes; //echo " $bytes , $duration ,$from_byte , $to_byte, $cuepoint_pos\n"; die; $this->cuepoint_time = 0; $this->cuepoint_pos = 0; if ($streamer == "chunked" && $clip_to != 2147483647) { $this->cuepoint_time = $clip_to - 1; $this->cuepoint_pos = $cuepoint_pos; $this->total_length += myFlvHandler::CUEPOINT_TAG_SIZE; } //$this->logMessage( "flvclipperAction: serving file [$path] entry_id [$entry_id] bytes with header & md [" . $this->total_length . "] bytes [$bytes] duration [$duration] [$from_byte]->[$to_byte]" , "warning" ); $this->flv_wrapper = $flv_wrapper; $this->audio_only = $audio_only; try { Propel::close(); } catch (Exception $e) { $this->logMessage("flvclipperAction: error closing db {$e}"); } return sfView::SUCCESS; }
/** * This will queue a batch job for converting the document file to swf * Returns the URL where the new swf will be available * * @action convertPptToSwf * @param string $entryId * @return string */ function convertPptToSwf($entryId) { $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (is_null($flavorAsset) || !$flavorAsset->isLocalReadyStatus()) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } $sync_key = null; $sync_key = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($sync_key)) { // if not found local file - perhaps wasn't created here and wasn't synced yet // try to see if remote exists - and proxy the request if it is. list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, true); if (!$local) { $remoteDCHost = kDataCenterMgr::getRemoteDcExternalUrl($fileSync); kFileUtils::dumpApiRequest($remoteDCHost); } KalturaLog::log("convertPptToSwf sync key doesn't exists"); return; } $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($dbEntry->getPartnerId(), flavorParams::CONTAINER_FORMAT_SWF); $flavorParamsId = $flavorParams->getId(); $puserId = $this->getKuser()->getPuserId(); $err = ""; kBusinessPreConvertDL::decideAddEntryFlavor(null, $dbEntry->getId(), $flavorParamsId, $err); $downloadPath = $dbEntry->getDownloadUrl(); //TODO: once api_v3 will support parameters with '/' instead of '?', we can change this to war with api_v3 return $downloadPath . '/direct_serve/true/type/download/forceproxy/true/format/swf'; }
public static function copyEntry(entry $entry, Partner $toPartner = null, $dontCopyUsers = false) { KalturaLog::log("copyEntry - Copying entry [" . $entry->getId() . "] to partner [" . $toPartner->getId() . "]"); $newEntry = $entry->copy(); $newEntry->setIntId(null); $newEntry->setCategories(null); $newEntry->setCategoriesIds(null); if ($toPartner instanceof Partner) { $newEntry->setPartnerId($toPartner->getId()); $newEntry->setSubpId($toPartner->getId() * 100); $newEntry->setAccessControlId($toPartner->getDefaultAccessControlId()); } $newKuser = null; if (!$dontCopyUsers) { // copy the kuser (if the same puser id exists its kuser will be used) kuserPeer::setUseCriteriaFilter(false); $kuser = $entry->getKuser(); $newKuser = kuserPeer::createKuserForPartner($newEntry->getPartnerId(), $kuser->getPuserId()); $newEntry->setKuserId($newKuser->getId()); $newEntry->setCreatorKuserId($newKuser->getId()); kuserPeer::setUseCriteriaFilter(true); } // copy the kshow kshowPeer::setUseCriteriaFilter(false); $kshow = $entry->getKshow(); if ($kshow) { $newKshow = $kshow->copy(); $newKshow->setIntId(null); $newKshow->setPartnerId($toPartner->getId()); $newKshow->setSubpId($toPartner->getId() * 100); if ($newKuser) { $newKshow->setProducerId($newKuser->getId()); } $newKshow->save(); $newEntry->setKshowId($newKshow->getId()); } kshowPeer::setUseCriteriaFilter(true); // reset the statistics myEntryUtils::resetEntryStatistics($newEntry); // set the new partner id into the default category criteria filter $defaultCategoryFilter = categoryPeer::getCriteriaFilter()->getFilter(); $oldPartnerId = $defaultCategoryFilter->get(categoryPeer::PARTNER_ID); $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID); $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId()); // save the entry $newEntry->save(); // restore the original partner id in the default category criteria filter $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID); $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $oldPartnerId); KalturaLog::log("copyEntry - New entry [" . $newEntry->getId() . "] was created"); // for any type that does not require assets: $shouldCopyDataForNonClip = true; if ($entry->getType() == entryType::MEDIA_CLIP) { $shouldCopyDataForNonClip = false; } if ($entry->getType() == entryType::PLAYLIST) { $shouldCopyDataForNonClip = false; } $shouldCopyDataForClip = false; // only images get their data copied if ($entry->getType() == entryType::MEDIA_CLIP) { if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_AUDIO) { $shouldCopyDataForClip = true; } } //if entry is a static playlist, link between it and its new child entries if ($entry->getType() == entryType::PLAYLIST) { switch ($entry->getMediaType()) { case entry::ENTRY_MEDIA_TYPE_TEXT: $from = $entry->getDataContent(); KalturaLog::debug("Entries to copy from source static playlist: [{$from}]"); $fromEntryIds = explode(",", $from); $toEntryIds = array(); foreach ($fromEntryIds as $fromEntryId) { $toEntryIds[] = kObjectCopyHandler::getMappedId(entryPeer::OM_CLASS, $fromEntryId); } $newEntry->setDataContent(implode(",", $toEntryIds)); break; case entry::ENTRY_MEDIA_TYPE_XML: list($totalResults, $fromFiltersList) = myPlaylistUtils::getPlaylistFilterListStruct($entry->getDataContent()); $toPlaylistXml = new SimpleXMLElement("<playlist/>"); $toPlaylistXml->addChild("total_results", $totalResults); $toFiltersXml = $toPlaylistXml->addChild("filters"); foreach ($fromFiltersList as $filterXML) { $entryFilter = new entryFilter(); $entryFilter->fillObjectFromXml($filterXML, "_"); if (isset($entryFilter->fields["_matchand_categories_ids"])) { $categoriesIds = explode(",", $entryFilter->fields["_matchand_categories_ids"]); $newCategoriesIds = array(); foreach ($categoriesIds as $categoryId) { $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId); } $entryFilter->fields["_matchand_categories_ids"] = implode(",", $newCategoriesIds); } if (isset($entryFilter->fields["_matchor_categories_ids"])) { $categoriesIds = explode(",", $entryFilter->fields["_matchor_categories_ids"]); $newCategoriesIds = array(); foreach ($categoriesIds as $categoryId) { $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId); } $entryFilter->fields["_matchor_categories_ids"] = implode(",", $newCategoriesIds); } if (isset($entryFilter->fields["_in_category_ancestor_id"])) { $categoriesIds = explode(",", $entryFilter->fields["_in_category_ancestor_id"]); $newCategoriesIds = array(); foreach ($categoriesIds as $categoryId) { $newCategoriesIds[] = kObjectCopyHandler::getMappedId(categoryPeer::OM_CLASS, $categoryId); } $entryFilter->fields["_in_category_ancestor_id"] = implode(",", $newCategoriesIds); } $toEntryFilterXML = $toFiltersXml->addChild("filter"); $toEntryFilterXML = $entryFilter->toXml($toEntryFilterXML); } $newEntry->setDataContent($toPlaylistXml->asXML()); break; } } if ($shouldCopyDataForNonClip || $shouldCopyDataForClip) { // copy the data $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath KalturaLog::log("copyEntriesByType - copying entry data [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } $ismFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); if (kFileSyncUtils::fileSync_exists($ismFrom)) { $ismTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); KalturaLog::log("copying entry ism [" . $ismFrom . "] to [" . $ismTo . "]"); kFileSyncUtils::softCopy($ismFrom, $ismTo); } $ismcFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); if (kFileSyncUtils::fileSync_exists($ismcFrom)) { $ismcTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); KalturaLog::log("copying entry ism [" . $ismcFrom . "] to [" . $ismcTo . "]"); kFileSyncUtils::softCopy($ismcFrom, $ismcTo); } $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath $considerCopyThumb = true; // if entry is image - data is thumbnail, and it was copied if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $considerCopyThumb = false; } // if entry is not clip, and there is no file in both DCs - nothing to copy if ($entry->getType() != entryType::MEDIA_CLIP && !kFileSyncUtils::file_exists($from, true)) { $considerCopyThumb = false; } if ($considerCopyThumb) { $skipThumb = false; // don't attempt to copy a thumbnail for images - it's the same as the data which was just created if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) { // check if audio entry has real thumb, if not - don't copy thumb. $originalFileSync = kFileSyncUtils::getOriginFileSyncForKey($from, false); if (!$originalFileSync) { $skipThumb = true; } } if (!$skipThumb) { $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath KalturaLog::log("copyEntriesByType - copying entry thumbnail [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } } // added by Tan-Tan 12/01/2010 to support falvors copy $sourceAssets = assetPeer::retrieveByEntryId($entry->getId()); foreach ($sourceAssets as $sourceAsset) { $sourceAsset->copyToEntry($newEntry->getId(), $newEntry->getPartnerId()); } // copy relationships to categories KalturaLog::debug('Copy relationships to categories from entry [' . $entry->getId() . '] to entry [' . $newEntry->getId() . ']'); $c = KalturaCriteria::create(categoryEntryPeer::OM_CLASS); $c->addAnd(categoryEntryPeer::ENTRY_ID, $entry->getId()); $c->addAnd(categoryEntryPeer::STATUS, CategoryEntryStatus::ACTIVE, Criteria::EQUAL); $c->addAnd(categoryEntryPeer::PARTNER_ID, $entry->getPartnerId()); categoryEntryPeer::setUseCriteriaFilter(false); $categoryEntries = categoryEntryPeer::doSelect($c); categoryEntryPeer::setUseCriteriaFilter(true); // Create srcCategoryIdToDstCategoryIdMap - a map of source partner category ids -> dst. partner category ids // // Build src category IDs set $srcCategoryIdSet = array(); foreach ($categoryEntries as $categoryEntry) { $srcCategoryIdSet[] = $categoryEntry->getCategoryId(); } $illegalCategoryStatus = array(CategoryStatus::DELETED, CategoryStatus::PURGED); // Get src category objects $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $c->add(categoryPeer::ID, $srcCategoryIdSet, Criteria::IN); $c->addAnd(categoryPeer::PARTNER_ID, $entry->getPartnerId()); $c->addAnd(categoryPeer::STATUS, $illegalCategoryStatus, Criteria::NOT_IN); categoryPeer::setUseCriteriaFilter(false); $srcCategories = categoryPeer::doSelect($c); categoryPeer::setUseCriteriaFilter(true); // Map the category names to their IDs $fullNamesToSrcCategoryIdMap = array(); foreach ($srcCategories as $category) { $fullNamesToSrcCategoryIdMap[$category->getFullName()] = $category->getId(); } // Get dst. partner categories based on src. category full-names $c = KalturaCriteria::create(categoryPeer::OM_CLASS); $c->add(categoryPeer::FULL_NAME, array_keys($fullNamesToSrcCategoryIdMap), KalturaCriteria::IN); $c->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId()); $c->addAnd(categoryPeer::STATUS, $illegalCategoryStatus, Criteria::NOT_IN); categoryPeer::setUseCriteriaFilter(false); $dstCategories = categoryPeer::doSelect($c); categoryPeer::setUseCriteriaFilter(true); $srcCategoryIdToDstCategoryIdMap = array(); foreach ($dstCategories as $dstCategory) { $fullName = $dstCategory->getFullName(); if (array_key_exists($fullName, $fullNamesToSrcCategoryIdMap)) { $srcCategoryId = $fullNamesToSrcCategoryIdMap[$fullName]; $srcCategoryIdToDstCategoryIdMap[$srcCategoryId] = $dstCategory->getId(); } } foreach ($categoryEntries as $categoryEntry) { /* @var $categoryEntry categoryEntry */ $newCategoryEntry = $categoryEntry->copy(); $newCategoryEntry->setPartnerId($newEntry->getPartnerId()); $newCategoryEntry->setEntryId($newEntry->getId()); $srcCategoryId = $categoryEntry->getCategoryId(); if (!array_key_exists($srcCategoryId, $srcCategoryIdToDstCategoryIdMap)) { continue; // Skip the category_entry's creation } $dstCategoryId = $srcCategoryIdToDstCategoryIdMap[$srcCategoryId]; $newCategoryEntry->setCategoryId($dstCategoryId); categoryPeer::setUseCriteriaFilter(false); entryPeer::setUseCriteriaFilter(false); $newCategoryEntry->save(); entryPeer::setUseCriteriaFilter(true); categoryPeer::setUseCriteriaFilter(true); } return $newEntry; }
/** * This will queue a batch job for converting the document file to swf * Returns the URL where the new swf will be available * * @action convertPptToSwf * @param string $entryId * @return string */ function convertPptToSwf($entryId) { $dbEntry = entryPeer::retrieveByPK($entryId); if (!$dbEntry || $dbEntry->getType() != KalturaEntryType::DOCUMENT) { throw new KalturaAPIException(KalturaErrors::ENTRY_ID_NOT_FOUND, $entryId); } assetPeer::resetInstanceCriteriaFilter(); $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (is_null($flavorAsset) || $flavorAsset->getStatus() != flavorAsset::FLAVOR_ASSET_STATUS_READY) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } $sync_key = null; $sync_key = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($sync_key)) { // if not found local file - perhaps wasn't created here and wasn't synced yet // try to see if remote exists - and proxy the request if it is. list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($sync_key, true, true); if (!$local) { // take input params and add to URL $queryArr = array('service' => 'document', 'action' => 'convertPptToSwf', 'entryId' => $entryId, 'format' => $this->params["format"], 'ks' => $this->getKs()->toSecureString()); $get_query = http_build_query($queryArr, '', '&'); $remote_url = kDataCenterMgr::getRedirectExternalUrl($fileSync, $_SERVER['REQUEST_URI']); $url = strpos($remote_url, '?') === FALSE ? $remote_url . '?' . $get_query : $remote_url . '&' . $get_query; // prxoy request to other DC KalturaLog::log(__METHOD__ . ": redirecting to [{$url}]"); kFile::dumpUrl($url); } KalturaLog::log("convertPptToSwf sync key doesn't exists"); return; } $flavorParams = myConversionProfileUtils::getFlavorParamsFromFileFormat($dbEntry->getPartnerId(), flavorParams::CONTAINER_FORMAT_SWF); $flavorParamsId = $flavorParams->getId(); $puserId = $this->getKuser()->getPuserId(); $err = ""; kBusinessPreConvertDL::decideAddEntryFlavor(null, $dbEntry->getId(), $flavorParamsId, $err); $downloadPath = $dbEntry->getDownloadUrl(); //TODO: once api_v3 will support parameters with '/' instead of '?', we can change this to war with api_v3 return $downloadPath . '/direct_serve/true/type/download/forceproxy/true/format/swf'; }
public function executeImpl($partner_id, $subp_id, $puser_id, $partner_prefix, $puser_kuser) { $kshowId = $this->getP("kshow_id"); $numberOfVersions = $this->getP("number_of_versions", 5); // must be int and not more than 50 $numberOfVersions = (int) $numberOfVersions; $numberOfVersions = min($numberOfVersions, 50); $kshow = kshowPeer::retrieveByPK($kshowId); if (!$kshow) { $this->addError(APIErrors::KSHOW_DOES_NOT_EXISTS); return; } $showEntry = $kshow->getShowEntry(); if (!$showEntry) { $this->addError(APIErrors::ROUGHCUT_NOT_FOUND); return; } $sync_key = $showEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); $showEntryDataPath = kFileSyncUtils::getLocalFilePathForKey($sync_key); $versionsInfoFilePath = $showEntryDataPath . '.info'; $lastVersionDoc = new KDOMDocument(); $lastVersionDoc->loadXML(kFileSyncUtils::file_get_contents($sync_key, true, false)); $lastVersion = myContentStorage::getVersion($showEntryDataPath); // check if we need to refresh the data in the info file $refreshInfoFile = true; if (file_exists($versionsInfoFilePath)) { $versionsInfoDoc = new KDOMDocument(); $versionsInfoDoc->load($versionsInfoFilePath); $lastVersionInInfoFile = kXml::getLastElementAsText($versionsInfoDoc, "ShowVersion"); if ($lastVersionInInfoFile && $lastVersion == $lastVersionInInfoFile) { $refreshInfoFile = false; } else { $refreshInfoFile = true; } } else { $refreshInfoFile = true; } // refresh or create the data in the info file if ($refreshInfoFile) { $versionsInfoDoc = new KDOMDocument(); $xmlElement = $versionsInfoDoc->createElement("xml"); // start from the first edited version (100001) and don't use 100000 for ($i = myContentStorage::MIN_OBFUSCATOR_VALUE + 1; $i <= $lastVersion; $i++) { $version_sync_key = $showEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $i); if (kFileSyncUtils::file_exists($version_sync_key, false)) { $xmlContent = kFileSyncUtils::file_get_contents($version_sync_key); //echo "[" . htmlspecialchars( $xmlContent ) . "]<br>"; $xmlDoc = new KDOMDocument(); $xmlDoc->loadXML($xmlContent); $elementToCopy = kXml::getFirstElement($xmlDoc, "MetaData"); //echo "[$i]"; $elementCloned = $elementToCopy->cloneNode(true); $elementImported = $versionsInfoDoc->importNode($elementCloned, true); $xmlElement->appendChild($elementImported); } } $versionsInfoDoc->appendChild($xmlElement); kFile::setFileContent($versionsInfoFilePath, $versionsInfoDoc->saveXML()); // FileSync OK - created a temp file on DC's disk } $metadataNodes = $versionsInfoDoc->getElementsByTagName("MetaData"); $count = 0; $versionsInfo = array(); for ($i = $metadataNodes->length - 1; $i >= 0; $i--) { $metadataNode = $metadataNodes->item($i); $node = kXml::getFirstElement($metadataNode, "ShowVersion"); $showVersion = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "PuserId"); $puserId = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "ScreenName"); $screenName = $node ? $node->nodeValue : ""; $node = kXml::getFirstElement($metadataNode, "UpdatedAt"); $updatedAt = $node ? $node->nodeValue : ""; $versionsInfo[] = array("version" => $showVersion, "puserId" => $puserId, "screenName" => $screenName, "updatedAt" => $updatedAt); $count++; if ($count >= $numberOfVersions) { break; } } $this->addMsg("show_versions", $versionsInfo); }
private function transformMetadata($metadataProfileId, $xmlData) { $result = null; $metadataProfile = MetadataProfilePeer::retrieveByPK($metadataProfileId); if (!$metadataProfile) { KalturaLog::err('Cannot find metadata profile id [' . $metadataProfileId . ']'); return null; } $metadataXsltKey = $metadataProfile->getSyncKey(MetadataProfile::FILE_SYNC_METADATA_XSLT); if (!kFileSyncUtils::file_exists($metadataXsltKey, true)) { return null; } $xsltString = kFileSyncUtils::file_get_contents($metadataXsltKey, true, false); if (!$xsltString) { return null; } $xsltParams = array(XsltParameterName::KALTURA_CURRENT_TIMESTAMP => time()); $xsltErrors = array(); $xmlDataTransformed = kXml::transformXmlUsingXslt($xmlData, $xsltString, $xsltParams, $xsltErrors); if (!empty($xsltErrors)) { throw new KalturaAPIException(MetadataErrors::XSLT_VALIDATION_ERROR, implode(',', $xsltErrors)); } if ($xmlDataTransformed) { return $xmlDataTransformed; } KalturaLog::err('Failed XML [$xmlData] transformation for metadata with XSL [$xsltString]'); return null; }
/** * batch addConvertProfileJobAction creates a new convert profile job * * @action addConvertProfileJob * @param string $entryId the id of the entry to be reconverted * @return KalturaBatchJobResponse */ function addConvertProfileJobAction($entryId) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { throw new KalturaAPIException(APIErrors::INVALID_ENTRY_ID, 'entry', $entryId); } $flavorAsset = assetPeer::retrieveOriginalByEntryId($entryId); if (!$flavorAsset) { throw new KalturaAPIException(KalturaErrors::ORIGINAL_FLAVOR_ASSET_IS_MISSING); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (!kFileSyncUtils::file_exists($syncKey, true)) { throw new KalturaAPIException(APIErrors::NO_FILES_RECEIVED); } $inputFileSyncLocalPath = kFileSyncUtils::getLocalFilePathForKey($syncKey); $wamsAssetId = kFileSyncUtils::getWamsAssetIdForKey($syncKey); $batchJob = kJobsManager::addConvertProfileJob(null, $entry, $flavorAsset->getId(), $inputFileSyncLocalPath, $wamsAssetId); return $this->getStatusAction($batchJob->getId(), KalturaBatchJobType::CONVERT_PROFILE); }
public static function copyEntry(entry $entry, Partner $toPartner = null, $dontCopyUsers = false) { KalturaLog::log("copyEntry - Copying entry [" . $entry->getId() . "] to partner [" . $toPartner->getId() . "]"); $newEntry = $entry->copy(); $newEntry->setIntId(null); if ($toPartner instanceof Partner) { $newEntry->setPartnerId($toPartner->getId()); $newEntry->setSubpId($toPartner->getId() * 100); $newEntry->setAccessControlId($toPartner->getDefaultAccessControlId()); $flavorParamsStr = $entry->getFlavorParamsIds(); $flavorParams = explode(',', $flavorParamsStr); $newFlavorParams = array(); foreach ($flavorParams as $flavorParamsId) { $newFlavorParamsId = kObjectCopyHandler::getMappedId('flavorParams', $flavorParamsId); if (is_null($newFlavorParamsId)) { $newFlavorParamsId = $flavorParamsId; } $newFlavorParams[] = $newFlavorParamsId; } $newEntry->setFlavorParamsIds(implode(',', $newFlavorParams)); } $newKuser = null; if (!$dontCopyUsers) { // copy the kuser (if the same puser id exists its kuser will be used) kuserPeer::setUseCriteriaFilter(false); $kuser = $entry->getKuser(); $newKuser = kuserPeer::createKuserForPartner($newEntry->getPartnerId(), $kuser->getPuserId()); $newEntry->setKuserId($newKuser->getId()); kuserPeer::setUseCriteriaFilter(true); } // copy the kshow kshowPeer::setUseCriteriaFilter(false); $kshow = $entry->getKshow(); if ($kshow) { $newKshow = $kshow->copy(); $newKshow->setIntId(null); $newKshow->setPartnerId($toPartner->getId()); $newKshow->setSubpId($toPartner->getId() * 100); if ($newKuser) { $newKshow->setProducerId($newKuser->getId()); } $newKshow->save(); $newEntry->setKshowId($newKshow->getId()); } kshowPeer::setUseCriteriaFilter(true); // reset the statistics myEntryUtils::resetEntryStatistics($newEntry); // set the new partner id into the default category criteria filter $defaultCategoryFilter = categoryPeer::getCriteriaFilter()->getFilter(); $oldPartnerId = $defaultCategoryFilter->get(categoryPeer::PARTNER_ID); $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID); $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $newEntry->getPartnerId()); // save the entry $newEntry->save(); // restore the original partner id in the default category criteria filter $defaultCategoryFilter->remove(categoryPeer::PARTNER_ID); $defaultCategoryFilter->addAnd(categoryPeer::PARTNER_ID, $oldPartnerId); KalturaLog::log("copyEntry - New entry [" . $newEntry->getId() . "] was created"); // for any type that does not require assets: $shouldCopyDataForNonClip = $entry->getType() != entryType::MEDIA_CLIP; $shouldCopyDataForClip = false; // only images get their data copied if ($entry->getType() == entryType::MEDIA_CLIP) { if ($entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_VIDEO && $entry->getMediaType() != entry::ENTRY_MEDIA_TYPE_AUDIO) { $shouldCopyDataForClip = true; } } if ($shouldCopyDataForNonClip || $shouldCopyDataForClip) { // copy the data $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); // replaced__getDataPath KalturaLog::log("copyEntriesByType - copying entry data [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } $ismFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); if (kFileSyncUtils::fileSync_exists($ismFrom)) { $ismTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM); KalturaLog::log("copying entry ism [" . $ismFrom . "] to [" . $ismTo . "]"); kFileSyncUtils::softCopy($ismFrom, $ismTo); } $ismcFrom = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); if (kFileSyncUtils::fileSync_exists($ismcFrom)) { $ismcTo = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC); KalturaLog::log("copying entry ism [" . $ismcFrom . "] to [" . $ismcTo . "]"); kFileSyncUtils::softCopy($ismcFrom, $ismcTo); } $from = $entry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath $considerCopyThumb = true; // if entry is image - data is thumbnail, and it was copied if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $considerCopyThumb = false; } // if entry is not clip, and there is no file in both DCs - nothing to copy if ($entry->getType() != entryType::MEDIA_CLIP && !kFileSyncUtils::file_exists($from, true)) { $considerCopyThumb = false; } if ($considerCopyThumb) { $skipThumb = false; // don't attempt to copy a thumbnail for images - it's the same as the data which was just created if ($entry->getMediaType() == entry::ENTRY_MEDIA_TYPE_AUDIO) { // check if audio entry has real thumb, if not - don't copy thumb. $originalFileSync = kFileSyncUtils::getOriginFileSyncForKey($from, false); if (!$originalFileSync) { $skipThumb = true; } } if (!$skipThumb) { $to = $newEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_THUMB); // replaced__getThumbnailPath KalturaLog::log("copyEntriesByType - copying entry thumbnail [" . $from . "] to [" . $to . "]"); kFileSyncUtils::softCopy($from, $to); } } // added by Tan-Tan 12/01/2010 to support falvors copy $sourceFlavorAssets = flavorAssetPeer::retrieveByEntryId($entry->getId()); foreach ($sourceFlavorAssets as $sourceFlavorAsset) { $sourceFlavorAsset->copyToEntry($newEntry->getId(), $newEntry->getPartnerId()); } }
$partner_id = @$argv[1]; $partner = PartnerPeer::retrieveByPK($partner_id); if (!$partner) { die('no such partner.' . PHP_EOL); } $c = new Criteria(); $c->add(assetPeer::PARTNER_ID, $partner_id); $c->add(assetPeer::IS_ORIGINAL, true); $c->add(assetPeer::STATUS, flavorAsset::FLAVOR_ASSET_STATUS_READY); $con = myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2); $flavorAssets = assetPeer::doSelect($c, $con); $changedEntriesCounter = 0; foreach ($flavorAssets as $flavorAsset) { $flavorSyncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); try { if (!kFileSyncUtils::file_exists($flavorSyncKey, true)) { echo 'changed source flavor asset to status deleted for entry: ' . $flavorAsset->getEntryId() . ' and for flavor id ' . $flavorAsset->getId() . PHP_EOL; // set the status of the flavor asset to deleted and set deleted time (taken from flavorAssetService) $entry = $flavorAsset->getEntry(); if ($entry) { $entry->removeFlavorParamsId($flavorAsset->getFlavorParamsId()); $entry->save(); } $flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_DELETED); $flavorAsset->setDeletedAt(time()); $flavorAsset->save(); $changedEntriesCounter++; } } catch (Exception $e) { } }
/** * Will forward to the regular swf player according to the widget_id */ public function execute() { // where file is {entryId/flavorId}.{ism,ismc,ismv} $objectId = $type = null; $objectIdStr = $this->getRequestParameter("objectId"); list($objectId, $type) = @explode(".", $objectIdStr); if (!$type || !$objectId) { die; } $ks = $this->getRequestParameter("ks"); $referrer = base64_decode($this->getRequestParameter("referrer")); if (!is_string($referrer)) { // base64_decode can return binary data $referrer = ''; } if ($type == "ism" || $type == "ismc") { // backward compatiblity - to be removed once ismc is created with pure objectId.ext instead of entryId_flavorId_version.ext if (strlen($objectId) != 10) { $version = substr($objectId, 13); $objectId = substr($objectId, 0, 10); } else { $version = null; } $entry = entryPeer::retrieveByPK($objectId); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } $syncKey = $entry->getSyncKey($type == "ism" ? entry::FILE_SYNC_ENTRY_SUB_TYPE_ISM : entry::FILE_SYNC_ENTRY_SUB_TYPE_ISMC, $version); } else { if ($type == "ismv") { // backward compatiblity - to be removed once ismc is created with pure objectId.ext instead of entryId_flavorId_version.ext if (strlen($objectId) != 10) { $version = substr($objectId, 22); $objectId = substr($objectId, 11, 10); } else { $version = null; } $flavorAsset = flavorAssetPeer::retrieveById($objectId); if (is_null($flavorAsset)) { KExternalErrors::dieError(KExternalErrors::FLAVOR_NOT_FOUND); } $entry = entryPeer::retrieveByPK($flavorAsset->getEntryId()); if (is_null($entry)) { KExternalErrors::dieError(KExternalErrors::ENTRY_NOT_FOUND); } $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET, $version); } else { die; } } if (!kFileSyncUtils::file_exists($syncKey, false)) { list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false); if (is_null($fileSync)) { KalturaLog::log("Error - no FileSync for type [{$type}] objectId [{$objectId}]"); KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } $remoteUrl = kDataCenterMgr::getRedirectExternalUrl($fileSync); kFile::dumpUrl($remoteUrl); } $path = kFileSyncUtils::getReadyLocalFilePathForKey($syncKey); kFile::dumpFile($path); }
public function setMetadata($kshow, $content, $override_existing = true, $total_duration = null, $specific_version = null) { if ($this->getMediaType() != entry::ENTRY_MEDIA_TYPE_SHOW) { return null; } // TODO - better to call this with slight modifications //myMetadataUtils::setMetadata ($content, $kshow, $this , $override_existing ); if ($specific_version == null) { // increment the counter of the file $this->setData(parent::getData()); } // check that the file of the desired version really exists // $content_dir = myContentStorage::getFSContentRootPath(); // $file_name = $content_dir . $this->getDataPath( $specific_version ); // replaced__getDataPath $sync_key = $this->getSyncKey(self::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $specific_version); if ($override_existing || !kFileSyncUtils::file_exists($sync_key, false)) { $duration = $total_duration ? $total_duration : myMetadataUtils::getDuration($content); $this->setLengthInMsecs($duration * 1000); $total_duration = null; $editor_type = null; $version = myContentStorage::getVersion(kFileSyncUtils::getReadyLocalFilePathForKey($sync_key)); $fixed_content = myFlvStreamer::fixMetadata($content, $version, $total_duration, $editor_type); $this->setModifiedAt(time()); // update the modified_at date $this->save(); $sync_key = $this->getSyncKey(self::FILE_SYNC_ENTRY_SUB_TYPE_DATA, $version); // TODO: here we assume we are UPDATING an exising version of the file - make sure all the following functions are tolerant. kFileSyncUtils::file_put_contents($sync_key, $fixed_content, false); // replaced__setFileContent // update the roughcut_entry table if ($kshow != null) { $kshow_id = $kshow->getId(); } else { $kshow_id = $this->getKshowId(); } $all_entries_for_roughcut = myMetadataUtils::getAllEntries($fixed_content); roughcutEntry::updateRoughcut($this->getId(), $version, $kshow_id, $all_entries_for_roughcut); return; } else { // no need to save changes - why increment the count if failed ?? return -1; } }
/** * @param BatchJob $dbBatchJob * @param kImportJobData $data * @param BatchJob $twinJob * @return BatchJob */ public static function handleImportFinished(BatchJob $dbBatchJob, kImportJobData $data, BatchJob $twinJob = null) { KalturaLog::debug("Import finished, with file: " . $data->getDestFileLocalPath()); if ($dbBatchJob->getAbort()) { return $dbBatchJob; } if (!$twinJob) { if (!file_exists($data->getDestFileLocalPath())) { throw new APIException(APIErrors::INVALID_FILE_NAME, $data->getDestFileLocalPath()); } } // get entry $entryId = $dbBatchJob->getEntryId(); $dbEntry = entryPeer::retrieveByPKNoFilter($entryId); // IMAGE media entries if ($dbEntry->getType() == entryType::MEDIA_CLIP && $dbEntry->getMediaType() == entry::ENTRY_MEDIA_TYPE_IMAGE) { $syncKey = $dbEntry->getSyncKey(entry::FILE_SYNC_ENTRY_SUB_TYPE_DATA); try { kFileSyncUtils::moveFromFile($data->getDestFileLocalPath(), $syncKey, true, false, $data->getCacheOnly()); } catch (Exception $e) { if ($dbEntry->getStatus() == entryStatus::NO_CONTENT) { $dbEntry->setStatus(entryStatus::ERROR_CONVERTING); $dbEntry->save(); } throw $e; } $dbEntry->setStatus(entryStatus::READY); $dbEntry->save(); return $dbBatchJob; } $flavorAsset = null; if ($data->getFlavorAssetId()) { $flavorAsset = assetPeer::retrieveById($data->getFlavorAssetId()); } $isNewFlavor = false; if (!$flavorAsset) { $msg = null; $flavorAsset = kFlowHelper::createOriginalFlavorAsset($dbBatchJob->getPartnerId(), $dbBatchJob->getEntryId(), $msg); if (!$flavorAsset) { KalturaLog::err("Flavor asset not created for entry [" . $dbBatchJob->getEntryId() . "]"); kBatchManager::updateEntry($dbBatchJob->getEntryId(), entryStatus::ERROR_CONVERTING); $dbBatchJob->setMessage($msg); $dbBatchJob->setDescription($dbBatchJob->getDescription() . "\n" . $msg); return $dbBatchJob; } $isNewFlavor = true; } $isNewContent = true; $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if (kFileSyncUtils::fileSync_exists($syncKey)) { $isNewContent = false; } if ($twinJob) { $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); // copy file sync $twinData = $twinJob->getData(); if ($twinData instanceof kImportJobData) { $twinFlavorAsset = assetPeer::retrieveById($twinData->getFlavorAssetId()); if ($twinFlavorAsset) { $twinSyncKey = $twinFlavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); if ($twinSyncKey && kFileSyncUtils::file_exists($twinSyncKey)) { kFileSyncUtils::softCopy($twinSyncKey, $syncKey); } } } } else { $ext = pathinfo($data->getDestFileLocalPath(), PATHINFO_EXTENSION); KalturaLog::info("Imported file extension: {$ext}"); if (!$flavorAsset->getVersion()) { $flavorAsset->incrementVersion(); } $flavorAsset->setFileExt($ext); $flavorAsset->save(); $syncKey = $flavorAsset->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET); kFileSyncUtils::moveFromFile($data->getDestFileLocalPath(), $syncKey, true, false, $data->getCacheOnly()); } // set the path in the job data $localFilePath = kFileSyncUtils::getLocalFilePathForKey($syncKey); $data->setDestFileLocalPath($localFilePath); $data->setFlavorAssetId($flavorAsset->getId()); $dbBatchJob->setData($data); $dbBatchJob->save(); if ($isNewContent || $dbEntry->getStatus() == entryStatus::IMPORT) { // check if status == import for importing file of type url (filesync exists, and we want to raise event for conversion profile to start) kEventsManager::raiseEvent(new kObjectAddedEvent($flavorAsset, $dbBatchJob)); } if (!$isNewFlavor && $flavorAsset->getIsOriginal()) { $entryFlavors = assetPeer::retrieveFlavorsByEntryId($flavorAsset->getEntryId()); foreach ($entryFlavors as $entryFlavor) { /* @var $entryFlavor flavorAsset */ if ($entryFlavor->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_WAIT_FOR_CONVERT && $entryFlavor->getFlavorParamsId()) { kBusinessPreConvertDL::decideAddEntryFlavor($dbBatchJob, $flavorAsset->getEntryId(), $entryFlavor->getFlavorParamsId()); } } $entryThumbnails = assetPeer::retrieveThumbnailsByEntryId($flavorAsset->getEntryId()); foreach ($entryThumbnails as $entryThumbnail) { /* @var $entryThumbnail thumbAsset */ if ($entryThumbnail->getStatus() != asset::ASSET_STATUS_WAIT_FOR_CONVERT || !$entryThumbnail->getFlavorParamsId()) { continue; } $thumbParamsOutput = assetParamsOutputPeer::retrieveByAssetId($entryThumbnail->getId()); /* @var $thumbParamsOutput thumbParamsOutput */ if ($thumbParamsOutput->getSourceParamsId() != $flavorAsset->getFlavorParamsId()) { continue; } $srcSyncKey = $flavorAsset->getSyncKey(asset::FILE_SYNC_ASSET_SUB_TYPE_ASSET); $srcAssetType = $flavorAsset->getType(); kJobsManager::addCapturaThumbJob($entryThumbnail->getPartnerId(), $entryThumbnail->getEntryId(), $entryThumbnail->getId(), $srcSyncKey, $flavorAsset->getId(), $srcAssetType, $thumbParamsOutput); } } return $dbBatchJob; }