build / build (push) Successful in 5m18s
Upstream passed the app id as t()'s translatable string in declareApp, registering 'integration_gotosocial' as the public OAuth client name — which GTS shows under every status, and which the auth bridge made the name on ALL posts. client_name is now 'Pinnacle', website the pinnacle repo, and the proxy User-Agent strings match. The operator's existing GTS application rows were renamed in place (no reconnect needed).
385 lines
11 KiB
PHP
385 lines
11 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Nextcloud - mastodon
|
|
*
|
|
* This file is licensed under the Affero General Public License version 3 or
|
|
* later. See the COPYING file.
|
|
*
|
|
* @author Julien Veyssier
|
|
* @copyright Julien Veyssier 2020
|
|
*/
|
|
|
|
namespace OCA\GoToSocial\Service;
|
|
|
|
use DateTime;
|
|
use Exception;
|
|
use GuzzleHttp\Exception\ClientException;
|
|
use GuzzleHttp\Exception\ServerException;
|
|
use OCA\GoToSocial\AppInfo\Application;
|
|
use OCP\AppFramework\Services\IAppConfig;
|
|
use OCP\Http\Client\IClient;
|
|
use OCP\Http\Client\IClientService;
|
|
use OCP\IConfig;
|
|
use OCP\IL10N;
|
|
use OCP\Security\ICrypto;
|
|
use Psr\Log\LoggerInterface;
|
|
use Throwable;
|
|
|
|
/**
|
|
* Service to make requests to GoToSocial v1 API
|
|
*/
|
|
class MastodonAPIService {
|
|
|
|
private IClient $client;
|
|
|
|
public function __construct(
|
|
string $appName,
|
|
private LoggerInterface $logger,
|
|
private IL10N $l10n,
|
|
private IAppConfig $appConfig,
|
|
private IConfig $config,
|
|
private ICrypto $crypto,
|
|
IClientService $clientService,
|
|
) {
|
|
$this->client = $clientService->newClient();
|
|
}
|
|
|
|
/**
|
|
* @param string $userId
|
|
* @return string
|
|
*/
|
|
public function getGoToSocialUrl(string $userId): string {
|
|
$adminOauthUrl = $this->appConfig->getAppValueString('oauth_instance_url', lazy: true);
|
|
$mastodonUrl = $this->config->getUserValue($userId, Application::APP_ID, 'url', $adminOauthUrl) ?: $adminOauthUrl;
|
|
if ($mastodonUrl !== '' && substr($mastodonUrl, 0, 4) !== 'http') {
|
|
$mastodonUrl = 'https://' . $mastodonUrl;
|
|
}
|
|
return trim($mastodonUrl, "/ \n\r\t\v\x00");
|
|
}
|
|
|
|
/**
|
|
* @param string|null $userId
|
|
* @param ?int $since
|
|
* @return array
|
|
*/
|
|
public function getHomeTimeline(?string $userId, ?int $since = null): array {
|
|
$params = [
|
|
'limit' => 30
|
|
];
|
|
// get home timeline
|
|
if (!is_null($since)) {
|
|
$params['since_id'] = $since;
|
|
}
|
|
$home = $this->request($userId, 'timelines/home', $params);
|
|
if (!isset($home['error'])) {
|
|
foreach ($home as $key => $value) {
|
|
$home[$key]['type'] = 'home';
|
|
}
|
|
}
|
|
return $home;
|
|
}
|
|
|
|
/**
|
|
* @param string|null $userId
|
|
* @param ?int $since
|
|
* @return array
|
|
* @throws Exception
|
|
*/
|
|
public function getNotifications(?string $userId, ?int $since = null): array {
|
|
$params = [
|
|
'limit' => 30
|
|
];
|
|
|
|
// get notifications
|
|
if (!is_null($since)) {
|
|
$params['since_id'] = $since;
|
|
}
|
|
$params['exclude_types'] = ['poll'];
|
|
$notifications = $this->request($userId, 'notifications', $params);
|
|
|
|
if (!isset($notifications['error'])) {
|
|
// sort merged results by date
|
|
usort($notifications, function ($a, $b) {
|
|
$a = new DateTime($a['created_at']);
|
|
$ta = $a->getTimestamp();
|
|
$b = new DateTime($b['created_at']);
|
|
$tb = $b->getTimestamp();
|
|
return ($ta > $tb) ? -1 : 1;
|
|
});
|
|
}
|
|
|
|
return $notifications;
|
|
}
|
|
|
|
/**
|
|
* @param string $userId
|
|
* @param string $avatarUrl
|
|
* @return null|resource|string
|
|
* @throws Exception
|
|
*/
|
|
public function getGoToSocialAvatar(string $userId, string $avatarUrl) {
|
|
// read or get instance avatar URL
|
|
$instanceImageHostname = $this->config->getUserValue($userId, Application::APP_ID, 'instance_image_hostname');
|
|
$instanceContactImageHostname = $this->config->getUserValue($userId, Application::APP_ID, 'instance_contact_image_hostname');
|
|
|
|
$mastodonUrl = $this->getGoToSocialUrl($userId);
|
|
// check the avatar hostname is the same as the account avatar one or the mastodon instance one
|
|
$mUrl = parse_url($mastodonUrl);
|
|
$aUrl = parse_url($avatarUrl);
|
|
if ($aUrl['host'] === $instanceImageHostname
|
|
|| $aUrl['host'] === $instanceContactImageHostname
|
|
|| $aUrl['host'] === $mUrl['host']
|
|
) {
|
|
return $this->client->get($avatarUrl)->getBody();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* @param string|null $userId
|
|
* @param string $query
|
|
* @param string|null $type
|
|
* @param int $offset
|
|
* @param int $limit
|
|
* @return array
|
|
*/
|
|
public function search(?string $userId, string $query, ?string $type = null, int $offset = 0, int $limit = 5): array {
|
|
$params = [
|
|
'limit' => $limit,
|
|
'offset' => $offset,
|
|
'q' => $query,
|
|
];
|
|
if ($type !== null) {
|
|
$params['type'] = $type;
|
|
}
|
|
$searchResult = $this->request($userId, 'search', $params, 'GET', 2);
|
|
if ($type !== null) {
|
|
return $searchResult[$type] ?? $searchResult;
|
|
}
|
|
if (!isset($searchResult['error'])) {
|
|
$accounts = $searchResult['accounts'] ?? [];
|
|
$accounts = array_map(static function (array $entry) {
|
|
$entry['type'] = 'account';
|
|
return $entry;
|
|
}, $accounts);
|
|
|
|
$statuses = $searchResult['statuses'] ?? [];
|
|
$statuses = array_map(static function (array $entry) {
|
|
$entry['type'] = 'status';
|
|
return $entry;
|
|
}, $statuses);
|
|
|
|
$hashtags = $searchResult['hashtags'] ?? [];
|
|
$hashtags = array_map(static function (array $entry) {
|
|
$entry['type'] = 'hashtag';
|
|
return $entry;
|
|
}, $hashtags);
|
|
|
|
return array_merge($accounts, $statuses, $hashtags);
|
|
}
|
|
return $searchResult;
|
|
}
|
|
|
|
/**
|
|
* @param string $userId
|
|
* @param string $redirect_uri
|
|
* @return array
|
|
*/
|
|
public function declareApp(string $userId, string $redirect_uri): array {
|
|
$url = $this->getGoToSocialUrl($userId);
|
|
$params = [
|
|
// the PUBLIC client name — what GTS shows under every post.
|
|
// Not the Nextcloud app id (ops/features#36; upstream passed the
|
|
// app id as t()'s translatable string, registering it as the name)
|
|
'client_name' => 'Pinnacle',
|
|
'redirect_uris' => $redirect_uri,
|
|
'scopes' => 'read write follow',
|
|
'website' => 'https://code.bawnet.io/bawnet/pinnacle'
|
|
];
|
|
return $this->anonymousRequest($url, 'apps', $params, 'POST');
|
|
}
|
|
|
|
/**
|
|
* @param string $url
|
|
* @param string $endPoint
|
|
* @param array $params
|
|
* @param string $method
|
|
* @return array
|
|
*/
|
|
public function anonymousRequest(string $url, string $endPoint, array $params = [], string $method = 'GET'): array {
|
|
try {
|
|
$url = $url . '/api/v1/' . $endPoint;
|
|
$options = [
|
|
'headers' => [
|
|
'User-Agent' => 'Pinnacle (Nextcloud)',
|
|
]
|
|
];
|
|
|
|
if (count($params) > 0) {
|
|
if ($method === 'GET') {
|
|
$paramsContent = http_build_query($params);
|
|
$url .= '?' . $paramsContent;
|
|
} else {
|
|
$options['body'] = $params;
|
|
}
|
|
}
|
|
|
|
if ($method === 'GET') {
|
|
$response = $this->client->get($url, $options);
|
|
} elseif ($method === 'POST') {
|
|
$response = $this->client->post($url, $options);
|
|
} elseif ($method === 'PUT') {
|
|
$response = $this->client->put($url, $options);
|
|
} elseif ($method === 'DELETE') {
|
|
$response = $this->client->delete($url, $options);
|
|
} else {
|
|
return ['error' => $this->l10n->t('Bad HTTP method')];
|
|
}
|
|
$body = $response->getBody();
|
|
$respCode = $response->getStatusCode();
|
|
|
|
if ($respCode >= 400) {
|
|
return ['error' => $this->l10n->t('Bad credentials')];
|
|
} else {
|
|
return json_decode($body, true);
|
|
}
|
|
} catch (Exception|Throwable $e) {
|
|
$this->logger->warning('Mastodon API error : ' . $e->getMessage(), ['app' => Application::APP_ID]);
|
|
return ['error' => $e->getMessage()];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param string|null $userId
|
|
* @param string $endPoint
|
|
* @param array $params
|
|
* @param string $method
|
|
* @param int $apiVersion
|
|
* @return array
|
|
*/
|
|
public function request(?string $userId, string $endPoint, array $params = [], string $method = 'GET', int $apiVersion = 1): array {
|
|
$url = $this->getGoToSocialUrl($userId);
|
|
if (!$url) {
|
|
return ['error' => 'No GoToSocial instance configured'];
|
|
}
|
|
$accessToken = $this->config->getUserValue($userId, Application::APP_ID, 'token');
|
|
$accessToken = $accessToken === '' ? '' : $this->crypto->decrypt($accessToken);
|
|
if (!$accessToken) {
|
|
return ['error' => 'Not connected to any mastodon account'];
|
|
}
|
|
try {
|
|
$url = $url . '/api/v' . $apiVersion . '/' . $endPoint;
|
|
$options = [
|
|
'headers' => [
|
|
'Authorization' => 'Bearer ' . $accessToken,
|
|
'User-Agent' => 'Pinnacle (Nextcloud)',
|
|
]
|
|
];
|
|
|
|
if (count($params) > 0) {
|
|
if ($method === 'GET') {
|
|
// manage array parameters
|
|
$paramsContent = '';
|
|
foreach ($params as $key => $value) {
|
|
if (is_array($value)) {
|
|
foreach ($value as $oneArrayValue) {
|
|
$paramsContent .= $key . '[]=' . urlencode($oneArrayValue) . '&';
|
|
}
|
|
unset($params[$key]);
|
|
}
|
|
}
|
|
$paramsContent .= http_build_query($params);
|
|
$url .= '?' . $paramsContent;
|
|
} else {
|
|
$options['body'] = $params;
|
|
}
|
|
}
|
|
|
|
if ($method === 'GET') {
|
|
$response = $this->client->get($url, $options);
|
|
} elseif ($method === 'POST') {
|
|
$response = $this->client->post($url, $options);
|
|
} elseif ($method === 'PUT') {
|
|
$response = $this->client->put($url, $options);
|
|
} elseif ($method === 'DELETE') {
|
|
$response = $this->client->delete($url, $options);
|
|
} else {
|
|
return ['error' => $this->l10n->t('Bad HTTP method')];
|
|
}
|
|
$body = $response->getBody();
|
|
$respCode = $response->getStatusCode();
|
|
|
|
if ($respCode >= 400) {
|
|
return ['error' => $this->l10n->t('Bad credentials')];
|
|
} else {
|
|
return json_decode($body, true);
|
|
}
|
|
} catch (ClientException|ServerException $e) {
|
|
$responseBody = $e->getResponse()->getBody()->__toString();
|
|
$parsedResponseBody = json_decode($responseBody, true);
|
|
if ($e->getResponse()->getStatusCode() === 404) {
|
|
$this->logger->debug('Mastodon API error (404): ' . $e->getMessage(), ['response_body' => $responseBody, 'app' => Application::APP_ID]);
|
|
} else {
|
|
$this->logger->warning('Mastodon API error: ' . $e->getMessage(), ['response_body' => $responseBody, 'app' => Application::APP_ID]);
|
|
}
|
|
return [
|
|
'error' => $e->getMessage(),
|
|
'body' => $parsedResponseBody,
|
|
];
|
|
} catch (Exception|Throwable $e) {
|
|
$this->logger->debug('Mastodon API unknown error', ['exception' => $e]);
|
|
return ['error' => $e->getMessage()];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param string $mastodonUrl
|
|
* @param array $params
|
|
* @param string $method
|
|
* @return array
|
|
*/
|
|
public function requestOAuthAccessToken(string $mastodonUrl, array $params = [], string $method = 'GET'): array {
|
|
try {
|
|
$url = $mastodonUrl . '/oauth/token';
|
|
$options = [
|
|
'headers' => [
|
|
'User-Agent' => 'Pinnacle (Nextcloud)',
|
|
]
|
|
];
|
|
|
|
if (count($params) > 0) {
|
|
if ($method === 'GET') {
|
|
$paramsContent = http_build_query($params);
|
|
$url .= '?' . $paramsContent;
|
|
} else {
|
|
$options['body'] = $params;
|
|
}
|
|
}
|
|
|
|
if ($method === 'GET') {
|
|
$response = $this->client->get($url, $options);
|
|
} elseif ($method === 'POST') {
|
|
$response = $this->client->post($url, $options);
|
|
} elseif ($method === 'PUT') {
|
|
$response = $this->client->put($url, $options);
|
|
} elseif ($method === 'DELETE') {
|
|
$response = $this->client->delete($url, $options);
|
|
} else {
|
|
return ['error' => $this->l10n->t('Bad HTTP method')];
|
|
}
|
|
$body = $response->getBody();
|
|
$respCode = $response->getStatusCode();
|
|
|
|
if ($respCode >= 400) {
|
|
return ['error' => $this->l10n->t('OAuth access token refused')];
|
|
} else {
|
|
return json_decode($body, true);
|
|
}
|
|
} catch (Exception|Throwable $e) {
|
|
$this->logger->warning('GoToSocial OAuth error', ['exception' => $e]);
|
|
return ['error' => $e->getMessage()];
|
|
}
|
|
}
|
|
}
|