]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/ActivityPub.php
Contact follow and unfollow workd partially
[friendica.git] / src / Protocol / ActivityPub.php
index 54c479b50c4ecb6ea547f5e66b8f8671ce27d942..78d5d44daff8fc82f58402348089a2f3f12d70e2 100644 (file)
@@ -32,6 +32,23 @@ use Friendica\Network\Probe;
  *
  * Digest: https://tools.ietf.org/html/rfc5843
  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
+ *
+ * Part of the code for HTTP signing is taken from the Osada project.
+ * 
+ *
+ * To-do:
+ *
+ * Receiver:
+ * - Activities: Undo, Update
+ * - Object Types: Person, Tombstome
+ *
+ * Transmitter:
+ * - Activities: Like, Dislike, Update, Undo
+ * - Object Tyoes: Article, Announce, Person, Tombstone
+ *
+ * General:
+ * - Message distribution
+ * - Endpoints: Outbox, Object, Follower, Following
  */
 class ActivityPub
 {
@@ -63,7 +80,7 @@ class ActivityPub
                Network::post($target, $content, $headers);
                $return_code = BaseObject::getApp()->get_curl_code();
 
-               echo $return_code."\n";
+               logger('Transmit to ' . $target . ' returned ' . $return_code);
        }
 
        /**
@@ -136,7 +153,7 @@ class ActivityPub
                        'toot' => 'http://joinmastodon.org/ns#']]];
 
                $data['type'] = 'Create';
-               $data['id'] = $item['plink'];
+               $data['id'] = $item['uri'];
                $data['actor'] = $item['author-link'];
                $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
                $data['object'] = self::createNote($item);
@@ -147,18 +164,31 @@ class ActivityPub
        {
                $data = [];
                $data['type'] = 'Note';
-               $data['id'] = $item['plink'];
-               //$data['context'] = $data['conversation'] = $item['parent-uri'];
+               $data['id'] = $item['uri'];
+
+               if ($item['uri'] != $item['thr-parent']) {
+                       $data['inReplyTo'] = $item['thr-parent'];
+               }
+
+               $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
+               if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
+                       $conversation_uri = $conversation['conversation-uri'];
+               } else {
+                       $conversation_uri = $item['parent-uri'];
+               }
+
+               $data['context'] = $data['conversation'] = $conversation_uri;
                $data['actor'] = $item['author-link'];
                $data['to'] = [];
                if (!$item['private']) {
-                       $data['to'][] = '"https://pleroma.soykaf.com/users/heluecht"';
+                       $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
                }
                $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
                $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
                $data['attributedTo'] = $item['author-link'];
                $data['name'] = BBCode::convert($item['title'], false, 7);
                $data['content'] = BBCode::convert($item['body'], false, 7);
+               $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
                //$data['summary'] = ''; // Ignore by now
                //$data['sensitive'] = false; // - Query NSFW
                //$data['emoji'] = []; // Ignore by now
@@ -174,11 +204,33 @@ class ActivityPub
                $owner = User::getOwnerDataById($uid);
 
                $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
-                       'id' => 'https://pirati.ca/' . strtolower($activity) . '/' . System::createGUID(),
+                       'id' => 'https://pirati.ca/activity/' . System::createGUID(),
                        'type' => $activity,
                        'actor' => $owner['url'],
                        'object' => $profile['url']];
 
+               logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
+               return self::transmit($data,  $profile['notify'], $uid);
+       }
+
+       public static function transmitContactActivity($activity, $target, $id, $uid)
+       {
+               $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+               if (empty($id)) {
+                       $id = 'https://pirati.ca/activity/' . System::createGUID();
+               }
+
+               $owner = User::getOwnerDataById($uid);
+               $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+                       'id' => 'https://pirati.ca/activity/' . System::createGUID(),
+                       'type' => $activity,
+                       'actor' => $owner['url'],
+                       'object' => ['id' => $id, 'type' => 'Follow',
+                               'actor' => $owner['url'],
+                               'object' => $profile['url']]];
+
+               logger('Sending ' . $activity . ' to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
                return self::transmit($data,  $profile['notify'], $uid);
        }
 
@@ -473,9 +525,9 @@ class ActivityPub
                return $profile;
        }
 
-       public static function processInbox($body, $header)
+       public static function processInbox($body, $header, $uid)
        {
-               logger('Incoming message', LOGGER_DEBUG);
+               logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
 
                if (!self::verifySignature($body, $header)) {
                        logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
@@ -489,7 +541,7 @@ class ActivityPub
                        return;
                }
 
-               self::processActivity($activity, $body);
+               self::processActivity($activity, $body, $uid);
        }
 
        public static function fetchOutbox($url)
@@ -515,7 +567,7 @@ class ActivityPub
                }
        }
 
-       function processActivity($activity, $body = '')
+       function processActivity($activity, $body = '', $uid = null)
        {
                if (empty($activity['type'])) {
                        logger('Empty type', LOGGER_DEBUG);
@@ -548,12 +600,6 @@ class ActivityPub
                        return;
                }
 
-               $receivers = self::getReceivers($activity);
-               if (empty($receivers)) {
-                       logger('No receivers found', LOGGER_DEBUG);
-                       return;
-               }
-
                // ----------------------------------
 /*
                // unhandled
@@ -571,15 +617,36 @@ class ActivityPub
                unset($activity['location']);
                unset($activity['signature']);
 */
