function tmgmt_smartling_download_file in TMGMT Translator Smartling 8.4
Same name and namespace in other branches
- 8 tmgmt_smartling.module \tmgmt_smartling_download_file()
- 8.2 tmgmt_smartling.module \tmgmt_smartling_download_file()
- 8.3 tmgmt_smartling.module \tmgmt_smartling_download_file()
11 calls to tmgmt_smartling_download_file()
- DownloadFlowTest::testDownloadByTmgmtJob in tests/
src/ Kernel/ DownloadFlowTest.php - Download success full flow: download by TMGMT Job (all TMGMT Job Items).
- DownloadFlowTest::testDownloadByTmgmtJobAndTmgmtJobItem in tests/
src/ Kernel/ DownloadFlowTest.php - Download success full flow: download by TMGMT Job and TMGMT Job Item.
- DownloadFlowTest::testDownloadFailFlow in tests/
src/ Kernel/ DownloadFlowTest.php - Download fail flow.
- DownloadFlowTest::testDownloadFailFlowGetTranslationRequestFailed in tests/
src/ Kernel/ DownloadFlowTest.php - Download fail flow: get translation request failed.
- DownloadFlowTest::testDownloadFailFlowImportFailed in tests/
src/ Kernel/ DownloadFlowTest.php - Download fail flow: import failed.
File
- ./
tmgmt_smartling.module, line 133 - Contains
Code
function tmgmt_smartling_download_file(JobInterface $job, JobItemInterface $passed_job_item = NULL) {
$api_wrapper = $job
->getTranslatorPlugin()
->getApiWrapper($job
->getTranslator()
->getSettings());
$translation_request_manager = Drupal::service('tmgmt_smartling.translation_request_manager');
$logger = \Drupal::logger('tmgmt_smartling');
$translation_request = $translation_request_manager
->getTranslationRequest($job);
if (empty($translation_request)) {
$job
->addMessage('File download failed for job = @job_id: can\'t find related translation request.', [
'@job' => $job
->id(),
], 'error');
$logger
->error('Can\'t retrieve translation request for file @name (job id = @job_id).', [
'@name' => $job
->getTranslatorPlugin()
->getFileName($job),
'@job_id' => $job
->id(),
]);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('File @name (job id = @job_id) wasn\'t downloaded: can\'t find related translation request. See logs for more info.', [
'@name' => $job
->getTranslatorPlugin()
->getFileName($job),
'@job_id' => $job
->id(),
])
->render(),
"type" => "error",
]);
return FALSE;
}
$api_wrapper
->createAuditLogRecord($job, NULL, Drupal::currentUser(), CreateRecordParameters::ACTION_TYPE_DOWNLOAD);
try {
$smartling_api = $api_wrapper
->getApi('file');
$retrieval_type = $job
->getTranslator()
->getSetting('retrieval_type');
$filename = $translation_request["fileUri"];
$download_parameters = new DownloadFileParameters();
$download_parameters
->set('retrievalType', $retrieval_type);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$xml = $smartling_api
->downloadFile($filename, $job
->getRemoteTargetLanguage(), $download_parameters);
} catch (\Exception $e) {
Drupal::logger('tmgmt_smartling')
->error($e
->getMessage());
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('File @name (job id = @job_id) wasn\'t downloaded. Please see logs for more info.', [
'@name' => $filename,
'@job_id' => $job
->id(),
])
->render(),
"type" => "error",
]);
$translation_request_manager
->commitError($job, $translation_request, $e);
return FALSE;
}
$path = $job
->getSetting('scheme') . '://tmgmt_smartling_translations/' . $filename;
$dirname = dirname($path);
if (\Drupal::service('file_system')
->prepareDirectory($dirname, FileSystemInterface::CREATE_DIRECTORY) && ($file = file_save_data($xml, $path, FileSystemInterface::EXISTS_REPLACE))) {
$plugin = \Drupal::service('plugin.manager.tmgmt_file.format')
->createInstance($extension);
if ($plugin) {
// Validate the file on job.
if (!$plugin
->validateImport($file
->getFileUri(), $job)) {
$job
->addMessage('Failed to validate file @file. Import for job @job_id aborted.', [
'@file' => $file
->getFileUri(),
'@job_id' => $job
->id(),
], 'error');
\Drupal::logger('tmgmt_smartling')
->error('Failed to validate file @file. Import for job @job_id aborted.', [
'@file' => $file
->getFileUri(),
'@job_id' => $job
->id(),
]);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('Translation for "@file" (job id = @job_id) was successfully downloaded but validation failed. See logs for more info.', [
'@file' => $file
->getFileUri(),
'@job_id' => $job
->id(),
])
->render(),
"type" => "error",
]);
return FALSE;
}
else {
try {
// Find job items with related entities which doesn't have
// target translation.
// Get the event_dispatcher service and dispatch the After File Download Event.
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher
->dispatch(AfterFileDownloadEvent::AFTER_FILE_DOWNLOAD_EVENT, new AfterFileDownloadEvent($job));
$job_items = $job
->getItems();
$force_import = NULL;
$entity_type_manager = \Drupal::entityTypeManager();
foreach ($job_items as $job_item) {
if (tmgmt_smartling_skip_passed_job_item_processing($job_item, $passed_job_item)) {
continue;
}
// Load target translation. Save job item id if it
// doesn't have target translation.
try {
$entity = $entity_type_manager
->getStorage($job_item
->getItemType())
->load($job_item
->getItemId());
// Entity can be removed by the moment we load it from the storage.
if ($entity instanceof ContentEntityInterface) {
$entity
->getTranslation($job
->getTargetLangcode());
}
} catch (Exception $e) {
// No translation found.
$force_import[$job_item
->id()] = $job_item;
}
// Force import in case connector works in "download by job item"
// mode.
if (!empty($passed_job_item)) {
$force_import[$passed_job_item
->id()] = $passed_job_item;
}
}
// Compare old and new hashes in order to decide should we apply
// translation or not. In other words we do not want to apply
// downloaded translation if it's the same as it was.
$old_hash = $job
->get('job_file_content_hash')
->getValue();
$old_hash = !empty($old_hash[0]['value']) ? $old_hash[0]['value'] : '';
$hash = md5($xml);
if ($old_hash !== $hash || $force_import) {
$job
->set('job_file_content_hash', $hash);
$job
->save();
// Validation successful, start import.
foreach ($plugin
->import($file
->getFileUri(), $job) as $key => $value) {
if (isset($job_items[$key])) {
if (tmgmt_smartling_skip_passed_job_item_processing($job_items[$key], $passed_job_item)) {
continue;
}
if ($old_hash !== $hash || isset($force_import[$key])) {
// Set active state for the job item in order to be able
// force translation. It allows to override existing
// translations that might be in an "Accepted" state.
// @see JobItem::addTranslatedData() method.
$job_items[$key]
->setState(JobItemInterface::STATE_ACTIVE);
// Import translation.
$job_items[$key]
->addTranslatedData($value, [], NULL);
}
}
}
$job
->addMessage('Successfully imported file.');
\Drupal::logger('tmgmt_smartling')
->info('Translation for "@filename" was successfully downloaded and imported.', [
'@filename' => $filename,
]);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('Translation for "@filename" (job id = @job_id) was successfully downloaded and imported.', [
'@filename' => $file
->getFileUri(),
'@job_id' => $job
->id(),
])
->render(),
"type" => "status",
]);
}
else {
$job
->addMessage('Import of downloaded file was skipped: downloaded and existing translations are equal.');
\Drupal::logger('tmgmt_smartling')
->warning('Translation for "@filename" was successfully downloaded but import was skipped: downloaded and existing translations are equal.', [
'@filename' => $filename,
]);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('Translation for "@filename" (job id = @job_id) was successfully downloaded but import was skipped: downloaded and existing translations are equal.', [
'@filename' => $file
->getFileUri(),
'@job_id' => $job
->id(),
])
->render(),
"type" => "warning",
]);
}
if (!$translation_request_manager
->commitSuccessfulDownload($job, $translation_request)) {
$warning_message = 'Can\'t update state and exported date for translation request = @translation_request.';
$warning_message_context = [
'@translation_request' => json_encode($translation_request),
];
$logger
->warning($warning_message, $warning_message_context);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => 'Can\'t update update state and exported date for translation request. See logs for more info.',
"type" => "warning",
]);
}
} catch (Exception $e) {
$job
->addMessage('File import failed with the following message: @message', [
'@message' => $e
->getMessage(),
], 'error');
\Drupal::logger('tmgmt_smartling')
->error('File import failed with the following message: @message', [
'@message' => $e
->getMessage(),
]);
$api_wrapper
->createFirebaseRecord("tmgmt_smartling", "notifications", 10, [
"message" => t('Translation for "@filename" (job id = @job_id) was successfully downloaded but import failed. See logs for more info.', [
'@filename' => $file
->getFileUri(),
'@job_id' => $job
->id(),
])
->render(),
"type" => "error",
]);
$translation_request_manager
->commitError($job, $translation_request, $e);
return FALSE;
}
}
}
}
return TRUE;
}