Merge pull request #14103 from annando/api-channel-list

API: Access channels and groups via lists
This commit is contained in:
Hypolite Petovan 2024-04-19 18:16:34 -04:00 committed by GitHub
commit fe9ef20392
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 160 additions and 41 deletions

View file

@ -22,6 +22,7 @@
namespace Friendica\Factory\Api\Mastodon; namespace Friendica\Factory\Api\Mastodon;
use Friendica\BaseFactory; use Friendica\BaseFactory;
use Friendica\Content\Conversation\Entity\Timeline;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -45,4 +46,14 @@ class ListEntity extends BaseFactory
$circle = $this->dba->selectFirst('group', ['name'], ['id' => $id, 'deleted' => false]); $circle = $this->dba->selectFirst('group', ['name'], ['id' => $id, 'deleted' => false]);
return new \Friendica\Object\Api\Mastodon\ListEntity($id, $circle['name'] ?? '', 'list'); return new \Friendica\Object\Api\Mastodon\ListEntity($id, $circle['name'] ?? '', 'list');
} }
public function createFromChannel(Timeline $channel): \Friendica\Object\Api\Mastodon\ListEntity
{
return new \Friendica\Object\Api\Mastodon\ListEntity('channel:' . $channel->code, $channel->label, 'followed');
}
public function createFromGroup(array $group): \Friendica\Object\Api\Mastodon\ListEntity
{
return new \Friendica\Object\Api\Mastodon\ListEntity('group:' . $group['id'], $group['name'], 'followed');
}
} }

View file

