remp-8.x-1.x-dev/src/RempService.php

src/RempService.php
<?php

namespace Drupal\remp;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Implementation of REMP Service.
 */
class RempService {

  /**
   * Request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  private $request;

  /**
   * Guzzle Http Client.
   *
   * @var \GuzzleHttp\Client|ClientInterface
   */
  private $httpClient;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory|ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Module Handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandler|ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * REMP User.
   *
   * @var array
   */
  protected $user;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  private $time;

  /**
   * Class Constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   Request.
   * @param \GuzzleHttp\ClientInterface $http_client
   *   HTTP Client.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config Factory.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   Module Handler.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct(RequestStack $request_stack, ClientInterface $http_client, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, TimeInterface $time) {
    $this->request = $request_stack->getCurrentRequest();
    $this->httpClient = $http_client;
    $this->configFactory = $config_factory;
    $this->moduleHandler = $module_handler;
    $this->time = $time;

    $this->loadUser();
  }

  /**
   * Returns active subscriptions.
   */
  public function getSubscriptions($access = NULL) {
    $subscriptions = [];

    if (empty($access)) {
      $access = $this->getAccessType();
    }

    try {
      $sub_request = $this->httpClient->request('GET', $this->apiUrl() . '/users/subscriptions', [
        'headers' => $this->getRequestHeaders(),
      ]);
      if ($sub_request->getStatusCode() == 200) {
        $body = Json::decode($sub_request->getBody()->getContents());
        // Search for active subscription with access to 'web'.
        foreach ($body['subscriptions'] as $subscription) {
          if (in_array($access, $subscription['access'])) {
            $start_date = new \DateTime($subscription['start_at']);
            if ($start_date->getTimestamp() < time()) {
              $subscriptions[] = $subscription;
            }
          }
        }
      }
    }
    catch (ClientException $e) {
      return [];
    }

    return $subscriptions;
  }

  /**
   * Checks if there is a valid token.
   */
  public function hasValidToken() {
    $token = $this->request->cookies->get('n_token');
    return $this->validToken($token);
  }

  /**
   * Loads REMP user.
   */
  protected function loadUser() {
    if ($token = $this->request->cookies->get('n_token')) {
      try {
        $checkRequest = $this->httpClient->request('GET',
          $this->apiUrl() . '/user/info',
          [
            'headers' => [
              'Content-Type' => 'application/json',
              'Authorization' => 'Bearer ' . $token,
            ],
          ]
        );
        $body = Json::decode($checkRequest->getBody()->getContents());
        if ($body['status'] == 'ok') {
          $this->user = $body['user'];
        }
      }
      catch (ClientException $e) {
      }
    }
  }

  /**
   * Checks if current token is valid.
   */
  protected function validToken($token) {
    try {
      $checkRequest = $this->httpClient->request('GET',
        $this->apiUrl() . '/user/info',
        [
          'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
          ],
        ]
      );
      $body = Json::decode($checkRequest->getBody()->getContents());
      return $body['status'] == 'ok';
    }
    catch (ClientException $e) {
      return FALSE;
    }
  }

  /**
   * View Content.
   */
  public function viewContent($entity) {
    $crm_result = [
      'available' => FALSE,
      'count_subscription' => FALSE,
      'remaining_articles' => 0,
    ];
    $entity_type = $entity->getEntityTypeId();
    $entity_id = $entity->id();

    $access = $this->getAccessType($entity);

    // Notify REMP CRM of article view.
    try {
      $view_request = $this->httpClient->request('POST', $this->apiUrl() . '/article/view', [
        'headers' => $this->getRequestHeaders(),
        'body' => 'url=' . $entity_type . '/' . $entity_id . '&access=' . $access,
      ]);

      if ($view_request->getStatusCode() == 200) {
        $body = $view_request->getBody();

        $view_result = Json::decode($body->getContents());

        if ($view_result['status'] == 'ok') {
          $crm_result['available'] = TRUE;
        }

        if (isset($view_result['remaining'])) {
          $crm_result['remaining_articles'] = $view_result['remaining'];
          $crm_result['count_subscription'] = TRUE;
        }
      }
    }
    catch (\Exception $e) {
      $subscriptions = $this->getSubscriptions($access);
      $crm_result['available'] = !empty($subscriptions);
    }

    return $crm_result;
  }

  /**
   * Tries to login user.
   */
  public function login(string $email, string $password) {
    try {
      $login_request = $this->httpClient->request('POST',
        $this->apiUrl() . '/users/login', [
          'headers' => [
            "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
            "Accept" => "application/json",
          ],
          'form_params' => [
            'email' => $email,
            'password' => $password,
          ],
        ]
      );

      $body = $login_request->getBody();
      $result = Json::decode($body->getContents());

      $c_params = session_get_cookie_params();

      $expire = strtotime('+1 month', $this->time->getRequestTime());
      setcookie('n_token', $result['access']['token'], $expire, $c_params['path'], $c_params['domain'], $c_params['secure'], $c_params['httponly']);
      setcookie('n_email', $result['user']['email'], $expire, $c_params['path'], $c_params['domain'], $c_params['secure'], $c_params['httponly']);
      return $result;
    }
    catch (ClientException $e) {
      $login_request = $e->getResponse();
      $body = $login_request->getBody();
      $result = Json::decode($body->getContents());
      return $result;
    }
  }

  /**
   * Determines content access.
   */
  protected function getAccessType($entity = NULL) {
    $access = 'web';
    $this->moduleHandler->alter('remp_content_access_key', $access, $entity);
    return $access;
  }

  /**
   * Builds request header.
   */
  protected function getRequestHeaders() {
    return [
      'Content-Type' => 'application/x-www-form-urlencoded',
      'Authorization' => 'Bearer ' . $this->request->cookies->get('n_token'),
    ];
  }

  /**
   * Returns api url.
   */
  protected function apiUrl() {
    $config = $this->configFactory->get('remp.config');
    return $config->get('host') . '/api/v1';
  }

  /**
   * Returns remp user token.
   */
  public function getUser() {
    return $this->user;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc