You are here

ContextUploader.php in TMGMT Translator Smartling 8

File

src/Context/ContextUploader.php
View source
<?php

namespace Drupal\tmgmt_smartling\Context;

use Drupal\tmgmt_smartling\Exceptions\EmptyContextParameterException;
use Drupal\tmgmt_smartling\Smartling\SmartlingApi;
use Drupal\tmgmt_smartling\Smartling\SmartlingApiException;
use Psr\Log\LoggerInterface;
use Drupal\tmgmt_smartling\Exceptions\SmartlingBaseException;
class ContextUploader {

  /**
   * @var TranslationJobToUrl
   */
  protected $urlConverter;

  /**
   * @var ContextCurrentUserAuth
   */
  protected $authenticator;

  /**
   * @var HtmlAssetInliner
   */
  protected $assetInliner;

  /**
   * @var LoggerInterface
   */
  protected $logger;
  public function __construct(TranslationJobToUrl $url_converter, ContextUserAuth $auth, HtmlAssetInliner $html_asset_inliner, LoggerInterface $logger) {
    $this->urlConverter = $url_converter;
    $this->authenticator = $auth;
    $this->assetInliner = $html_asset_inliner;
    $this->logger = $logger;
  }
  public function jobItemToUrl($job_item) {
    return $this->urlConverter
      ->convert($job_item);
  }

  /**
   * @param $url
   * @param array $settings
   * @param bool $debug
   *
   * @return mixed|string|void
   * @throws \Drupal\tmgmt_smartling\Exceptions\EmptyContextParameterException
   * @throws \Exception
   */
  public function getContextualizedPage($url, array $settings, $debug = FALSE) {
    if (empty($url)) {
      throw new EmptyContextParameterException('Context url must be a non-empty string.');
    }
    $username = $settings['contextUsername'];
    if (empty($username)) {
      $username = $this->authenticator
        ->getCurrentAccount()
        ->getAccountName();
    }
    $cookies = $this->authenticator
      ->getCookies($username, $settings['context_silent_user_switching']);
    $html = $this->assetInliner
      ->getCompletePage($url, $cookies, TRUE, FALSE, $settings, $debug);
    $html = str_replace('<html ', '<html class="sl-override-context" ', $html);
    $html = str_replace('<p></p>', "\n", $html);
    return $html;
  }

  /**
   * @param string $url
   * @param string $filename
   * @param array $proj_settings
   * @return bool
   * @throws EmptyContextParameterException
   */
  public function upload($url, $filename = '', $proj_settings = []) {
    if (empty($url)) {
      throw new EmptyContextParameterException('Context url must be a non-empty field.');
    }
    try {
      $html = $this
        ->getContextualizedPage($url, $proj_settings);
      $response = $this
        ->uploadContextBody($url, $html, $filename, $proj_settings);
      if (!empty($response['items'])) {
        foreach ($response['items'] as $resource) {
          $this
            ->uploadAsset($resource['url'], $resource['resourceId'], $proj_settings);
        }
      }
    } catch (SmartlingApiException $e) {
      $this->logger
        ->error($e
        ->getMessage());
      return [];
    } catch (SmartlingBaseException $e) {
      $this->logger
        ->error($e
        ->getMessage());
      return [];
    }
    $this->logger
      ->info('Context upload for file @filename completed successfully.', [
      '@filename' => $filename,
    ]);
    return $response;
  }

  /**
   * @param bool $override_service_url
   * @return SmartlingApi
   */
  protected function getApi($proj_settings, $override_service_url = FALSE) {
    $key = $proj_settings['key'];
    $project_id = $proj_settings['project_id'];
    $api_url = $proj_settings['api_url'];
    $client = \Drupal::getContainer()
      ->get('http_client');
    if ($override_service_url) {
      $smartlingApi = new SmartlingApi($key, $project_id, $client, 'https://api.smartling.com/context-api/v2');
    }
    else {
      $smartlingApi = new SmartlingApi($key, $project_id, $client, $api_url);
    }
    return $smartlingApi;
  }

  /**
   * @param $url
   * @param $html
   * @param $filename
   * @return array
   * @throws EmptyContextParameterException
   */
  protected function uploadContextBody($url, $html, $filename, $proj_settings) {
    $orgId = $proj_settings['orgID'];
    if (empty($orgId)) {
      throw new EmptyContextParameterException('OrgId is a mandatory field. Please, fill it in.');
    }
    $api = $this
      ->getApi($proj_settings, TRUE);
    if (!empty($filename)) {
      $response = $api
        ->uploadContext(array(
        'url' => $url,
        'html' => $html,
        'fileUri' => $filename,
        'orgId' => $orgId,
      ), [
        'html' => [
          'name' => 'context.html',
          'content_type' => 'text/html',
        ],
      ]);
    }
    $response2 = $api
      ->uploadContext(array(
      'url' => $url,
      'html' => $html,
      'orgId' => $orgId,
    ), [
      'html' => [
        'name' => 'context.html',
        'content_type' => 'text/html',
      ],
    ]);
    if (empty($response)) {
      $response = $response2;
    }
    return $response;
  }

  /**
   * @param string $url
   * @param string $resourceId
   */
  protected function uploadAsset($url, $resourceId, $proj_settings) {
    $orgId = $proj_settings['orgID'];
    $resource['url'] = $url;
    $resource['resource'] = @file_get_contents($url);
    if ($resource['resource'] !== FALSE) {
      $contet_type = get_headers($resource['url'], 1)["Content-Type"];

      //$resource['resource'] = @fopen($resource['url'], 'r');//$content;
      $resource['orgId'] = $orgId;
      $resource['resourceId'] = $resourceId;
      $res_fil = basename($resource['url']);
      $res_fil = strpos($res_fil, '?') === FALSE ? $res_fil : strstr($res_fil, '?', TRUE);
      if (empty($res_fil)) {
        $this->logger
          ->warning('Asset "@url" can not be uploaded. Bad filename.', [
          '@url' => $resource['url'],
        ]);
        return;
      }
      $res = $this
        ->getApi($proj_settings, TRUE)
        ->putResource($resource, [
        'resource' => [
          'name' => $res_fil,
          'content_type' => $contet_type,
        ],
      ]);
    }
    else {
      $this->logger
        ->warning('File "@url" can not be downloaded. Probably it does not exist or server returned 403 status code for a given resource.', [
        '@url' => $resource['url'],
      ]);
    }
  }

  /**
   * @param $filename
   * @return bool
   */
  public function isReadyAcceptContext($filename, $proj_settings) {
    $api = $this
      ->getApi($proj_settings, FALSE);
    try {
      $res = $api
        ->getStatusAllLocales($filename);
      if (!$res) {
        $this->logger
          ->warning('File "@filename" is not ready to accept context. Most likely it is being processed by Smartling right now.', [
          '@filename' => $filename,
        ]);
      }
      return $res;
    } catch (\Exception $e) {
      $this->logger
        ->warning($e
        ->getMessage());
      return FALSE;
    }
    return FALSE;
  }

}

Classes

Namesort descending Description
ContextUploader