+               // Fetch all receivers from to, cc, bto and bcc
+               $receivers = self::getReceivers($activity);
+
+               // When it is a delivery to a personal inbox we add that user to the receivers
+               if (!empty($uid)) {
+                       $owner = User::getOwnerDataById($uid);
+                       $additional = [$owner['url'] => $uid];
+                       $receivers = array_merge($receivers, $additional);
+               }
+
+               logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
+
+               logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
 
-               if (!in_array($activity['type'], ['Like', 'Dislike'])) {
+               // Fetch the content only on activities where this matters
+               if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
                        $item = self::fetchObject($object_url, $activity['object']);
                        if (empty($item)) {
                                logger("Object data couldn't be processed", LOGGER_DEBUG);
                                return;
                        }
                } else {
-                       $item['object'] = $object_url;
+                       if (in_array($activity['type'], ['Accept'])) {
+                               $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
+                       } elseif (in_array($activity['type'], ['Undo'])) {
+                               $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
+                       } else {
+                               $item['object'] = $object_url;
+                       }
+                       $item['id'] = $activity['id'];
                        $item['receiver'] = [];
                        $item['type'] = $activity['type'];
                }
@@ -590,8 +657,6 @@ class ActivityPub
 
                $item['receiver'] = array_merge($item['receiver'], $receivers);
 
-               logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
-
                switch ($activity['type']) {
                        case 'Create':
                        case 'Update':
@@ -600,11 +665,25 @@ class ActivityPub
                                break;
 
                        case 'Like':
+                               self::likeItem($item, $body);
+                               break;
+
                        case 'Dislike':
-                               self::activityItem($item, $body);
+                               break;
+
+                       case 'Delete':
                                break;
 
                        case 'Follow':
+                               self::followUser($item);
+                               break;
+
+                       case 'Accept':
+                               self::acceptFollowUser($item);
+                               break;
+
+                       case 'Undo':
+                               self::undoFollowUser($item);
                                break;
 
                        default:
@@ -659,7 +738,7 @@ class ActivityPub
                }
 
                if (!empty($activity['instrument'])) {
-                       $item['service'] = self::processElement($activity, 'instrument', 'name', 'Service');
+                       $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
                }
                return $item;
        }
@@ -670,19 +749,28 @@ class ActivityPub
                if (empty($data)) {
                        $data = $object;
                        if (empty($data)) {
-                               logger('Empty content');
+                               logger('Empty content', LOGGER_DEBUG);
                                return false;
+                       } elseif (is_string($data)) {
+                               logger('No object array provided.', LOGGER_DEBUG);
+                               $item = Item::selectFirst([], ['uri' => $data]);
+                               if (!DBA::isResult($item)) {
+                                       logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
+                                       return false;
+                               }
+                               logger('Using already stored item', LOGGER_DEBUG);
+                               $data = self::createNote($item);
                        } else {
-                               logger('Using provided object');
+                               logger('Using provided object', LOGGER_DEBUG);
                        }
                }
 
                if (empty($data['type'])) {
-                       logger('Empty type');
+                       logger('Empty type', LOGGER_DEBUG);
                        return false;
                } else {
                        $type = $data['type'];
-                       logger('Type ' . $type);
+                       logger('Type ' . $type, LOGGER_DEBUG);
                }
 
                if (in_array($type, ['Note', 'Article', 'Video'])) {
@@ -745,10 +833,11 @@ class ActivityPub
                $item['name'] = defaults($object, 'name', $item['name']);
                $item['summary'] = defaults($object, 'summary', null);
                $item['content'] = defaults($object, 'content', null);
-               $item['location'] = self::processElement($object, 'location', 'name', 'Place');
+               $item['source'] = defaults($object, 'source', null);
+               $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
                $item['attachments'] = defaults($object, 'attachment', null);
                $item['tags'] = defaults($object, 'tag', null);
-               $item['service'] = self::processElement($object, 'instrument', 'name', 'Service');
+               $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
                $item['alternate-url'] = self::processElement($object, 'url', 'href');
                $item['receiver'] = self::getReceivers($object);
 
@@ -828,7 +917,7 @@ class ActivityPub
                return $item;
        }
 
