API: First steps to support subscriptions

This commit is contained in:
Michael 2021-08-15 00:30:41 +00:00
parent 1e305e748d
commit e28a4265c5
18 changed files with 416 additions and 20 deletions

View file

@ -319,6 +319,14 @@ abstract class DI
return self::$dice->create(Factory\Api\Mastodon\ScheduledStatus::class);
}
/**
* @return Factory\Api\Mastodon\Subscription
*/
public static function mstdnSubscription()
{
return self::$dice->create(Factory\Api\Mastodon\Subscription::class);
}
/**
* @return Factory\Api\Mastodon\ListEntity
*/

View file

@ -0,0 +1,41 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Factory\Api\Mastodon;
use Friendica\BaseFactory;
use Friendica\Database\DBA;
use Friendica\Model\Subscription as ModelSubscription;
class Subscription extends BaseFactory
{
/**
* @param int $applicationid Application Id
* @param int $uid Item user
*
* @return \Friendica\Object\Api\Mastodon\Status
*/
public function createForApplicationIdAndUserId(int $applicationid, int $uid): \Friendica\Object\Api\Mastodon\Subscription
{
$subscription = DBA::selectFirst('subscription', ['application-id' => $applicationid, 'uid' => $uid]);
return new \Friendica\Object\Api\Mastodon\Subscription($subscription, ModelSubscription::getVapidKey());
}
}

View file

@ -0,0 +1,66 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Model;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Util\Crypto;
class Subscription
{
/**
* Insert an Subscription record
*
* @param array $fields subscription fields
*
* @return bool result of replace
*/
public static function replace(array $fields)
{
return DBA::replace('subscription', $fields);
}
/**
* Delete a subscription record
* @param int $applicationid
* @param int $uid
* @return bool
*/
public static function delete(int $applicationid, int $uid)
{
return DBA::delete('subscription', ['application-id' => $applicationid, 'uid' => $uid]);
}
/**
* Fetch a VAPID key
* @return string
*/
public static function getVapidKey():string
{
$keypair = DI::config()->get('system', 'ec_keypair');
if (empty($keypair)) {
$keypair = Crypto::newECKeypair();
DI::config()->set('system', 'ec_keypair', $keypair);
}
return $keypair['vapid'];
}
}

View file

