Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/feature/notifications' into staging
Browse files Browse the repository at this point in the history
  • Loading branch information
mahiarirani committed Oct 15, 2024
2 parents eddbe46 + 9bd988f commit 4be64d8
Show file tree
Hide file tree
Showing 7 changed files with 236 additions and 19 deletions.
31 changes: 31 additions & 0 deletions lib/AppInfo/AppConstants.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2024, MetaProvide Holding EKF
*
* @author Ron Trevor <ecoron@proton.me>
*
* @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 OCA\Files_External_Ethswarm\AppInfo;

class AppConstants {
// Application-wide constants go here
public const APP_NAME = 'files_external_ethswarm';
}
16 changes: 7 additions & 9 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@

namespace OCA\Files_External_Ethswarm\AppInfo;

use OCA\Files\Event\LoadAdditionalScriptsEvent;
use OCA\Files_External_Ethswarm\AppInfo\AppConstants;
use OCA\Files_External_Ethswarm\Backend\BeeSwarm;
use OCA\Files_External_Ethswarm\Auth\License;
use OCA\Files_External\Lib\Config\IBackendProvider;
use OCA\Files_External\Service\BackendService;
use OCA\Files_External\Lib\Config\IAuthMechanismProvider;
use OCA\Files_External_Ethswarm\Notification\Notifier;
use OCP\AppFramework\App;
use OCP\Util;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
Expand All @@ -42,10 +43,9 @@
* @package OCA\Files_external_beeswarm\AppInfo
*/
class Application extends App implements IBootstrap, IBackendProvider, IAuthMechanismProvider {
public const APP_ID = 'files_external_ethswarm';

public function __construct(array $urlParams = []) {
parent::__construct(self::APP_ID, $urlParams);
parent::__construct(AppConstants::APP_NAME, $urlParams);
}

/**
Expand All @@ -67,16 +67,13 @@ public function boot(IBootContext $context): void {
});

// Load custom JS
Util::addScript(SELF::APP_ID, 'admin-settings');
Util::addScript(AppConstants::APP_NAME, 'admin-settings');

/** @var IEventDispatcher $dispatcher */
$dispatcher = $context->getAppContainer()->get(IEventDispatcher::class);
$dispatcher->addListener('OCA\Files::loadAdditionalScripts', function () {
Util::addScript(SELF::APP_ID, 'fileactions');
Util::addScript(SELF::APP_ID, 'menuobserver');
});
$dispatcher->addListener(LoadAdditionalScriptsEvent::class, function () {
Util::addScript(SELF::APP_ID, 'nextcloud-swarm-plugin-fileactions');
Util::addScript(AppConstants::APP_NAME, 'fileactions');
Util::addScript(AppConstants::APP_NAME, 'menuobserver');
});

$this->getAuthMechanisms();
Expand All @@ -88,6 +85,7 @@ public function registerEventsScripts(IEventDispatcher $dispatcher) {

public function register(IRegistrationContext $context): void {
// Register AddContentSecurityPolicyEvent for CSPListener class listenser here
$context->registerNotifierService(Notifier::class);
}

public function getAuthMechanisms() {
Expand Down
5 changes: 2 additions & 3 deletions lib/Backend/BeeSwarm.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@

namespace OCA\Files_External_Ethswarm\Backend;


use OCA\Files_External_Ethswarm\AppInfo\AppConstants;
use OCA\Files_External\Lib\Backend\Backend;
use OCA\Files_External\Lib\DefinitionParameter;
use OCA\Files_External\Lib\StorageConfig;
use OCA\Files_External\Service\GlobalStoragesService;
use OCA\Files_External_Ethswarm\Auth\License;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IUser;
use Psr\Log\LoggerInterface;

class BeeSwarm extends Backend
Expand Down Expand Up @@ -69,7 +68,7 @@ public function __construct(string $appName, IL10N $l, IConfig $config, LoggerIn
$this->logger = $logger;
$this->globalStoragesService = $globalStoragesService;
$this
->setIdentifier('files_external_ethswarm')
->setIdentifier(AppConstants::APP_NAME)
->addIdentifierAlias('\OC\Files\External_Storage\BeeSwarm') // legacy compat
->setStorageClass('\OCA\Files_External_Ethswarm\Storage\BeeSwarm')
->setText($l->t('Swarm By Hejbit'))
Expand Down
117 changes: 117 additions & 0 deletions lib/Notification/Notifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php
/**
* @copyright Copyright (c) 2024, MetaProvide Holding EKF
*
* @author Ron Trevor <ecoron@proton.me>
*
* @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 OCA\Files_External_Ethswarm\Notification;

use OCA\Files_External_Ethswarm\AppInfo\AppConstants;

class Notifier implements \OCP\Notification\INotifier {
protected $factory;
protected $url;

public function __construct(\OCP\L10N\IFactory $factory,
\OCP\IURLGenerator $urlGenerator) {
$this->factory = $factory;
$this->url = $urlGenerator;
}

/**
* Identifier of the notifier, only use [a-z0-9_]
* @return string
*/
public function getID(): string {
return AppConstants::APP_NAME;
}

/**
* Human-readable name describing the notifier
* @return string
*/
public function getName(): string {
return $this->factory->get(AppConstants::APP_NAME)->t('Hejbit External Storage');
}

/**
* @param \OCP\Notification\INotification $notification
* @param string $languageCode The code of the language that should be used to prepare the notification
*/
public function prepare(\OCP\Notification\INotification $notification, string $languageCode): \OCP\Notification\INotification {
if ($notification->getApp() !== AppConstants::APP_NAME) {
// Not my app => throw
throw new \InvalidArgumentException();
}

// Read the language from the notification
$l = $this->factory->get(AppConstants::APP_NAME, $languageCode);

// Deal with known subjects
switch ($notification->getSubject()) {
// Set the parsed subject, message and action labels
case 'swarm-fileupload':
// Set rich subject, see https://github.com/nextcloud/server/issues/1706 for more information
// and https://github.com/nextcloud/server/blob/master/lib/public/RichObjectStrings/Definitions.php
// for a list of defined objects and their parameters.
$parameters = $notification->getSubjectParameters();
$notification->setRichSubject($l->t('Your file \'{filename}\' was decentralized.'),
[
'filename' => [
'type' => 'file',
'id' => '',
'name' => basename($parameters['path']),
'path' => $parameters['path'],
],
]);

// Set the plain text subject automatically
$this->setParsedSubjectFromRichSubject($notification);
return $notification;

default:
// Unknown subject => Unknown notification => throw
throw new \InvalidArgumentException();
}
}

/**
* This is a little helper function which automatically sets the simple parsed subject
* based on the rich subject you set. This is also the default behaviour of the API
* since Nextcloud 26, but in case you would like to return simpler or other strings,
* this function allows you to take over.
*
* @param \OCP\Notification\INotification $notification
*/
protected function setParsedSubjectFromRichSubject(\OCP\Notification\INotification $notification): void {
$placeholders = $replacements = [];
foreach ($notification->getRichSubjectParameters() as $placeholder => $parameter) {
$placeholders[] = '{' . $placeholder . '}';
if ($parameter['type'] === 'file') {
$replacements[] = $parameter['path'];
} else {
$replacements[] = $parameter['name'];
}
}

$notification->setParsedSubject(str_replace($placeholders, $replacements, $notification->getRichSubject()));
}
}

55 changes: 55 additions & 0 deletions lib/Service/NotificationService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php
/**
* @copyright Copyright (c) 2024, MetaProvide Holding EKF
*
* @author Ron Trevor <ecoron@proton.me>
*
* @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 OCA\Files_External_Ethswarm\Service;

use OCA\Files_External_Ethswarm\AppInfo\AppConstants;
use OCP\Notification\IManager;
use OCP\IUserManager;
use OCP\IUserSession;

class NotificationService {
private $notificationManager;
private $userManager;
private $userSession;

public function __construct(IManager $notificationManager, IUserManager $userManager, IUserSession $userSession) {
$this->notificationManager = $notificationManager;
$this->userManager = $userManager;
$this->userSession = $userSession;
}

public function sendTemporaryNotification($subject, $path) {
// Create a notification
$notification = $this->notificationManager->createNotification();
$notification->setApp(AppConstants::APP_NAME);
$userId = $this->userSession->getUser()->getUID();
$notification->setUser($userId);
$notification->setSubject($subject, ['path' => $path]);
$notification->setObject('temporary', $userId); // Marks the notification as temporary
$notification->setDateTime(new \DateTime());

// Send the notification
$this->notificationManager->notify($notification);
}
}
30 changes: 24 additions & 6 deletions lib/Storage/BeeSwarm.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

namespace OCA\Files_External_Ethswarm\Storage;

use OCA\Files_External_Ethswarm\AppInfo\AppConstants;
use Exception;
use OC\Files\Cache\Cache;
use OC\Files\Storage\Common;
Expand All @@ -34,12 +35,18 @@
use OCP\IConfig;
use OCP\IDBConnection;
use Sabre\DAV\Exception\BadRequest;
use OCP\IL10N;
use OCP\L10N\IFactory as IL10NFactory;
use OCA\Files_External_Ethswarm\Service\NotificationService;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Notification\IManager;

class BeeSwarm extends Common
{
use BeeSwarmTrait;

public const APP_NAME = 'files_external_ethswarm';
protected IL10N $l10n;

/** @var int */
protected int $storageId;
Expand Down Expand Up @@ -68,9 +75,16 @@ class BeeSwarm extends Common
/** @var string */
protected string $id;

/** @var NotificationService */
private $notificationService;

public function __construct($params)
{
/** @var IL10NFactory $l10nFactory */
$l10nFactory = \OC::$server->get(IL10NFactory::class);
$this->l10n = $l10nFactory->get(AppConstants::APP_NAME);

$this->notificationService = new NotificationService( \OC::$server->get(IManager::class), \OC::$server->get(IUserManager::class), \OC::$server->get(IUserSession::class));
$this->parseParams($params);
$this->id = 'ethswarm::'.$this->access_key;
$this->storageId = $this->getStorageCache()->getNumericId();
Expand All @@ -89,7 +103,7 @@ public function __construct($params)
$mountId = $storageMount->getMountId();

$this->config = \OC::$server->get(IConfig::class);
$configSettings = $this->config->getAppValue(self::APP_NAME, "storageconfig", ""); //default
$configSettings = $this->config->getAppValue(AppConstants::APP_NAME, "storageconfig", ""); //default
$mounts = json_decode($configSettings, true);
if (is_array($mounts)) {
$mountIds = array_column($mounts, 'mount_id');
Expand Down Expand Up @@ -317,6 +331,9 @@ public function fopen($path, $mode)
$swarmFile = $this->filemapper->find($path, $this->storageId);
$reference = $swarmFile->getSwarmReference();

if (!isset($reference)) {
return false;
}
switch ($mode) {
case 'r':
case 'rb':
Expand Down Expand Up @@ -427,9 +444,7 @@ public function getMetaData($path)

public function getDirectoryContent($path): \Traversable
{
$rows = $this->filemapper->getPathTree($path, $this->storageId,
incSelf: false,
recursive: false);
$rows = $this->filemapper->getPathTree($path, $this->storageId, false);
$content = array_map(fn($val) => $this->getMetaData($val->getName()), $rows);

return new \ArrayIterator($content);
Expand Down Expand Up @@ -461,8 +476,9 @@ public function writeStream(string $path, $stream, int $size = null): int
$reference = (isset($result["reference"]) ? $result['reference'] : null);

if (!isset($reference)) {
throw new BadRequest("Failed to upload file to " . $this->id . ": " . $result['message']);
throw new BadRequest("Failed to upload file to " . $this->id . ": " . $result['message']);
}

} catch (\Exception $e) {
throw new \Exception($e->getMessage());
} finally {
Expand All @@ -483,6 +499,8 @@ public function writeStream(string $path, $stream, int $size = null): int
];
$this->filemapper->createFile($uploadfiles);

$this->notificationService->sendTemporaryNotification("swarm-fileupload", $path);

// //TODO: Read back from swarm to return filesize?
return $tmpFilesize;
}
Expand Down
1 change: 0 additions & 1 deletion lib/Storage/BeeSwarmTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ private function uploadStream(string $path, string $tmpfile, string $mimetype, i
private function downloadStream(string $reference)
{
$endpoint = $this->api_url . DIRECTORY_SEPARATOR . 'bzz' . DIRECTORY_SEPARATOR . $reference . DIRECTORY_SEPARATOR;

$curl = new Curl($endpoint, [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
Expand Down

0 comments on commit 4be64d8

Please sign in to comment.