activitypub-1.0.x-dev/src/Commands/ActivityPubCommands.php

src/Commands/ActivityPubCommands.php
<?php

namespace Drupal\activitypub\Commands;

use Drupal\activitypub\Plugin\activitypub\type\Core;
use Drupal\Component\Utility\UrlHelper;
use Drush\Commands\DrushCommands;

/**
 * ActivityPub Drush commands file.
 */
class ActivityPubCommands extends DrushCommands {

  /**
   * Prepare outbox.
   *
   * @param int $create_queue_item
   *   Create send queue item.
   * @param int $time_limit
   *   How long in seconds this command may run.
   * @param int $remove_queue_item
   *   Delete item from queue.
   * @param int $debug
   *   Whether to view debug statements.
   *
   * @command activitypub:prepare-outbox
   */
  public function prepareOutbox($create_queue_item = 1, $time_limit = 30, $remove_queue_item = 1, $debug = 0) {
    if (\Drupal::config('activitypub.settings')->get('process_outbox_handler') == 'drush') {

      // Make sure the host is not set to default.
      if (\Drupal::request()->getHost() == 'default') {
        $this->writeln("Please provide the -l or --uri parameter to set the host.");
        return;
      }

      \Drupal::service('activitypub.process.client')->prepareOutboxQueue((bool) $create_queue_item, $time_limit, (bool) $remove_queue_item, (bool) $debug);
    }
  }

  /**
   * Process outbox.
   *
   * @param int $send
   *   Whether to send to activities to inboxes.
   * @param int $time_limit
   *   How long in seconds this command may run.
   * @param int $remove_queue_item
   *   Delete item from queue.
   * @param int $debug
   *   Whether to view debug statements.
   *
   * @command activitypub:process-outbox
   */
  public function processOutbox($send = 1, $time_limit = 30, $remove_queue_item = 1, $debug = 0) {
    if (\Drupal::config('activitypub.settings')->get('process_outbox_handler') == 'drush') {

      // Make sure the host is not set to default.
      if (\Drupal::request()->getHost() == 'default') {
        $this->writeln("Please provide the -l or --uri parameter to set the host.");
        return;
      }

      \Drupal::service('activitypub.process.client')->handleOutboxQueue((bool) $send, $time_limit, (bool) $remove_queue_item, (bool) $debug);
    }
  }

  /**
   * Process inbox.
   *
   * @param int $time_limit
   *   How long in seconds this command may run.
   * @param int $remove_queue_item
   *   Delete item from queue.
   * @param int $debug
   *   Whether to view debug statements.
   *
   * @command activitypub:process-inbox
   */
  public function processInbox($time_limit = 30, $remove_queue_item = 1, $debug = 0) {
    if (\Drupal::config('activitypub.settings')->get('process_inbox_handler') == 'drush') {

      // Make sure the host is not set to default.
      if (\Drupal::request()->getHost() == 'default') {
        $this->writeln("Please provide the -l or --uri parameter to set the host.");
        return;
      }

      \Drupal::service('activitypub.process.client')->handleInboxQueue($time_limit, (bool) $remove_queue_item, (bool) $debug);
    }
  }

  /**
   * Removes old activities.
   *
   * @command activitypub:remove-old-activities
   */
  public function removeOldActivities() {
    if (\Drupal::config('activitypub.settings')->get('inbox_remove_x_days_handler') == 'drush') {
      \Drupal::service('activitypub.process.client')->removeOldActivities();
    }
  }