-       private static function processElement($array, $element, $key, $type = null)
+       private static function processElement($array, $element, $key, $type = null, $type_value = null)
        {
                if (empty($array)) {
                        return false;
@@ -842,7 +931,7 @@ class ActivityPub
                        return $array[$element];
                }
 
-               if (is_null($type)) {
+               if (is_null($type_value)) {
                        if (!empty($array[$element][$key])) {
                                return $array[$element][$key];
                        }
@@ -854,7 +943,7 @@ class ActivityPub
                        return false;
                }
 
-               if (!empty($array[$element][$key]) && !empty($array[$element]['type']) && ($array[$element]['type'] == $type)) {
+               if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
                        return $array[$element][$key];
                }
 
@@ -921,17 +1010,41 @@ class ActivityPub
 
        private static function createItem($activity, $body)
        {
-               /// @todo What to do with $activity['context']?
+               $item = [];
+               $item['verb'] = ACTIVITY_POST;
+               $item['parent-uri'] = $activity['reply-to-uri'];
+
+               if ($activity['reply-to-uri'] == $activity['uri']) {
+                       $item['gravity'] = GRAVITY_PARENT;
+                       $item['object-type'] = ACTIVITY_OBJ_NOTE;
+               } else {
+                       $item['gravity'] = GRAVITY_COMMENT;
+                       $item['object-type'] = ACTIVITY_OBJ_COMMENT;
+               }
+
+               self::postItem($activity, $item, $body);
+       }
 
+       private static function likeItem($activity, $body)
+       {
                $item = [];
+               $item['verb'] = ACTIVITY_LIKE;
+               $item['parent-uri'] = $activity['object'];
+               $item['gravity'] = GRAVITY_ACTIVITY;
+               $item['object-type'] = ACTIVITY_OBJ_NOTE;
+
+               self::postItem($activity, $item, $body);
+       }
+
+       private static function postItem($activity, $item, $body)
+       {
+               /// @todo What to do with $activity['context']?
+
                $item['network'] = Protocol::ACTIVITYPUB;
                $item['private'] = !in_array(0, $activity['receiver']);
                $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
                $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
                $item['uri'] = $activity['uri'];
-               $item['parent-uri'] = $activity['reply-to-uri'];
-               $item['verb'] = ACTIVITY_POST;
-               $item['object-type'] = ACTIVITY_OBJ_NOTE; /// Todo?
                $item['created'] = $activity['published'];
                $item['edited'] = $activity['updated'];
                $item['guid'] = $activity['uuid'];
@@ -945,6 +1058,11 @@ class ActivityPub
 
                $item = self::constructAttachList($activity['attachments'], $item);
 
+               $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
+               if (!empty($source)) {
+                       $item['body'] = $source;
+               }
+
                $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
                $item['source'] = $body;
                $item['conversation-uri'] = $activity['conversation'];
@@ -965,16 +1083,82 @@ class ActivityPub
                }
        }
 
-       private static function activityItem($data)
+       private static function followUser($activity)
+       {
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
+               }
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (!empty($cid)) {
+                       $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+               } else {
+                       $contact = false;
+               }
+
+               $item = ['author-id' => Contact::getIdForURL($activity['owner'])];
+
+               Contact::addRelationship($owner, $contact, $item);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       return;
+               }
+
+               $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
+               if ($contact['network'] != Protocol::ACTIVITYPUB) {
+                       Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
+               }
+
+               DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
+               logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
+       }
+
+       private static function acceptFollowUser($activity)
        {
-               logger('Activity "' . $data['type'] . '" for ' . $data['object']);
-               $items = Item::select(['id'], ['uri' => $data['object']]);
-               while ($item = Item::fetch($items)) {
-                       logger('Activity ' . $data['type'] . ' for item ' . $item['id'], LOGGER_DEBUG);
-                       Item::performLike($item['id'], strtolower($data['type']));
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
                }
-               DBA::close($item);
-               logger('Activity done');
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+                       return;
+               }
+
+               $fields = ['pending' => false];
+               $condition = ['id' => $cid, 'pending' => true];
+               DBA::update('comtact', $fields, $condition);
+               logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
        }
 
+       private static function undoFollowUser($activity)
+       {
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
+               }
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+                       return;
+               }
+
+               $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+               if (!DBA::isResult($contact)) {
+                       return;
+               }
+
+               Contact::removeFollower($owner, $contact);
+               logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
+       }
 }