Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend dashboard api to allow listing of widgets #33658

Merged
merged 12 commits into from
Sep 16, 2022
1 change: 1 addition & 0 deletions apps/dashboard/appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
['name' => 'dashboard#updateStatuses', 'url' => '/statuses', 'verb' => 'POST'],
],
'ocs' => [
['name' => 'dashboardApi#getWidgets', 'url' => '/api/v1/widgets', 'verb' => 'GET'],
['name' => 'dashboardApi#getWidgetItems', 'url' => '/api/v1/widget-items', 'verb' => 'GET'],
]
];
68 changes: 59 additions & 9 deletions apps/dashboard/lib/Controller/DashboardApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,13 @@

use OCP\AppFramework\OCSController;
use OCP\AppFramework\Http\DataResponse;
use OCP\Dashboard\IButtonWidget;
use OCP\Dashboard\IIconWidget;
use OCP\Dashboard\IOptionWidget;
use OCP\Dashboard\IManager;
use OCP\Dashboard\IWidget;
use OCP\Dashboard\Model\WidgetButton;
use OCP\Dashboard\Model\WidgetOptions;
use OCP\IConfig;
use OCP\IRequest;

Expand All @@ -44,11 +50,13 @@ class DashboardApiController extends OCSController {
/** @var string|null */
private $userId;

public function __construct(string $appName,
IRequest $request,
IManager $dashboardManager,
IConfig $config,
?string $userId) {
public function __construct(
string $appName,
IRequest $request,
IManager $dashboardManager,
IConfig $config,
?string $userId
) {
parent::__construct($appName, $request);

$this->dashboardManager = $dashboardManager;
Expand All @@ -62,19 +70,23 @@ public function __construct(string $appName,
*
* @param array $sinceIds Array indexed by widget Ids, contains date/id from which we want the new items
* @param int $limit Limit number of result items per widget
* @param string[] $widgets Limit results to specific widgets
*
* @NoAdminRequired
* @NoCSRFRequired
*/
public function getWidgetItems(array $sinceIds = [], int $limit = 7): DataResponse {
public function getWidgetItems(array $sinceIds = [], int $limit = 7, array $widgets = []): DataResponse {
$showWidgets = $widgets;
$items = [];

$systemDefault = $this->config->getAppValue('dashboard', 'layout', 'recommendations,spreed,mail,calendar');
$userLayout = explode(',', $this->config->getUserValue($this->userId, 'dashboard', 'layout', $systemDefault));
if (empty($showWidgets)) {
$systemDefault = $this->config->getAppValue('dashboard', 'layout', 'recommendations,spreed,mail,calendar');
$showWidgets = explode(',', $this->config->getUserValue($this->userId, 'dashboard', 'layout', $systemDefault));
}

$widgets = $this->dashboardManager->getWidgets();
foreach ($widgets as $widget) {
if ($widget instanceof IAPIWidget && in_array($widget->getId(), $userLayout)) {
if ($widget instanceof IAPIWidget && in_array($widget->getId(), $showWidgets)) {
$items[$widget->getId()] = array_map(function (WidgetItem $item) {
return $item->jsonSerialize();
}, $widget->getItems($this->userId, $sinceIds[$widget->getId()] ?? null, $limit));
Expand All @@ -83,4 +95,42 @@ public function getWidgetItems(array $sinceIds = [], int $limit = 7): DataRespon

return new DataResponse($items);
}

/**
* Example request with Curl:
* curl -u user:passwd http://my.nc/ocs/v2.php/apps/dashboard/api/v1/widgets
*
* @NoAdminRequired
* @NoCSRFRequired
*/
public function getWidgets(): DataResponse {
$widgets = $this->dashboardManager->getWidgets();

$items = array_map(function (IWidget $widget) {
$options = ($widget instanceof IOptionWidget) ? $widget->getWidgetOptions() : WidgetOptions::getDefault();
$data = [
'id' => $widget->getId(),
'title' => $widget->getTitle(),
'order' => $widget->getOrder(),
'icon_class' => $widget->getIconClass(),
'icon_url' => ($widget instanceof IIconWidget) ? $widget->getIconUrl() : '',
'widget_url' => $widget->getUrl(),
'item_icons_round' => $options->withRoundItemIcons(),
];
if ($widget instanceof IButtonWidget) {
$data += [
'buttons' => array_map(function (WidgetButton $button) {
return [
'type' => $button->getType(),
'text' => $button->getText(),
'link' => $button->getLink(),
];
}, $widget->getWidgetButtons($this->userId)),

Check notice

Code scanning / Psalm

PossiblyNullArgument

Argument 1 of OCP\Dashboard\IButtonWidget::getWidgetButtons cannot be null, possibly null value provided
];
}
return $data;
}, $widgets);

return new DataResponse($items);
}
}
105 changes: 76 additions & 29 deletions apps/user_status/lib/Dashboard/UserStatusWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,50 +28,56 @@
use OCA\UserStatus\AppInfo\Application;
use OCA\UserStatus\Db\UserStatus;
use OCA\UserStatus\Service\StatusService;
use OCP\Dashboard\IWidget;
use OCP\IInitialStateService;
use OCP\AppFramework\Services\IInitialState;
use OCP\Dashboard\IAPIWidget;
use OCP\Dashboard\IButtonWidget;
use OCP\Dashboard\IIconWidget;
use OCP\Dashboard\IOptionWidget;
use OCP\Dashboard\Model\WidgetItem;
use OCP\Dashboard\Model\WidgetOptions;
use OCP\IDateTimeFormatter;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\UserStatus\IUserStatus;
use OCP\Util;

/**
* Class UserStatusWidget
*
* @package OCA\UserStatus
*/
class UserStatusWidget implements IWidget {

/** @var IL10N */
private $l10n;

/** @var IInitialStateService */
private $initialStateService;

/** @var IUserManager */
private $userManager;

/** @var IUserSession */
private $userSession;

/** @var StatusService */
private $service;
class UserStatusWidget implements IAPIWidget, IIconWidget, IOptionWidget {
private IL10N $l10n;
private IDateTimeFormatter $dateTimeFormatter;
private IURLGenerator $urlGenerator;
private IInitialState $initialStateService;
private IUserManager $userManager;
private IUserSession $userSession;
private StatusService $service;

/**
* UserStatusWidget constructor
*
* @param IL10N $l10n
* @param IInitialStateService $initialStateService
* @param IDateTimeFormatter $dateTimeFormatter
* @param IURLGenerator $urlGenerator
* @param IInitialState $initialStateService
* @param IUserManager $userManager
* @param IUserSession $userSession
* @param StatusService $service
*/
public function __construct(IL10N $l10n,
IInitialStateService $initialStateService,
IDateTimeFormatter $dateTimeFormatter,
IURLGenerator $urlGenerator,
IInitialState $initialStateService,
IUserManager $userManager,
IUserSession $userSession,
StatusService $service) {
$this->l10n = $l10n;
$this->dateTimeFormatter = $dateTimeFormatter;
$this->urlGenerator = $urlGenerator;
$this->initialStateService = $initialStateService;
$this->userManager = $userManager;
$this->userSession = $userSession;
Expand Down Expand Up @@ -106,6 +112,15 @@ public function getIconClass(): string {
return 'icon-user-status';
}

/**
* @inheritDoc
*/
public function getIconUrl(): string {
return $this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->imagePath(Application::APP_ID, 'app.svg')
);
}

/**
* @inheritDoc
*/
Expand All @@ -117,28 +132,33 @@ public function getUrl(): ?string {
* @inheritDoc
*/
public function load(): void {
\OCP\Util::addScript(Application::APP_ID, 'dashboard');
Util::addScript(Application::APP_ID, 'dashboard');

$currentUser = $this->userSession->getUser();
if ($currentUser === null) {
$this->initialStateService->provideInitialState(Application::APP_ID, 'dashboard_data', []);
$this->initialStateService->provideInitialState('dashboard_data', []);
return;
}
$currentUserId = $currentUser->getUID();

$widgetItemsData = $this->getWidgetData($currentUserId);
$this->initialStateService->provideInitialState('dashboard_data', $widgetItemsData);
}

private function getWidgetData(string $userId, ?string $since = null, int $limit = 7): array {
// Fetch status updates and filter current user
$recentStatusUpdates = array_slice(
array_filter(
$this->service->findAllRecentStatusChanges(8, 0),
static function (UserStatus $status) use ($currentUserId): bool {
return $status->getUserId() !== $currentUserId;
$this->service->findAllRecentStatusChanges($limit + 1, 0),
static function (UserStatus $status) use ($userId, $since): bool {
return $status->getUserId() !== $userId
&& ($since === null || $status->getStatusTimestamp() > (int) $since);
}
),
0,
7
$limit
);

$this->initialStateService->provideInitialState(Application::APP_ID, 'dashboard_data', array_map(function (UserStatus $status): array {
return array_map(function (UserStatus $status): array {
$user = $this->userManager->get($status->getUserId());
$displayName = $status->getUserId();
if ($user !== null) {
Expand All @@ -155,6 +175,33 @@ static function (UserStatus $status) use ($currentUserId): bool {
'message' => $status->getCustomMessage(),
'timestamp' => $status->getStatusTimestamp(),
];
}, $recentStatusUpdates));
}, $recentStatusUpdates);
}

/**
* @inheritDoc
*/
public function getItems(string $userId, ?string $since = null, int $limit = 7): array {
$widgetItemsData = $this->getWidgetData($userId, $since, $limit);

return array_map(function(array $widgetData) {
$formattedDate = $this->dateTimeFormatter->formatTimeSpan($widgetData['timestamp']);
return new WidgetItem(
$widgetData['displayName'],
$widgetData['icon'] . ($widgetData['icon'] ? ' ' : '') . $widgetData['message'] . ', ' . $formattedDate,
// https://nextcloud.local/index.php/u/julien
$this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->linkToRoute('core.ProfilePage.index', ['targetUserId' => $widgetData['userId']])
),
$this->urlGenerator->getAbsoluteURL(
$this->urlGenerator->linkToRoute('core.avatar.getAvatar', ['userId' => $widgetData['userId'], 'size' => 44])
),
(string) $widgetData['timestamp']
);
}, $widgetItemsData);
}

public function getWidgetOptions(): WidgetOptions {
return new WidgetOptions(true);
}
}
5 changes: 5 additions & 0 deletions lib/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,18 @@
'OCP\\DB\\Types' => $baseDir . '/lib/public/DB/Types.php',
'OCP\\Dashboard\\Exceptions\\DashboardAppNotAvailableException' => $baseDir . '/lib/public/Dashboard/Exceptions/DashboardAppNotAvailableException.php',
'OCP\\Dashboard\\IAPIWidget' => $baseDir . '/lib/public/Dashboard/IAPIWidget.php',
'OCP\\Dashboard\\IButtonWidget' => $baseDir . '/lib/public/Dashboard/IButtonWidget.php',
'OCP\\Dashboard\\IDashboardManager' => $baseDir . '/lib/public/Dashboard/IDashboardManager.php',
'OCP\\Dashboard\\IDashboardWidget' => $baseDir . '/lib/public/Dashboard/IDashboardWidget.php',
'OCP\\Dashboard\\IIconWidget' => $baseDir . '/lib/public/Dashboard/IIconWidget.php',
'OCP\\Dashboard\\IManager' => $baseDir . '/lib/public/Dashboard/IManager.php',
'OCP\\Dashboard\\IOptionWidget' => $baseDir . '/lib/public/Dashboard/IOptionWidget.php',
'OCP\\Dashboard\\IWidget' => $baseDir . '/lib/public/Dashboard/IWidget.php',
'OCP\\Dashboard\\Model\\IWidgetConfig' => $baseDir . '/lib/public/Dashboard/Model/IWidgetConfig.php',
'OCP\\Dashboard\\Model\\IWidgetRequest' => $baseDir . '/lib/public/Dashboard/Model/IWidgetRequest.php',
'OCP\\Dashboard\\Model\\WidgetButton' => $baseDir . '/lib/public/Dashboard/Model/WidgetButton.php',
'OCP\\Dashboard\\Model\\WidgetItem' => $baseDir . '/lib/public/Dashboard/Model/WidgetItem.php',
'OCP\\Dashboard\\Model\\WidgetOptions' => $baseDir . '/lib/public/Dashboard/Model/WidgetOptions.php',
'OCP\\Dashboard\\Model\\WidgetSetting' => $baseDir . '/lib/public/Dashboard/Model/WidgetSetting.php',
'OCP\\Dashboard\\Model\\WidgetSetup' => $baseDir . '/lib/public/Dashboard/Model/WidgetSetup.php',
'OCP\\Dashboard\\Model\\WidgetTemplate' => $baseDir . '/lib/public/Dashboard/Model/WidgetTemplate.php',
Expand Down
5 changes: 5 additions & 0 deletions lib/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,18 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2
'OCP\\DB\\Types' => __DIR__ . '/../../..' . '/lib/public/DB/Types.php',
'OCP\\Dashboard\\Exceptions\\DashboardAppNotAvailableException' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Exceptions/DashboardAppNotAvailableException.php',
'OCP\\Dashboard\\IAPIWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IAPIWidget.php',
'OCP\\Dashboard\\IButtonWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IButtonWidget.php',
'OCP\\Dashboard\\IDashboardManager' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IDashboardManager.php',
'OCP\\Dashboard\\IDashboardWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IDashboardWidget.php',
'OCP\\Dashboard\\IIconWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IIconWidget.php',
'OCP\\Dashboard\\IManager' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IManager.php',
'OCP\\Dashboard\\IOptionWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IOptionWidget.php',
'OCP\\Dashboard\\IWidget' => __DIR__ . '/../../..' . '/lib/public/Dashboard/IWidget.php',
'OCP\\Dashboard\\Model\\IWidgetConfig' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/IWidgetConfig.php',
'OCP\\Dashboard\\Model\\IWidgetRequest' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/IWidgetRequest.php',
'OCP\\Dashboard\\Model\\WidgetButton' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetButton.php',
'OCP\\Dashboard\\Model\\WidgetItem' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetItem.php',
'OCP\\Dashboard\\Model\\WidgetOptions' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetOptions.php',
'OCP\\Dashboard\\Model\\WidgetSetting' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetSetting.php',
'OCP\\Dashboard\\Model\\WidgetSetup' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetSetup.php',
'OCP\\Dashboard\\Model\\WidgetTemplate' => __DIR__ . '/../../..' . '/lib/public/Dashboard/Model/WidgetTemplate.php',
Expand Down
41 changes: 41 additions & 0 deletions lib/public/Dashboard/IButtonWidget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\Dashboard;

use OCP\Dashboard\Model\WidgetButton;

/**
* Adds a button to the dashboard api representation
*
* @since 25.0.0
*/
interface IButtonWidget extends IWidget {
/**
* Get the buttons to show on the widget
*
* @param string $userId
* @return WidgetButton[]
* @since 25.0.0
*/
public function getWidgetButtons(string $userId): array;
}
37 changes: 37 additions & 0 deletions lib/public/Dashboard/IIconWidget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
*
* @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 <http://www.gnu.org/licenses/>.
*
*/
namespace OCP\Dashboard;

/**
* Allow getting the absolute icon url for a widget
*
* @since 25.0.0
*/
interface IIconWidget extends IWidget {
/**
* Get the absolute url for the widget icon
*
* @return string
*/
public function getIconUrl(): string;
}
Loading