public function run($jobs = null) { KalturaLog::info("Validating live media servers"); $filter = new KalturaLiveStreamEntryFilter(); $filter->isLive = KalturaNullableBoolean::TRUE_VALUE; $filter->orderBy = KalturaLiveStreamEntryOrderBy::CREATED_AT_ASC; $filter->moderationStatusIn = KalturaEntryModerationStatus::PENDING_MODERATION . ',' . KalturaEntryModerationStatus::APPROVED . ',' . KalturaEntryModerationStatus::REJECTED . ',' . KalturaEntryModerationStatus::FLAGGED_FOR_REVIEW . ',' . KalturaEntryModerationStatus::AUTO_APPROVED; $pager = new KalturaFilterPager(); $pager->pageSize = 500; $pager->pageIndex = 1; $entries = self::$kClient->liveStream->listAction($filter, $pager); while (count($entries->objects)) { foreach ($entries->objects as $entry) { try { /* @var $entry KalturaLiveEntry */ self::impersonate($entry->partnerId); self::$kClient->liveStream->validateRegisteredMediaServers($entry->id); self::unimpersonate(); $filter->createdAtGreaterThanOrEqual = $entry->createdAt; } catch (KalturaException $e) { self::unimpersonate(); KalturaLog::err("Caught exception with message [" . $e->getMessage() . "]"); } } $pager->pageIndex++; $entries = self::$kClient->liveStream->listAction($filter, $pager); } }
/** * * Starts the bulk upload * @param KalturaBatchJob $job */ private function startBulkUpload(KalturaBatchJob $job) { KalturaLog::info("Start bulk upload ({$job->id})"); //Gets the right Engine instance $engine = KBulkUploadEngine::getEngine($job->jobSubType, $job); if (is_null($engine)) { throw new KalturaException("Unable to find bulk upload engine", KalturaBatchJobAppErrors::ENGINE_NOT_FOUND); } $job = $this->updateJob($job, 'Parsing file [' . $engine->getName() . ']', KalturaBatchJobStatus::QUEUED, $engine->getData()); $engine->setJob($job); $engine->setData($job->data); $engine->handleBulkUpload(); $job = $engine->getJob(); $data = $engine->getData(); $countObjects = $this->countCreatedObjects($job->id, $job->data->bulkUploadObjectType); $countHandledObjects = $countObjects[0]; $countErrorObjects = $countObjects[1]; if (!$countHandledObjects && !$engine->shouldRetry() && $countErrorObjects) { throw new KalturaBatchException("None of the uploaded items were processed succsessfuly", KalturaBatchJobAppErrors::BULK_NO_ENTRIES_HANDLED, $engine->getData()); } if ($engine->shouldRetry()) { self::$kClient->batch->resetJobExecutionAttempts($job->id, $this->getExclusiveLockKey(), $job->jobType); return $this->closeJob($job, null, null, "Retrying: " . $countHandledObjects . " " . $engine->getObjectTypeTitle() . " objects were handled untill now", KalturaBatchJobStatus::RETRY); } return $this->closeJob($job, null, null, 'Waiting for objects closure', KalturaBatchJobStatus::ALMOST_DONE, $data); }
public function run($jobs = null) { if (KBatchBase::$taskConfig->isInitOnly()) { return $this->init(); } if (is_null($jobs)) { $jobs = KBatchBase::$kClient->batch->getExclusiveAlmostDone($this->getExclusiveLockKey(), KBatchBase::$taskConfig->maximumExecutionTime, $this->getMaxJobsEachRun(), $this->getFilter(), static::getType()); } KalturaLog::info(count($jobs) . " jobs to close"); if (!count($jobs) > 0) { KalturaLog::info("Queue size: 0 sent to scheduler"); $this->saveSchedulerQueue(static::getType()); return null; } foreach ($jobs as &$job) { try { self::setCurrentJob($job); $job = $this->exec($job); } catch (KalturaException $kex) { KBatchBase::unimpersonate(); $job = $this->closeJob($job, KalturaBatchJobErrorTypes::KALTURA_API, $kex->getCode(), "Error: " . $kex->getMessage(), KalturaBatchJobStatus::FAILED); } catch (KalturaClientException $kcex) { KBatchBase::unimpersonate(); $job = $this->closeJob($job, KalturaBatchJobErrorTypes::KALTURA_CLIENT, $kcex->getCode(), "Error: " . $kcex->getMessage(), KalturaBatchJobStatus::RETRY); } catch (Exception $ex) { KBatchBase::unimpersonate(); $job = $this->closeJob($job, KalturaBatchJobErrorTypes::RUNTIME, $ex->getCode(), "Error: " . $ex->getMessage(), KalturaBatchJobStatus::FAILED); } self::unsetCurrentJob(); } return $jobs; }
protected function deleteFilesPHP($searchPath, $minutesOld, $simulateOnly) { $secondsOld = $minutesOld * 60; $files = glob($searchPath); KalturaLog::info("Found [" . count($files) . "] to scan"); $now = time(); KalturaLog::info("Deleting files that are " . $secondsOld . " seconds old (modified before " . date('c', $now - $secondsOld) . ")"); $deletedCount = 0; foreach ($files as $file) { $filemtime = filemtime($file); if ($filemtime > $now - $secondsOld) { continue; } if ($simulateOnly) { KalturaLog::info("Simulating: Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); continue; } KalturaLog::info("Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); $res = @unlink($file); if (!$res) { KalturaLog::err("Error: problem while deleting [{$file}]"); continue; } $deletedCount++; } }
protected function parseCreatedFiles() { $xmlPath = $this->outDir . DIRECTORY_SEPARATOR . $this->destFileName . '.ism'; KalturaLog::info("Parse created files from ism[{$xmlPath}]"); // in case of wma if (!file_exists($xmlPath)) { KalturaLog::info("ism file[{$xmlPath}] doesn't exist"); $wmaPath = $this->outDir . DIRECTORY_SEPARATOR . $this->destFileName . '.wma'; if (file_exists($wmaPath)) { KalturaLog::info("wma file[{$wmaPath}] found"); $this->outFilesPath[0] = $wmaPath; } return; } $xml = file_get_contents($xmlPath); $xml = mb_convert_encoding($xml, 'ASCII', 'UTF-16'); KalturaLog::debug("ism content:\n{$xml}"); $arr = null; if (preg_match('/(<smil[\\s\\w\\W]+<\\/smil>)/', $xml, $arr)) { $xml = $arr[1]; } file_put_contents($xmlPath, $xml); //echo $xml; $doc = new DOMDocument(); $doc->loadXML($xml); $videoEntities = $doc->getElementsByTagName('video'); foreach ($videoEntities as $videoEntity) { $src = $this->outDir . DIRECTORY_SEPARATOR . $videoEntity->getAttribute("src"); $bitrate = $videoEntity->getAttribute("systemBitrate") / 1000; KalturaLog::info("Media found in ism bitrate[{$bitrate}] source[{$src}]"); $this->outFilesPath[$bitrate] = $src; } }
public function doFromObject($dbObject, KalturaDetachedResponseProfile $responseProfile = null) { parent::doFromObject($dbObject, $responseProfile); /* @var $dbObject kEmailNotificationCategoryRecipientProvider */ $categoryIdFieldType = get_class($dbObject->getCategoryId()); KalturaLog::info("Retrieving API object for categoryId fild of type [{$categoryIdFieldType}]"); switch ($categoryIdFieldType) { case 'kObjectIdField': $this->categoryId = new KalturaObjectIdField(); break; case 'kEvalStringField': $this->categoryId = new KalturaEvalStringField(); break; case 'kStringValue': $this->categoryId = new KalturaStringValue(); break; default: $this->categoryId = KalturaPluginManager::loadObject('KalturaStringValue', $categoryIdFieldType); break; } if ($this->categoryId) { $this->categoryId->fromObject($dbObject->getCategoryId()); } if ($dbObject->getCategoryUserFilter()) { $this->categoryUserFilter = new KalturaCategoryUserProviderFilter(); $this->categoryUserFilter->fromObject($dbObject->getCategoryUserFilter()); } }
private function call($method, $args = array()) { KalturaLog::info("Call [{$method}] args [" . print_r($args, true) . "]"); $result = $this->api->call($method, $args); KalturaLog::info("Result [" . print_r($result, true) . "]"); return $result; }
public function configure(KalturaConvartableJobData $data, KalturaBatchJob $job) { $this->data = $data; $this->job = $job; $this->setMediaInfoEnabled(KBatchBase::$taskConfig->params->mediaInfoEnabled); KalturaLog::info("taskConfig-->" . print_r(KBatchBase::$taskConfig, true) . "\ndata->" . print_r($data, true)); }
protected function getFieldValue(kScope $scope = null) { if (!$scope) { KalturaLog::info('No scope specified'); return null; } if (!$scope instanceof kEventScope) { KalturaLog::info('Scope must be of type kEventScope, [' . get_class($scope) . '] given'); return; } if (!$scope->getEvent()) { KalturaLog::info('$scope->getEvent() must return a value'); return; } if ($scope->getEvent() && !$scope->getEvent() instanceof IKalturaObjectRelatedEvent) { KalturaLog::info('Scope event must realize interface IKalturaObjectRelatedEvent'); return; } if ($scope->getEvent() && !$scope->getEvent()->getObject()) { KalturaLog::info('Object not found on scope event'); return; } if (!method_exists($scope->getEvent()->getObject(), 'getId')) { KalturaLog::info('Getter method for object id not found'); return; } return $scope->getEvent()->getObject()->getId(); }
/** * Will return the first virus scan profile of the entry's partner, that defines an entry filter suitable for the given entry. * @param int $entryId * @return VirusScanProfile the suitable profile object, or null if none found */ public static function getSuitableProfile($entryId) { $entry = entryPeer::retrieveByPK($entryId); if (!$entry) { KalturaLog::err('Cannot find entry with id [' . $entryId . ']'); return null; } if ($entry->getSource() == entry::ENTRY_MEDIA_SOURCE_WEBCAM) { return null; } $cProfile = new Criteria(); $cProfile->addAnd(VirusScanProfilePeer::PARTNER_ID, $entry->getPartnerId()); $cProfile->addAnd(VirusScanProfilePeer::STATUS, VirusScanProfileStatus::ENABLED, Criteria::EQUAL); $profiles = VirusScanProfilePeer::doSelect($cProfile); if (!$profiles) { KalturaLog::info('No virus scan profiles found for partner [' . $entry->getPartnerId() . ']'); return null; } foreach ($profiles as $profile) { $virusEntryFilter = $profile->getEntryFilterObject(); if ($virusEntryFilter->matches($entry)) { KalturaLog::info('Returning profile with id [' . $profile->getId() . ']'); return $profile; } } return null; }
public static function dumpApiRequest($host, $onlyIfAvailable = false) { if ($onlyIfAvailable) { //validate that the other DC is available before dumping the request if (kConf::hasParam('disable_dump_api_request') && kConf::get('disable_dump_api_request')) { KalturaLog::info('dumpApiRequest is disabled'); return; } } if (kCurrentContext::$multiRequest_index > 1) { KExternalErrors::dieError(KExternalErrors::MULTIREQUEST_PROXY_FAILED); } self::closeDbConnections(); // prevent loop back of the proxied request by detecting the "X-Kaltura-Proxy header if (isset($_SERVER["HTTP_X_KALTURA_PROXY"])) { KExternalErrors::dieError(KExternalErrors::PROXY_LOOPBACK); } $get_params = $post_params = array(); // pass uploaded files by adding them as post data with curl @ prefix // signifying a file. the $_FILES[xxx][tmp_name] points to the location // of the uploaded file. // we preserve the original file name by passing the extra ;filename=$_FILES[xxx][name] foreach ($_FILES as $key => $value) { $post_params[$key] = "@" . $value['tmp_name'] . ";filename=" . $value['name']; if (!is_uploaded_file($value['tmp_name'])) { KExternalErrors::dieError(KExternalErrors::FILE_NOT_FOUND); } } foreach ($_POST as $key => $value) { $post_params[$key] = $value; } $url = $_SERVER['REQUEST_URI']; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' && kConf::hasParam('https_param_salt')) { $post_params['apiProtocol'] = 'https_' . kConf::get('https_param_salt'); } $httpHeader = array("X-Kaltura-Proxy: dumpApiRequest"); $ipHeader = infraRequestUtils::getSignedIpAddressHeader(); if ($ipHeader) { list($headerName, $headerValue) = $ipHeader; $httpHeader[] = $headerName . ": " . $headerValue; } $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $host . $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader); curl_setopt($ch, CURLOPT_USERAGENT, "curl/7.11.1"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params); // Set callback function for body curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'kFileUtils::read_body'); // Set callback function for headers curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'kFileUtils::read_header'); header("X-Kaltura:dumpApiRequest " . kDataCenterMgr::getCurrentDcId()); // grab URL and pass it to the browser $content = curl_exec($ch); // close curl resource, and free up system resources curl_close($ch); KExternalErrors::dieGracefully(); }
protected function closeStorageExport(KalturaBatchJob $job) { KalturaLog::info("Attempting to close the job"); $storageExportEngine = KExportEngine::getInstance($job->jobSubType, $job->partnerId, $job->data); $closeResult = $storageExportEngine->verifyExportedResource(); $this->closeJob($job, null, null, null, $closeResult ? KalturaBatchJobStatus::FINISHED : KalturaBatchJobStatus::ALMOST_DONE); }
/** * @param KalturaBaseEntry $object */ function processObject($object) { $client = $this->getClient(); $entryId = $object->id; KalturaLog::info('Deleting entry ' . $entryId); $client->baseEntry->delete($entryId); }
/** * @param Partner $fromPartner * @param Partner $toPartner */ protected function copyEventNotificationTemplates(Partner $fromPartner, Partner $toPartner, $permissionRequiredOnly = false) { $fromPartnerId = $fromPartner->getId(); $toPartnerId = $toPartner->getId(); KalturaLog::info("Copy event-notification templates from [{$fromPartnerId}] to [{$toPartnerId}]"); $c = new Criteria(); $c->add(EventNotificationTemplatePeer::PARTNER_ID, $fromPartnerId); $systemNameCriteria = new Criteria(); $systemNameCriteria->add(EventNotificationTemplatePeer::PARTNER_ID, $toPartnerId); $systemNameCriteria->add(EventNotificationTemplatePeer::STATUS, EventNotificationTemplateStatus::ACTIVE); $eventNotificationTemplates = EventNotificationTemplatePeer::doSelect($c); foreach ($eventNotificationTemplates as $eventNotificationTemplate) { /* @var $eventNotificationTemplate EventNotificationTemplate */ if ($permissionRequiredOnly && !count($eventNotificationTemplate->getRequiredCopyTemplatePermissions())) { continue; } if (!myPartnerUtils::isPartnerPermittedForCopy($toPartner, $eventNotificationTemplate->getRequiredCopyTemplatePermissions())) { continue; } if ($eventNotificationTemplate->getSystemName()) { $c = clone $systemNameCriteria; $c->add(EventNotificationTemplatePeer::SYSTEM_NAME, $eventNotificationTemplate->getSystemName()); if (EventNotificationTemplatePeer::doCount($c)) { continue; } } $newEventNotificationTemplate = $eventNotificationTemplate->copy(); $newEventNotificationTemplate->setPartnerId($toPartnerId); $newEventNotificationTemplate->save(); } }
/** * Action goes over all tags with instanceCount==0 and checks whether they need to be removed from the DB. Returns number of removed tags. * @action deletePending * @return int */ public function deletePendingAction() { TagPeer::setUseCriteriaFilter(false); $c = KalturaCriteria::create(TagPeer::OM_CLASS); $filter = new TagFilter(); $filter->set('_eq_instance_count', 0); $filter->attachToCriteria($c); $c->applyFilters(); $count = $c->getRecordsCount(); if (!$count) { KalturaLog::info('No tags pending for deletion.'); return 0; } $deletedTags = 0; $tagsForDelete = TagPeer::doSelect($c); TagPeer::setUseCriteriaFilter(true); foreach ($tagsForDelete as $tag) { /* @var $tag Tag */ switch ($tag->getObjectType()) { case taggedObjectType::ENTRY: $deletedTags += $this->resolveEntryTag($tag); break; case taggedObjectType::CATEGORY: $deletedTags += $this->resolveCategoryTag($tag); break; } } return $deletedTags; }
protected function handleResults(array $results, array $items) { //Added to support cases where the resource is entry resource $conversionProfileId = null; try { KBatchBase::impersonate($this->xmlBulkUploadEngine->getCurrentPartnerId()); $entry = KBatchBase::$kClient->baseEntry->get($this->entryId); KBatchBase::unimpersonate(); if ($entry && $entry->conversionProfileId) { $conversionProfileId = $entry->conversionProfileId; } } catch (Exception $ex) { KBatchBase::unimpersonate(); KalturaLog::info("Entry ID [" . $this->entryId . "] not found, continuing with no conversion profile"); } foreach ($results as $index => $cuePoint) { if ($cuePoint instanceof KalturaThumbCuePoint) { if (!isset($items[$index]->slide) || empty($items[$index]->slide)) { continue; } $timedThumbResource = $this->xmlBulkUploadEngine->getResource($items[$index]->slide, $conversionProfileId); $thumbAsset = new KalturaTimedThumbAsset(); $thumbAsset->cuePointId = $cuePoint->id; KBatchBase::impersonate($this->xmlBulkUploadEngine->getCurrentPartnerId()); KBatchBase::$kClient->startMultiRequest(); KBatchBase::$kClient->thumbAsset->add($cuePoint->entryId, $thumbAsset); KBatchBase::$kClient->thumbAsset->setContent(KBatchBase::$kClient->getMultiRequestResult()->id, $timedThumbResource); KBatchBase::$kClient->doMultiRequest(); KBatchBase::unimpersonate(); } } return parent::handleResults($results, $items); }
public function callNodeApi($service, $params) { $url = $this->getNodeApiBaseUrl($service, $params); $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params)); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); $responseStr = curl_exec($curl); KalturaLog::info('Raw response from aspera node api: ' . $responseStr); $error = curl_error($curl); if ($error) { throw new kCoreException('Failed to call node api server: ' . $error); } $response = json_decode($responseStr); if (is_null($response)) { // the json response from the node api could be wrapped in an extra '{' and '}', which doesn't decode well in php // small hack to remove it and try decoding again if (strlen($responseStr) > 2) { $responseStr = substr($responseStr, 1); $responseStr = substr($responseStr, 0, strlen($responseStr) - 1); } $response = json_decode($responseStr); } if (is_null($response)) { throw new kCoreException('Aspera node api response could not be decoded'); } return $response; }
public function objectReplaced(BaseObject $object, BaseObject $replacingObject, BatchJob $raisedJob = null) { try { $replacingDrmKey = $this->getDrmKey($replacingObject); if ($replacingDrmKey) { $newKeyId = $replacingDrmKey->getDrmKey(); KalturaLog::info("replacing drm key with: " . $newKeyId); $entryDrmKey = $this->getDrmKey($object); if (!$entryDrmKey) { $entryDrmKey = new DrmKey(); $entryDrmKey->setPartnerId($object->getPartnerId()); $entryDrmKey->setObjectId($object->getId()); $entryDrmKey->setObjectType(DrmKeyObjectType::ENTRY); $entryDrmKey->setProvider(PlayReadyPlugin::getPlayReadyProviderCoreValue()); } $entryDrmKey->setDrmKey($newKeyId); $entryDrmKey->save(); $object->putInCustomData(PlayReadyPlugin::ENTRY_CUSTOM_DATA_PLAY_READY_KEY_ID, $newKeyId); $object->save(); } } catch (Exception $e) { KalturaLog::err("Failed to update drm key for entry " . $object->getId()); } return true; }
protected function createDirDescriber($outDir, $fileName) { $fileList = kFile::dirList($outDir, false); $fileListXml = $this->createImagesListXML($fileList); kFile::setFileContent($outDir . DIRECTORY_SEPARATOR . $fileName, $fileListXml->asXML()); KalturaLog::info('file list xml [' . $outDir . DIRECTORY_SEPARATOR . $fileName . '] created'); }
/** * @param entry $object * @return bool true if should continue to the next consumer */ public function entryCreated(entry $object) { $mediaType = null; if ($object->getType() == entryType::AUTOMATIC) { $mediaType = $object->getMediaType(); if (isset(self::$fileExtensions[$mediaType])) { $object->setType(entryType::DOCUMENT); } elseif (is_null($mediaType) || $mediaType == entry::ENTRY_MEDIA_TYPE_ANY || $mediaType == entry::ENTRY_MEDIA_TYPE_AUTOMATIC) { $this->setDocumentType($object); } } if ($object->getType() != entryType::DOCUMENT) { KalturaLog::info("entry id [" . $object->getId() . "] type [" . $object->getType() . "]"); return true; } if (is_null($mediaType) || $mediaType == entry::ENTRY_MEDIA_TYPE_ANY || $mediaType == entry::ENTRY_MEDIA_TYPE_AUTOMATIC) { $this->setDocumentType($object); } if ($object instanceof DocumentEntry) { KalturaLog::info("entry id [" . $object->getId() . "] already handled"); return true; } if ($object->getConversionProfileId()) { $object->setStatus(entryStatus::PRECONVERT); $object->save(); } return true; }
/** * Add bulk upload job * @param DropFolder $folder * @param DropFolderFile $leadDropFolderFile * @throws Exception */ private function addXMLBulkUploadJob(DropFolder $folder, DropFolderFile $leadDropFolderFile) { /* @var $leadDropFolderFile FeedDropFolderFile */ KalturaLog::info('Adding BulkUpload job'); try { $coreBulkUploadType = BulkUploadXmlPlugin::getBulkUploadTypeCoreValue(BulkUploadXmlType::XML); $objectId = $leadDropFolderFile->getId(); $objectType = DropFolderXmlBulkUploadPlugin::getBatchJobObjectTypeCoreValue(DropFolderBatchJobObjectType::DROP_FOLDER_FILE); $partner = PartnerPeer::retrieveByPK($folder->getPartnerId()); $data = KalturaPluginManager::loadObject('kBulkUploadJobData', $coreBulkUploadType); /* @var $data kBulkUploadJobData */ $data->setUploadedBy(kDropFolderXmlEventsConsumer::UPLOADED_BY); KalturaLog::info("Feed XML path: " . $leadDropFolderFile->getFeedXmlPath()); $data->setFilePath($leadDropFolderFile->getFeedXmlPath()); $data->setFileName(basename($data->getFilePath()) . '.xml'); $objectData = new kBulkUploadEntryData(); KalturaLog::info('Conversion profile id: ' . $folder->getConversionProfileId()); $objectData->setConversionProfileId($folder->getConversionProfileId()); $data->setObjectData($objectData); $job = kJobsManager::addBulkUploadJob($partner, $data, $coreBulkUploadType, $objectId, $objectType); $this->setFileToProcessing($leadDropFolderFile); return $job; } catch (Exception $e) { KalturaLog::err("Error adding BulkUpload job -" . $e->getMessage()); throw new Exception(DropFolderXmlBulkUploadPlugin::ERROR_ADDING_BULK_UPLOAD_MESSAGE, DropFolderXmlBulkUploadPlugin::getErrorCodeCoreValue(DropFolderXmlBulkUploadErrorCode::ERROR_ADDING_BULK_UPLOAD)); } }
public function run($jobs = null) { KalturaLog::info("Directory Cleanup is running"); $path = $this->getAdditionalParams("path"); $pattern = $this->getAdditionalParams("pattern"); $simulateOnly = $this->getAdditionalParams("simulateOnly"); $minutesOld = $this->getAdditionalParams("minutesOld"); $secondsOld = $minutesOld * 60; $path_to_search = $path . $pattern; KalturaLog::debug("Searching [{$path_to_search}]"); $files = glob($path_to_search); KalturaLog::debug("Found [" . count($files) . "] to scan"); $now = time(); KalturaLog::debug("The time now is: " . date('c', $now)); KalturaLog::debug("Deleting files that are " . $secondsOld . " seconds old (modified before " . date('c', $now - $secondsOld) . ")"); $deletedCount = 0; foreach ($files as $file) { $filemtime = filemtime($file); if ($filemtime > $now - $secondsOld) { continue; } if ($simulateOnly) { KalturaLog::debug("Simulating: Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); continue; } KalturaLog::debug("Deleting file [{$file}], it's last modification time was " . date('c', $filemtime)); $res = @unlink($file); if (!$res) { KalturaLog::debug("Error: problem while deleting [{$file}]"); continue; } $deletedCount++; } KalturaLog::debug("Deleted {$deletedCount} files"); }
/** * @return array */ protected function getSecureHdUrl() { $params = array(); if ($this->getSupportClipping()) { $seekStart = $this->params->getSeekFromTime(); $seekEnd = $this->params->getClipTo(); if ($seekStart != -1) { $params['start'] = floor($this->params->getSeekFromTime() / 1000); $this->params->setSeekFromTime(-1); } else { if ($seekEnd) { $params['start'] = 0; } } if ($seekEnd) { $params['end'] = ceil($this->params->getClipTo() / 1000); $this->params->setClipTo(null); } } $flavors = $this->buildHttpFlavorsArray(); $flavors = $this->sortFlavors($flavors); $flavor = AkamaiDeliveryUtils::getHDN2ManifestUrl($flavors, $this->params->getMediaProtocol(), $this->getUrl(), '/master.m3u8', '/i', $params); if (!$flavor) { KalturaLog::info(get_class() . ' failed to find flavor'); return null; } return $flavor; }
public function run() { KalturaLog::info("Directory Cleanup is running"); $path = $this->getAdditionalParams("path"); $pattern = $this->getAdditionalParams("pattern"); $simulateOnly = $this->getAdditionalParams("simulateOnly"); $minutesOld = $this->getAdditionalParams("minutesOld"); $secondsOld = $minutesOld * 60; $path_to_search = $path . $pattern; KalturaLog::debug("Searching [{$path_to_search}]"); $files = glob($path_to_search); KalturaLog::debug("Found [" . count($files) . "] to scan"); $now = time(); $deletedCount = 0; foreach ($files as $file) { if (filemtime($file) > $now - $secondsOld) { continue; } $deletedCount++; if ($simulateOnly) { KalturaLog::debug("Simulating: Deleting file [{$file}]"); continue; } KalturaLog::debug("Deleting file [{$file}]"); $res = @unlink($file); if (!$res) { KalturaLog::debug("Error: problem while deleting [{$file}]"); } } KalturaLog::debug("Deleted {$deletedCount} files"); }
public function checkIsLive($url) { KalturaLog::info('url to check:' . $url); $parts = parse_url($url); parse_str($parts['query'], $query); $token = $query[$this->getParamName()]; $data = $this->urlExists($url, array($this->getHdsManifestContentType())); if (!$data) { KalturaLog::Info("URL [{$url}] returned no valid data. Exiting."); return false; } KalturaLog::info('Velocix HDS manifest data:' . $data); $dom = new KDOMDocument(); $dom->loadXML($data); $element = $dom->getElementsByTagName('baseURL')->item(0); if (!$element) { KalturaLog::Info("No base url was given"); return false; } $baseUrl = $element->nodeValue; foreach ($dom->getElementsByTagName('media') as $media) { $href = $media->getAttribute('href'); $streamUrl = $baseUrl . $href; $streamUrl .= $token ? '?' . $this->getParamName() . "={$token}" : ''; if ($this->urlExists($streamUrl, array(), '0-0') !== false) { KalturaLog::info('is live:' . $streamUrl); return true; } } return false; }
public function apply(KalturaRelatedFilter $filter, KalturaObject $parentObject) { $filterProperty = $this->filterProperty; $parentProperty = $this->parentProperty; KalturaLog::info("Mapping XPath {$parentProperty} to " . get_class($filter) . "::{$filterProperty}"); if (!$parentObject instanceof KalturaMetadata) { throw new KalturaAPIException(KalturaErrors::INVALID_OBJECT_TYPE, get_class($parentObject)); } if (!property_exists($filter, $filterProperty)) { throw new KalturaAPIException(KalturaErrors::PROPERTY_IS_NOT_DEFINED, $filterProperty, get_class($filter)); } $xml = $parentObject->xml; $doc = new KDOMDocument(); $doc->loadXML($xml); $xpath = new DOMXPath($doc); $metadataElements = $xpath->query($parentProperty); if ($metadataElements->length == 1) { $filter->{$filterProperty} = $metadataElements->item(0)->nodeValue; } elseif ($metadataElements->length > 1) { $values = array(); foreach ($metadataElements as $element) { $values[] = $element->nodeValue; } $filter->{$filterProperty} = implode(',', $values); } elseif (!$this->allowNull) { return false; } return true; }
/** * getAccessAction * input: flavor ids, drmProvider * Get Access Action * @action getAccess * @param string $entryId * @param string $flavorIds * @param string $referrer * @return KalturaDrmLicenseAccessDetails **/ public function getAccessAction($entryId, $flavorIds, $referrer) { $response = new KalturaDrmLicenseAccessDetails(); $response->policy = ""; $response->duration = 0; $response->absolute_duration = 0; $flavorIdsArr = explode(",", $flavorIds); $entry = entryPeer::retrieveByPK($entryId); if (isset($entry)) { try { $drmLU = new DrmLicenseUtils($entry, $referrer); if ($this->validateFlavorAssetssAllowed($drmLU, $flavorIdsArr) == true) { $policyId = $drmLU->getPolicyId(); KalturaLog::info("policy_id is '{$policyId}'"); $dbPolicy = DrmPolicyPeer::retrieveByPK($policyId); if (isset($dbPolicy)) { $expirationDate = DrmLicenseUtils::calculateExpirationDate($dbPolicy, $entry); $response->policy = $dbPolicy->getName(); $response->duration = $expirationDate; $response->absolute_duration = $expirationDate; KalturaLog::info("response is '" . print_r($response, true) . "' "); } else { KalturaLog::err("Could not get DRM policy from DB"); } } } catch (Exception $e) { KalturaLog::err("Could not validate license access, returned with message '" . $e->getMessage() . "'"); } } else { KalturaLog::err("Entry '{$entryId}' not found"); } return $response; }
public function copyAssets(entry $toEntry, ThumbCuePoint $toCuePoint, $adjustedStartTime = null) { $timedThumbAsset = assetPeer::retrieveById($this->getAssetId()); if (!$timedThumbAsset) { KalturaLog::info("Can't retrieve timedThumbAsset with id: {$this->getAssetId()}"); return; } // Offset the startTime according to the duration gap between the live and VOD entries if (!is_null($adjustedStartTime)) { $toCuePoint->setStartTime($adjustedStartTime); } $toCuePoint->save(); // Must save in order to produce an id $timedThumbAsset->setCuePointID($toCuePoint->getId()); // Set the destination cue point's id $timedThumbAsset->setCustomDataObj(); // Write the cached custom data object into the thumb asset // Make a copy of the current thumb asset // copyToEntry will create a filesync softlink to the original filesync $toTimedThumbAsset = $timedThumbAsset->copyToEntry($toEntry->getId(), $toEntry->getPartnerId()); $toCuePoint->setAssetId($toTimedThumbAsset->getId()); $toCuePoint->save(); // Restore the thumb asset's prev. cue point id (for good measures) $timedThumbAsset->setCuePointID($this->getId()); $timedThumbAsset->setCustomDataObj(); // Save the destination entry's thumb asset $toTimedThumbAsset->setCuePointID($toCuePoint->getId()); $toTimedThumbAsset->save(); KalturaLog::log("Saved cue point [{$toCuePoint->getId()}] and timed thumb asset [{$toTimedThumbAsset->getId()}]"); }
public function execute() { $ksStr = $this->getP("ks"); if ($ksStr) { $ksObj = null; try { $ksObj = ks::fromSecureString($ksStr); } catch (Exception $e) { } if ($ksObj) { $partner = PartnerPeer::retrieveByPK($ksObj->partner_id); if (!$partner) { KExternalErrors::dieError(KExternalErrors::PARTNER_NOT_FOUND); } if (!$partner->validateApiAccessControl()) { KExternalErrors::dieError(KExternalErrors::SERVICE_ACCESS_CONTROL_RESTRICTED); } $ksObj->kill(); } KalturaLog::info("Killing session with ks - [{$ksStr}], decoded - [" . base64_decode($ksStr) . "]"); } else { KalturaLog::err('logoutAction called with no KS'); } setcookie('pid', "", 0, "/"); setcookie('subpid', "", 0, "/"); setcookie('kmcks', "", 0, "/"); return sfView::NONE; //redirection to kmc/kmc is done from java script }
/** * @return string */ public function getRawMediaInfo() { $adApi = new ADContentAPI(); $adApi->setUser($this->taskConfig->params->AlldigitalApiUser); $adApi->setPassw($this->taskConfig->params->AlldigitalApiPassword); $adApi->setUrl($this->taskConfig->params->AlldigitalApiUrl); KalturaLog::info("adApi-->" . print_r($adApi, true)); $fileName = $this->job->data->srcFileSyncLocalPath; // Calls from PostConvertJob represent 'output' AD location, // while calls from ExtractMediaJob represnt 'input' AD location if ($this->job->data instanceof KalturaPostConvertJobData) { $location = 'output'; // $folder=str_replace ("-", "/", $this->job->data->customData); // $fileName="$folder/encode/$fileName"; $fileName = $this->job->data->customData; } else { // if($this->job->data instanceof KalturaExtractMediaJobData) $location = 'input'; } $mi = $adApi->MediaInfoToText($location, $fileName, $err); if (!isset($mi)) { KalturaLog::info("AlldigitalApi: mediainfo failure(location:{$location},fileName:{$fileName}) - {$err}"); throw new KOperationEngineException("AlldigitalApi: mediainfo failure(location:{$location},fileName:{$fileName}) - {$err}"); } KalturaLog::info("mediaInfo-->\n" . $mi); return $mi; $mediaInfoSample = "\nGeneral\nComplete name : C:\\xampp\\htdocs\\mvdr6t454m.mov\nFormat : MPEG-4\nFormat profile : QuickTime\nCodec ID : qt \nFile size : 66.6MiB \nDuration : 2mn 25s\nOverall bit rate : 3 851 Kbps\nEncoded date : UTC 2009-08-21 18:45:38\nTagged date : UTC 2009-08-21 18:45:40\nWriting library : Apple QuickTime\ncom.apple.finalcutstudio.media.u : 7ABA86C3-580D-4364-970F-5C8103CC66C9\n\nVideo\nID : 1\nFormat : AVC\nFormat/Info : Advanced Video Codec\nFormat profile : Main@L4.0\nFormat settings, CABAC : No\nFormat settings, ReFrames : 2 frames\nCodec ID : vp6\nCodec ID/Info : Advanced Video Coding\nDuration : 2mn 25s\nBit rate mode : Variable\nBit rate : 721 Kbps\nWidth : 1 280 pixels\nHeight : 720 pixels\nDisplay aspect ratio : 16:9\nFrame rate mode : Constant\nFrame rate : 29.970 fps\nResolution : 24 bits\nColorimetry : 4:2:0\nScan type : Progressive\nBits/(Pixel*Frame) : 0.060\nStream size : 64.4 MiB (97%)\nEncoded date : UTC 2009-08-21 18:45:37\nTagged date : UTC 2009-08-21 18:45:40\n\nAudio\nID : 3\nFormat : AAC\nFormat/Info : Advanced Audio Codec\nFormat version : Version 4\nFormat profile : LC\nFormat settings, SBR : No\nCodec ID : 40\nDuration : 2mn 25s\nBit rate mode : Constant\nBit rate : 124 Kbps\nNominal bit rate : 128 Kbps\nChannel(s) : 2 channels\nChannel positions : L R\nSampling rate : 48.0 KHz\nResolution : 16 bits\nStream size : 2.15 MiB (3%)\nEncoded date : UTC 2009-08-21 18:45:38\nTagged date : UTC 2009-08-21 18:45:40\n\nMenu\nID : 2\nEncoded_Date : UTC 2009-08-21 18:45:37\nTagged_Date : UTC 2009-08-21 18:45:40\nBitRate_Mode : CBR\n\n"; return $mediaInfoSample; }