Endpoint deluje in vraca veliko o novi reviziji.

pull/34/head
Lio Novelli 2023-11-12 23:42:52 +01:00
parent 0827d59955
commit 6559793714
3 changed files with 106 additions and 83 deletions

View File

@ -4,10 +4,10 @@ namespace Drupal\yufu_concept\Plugin\rest\resource;
use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Session\AccountProxyInterface; use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\TypedData\Exception\MissingDataException; use Drupal\Core\TypedData\Exception\MissingDataException;
use Drupal\node\NodeInterface;
use Drupal\rest\Plugin\ResourceBase; use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse; use Drupal\rest\ResourceResponse;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
@ -39,20 +39,6 @@ class AddConcept extends ResourceBase {
*/ */
protected $currentUser; protected $currentUser;
/**
* Mail manager service.
*
* @var \Drupal\Core\Mail\MailManagerInterface
*/
protected $mailManager;
/**
* Site configs.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $config;
/** /**
* Entity type manager service. * Entity type manager service.
* *
@ -75,10 +61,6 @@ class AddConcept extends ResourceBase {
* A logger instance. * A logger instance.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user * @param \Drupal\Core\Session\AccountProxyInterface $current_user
* A current user instance. * A current user instance.
* @param \Drupal\Core\Mail\MailManagerInterface $mailManager
* Mail manager service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* Config factory service.
*/ */
public function __construct( public function __construct(
array $configuration, array $configuration,
@ -87,13 +69,9 @@ class AddConcept extends ResourceBase {
array $serializer_formats, array $serializer_formats,
LoggerInterface $logger, LoggerInterface $logger,
AccountProxyInterface $current_user, AccountProxyInterface $current_user,
MailManagerInterface $mailManager,
ConfigFactoryInterface $configFactory,
EntityTypeManagerInterface $entity_type_manager) { EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger); parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->currentUser = $current_user; $this->currentUser = $current_user;
$this->mailManager = $mailManager;
$this->config = $configFactory;
$this->entityTypeManager = $entity_type_manager; $this->entityTypeManager = $entity_type_manager;
} }
@ -106,10 +84,8 @@ class AddConcept extends ResourceBase {
$plugin_id, $plugin_id,
$plugin_definition, $plugin_definition,
$container->getParameter('serializer.formats'), $container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('yufu_concept'), $container->get('logger.channel.yufu_concept'),
$container->get('current_user'), $container->get('current_user'),
$container->get('plugin.manager.mail'),
$container->get('config.factory'),
$container->get('entity_type.manager') $container->get('entity_type.manager')
); );
} }
@ -117,6 +93,11 @@ class AddConcept extends ResourceBase {
/** /**
* Ustvari nov koncept. * Ustvari nov koncept.
* *
* Logika:
* 1. Zloadamo uporabnika preko emaila, ce ne obstaja, ga ustvarimo.
* 2. Zloadamo koncept prek uuid, ce ne obstaja, da ustvarimo.
* - avtor je zloadan prek maila
*
* @param \Symfony\Component\HttpFoundation\Request; * @param \Symfony\Component\HttpFoundation\Request;
* Post request. * Post request.
* *
@ -133,48 +114,108 @@ class AddConcept extends ResourceBase {
} }
// Fields: naslov, text, povezani pojmi, email // Fields: naslov, text, povezani pojmi, email
// Optional fields: language, related concept. // Optional fields: language, related concept.
if (!empty($data['title']) && !empty($data['text'])) { if (empty($data['title']) || empty($data['text']) || empty($data['uuid'])) {
throw new MissingDataException('Title or text missing.'); throw new MissingDataException('Title, uuid or text missing.');
}
$uid = $this->getUserIdByEmail($data['email'] ?? null);
if ($concept = $this->getConceptFromUuid($data['uuid'])) {
// Concept exists - create a new revision.
$concept->setNewRevision(TRUE);
$concept->setRevisionUserId($uid);
$concept->set('title', $data['title']);
$concept->set('body', $data['text'] ?? $concept->body->value);
$concept->isDefaultRevision(FALSE);
$concept->setRevisionLogMessage('New revision by concept endpoint.');
$concept->moderation_state->target_id = 'draft';
$concept->save();
$this->logger->notice('New concept @title revision @revid created by uid @uid.', [
'@title' => $concept->getTitle(),
'@revid' => $concept->getRevisionId(),
'@uid' => $uid,
]);
}
else {
// Concept does not exist - create a new node.
$concept = [
'type' => 'concept',
'title' => $data['title'],
'body' => $data['text'],
'uuid' => $data['uuid'],
'uid' => $uid,
'moderation_state' => 'draft',
];
// @TODO Check if related concepts are set and add them to the concept.
// @TODO Check language and add set it on concept if exists.
/** @var \Drupal\node\Entity\NodeInterface $concept */
$concept = $this->entityTypeManager->getStorage('node')->create($concept);
$concept->save();
$this->logger->log(LogLevel::NOTICE, $this->t('Creating concept: @title', [
'@title' => $concept->getTitle(),
]));
} }
$concept = [
'type' => 'concept',
'title' => $data['title'],
'body' => $data['body'],
];
$this->logger->log(LogLevel::NOTICE, $this->t('Creating concept: @title', [
'@title' => $concept['title'],
]));
// @TODO Check if related concepts are set and add them to the concept.
// @TODO Check language and add set it on concept if exists.
/** @var \Drupal\node\Entity\NodeInterface $concept */
$concept = $this->entityTypeManager->getStorage('node')->create($concept);
$concept->save();
$response_status['concept'] = [ $response_status['concept'] = [
'title' => $concept->label(), 'title' => $concept->label(),
'id' => $concept->id(), 'id' => $concept->id(),
'uuid' => $concept->uuid(), 'uuid' => $concept->uuid(),
'revision_id' => $concept->getRevisionId(),
'revision_create_time' => $concept->getRevisionCreationTime(),
'revision_uid' => $concept->getRevisionUserId(),
'uid' => $concept->uid->target_id,
]; ];
if (!empty($data['email'])) {
// @TODO Poslji mail uporabniku, da se lahko registrira.
$site_email = $this->config->get('system.site')->get('mail');
$module = 'yufu_concept';
$key = 'add_concept_rest_resource';
$to = $site_email;
// Send email to user to make him register to the website.
$params['message'] = $this->t('Creating concept: @title', [
'@title' => $concept->label(),
]);
$params['subject'] = $data['title'];
$params['from'] = $data['email'];
// @TODO Add validation for langode (must be from system configured endpoints).
$langcode = $data['lang'] ?? 'en';
$send = TRUE;
$result = $this->mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
$response_status['status'] = $result['result'];
}
$response = new ResourceResponse($response_status); $response = new ResourceResponse($response_status);
return $response; return $response;
} }
/**
* Get concept from uuid.
*
* If concept is new, return null.
*
* @param string|null $uuid
* Uuid of the node.
*
* @return \Drupal\node\NodeInterface|null
*/
protected function getConceptFromUuid(?string $uuid): ?NodeInterface {
if (!$uuid) {
return NULL;
}
$node_storage = $this->entityTypeManager->getStorage('node');
if ($concept = end($node_storage->loadByProperties(['uuid' => $uuid]))) {
return $concept;
}
return NULL;
}
/**
* Loads user from email or creates a new blocked user.
*
* Side effect is to create a new user.
*
* @param string|null $email
* Email provided by the fe call to endpoint.
*
* @return int
* Id of the user.
*
*/
protected function getUserIdByEmail(?string $email): int {
if (!$email) {
return 0;
}
// Load user by email. If it doesn't exist, create one.
$user_storage = $this->entityTypeManager->getStorage('user');
if ($user = end($user_storage->loadByProperties(['mail' => $email]))) {
return $user->id();
}
$user = [
'mail' => $email,
'name' => $email,
'status' => 0,
];
$new_user = $user_storage->create($user);
$new_user->save();
return $new_user->id();
}
} }