  /**
   * Add activity to queue.
   *
   * @param $activityId
   *
   * @command activitypub:add-to-queue
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function addActivityToQueue($activityId) {
    /** @var \Drupal\activitypub\Entity\ActivityPubActivityInterface $activity */
    $activity = \Drupal::entityTypeManager()->getStorage('activitypub_activity')->load($activityId);
    if ($activity) {
      $activity
        ->set('processed', FALSE)
        ->set('queued', TRUE)
        ->save();
      \Drupal::service('activitypub.process.client')->createQueueItem($activity);
      $this->logger()->notice('Added to queue');
    }
    else {
      $this->logger()->notice('Activity not found');
    }
  }

  /**
   * Fetches and caches remote users for a user.
   *
   * @param $uid
   *
   * @command activitypub:fetch-remote-users
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function cacheRemoteUsers($uid) {
    $server = \Drupal::service('activitypub.utility')->getServer();
    $conditions = ['type' => 'Follow', 'uid' => $uid, 'status' => 1];
    /** @var \Drupal\activitypub\Entity\ActivityPubActivityInterface[] $activities */
    $activities = \Drupal::entityTypeManager()->getStorage('activitypub_activity')->loadByProperties($conditions);
    foreach ($activities as $activity) {
      $this->writeln('Fetching ' . $activity->getActor());
      $server->actor($activity->getActor());
    }
  }

  /**
   * Get info about a name via WebFinger.
   *
   * @param $handle
   *   The handle to fetch.
   * @param int $debug
   *   Whether to debug or not.
   *
   * @command activitypub:webfinger-info
   */
  public function getWebfingerInfo($handle, $debug = 1) {
    /** @var \Drupal\activitypub\Services\ActivityPubUtilityInterface $utility */
    $utility = \Drupal::service('activitypub.utility');
    $server = $utility->getServer(['instance' => ['debug' => (bool) $debug]]);

    // Get actor.
    $actor = $server->actor($handle);
    print_r($actor->get('inbox'));

    // Get a WebFinger instance
    $webfinger = $actor->webfinger();
    print_r($webfinger->toArray());
  }

  /**
   * Updates entity id and entity type id on activities in the Inbox collection
   * where the object is pointing to an internal node. Typical types are  Like,
   * Announce,
   *
   * @param int $save
   * @param string $types
   *
   * @command activitypub:update-references
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException|\Drupal\Core\Entity\EntityStorageException
   */
  public function updateReferences(int $save = 0, string $types = 'Like,Announce') {

    // Make sure the host is not set to default.
    if (\Drupal::request()->getHost() == 'default') {
      $this->writeln("Please provide the -l or --uri parameter to set the host.");
      return;
    }

    $counter = $saved = 0;
    if (!$save) {
      $this->logger()->notice('Note: not updating the activities, just analyzing');
    }

    $conditions = [
      'collection' => 'inbox',
      'status' => 1,
      'type' => explode(',', $types),
    ];
    /** @var \Drupal\activitypub\Entity\Storage\ActivityPubActivityStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()->getStorage('activitypub_activity');
    foreach ($storage->getActivities($conditions) as $activity) {
      $counter++;
      if ($object = $activity->getObject()) {
        $this->logger()->notice('Checking ' . $object);
        $entity = Core::getEntityFromUrl($object);
        if ($entity) {
          $saved++;
          $this->logger()->notice('Updating ' . $activity->id() . ' (' . $activity->getType() . ' - ' . $activity->getActor() . '): id/type: ' . $entity->id() . '/' . $entity->getEntityTypeId());

          if ($save) {
            $activity->set('entity_id', $entity->id());
            $activity->set('entity_type_id', $entity->getEntityTypeId());
            $activity->save();
          }
        }
      }
    }

    $this->logger()->notice("Checked $counter, updated $saved");
  }

  /**
   * Deletes activities
   *
   * @param int $delete
   * @param $actor
   * @param $object
   * @param $type
   * @param $visibility
   *
   * @command activitypub:delete-activities
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function deleteActivities(int $delete = 0, $actor = NULL, $object = NULL, $type = NULL, $visibility = NULL) {
    $deleted = 0;

    if (!$delete) {
      $this->logger()->notice('Note: not deleting as delete argument is set to 0. The counter will work though.');
      sleep(1);
    }

    if (empty($actor) && empty($object) && empty($type)) {
      $this->logger()->notice('Please provide an actor, object or type to search on');
      return;
    }

    /** @var \Drupal\activitypub\Entity\Storage\ActivityPubActivityStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()->getStorage('activitypub_activity');
    $query = $storage->getQuery();
    if ($actor) {
      $query->condition('actor', $actor, 'CONTAINS');
    }
    if ($object) {
      $query->condition('object', $object, 'CONTAINS');
    }
    if ($type) {
      $query->condition('type', $type);
    }
    if ($visibility) {
      $query->condition('visibility', $visibility);
    }
    $ids = $query->execute();

    /** @var \Drupal\activitypub\Entity\ActivityPubActivityInterface $activity */
    foreach ($storage->loadMultiple($ids) as $activity) {
      $deleted++;
      $this->logger()->notice('Checking activity ' . $activity->id() . ': ' . $activity->getActor() . ' - ' . $activity->getType());
      if ($delete) {
        $activity->delete();
      }
    }

    $this->logger()->notice('Deleted: ' . $deleted);
  }

  /**
   * @command activitypub:test-getting-entity-from-url
   */
  public function testGettingEntityFromUrl($url, $host) {
    $local_url = UrlHelper::externalIsLocal($url, $host);
    $this->logger()->notice('local: ' . (int) $local_url);
    $user_input = str_replace($host . base_path(), '', $url);
    $this->logger()->notice('url: ' . $url);
    $this->logger()->notice('User input: ' . $user_input);
    $url_object = \Drupal::service('path.validator')->getUrlIfValidWithoutAccessCheck($user_input);
    if ($url_object) {
      $this->logger()->notice('Object: ' . $url_object->getRouteName() . ' - ' . print_r($url_object->getRouteParameters(), 1));
    }
    else {
      $this->logger()->notice('not match');
    }
  }
}

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

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