activitypub-1.0.x-dev/src/Plugin/activitypub/type/Context.php
src/Plugin/activitypub/type/Context.php
<?php
namespace Drupal\activitypub\Plugin\activitypub\type;
use Drupal\activitypub\Entity\ActivityPubActivityInterface;
use Drupal\activitypub\Services\Type\TypePluginBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* The ActivityPub context.
*
* @ActivityPubType(
* id = "activitypub_context",
* label = @Translation("Context"),
* )
*/
class Context extends TypePluginBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
return $form;
}
/**
* {@inheritdoc}
*/
public function onActivityPostSave(ActivityPubActivityInterface $activity, $update = TRUE) {
if (in_array($activity->getType(), $this->activityPubUtility->getTimelineTypes()) && !$update && $activity->getCollection() == ActivityPubActivityInterface::INBOX) {
// Is the context config entity enabled or not.
/** @var \Drupal\activitypub\Entity\ActivityPubTypeInterface $activityPubType */
$activityPubType = $this->entityTypeManager->getStorage('activitypub_type')->load('context');
if ($activityPubType && $activityPubType->isEnabled() && ($activity->getReply() || in_array($activity->getType(), ['Like', 'Announce']))) {
$this->activityPubProcessClient->createQueueItem($activity, ACTIVITYPUB_INBOX_QUEUE, ['config_id' => 'context']);
}
}
}
/**
* {@inheritdoc}
*/
public function doInboxProcess(ActivityPubActivityInterface $activity, EntityInterface $entity = NULL) {
$url = NULL;
if ($activity->getReply()) {
$url = $activity->getReply();
}
elseif (in_array($activity->getType(), ['Like', 'Announce'])) {
$url = $activity->getObject();
}
if (isset($url)) {
$client = \Drupal::httpClient();
try {
$options = [
'headers' => [
'Accept' => 'application/activity+json',
],
];
$response = $client->get($url, $options);
$body = $response->getBody()->getContents();
$context = @json_decode($body, TRUE);
if (isset($context['id']) && $context['id'] == $url) {
$activity->set('context', $body);
}
}
catch (\Exception $e) {
$this->logger->warning('Error fetching context for activity @id: @message', ['@id' => $activity->id(), '@message' => $e->getMessage()]);
}
}
}
}