@ -21,16 +21,36 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\System; use Friendica\App;
use Friendica\Core\L10n;
use Friendica\DI; use Friendica\DI;
use Friendica\Content\Conversation\Factory\Channel as ChannelFactory;
use Friendica\Content\Conversation\Repository;
use Friendica\Content\GroupManager;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Model\Circle; use Friendica\Model\Circle;
use Friendica\Module\Api\ApiResponse;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/** /**
* @see https://docs.joinmastodon.org/methods/timelines/lists/ * @see https://docs.joinmastodon.org/methods/timelines/lists/
*/ */
class Lists extends BaseApi class Lists extends BaseApi
{ {
/** @var ChannelFactory */
protected $channel;
/** @var Repository\UserDefinedChannel */
protected $userDefinedChannel;
public function __construct(Repository\UserDefinedChannel $userDefinedChannel, ChannelFactory $channel, \Friendica\Factory\Api\Mastodon\Error $errorFactory, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($errorFactory, $app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->channel = $channel;
$this->userDefinedChannel = $userDefinedChannel;
}
protected function delete(array $request = []) protected function delete(array $request = [])
{ {
$this->checkAllowedScope(self::SCOPE_WRITE); $this->checkAllowedScope(self::SCOPE_WRITE);
@ -102,6 +122,18 @@ class Lists extends BaseApi
foreach (Circle::getByUserId($uid) as $circle) { foreach (Circle::getByUserId($uid) as $circle) {
$lists[] = DI::mstdnList()->createFromCircleId($circle['id']); $lists[] = DI::mstdnList()->createFromCircleId($circle['id']);
} }
foreach ($this->channel->getTimelines($uid) as $channel) {
$lists[] = DI::mstdnList()->createFromChannel($channel);
}
foreach ($this->userDefinedChannel->selectByUid($uid) as $channel) {
$lists[] = DI::mstdnList()->createFromChannel($channel);
}
foreach (GroupManager::getList($uid, true, true, true) as $group) {
$lists[] = DI::mstdnList()->createFromGroup($group);
}
} else { } else {
$id = $this->parameters['id']; $id = $this->parameters['id'];

View file

@ -21,21 +21,39 @@
namespace Friendica\Module\Api\Mastodon\Timelines; namespace Friendica\Module\Api\Mastodon\Timelines;
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Conversation;
use Friendica\Model\Item; use Friendica\Model\Item;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Model\Verb;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Module\Conversation\Timeline;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Object\Api\Mastodon\TimelineOrderByTypes; use Friendica\Object\Api\Mastodon\TimelineOrderByTypes;
use Friendica\Protocol\Activity;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/** /**
* @see https://docs.joinmastodon.org/methods/timelines/ * @see https://docs.joinmastodon.org/methods/timelines/
*/ */
class ListTimeline extends BaseApi class ListTimeline extends BaseApi
{ {
/** @var Timeline */
protected $timeline;
public function __construct(Timeline $timeline, \Friendica\Factory\Api\Mastodon\Error $errorFactory, App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($errorFactory, $app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->timeline = $timeline;
}
/** /**
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
@ -61,6 +79,70 @@ class ListTimeline extends BaseApi
'friendica_order' => TimelineOrderByTypes::ID, // Sort order options (defaults to ID) 'friendica_order' => TimelineOrderByTypes::ID, // Sort order options (defaults to ID)
], $request); ], $request);
$display_quotes = self::appSupportsQuotes();
if (substr($this->parameters['id'], 0, 6) == 'group:') {
$items = $this->getStatusesForGroup($uid, $request);
} elseif (substr($this->parameters['id'], 0, 8) == 'channel:') {
$items = $this->getStatusesForChannel($uid, $request);
} else{
$items = $this->getStatusesForCircle($uid, $request);
}
$statuses = [];
foreach ($items as $item) {
try {
$status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
$this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status;
} catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
}
}
if (!empty($request['min_id'])) {
$statuses = array_reverse($statuses);
}
self::setLinkHeader($request['friendica_order'] != TimelineOrderByTypes::ID);
$this->jsonExit($statuses);
}
private function getStatusesForGroup(int $uid, array $request): array
{
$cdata = Contact::getPublicAndUserContactID((int)substr($this->parameters['id'], 6), $uid);
$cid = $cdata['public'];
$condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, $uid];
$condition1 = DBA::mergeConditions($condition, ["`owner-id` = ? AND `gravity` = ?", $cid, Item::GRAVITY_PARENT]);
$condition2 = DBA::mergeConditions($condition, [
"`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`",
$cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA
]);
$condition1 = $this->addPagingConditions($request, $condition1);
$condition2 = $this->addPagingConditions($request, $condition2);
$sql1 = "SELECT `uri-id` FROM `post-thread-user-view` WHERE " . array_shift($condition1);
$sql2 = "SELECT `thr-parent-id` AS `uri-id` FROM `post-user-view` WHERE " . array_shift($condition2);
$condition = array_merge($condition1, $condition2);
$sql = $sql1 . " UNION " . $sql2 . " GROUP BY `uri-id` " . DBA::buildParameter($this->buildOrderAndLimitParams($request));
return Post::toArray(DBA::p($sql, $condition));
}
private function getStatusesForChannel(int $uid, array $request): array
{
$request['friendica_order'] = TimelineOrderByTypes::ID;
return $this->timeline->getChannelItemsForAPI(substr($this->parameters['id'], 8), $uid, $request['limit'], $request['min_id'], $request['max_id']);
}
private function getStatusesForCircle(int $uid, array $request): array
{
$condition = [ $condition = [
"`uid` = ? AND `gravity` IN (?, ?) AND `contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)", "`uid` = ? AND `gravity` IN (?, ?) AND `contact-id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)",
$uid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, $this->parameters['id'] $uid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, $this->parameters['id']
@ -89,26 +171,6 @@ class ListTimeline extends BaseApi
} }
$items = Post::selectTimelineForUser($uid, ['uri-id'], $condition, $params); $items = Post::selectTimelineForUser($uid, ['uri-id'], $condition, $params);
return Post::toArray($items);
$display_quotes = self::appSupportsQuotes();
$statuses = [];
while ($item = Post::fetch($items)) {
try {
$status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
$this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status;
} catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
}
}
DBA::close($items);
if (!empty($request['min_id'])) {
$statuses = array_reverse($statuses);
}
self::setLinkHeader($request['friendica_order'] != TimelineOrderByTypes::ID);
$this->jsonExit($statuses);
} }
} }

View file

@ -128,7 +128,7 @@ class Channel extends Timeline
} }
if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) { if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
$items = $this->getChannelItems($request); $items = $this->getChannelItems($request, $this->session->getLocalUserId());
$order = 'created'; $order = 'created';
} else { } else {
$items = $this->getCommunityItems(); $items = $this->getCommunityItems();

View file

@ -225,7 +225,7 @@ class Network extends Timeline
try { try {
if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) { if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
$items = $this->getChannelItems($request); $items = $this->getChannelItems($request, $this->session->getLocalUserId());
} elseif ($this->community->isTimeline($this->selectedTab)) { } elseif ($this->community->isTimeline($this->selectedTab)) {
$items = $this->getCommunityItems(); $items = $this->getCommunityItems();
} else { } else {

View file

@ -95,7 +95,7 @@ class Timeline extends BaseModule
/** @var UserDefinedChannel */ /** @var UserDefinedChannel */
protected $channelRepository; protected $channelRepository;
public function __construct(UserDefinedChannel $channel, Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = []) public function __construct(UserDefinedChannel $channel, Mode $mode, IHandleUserSessions $session, Database $database, IManagePersonalConfigValues $pConfig, IManageConfigValues $config, ICanCache $cache, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server = [], array $parameters = [])
{ {
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters); parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
@ -167,7 +167,7 @@ class Timeline extends BaseModule
$this->maxId = $request['last_created'] ?? $this->maxId; $this->maxId = $request['last_created'] ?? $this->maxId;
$this->minId = $request['first_created'] ?? $this->minId; $this->minId = $request['first_created'] ?? $this->minId;
break; break;
case 'uriid': case 'uri-id':
$this->maxId = $request['last_uriid'] ?? $this->maxId; $this->maxId = $request['last_uriid'] ?? $this->maxId;
$this->minId = $request['first_uriid'] ?? $this->minId; $this->minId = $request['first_uriid'] ?? $this->minId;
break; break;
@ -229,15 +229,29 @@ class Timeline extends BaseModule
return $tabs; return $tabs;
} }
public function getChannelItemsForAPI(string $channel, int $uid, int $limit, int $min = null, int $max = null): array
{
$this->itemsPerPage = $limit;
$this->itemUriId = 0;
$this->maxId = $max;
$this->minId = $min;
$this->noSharer = false;
$this->order = 'uri-id';
$this->ping = false;
$this->selectedTab = $channel;
return $this->getChannelItems([], $uid);
}
/** /**
* Database query for the channel page * Database query for the channel page
* *
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
protected function getChannelItems(array $request) protected function getChannelItems(array $request, int $uid): array
{ {
$items = $this->getRawChannelItems($request); $items = $this->getRawChannelItems($request, $uid);
$total = min(count($items), $this->itemsPerPage); $total = min(count($items), $this->itemsPerPage);
$contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]); $contacts = $this->database->selectToArray('user-contact', ['cid'], ['channel-frequency' => Contact\User::FREQUENCY_REDUCED, 'cid' => array_column($items, 'owner-id')]);
@ -284,14 +298,14 @@ class Timeline extends BaseModule
} }
if (count($selected_items) < $total) { if (count($selected_items) < $total) {
$items = $this->getRawChannelItems($request); $items = $this->getRawChannelItems($request, $uid);
} }
} }
} else { } else {
$selected_items = $items; $selected_items = $items;
} }
$condition = ['unseen' => true, 'uid' => $this->session->getLocalUserId(), 'parent-uri-id' => array_column($selected_items, 'uri-id')]; $condition = ['unseen' => true, 'uid' => $uid, 'parent-uri-id' => array_column($selected_items, 'uri-id')];
$this->setItemsSeenByCondition($condition); $this->setItemsSeenByCondition($condition);
return $selected_items; return $selected_items;
@ -303,10 +317,8 @@ class Timeline extends BaseModule
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
private function getRawChannelItems(array $request) private function getRawChannelItems(array $request, int $uid): array
{ {
$uid = $this->session->getLocalUserId();
$table = 'post-engagement'; $table = 'post-engagement';
if ($this->selectedTab == ChannelEntity::WHATSHOT) { if ($this->selectedTab == ChannelEntity::WHATSHOT) {

View file

@ -88,7 +88,7 @@ class Network extends NetworkModule
$this->itemsPerPage = 100; $this->itemsPerPage = 100;
if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) { if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
$items = $this->getChannelItems($request); $items = $this->getChannelItems($request, $this->session->getLocalUserId());
} elseif ($this->community->isTimeline($this->selectedTab)) { } elseif ($this->community->isTimeline($this->selectedTab)) {
$items = $this->getCommunityItems(); $items = $this->getCommunityItems();
} else { } else {

View file

@ -39,7 +39,7 @@ class Channel extends ChannelModule
$o = ''; $o = '';
if ($this->update || $this->force) { if ($this->update || $this->force) {
if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) { if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
$items = $this->getChannelItems($request); $items = $this->getChannelItems($request, $this->session->getLocalUserId());
} else { } else {
$items = $this->getCommunityItems(); $items = $this->getCommunityItems();
} }

View file

@ -42,7 +42,7 @@ class Network extends NetworkModule
} }
if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) { if ($this->channel->isTimeline($this->selectedTab) || $this->userDefinedChannel->isTimeline($this->selectedTab, $this->session->getLocalUserId())) {
$items = $this->getChannelItems($request); $items = $this->getChannelItems($request, $this->session->getLocalUserId());
} elseif ($this->community->isTimeline($this->selectedTab)) { } elseif ($this->community->isTimeline($this->selectedTab)) {
$items = $this->getCommunityItems(); $items = $this->getCommunityItems();
} else { } else {

View file

@ -34,6 +34,8 @@ class ListEntity extends BaseDataTransferObject
protected $id; protected $id;
/** @var string */ /** @var string */
protected $title; protected $title;
/** @var string */
protected $replies_policy;
/** /**
* Creates an list record * Creates an list record
@ -42,9 +44,9 @@ class ListEntity extends BaseDataTransferObject
* @param string $title * @param string $title
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public function __construct(int $id, string $title, string $policy) public function __construct(string $id, string $title, string $policy)
{ {
$this->id = (string)$id; $this->id = $id;
$this->title = $title; $this->title = $title;
$this->replies_policy = $policy; $this->replies_policy = $policy;
} }

View file

@ -160,7 +160,7 @@ class Status extends BaseDataTransferObject
/** /**
* Returns the current created_at string or null if not set * Returns the current created_at string or null if not set
* @return \DateTime|null * @return ?string
*/ */
public function createdAt(): ?string public function createdAt(): ?string
{ {

View file

@ -308,7 +308,7 @@ return [
'/tags/{hashtag}/unfollow' => [Module\Api\Mastodon\Tags\Unfollow::class, [ R::POST]], '/tags/{hashtag}/unfollow' => [Module\Api\Mastodon\Tags\Unfollow::class, [ R::POST]],
'/timelines/direct' => [Module\Api\Mastodon\Timelines\Direct::class, [R::GET ]], '/timelines/direct' => [Module\Api\Mastodon\Timelines\Direct::class, [R::GET ]],
'/timelines/home' => [Module\Api\Mastodon\Timelines\Home::class, [R::GET ]], '/timelines/home' => [Module\Api\Mastodon\Timelines\Home::class, [R::GET ]],
'/timelines/list/{id:\d+}' => [Module\Api\Mastodon\Timelines\ListTimeline::class, [R::GET ]], '/timelines/list/{id}' => [Module\Api\Mastodon\Timelines\ListTimeline::class, [R::GET ]],
'/timelines/public' => [Module\Api\Mastodon\Timelines\PublicTimeline::class, [R::GET ]], '/timelines/public' => [Module\Api\Mastodon\Timelines\PublicTimeline::class, [R::GET ]],
'/timelines/tag/{hashtag}' => [Module\Api\Mastodon\Timelines\Tag::class, [R::GET ]], '/timelines/tag/{hashtag}' => [Module\Api\Mastodon\Timelines\Tag::class, [R::GET ]],
'/trends' => [Module\Api\Mastodon\Trends\Tags::class, [R::GET ]], '/trends' => [Module\Api\Mastodon\Trends\Tags::class, [R::GET ]],