@ -49,8 +49,6 @@ class Followers extends BaseApi
DI::mstdnError()->RecordNotFound();
}
// @todo provide HTTP link header
$request = self::getRequest([
'max_id' => 0, // Return results older than this id
'since_id' => 0, // Return results newer than this id

View file

@ -49,8 +49,6 @@ class Following extends BaseApi
DI::mstdnError()->RecordNotFound();
}
// @todo provide HTTP link header
$request = self::getRequest([
'max_id' => 0, // Return results older than this id
'since_id' => 0, // Return results newer than this id

View file

@ -49,8 +49,6 @@ class Blocks extends BaseApi
DI::mstdnError()->RecordNotFound();
}
// @todo provide HTTP link header
$request = self::getRequest([
'max_id' => 0, // Return results older than this id
'since_id' => 0, // Return results newer than this id

View file

@ -43,8 +43,6 @@ class Favourited extends BaseApi
self::checkAllowedScope(self::SCOPE_READ);
$uid = self::getCurrentUserID();
// @todo provide HTTP link header
$request = self::getRequest([
'limit' => 20, // Maximum number of results to return. Defaults to 20.
'min_id' => 0, // Return results immediately newer than id

View file

@ -62,8 +62,6 @@ class Accounts extends BaseApi
DI::mstdnError()->RecordNotFound();
}
// @todo provide HTTP link header
$request = self::getRequest([
'max_id' => 0, // Return results older than this id
'since_id' => 0, // Return results newer than this id

View file

@ -49,8 +49,6 @@ class Mutes extends BaseApi
DI::mstdnError()->RecordNotFound();
}
// @todo provide HTTP link header
$request = self::getRequest([
'max_id' => 0, // Return results older than this id
'since_id' => 0, // Return results newer than this id

View file

@ -0,0 +1,97 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Module\Api\Mastodon;
use Friendica\App\Router;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\DI;
use Friendica\Model\Subscription;
use Friendica\Module\BaseApi;
/**
* @see https://docs.joinmastodon.org/methods/notifications/push/
*/
class PushSubscription extends BaseApi
{
public static function post(array $parameters = [])
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
$application = self::getCurrentApplication();
$request = self::getRequest([
'subscription' => [],
'data' => [],
]);
$subscription = [
'application-id' => $application['id'],
'uid' => $uid,
'endpoint' => $request['subscription']['endpoint'] ?? '',
'pubkey' => $request['subscription']['keys']['p256dh'] ?? '',
'secret' => $request['subscription']['keys']['auth'] ?? '',
'follow' => $request['data']['alerts']['follow'] ?? false,
'favourite' => $request['data']['alerts']['favourite'] ?? false,
'reblog' => $request['data']['alerts']['reblog'] ?? false,
'mention' => $request['data']['alerts']['mention'] ?? false,
'poll' => $request['data']['alerts']['poll'] ?? false,
'follow_request' => $request['data']['alerts']['follow_request'] ?? false,
'status' => $request['data']['alerts']['status'] ?? false,
];
$ret = Subscription::replace($subscription);
Logger::info('Subscription stored', ['ret' => $ret, 'subscription' => $subscription]);
return DI::mstdnSubscription()->createForApplicationIdAndUserId($application['id'], $uid)->toArray();
}
public static function put(array $parameters = [])
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
$application = self::getCurrentApplication();
self::unsupported(Router::PUT);
}
public static function delete(array $parameters = [])
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
$application = self::getCurrentApplication();
Subscription::delete($application['id'], $uid);
System::jsonExit([]);
}
public static function rawContent(array $parameters = [])
{
self::checkAllowedScope(self::SCOPE_PUSH);
$uid = self::getCurrentUserID();
$application = self::getCurrentApplication();
return DI::mstdnSubscription()->createForApplicationIdAndUserId($application['id'], $uid)->toArray();
}
}

View file

@ -0,0 +1,63 @@
<?php
/**
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Object\Api\Mastodon;
use Friendica\BaseDataTransferObject;
/**
* Class Subscription
*
* @see https://docs.joinmastodon.org/entities/pushsubscription
*/
class Subscription extends BaseDataTransferObject
{
/** @var string */
protected $id;
/** @var string|null (URL)*/
protected $endpoint;
/** @var array */
protected $alerts;
/** @var string */
protected $server_key;
/**
* Creates a subscription record from an item record.
*
* @param array $subscription
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public function __construct(array $subscription, string $vapid)
{
$this->id = (string)$subscription['id'];
$this->endpoint = $subscription['endpoint'];
$this->alerts = [
'follow' => $subscription['follow'],
'favourite' => $subscription['favourite'],
'reblog' => $subscription['reblog'],
'mention' => $subscription['mention'],
'mention' => $subscription['mention'],
'poll' => $subscription['poll'],
];
$this->server_key = $vapid;
}
}

View file

@ -25,6 +25,7 @@ use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\DI;
use ParagonIE\ConstantTime\Base64UrlSafe;
use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;
@ -150,6 +151,48 @@ class Crypto
return $response;
}
/**
* Create a new elliptic curve key pair
*
* @return array with the elements "prvkey", "vapid" and "pubkey"
*/
public static function newECKeypair()
{
$openssl_options = [
'curve_name' => 'prime256v1',
'private_key_type' => OPENSSL_KEYTYPE_EC
];
$conf = DI::config()->get('system', 'openssl_conf_file');
if ($conf) {
$openssl_options['config'] = $conf;
}
$result = openssl_pkey_new($openssl_options);
if (empty($result)) {
Logger::notice('new_keypair: failed');
return [];
}
$response = ['prvkey' => '', 'pubkey' => '', 'vapid' => ''];
// Get private key
openssl_pkey_export($result, $response['prvkey']);
// Get public key
$pkey = openssl_pkey_get_details($result);
$response['pubkey'] = $pkey['key'];
// Create VAPID key
// @see https://github.com/web-push-libs/web-push-php/blob/256a18b2a2411469c94943725fb6eccb9681bd75/src/Utils.php#L60-L62
$hexString = '04';
$hexString .= str_pad(bin2hex($pkey['ec']['x']), 64, '0', STR_PAD_LEFT);
$hexString .= str_pad(bin2hex($pkey['ec']['y']), 64, '0', STR_PAD_LEFT);
$response['vapid'] = Base64UrlSafe::encode(hex2bin($hexString));
return $response;
}
/**
* Encrypt a string with 'aes-256-cbc' cipher method.
*