View File

@ -1,6 +1,7 @@
# _*_ restclient _*_ # _*_ restclient _*_
# Makes post http request to a resource from yufu_concept module. # Makes post http request to a resource from yufu_concept module.
# Make sure uuid is uniq or it will create new revision.
POST https://yufu-manifest.ddev.site/api/pojem/dodaj POST https://yufu-manifest.ddev.site/api/pojem/dodaj
User-Agent: Emacs Restclient User-Agent: Emacs Restclient
@ -8,7 +9,8 @@ Content-Type: application/json
Cookies: "SSESSb6f5da6ef565138b872e3e58509d8150=0z6Zk4tRwTF4WAR%2CSO6rH0K5F7hqKpbe28XRRHwvTxo%2CUnpC" Cookies: "SSESSb6f5da6ef565138b872e3e58509d8150=0z6Zk4tRwTF4WAR%2CSO6rH0K5F7hqKpbe28XRRHwvTxo%2CUnpC"
{ {
"title": "Emacs restclient test 102", "title": "888 Emacs restclient test 888",
"body": "O wau. Emacs restclient. How nice.", "text": "O wau. Emacs restclient. How nice. Dodam text. Spet.",
"email": "lio.novelli@radiostudent.si" "email": "lio.novelli@radiostudent.si",
"uuid": "70c1ace2-aaaa-4dc5-84ed-3f21b83cb23a"
} }

View File

@ -4,23 +4,3 @@
* @file * @file
* Primary module hooks for Yufu Concept module. * Primary module hooks for Yufu Concept module.
*/ */
/**
* Implements hook_mail().
*
* @TODO this should go into hook presave.
*/
function yufu_concept_mail($key, &$message, $params) {
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
case 'add_concept_rest_resource':
// This is just a test implementation for sending emails.
$message['from'] = $params['from'];
$message['subject'] = $params['subject'];
$message['body'][] = $params['message'];
break;
}
}