[ActivityPub][Model][Activity] Translate including objects

This commit is contained in:
Diogo Peralta Cordeiro 2021-12-01 20:53:32 +00:00
parent e7ee558f4a
commit 6f543ccc06
Signed by: diogo
GPG Key ID: 18D2D35001FBFAB0
6 changed files with 36 additions and 40 deletions

View File

@ -1,6 +1,6 @@
<?php <?php
declare(strict_types = 1); declare(strict_types=1);
namespace Plugin\ActivityPub; namespace Plugin\ActivityPub;
@ -14,18 +14,11 @@ use App\Entity\Activity;
use App\Entity\Actor; use App\Entity\Actor;
use App\Entity\LocalUser; use App\Entity\LocalUser;
use App\Util\Common; use App\Util\Common;
use App\Util\Exception\NicknameEmptyException;
use App\Util\Exception\NicknameException;
use App\Util\Exception\NicknameInvalidException;
use App\Util\Exception\NicknameNotAllowedException;
use App\Util\Exception\NicknameTakenException;
use App\Util\Exception\NicknameTooLongException;
use App\Util\Exception\NoSuchActorException; use App\Util\Exception\NoSuchActorException;
use App\Util\Nickname; use App\Util\Nickname;
use Exception; use Exception;
use Plugin\ActivityPub\Controller\Inbox; use Plugin\ActivityPub\Controller\Inbox;
use Plugin\ActivityPub\Entity\ActivitypubActor; use Plugin\ActivityPub\Entity\ActivitypubActor;
use Plugin\ActivityPub\Util\Explorer;
use Plugin\ActivityPub\Util\HTTPSignature; use Plugin\ActivityPub\Util\HTTPSignature;
use Plugin\ActivityPub\Util\Model\EntityToType\EntityToType; use Plugin\ActivityPub\Util\Model\EntityToType\EntityToType;
use Plugin\ActivityPub\Util\Response\ActorResponse; use Plugin\ActivityPub\Util\Response\ActorResponse;
@ -55,7 +48,7 @@ class ActivityPub extends Plugin
'as:Public', 'as:Public',
]; ];
public const HTTP_CLIENT_HEADERS = [ public const HTTP_CLIENT_HEADERS = [
'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent' => 'GNUsocialBot ' . GNUSOCIAL_VERSION . ' - ' . GNUSOCIAL_PROJECT_URL, 'User-Agent' => 'GNUsocialBot ' . GNUSOCIAL_VERSION . ' - ' . GNUSOCIAL_PROJECT_URL,
]; ];
@ -93,7 +86,7 @@ class ActivityPub extends Plugin
return Event::next; return Event::next;
} }
public function onStartGetActorUrl(Actor $actor, int $type, ?string &$url):bool public function onStartGetActorUrl(Actor $actor, int $type, ?string &$url): bool
{ {
if ( if (
// Is remote? // Is remote?
@ -110,7 +103,8 @@ class ActivityPub extends Plugin
return Event::next; return Event::next;
} }
public function onAddFreeNetworkProtocol (array &$protocols): bool { public function onAddFreeNetworkProtocol(array &$protocols): bool
{
$protocols[] = '\Plugin\ActivityPub\ActivityPub'; $protocols[] = '\Plugin\ActivityPub\ActivityPub';
return Event::next; return Event::next;
} }
@ -118,7 +112,7 @@ class ActivityPub extends Plugin
public static function freeNetworkDistribute(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool public static function freeNetworkDistribute(Actor $sender, Activity $activity, array $targets, ?string $reason = null): bool
{ {
$to_addr = []; $to_addr = [];
foreach($targets as $target) { foreach ($targets as $target) {
if (is_null($ap_target = ActivitypubActor::getWithPK(['actor_id' => $target->getId()]))) { if (is_null($ap_target = ActivitypubActor::getWithPK(['actor_id' => $target->getId()]))) {
continue; continue;
} }
@ -170,7 +164,7 @@ class ActivityPub extends Plugin
Log::debug('ActivityPub Postman: Delivery headers were: ' . print_r($headers, true)); Log::debug('ActivityPub Postman: Delivery headers were: ' . print_r($headers, true));
$response = HTTPClient::$method($inbox, ['headers' => $headers, 'body' => $data]); $response = HTTPClient::$method($inbox, ['headers' => $headers, 'body' => $data]);
Log::debug('ActivityPub Postman: Delivery result with status code '.$response->getStatusCode().': '.$response->getContent()); Log::debug('ActivityPub Postman: Delivery result with status code ' . $response->getStatusCode() . ': ' . $response->getContent());
return $response; return $response;
} }
@ -191,7 +185,7 @@ class ActivityPub extends Plugin
if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) { if (preg_match_all($renick, $str, $matches, PREG_SET_ORDER, 0) === 1) {
return LocalUser::getWithPK(['nickname' => $matches[0][1]])->getActor(); return LocalUser::getWithPK(['nickname' => $matches[0][1]])->getActor();
} elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) { } elseif (preg_match_all($reuri, $str, $matches, PREG_SET_ORDER, 0) === 1) {
return Actor::getById((int) $matches[0][1]); return Actor::getById((int)$matches[0][1]);
} }
} }
} }
@ -265,21 +259,21 @@ class ActivityPub extends Plugin
/** /**
* Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
* *
* @param string $text The text from which to extract webfinger IDs * @param string $text The text from which to extract webfinger IDs
* @param string $preMention Character(s) that signals a mention ('@', '!'...) * @param string $preMention Character(s) that signals a mention ('@', '!'...)
* @return array The matching IDs (without $preMention) and each respective position in the given string. * @return array The matching IDs (without $preMention) and each respective position in the given string.
*/ */
public static function extractWebfingerIds(string $text, string $preMention='@'): array public static function extractWebfingerIds(string $text, string $preMention = '@'): array
{ {
$wmatches = []; $wmatches = [];
$result = preg_match_all( $result = preg_match_all(
'/'.Nickname::BEFORE_MENTIONS.preg_quote($preMention, '/').'('.Nickname::WEBFINGER_FMT.')/', '/' . Nickname::BEFORE_MENTIONS . preg_quote($preMention, '/') . '(' . Nickname::WEBFINGER_FMT . ')/',
$text, $text,
$wmatches, $wmatches,
PREG_OFFSET_CAPTURE PREG_OFFSET_CAPTURE
); );
if ($result === false) { if ($result === false) {
Log::error(__METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').'); Log::error(__METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error==' . preg_last_error() . ').');
return []; return [];
} elseif (($n_matches = count($wmatches)) != 0) { } elseif (($n_matches = count($wmatches)) != 0) {
Log::debug((sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, print_r($wmatches, true)))); Log::debug((sprintf('Found %d matches for WebFinger IDs: %s', $n_matches, print_r($wmatches, true))));
@ -288,25 +282,25 @@ class ActivityPub extends Plugin
} }
/** /**
* Profile URL matches: @example.com/mublog/user * Profile URL matches: @param string $text The text from which to extract URL mentions
* * @param string $preMention Character(s) that signals a mention ('@', '!'...)
* @param string $text The text from which to extract URL mentions
* @param string $preMention Character(s) that signals a mention ('@', '!'...)
* @return array The matching URLs (without @ or acct:) and each respective position in the given string. * @return array The matching URLs (without @ or acct:) and each respective position in the given string.
* @example.com/mublog/user
*
*/ */
public static function extractUrlMentions(string $text, string $preMention='@'): array public static function extractUrlMentions(string $text, string $preMention = '@'): array
{ {
$wmatches = []; $wmatches = [];
// In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
// with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important) // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
$result = preg_match_all( $result = preg_match_all(
'/(?:^|\s+)'.preg_quote($preMention, '/').'('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/', '/(?:^|\s+)' . preg_quote($preMention, '/') . '(' . URL_REGEX_DOMAIN_NAME . '(?:\/[' . URL_REGEX_VALID_PATH_CHARS . ']*)*)/',
$text, $text,
$wmatches, $wmatches,
PREG_OFFSET_CAPTURE PREG_OFFSET_CAPTURE
); );
if ($result === false) { if ($result === false) {
Log::error(__METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').'); Log::error(__METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error==' . preg_last_error() . ').');
return []; return [];
} elseif (count($wmatches)) { } elseif (count($wmatches)) {
Log::debug((sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), print_r($wmatches, true)))); Log::debug((sprintf('Found %d matches for profile URL mentions: %s', count($wmatches), print_r($wmatches, true))));
@ -317,11 +311,11 @@ class ActivityPub extends Plugin
/** /**
* Find any explicit remote mentions. Accepted forms: * Find any explicit remote mentions. Accepted forms:
* Webfinger: @user@example.com * Webfinger: @user@example.com
* Profile link: @example.com/mublog/user * Profile link: @param Actor $sender
* @param Actor $sender
* @param string $text input markup text * @param string $text input markup text
* @param $mentions * @param $mentions
* @return bool hook return value * @return bool hook return value
* @example.com/mublog/user
*/ */
public function onEndFindMentions(Actor $sender, string $text, array &$mentions): bool public function onEndFindMentions(Actor $sender, string $text, array &$mentions): bool
{ {
@ -421,10 +415,10 @@ class ActivityPub extends Plugin
/** /**
* Profile from URI. * Profile from URI.
* *
* @author GNU social
* @param string $uri * @param string $uri
* @param Actor &$profile in/out param: Profile got from URI * @param Actor &$profile in/out param: Profile got from URI
* @return mixed hook return code * @return mixed hook return code
* @author GNU social
*/ */
//public function onStartGetProfileFromURI($uri, &$profile) //public function onStartGetProfileFromURI($uri, &$profile)
//{ //{

View File

@ -17,7 +17,7 @@ use Plugin\ActivityPub\Entity\ActivitypubActivity;
abstract class AS2ToEntity abstract class AS2ToEntity
{ {
public static function activity_stream_two_verb_to_gs_verb($verb) public static function activity_stream_two_verb_to_gs_verb(string $verb): string
{ {
return match ($verb) { return match ($verb) {
'Create' => 'create', 'Create' => 'create',
@ -25,7 +25,7 @@ abstract class AS2ToEntity
}; };
} }
public static function activity_stream_two_object_type_to_gs_table($object) public static function activity_stream_two_object_type_to_gs_table(string $object): string
{ {
return match ($object) { return match ($object) {
'Note' => 'note', 'Note' => 'note',

View File

@ -32,9 +32,9 @@ class ActivityToType
'id' => Router::url('activity_view', ['id' => $activity->getId()], Router::ABSOLUTE_URL), 'id' => Router::url('activity_view', ['id' => $activity->getId()], Router::ABSOLUTE_URL),
'published' => $activity->getCreated()->format(DateTimeInterface::RFC3339), 'published' => $activity->getCreated()->format(DateTimeInterface::RFC3339),
'actor' => $activity->getActor()->getUri(Router::ABSOLUTE_URL), 'actor' => $activity->getActor()->getUri(Router::ABSOLUTE_URL),
//'to' => $to, 'to' => ['https://www.w3.org/ns/activitystreams#Public'], // TODO: implement proper scope address
//'cc' => $cc, 'cc' => ['https://www.w3.org/ns/activitystreams#Public'],
'object' => $activity->getObject()->getUrl(), 'object' => EntityToType::translate($activity->getObject()),
]; ];
return Type::create($attr); return Type::create($attr);
} }

View File

@ -22,9 +22,9 @@ class NoteToType
'id' => Router::url('note_view', ['id' => $note->getId()], Router::ABSOLUTE_URL), 'id' => Router::url('note_view', ['id' => $note->getId()], Router::ABSOLUTE_URL),
'published' => $note->getCreated()->format(DateTimeInterface::RFC3339), 'published' => $note->getCreated()->format(DateTimeInterface::RFC3339),
'attributedTo' => $note->getActor()->getUri(Router::ABSOLUTE_URL), 'attributedTo' => $note->getActor()->getUri(Router::ABSOLUTE_URL),
//'to' => $to, 'to' => ['https://www.w3.org/ns/activitystreams#Public'], // TODO: implement proper scope address
//'cc' => $cc, 'cc' => ['https://www.w3.org/ns/activitystreams#Public'],
'content' => json_encode($note->getRendered()), 'content' => $note->getRendered(),
//'tag' => $tags //'tag' => $tags
]; ];
return Type::create(type: 'Note', attributes: $attr); return Type::create(type: 'Note', attributes: $attr);

View File

@ -260,8 +260,8 @@ abstract class AbstractObject
public function toJson(?int $options = null): string public function toJson(?int $options = null): string
{ {
return json_encode( return json_encode(
$this->toArray(), value: $this->toArray(),
(int) $options, flags: (int) $options,
); );
} }

View File

@ -13,6 +13,8 @@ declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Type\Core; namespace Plugin\ActivityPub\Util\Type\Core;
use Plugin\ActivityPub\Util\Type;
/** /**
* \Plugin\ActivityPub\Util\Type\Core\Activity is an implementation of one of the * \Plugin\ActivityPub\Util\Type\Core\Activity is an implementation of one of the
* Activity Streams Core Types. * Activity Streams Core Types.
@ -39,5 +41,5 @@ class Activity extends AbstractActivity
* | Link * | Link
* | null * | null
*/ */
protected string $object; protected ObjectType $object;
} }