migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,303 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2021 Julien Veyssier <eneiluj@posteo.net>
*
* @author Julien Veyssier <eneiluj@posteo.net>
*
* @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\Text\Controller;
use Exception;
use OCA\Text\Exception\InvalidSessionException;
use OCA\Text\Exception\UploadException;
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Middleware\Attribute\RequireDocumentSessionOrUserOrShareToken;
use OCA\Text\Service\AttachmentService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataDownloadResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\Files\IMimeTypeDetector;
use OCP\IL10N;
use OCP\IRequest;
use OCP\Util;
use Psr\Log\LoggerInterface;
class AttachmentController extends ApiController implements ISessionAwareController {
use TSessionAwareController;
public const IMAGE_MIME_TYPES = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'image/x-xbitmap',
'image/x-ms-bmp',
'image/bmp',
'image/svg+xml',
'image/webp',
'image/heic',
'image/heif',
];
public const BROWSER_SUPPORTED_IMAGE_MIME_TYPES = [
'image/png',
'image/jpeg',
'image/jpg',
'image/gif',
'image/x-xbitmap',
'image/x-ms-bmp',
'image/bmp',
'image/svg+xml',
'image/webp',
];
public function __construct(
string $appName,
IRequest $request,
private IL10N $l10n,
private LoggerInterface $logger,
private IMimeTypeDetector $mimeTypeDetector,
private AttachmentService $attachmentService
) {
parent::__construct($appName, $request);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSessionOrUserOrShareToken]
public function getAttachmentList(?string $shareToken = null): DataResponse {
$documentId = $this->getDocument()->getId();
try {
$session = $this->getSession();
} catch (InvalidSessionException) {
$session = null;
}
if ($shareToken) {
$attachments = $this->attachmentService->getAttachmentList($documentId, null, $session, $shareToken);
} else {
$userId = $this->getUserId();
$attachments = $this->attachmentService->getAttachmentList($documentId, $userId, $session, null);
}
return new DataResponse($attachments);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function insertAttachmentFile(string $filePath): DataResponse {
$userId = $this->getSession()->getUserId();
try {
$insertResult = $this->attachmentService->insertAttachmentFile($this->getSession()->getDocumentId(), $filePath, $userId);
if (isset($insertResult['error'])) {
return new DataResponse($insertResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($insertResult);
}
} catch (Exception $e) {
$this->logger->error('File insertion error', ['exception' => $e]);
return new DataResponse(['error' => 'File insertion error'], Http::STATUS_BAD_REQUEST);
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function uploadAttachment(?string $shareToken = null): DataResponse {
$documentId = $this->getSession()->getDocumentId();
try {
$file = $this->getUploadedFile('file');
if (isset($file['tmp_name'], $file['name'], $file['type'])) {
$newFileResource = fopen($file['tmp_name'], 'rb');
if ($newFileResource === false) {
throw new Exception('Could not read file');
}
$newFileName = $file['name'];
if ($shareToken) {
$uploadResult = $this->attachmentService->uploadAttachmentPublic($documentId, $newFileName, $newFileResource, $shareToken);
} else {
$userId = $this->getSession()->getUserId();
$uploadResult = $this->attachmentService->uploadAttachment($documentId, $newFileName, $newFileResource, $userId);
}
if (isset($uploadResult['error'])) {
return new DataResponse($uploadResult, Http::STATUS_BAD_REQUEST);
} else {
return new DataResponse($uploadResult);
}
}
return new DataResponse(['error' => 'No uploaded file'], Http::STATUS_BAD_REQUEST);
} catch (Exception $e) {
$this->logger->error('Upload error', ['exception' => $e]);
return new DataResponse(['error' => 'Upload error'], Http::STATUS_BAD_REQUEST);
}
}
private function getUploadedFile(string $key): array {
$file = $this->request->getUploadedFile($key);
$error = null;
$phpFileUploadErrors = [
UPLOAD_ERR_OK => $this->l10n->t('The file was uploaded'),
UPLOAD_ERR_INI_SIZE => $this->l10n->t('The uploaded file exceeds the upload_max_filesize directive in php.ini'),
UPLOAD_ERR_FORM_SIZE => $this->l10n->t('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'),
UPLOAD_ERR_PARTIAL => $this->l10n->t('The file was only partially uploaded'),
UPLOAD_ERR_NO_FILE => $this->l10n->t('No file was uploaded'),
UPLOAD_ERR_NO_TMP_DIR => $this->l10n->t('Missing a temporary folder'),
UPLOAD_ERR_CANT_WRITE => $this->l10n->t('Could not write file to disk'),
UPLOAD_ERR_EXTENSION => $this->l10n->t('A PHP extension stopped the file upload'),
];
if (empty($file)) {
$error = $this->l10n->t('No file uploaded or file size exceeds maximum of %s', [Util::humanFileSize(Util::uploadLimit())]);
}
if (!empty($file) && array_key_exists('error', $file) && $file['error'] !== UPLOAD_ERR_OK) {
$error = $phpFileUploadErrors[$file['error']];
}
if ($error !== null) {
throw new UploadException($error);
}
return $file;
}
/**
* Serve the image files in the editor
*
* @return DataDownloadResponse|DataResponse
*
* @psalm-return DataDownloadResponse<200, string, array<never, never>>|DataResponse<404, '', array<never, never>>
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getImageFile(string $imageFileName, ?string $shareToken = null,
int $preferRawImage = 0): DataResponse|DataDownloadResponse {
$documentId = $this->getDocument()->getId();
try {
if ($shareToken) {
$imageFile = $this->attachmentService->getImageFilePublic($documentId, $imageFileName, $shareToken, $preferRawImage === 1);
} else {
$userId = $this->getUserId();
$imageFile = $this->attachmentService->getImageFile($documentId, $imageFileName, $userId, $preferRawImage === 1);
}
return $imageFile !== null
? new DataDownloadResponse(
$imageFile->getContent(),
$imageFile->getName(),
$this->getSecureMimeType($imageFile->getMimeType())
)
: new DataResponse('', Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('getImageFile error', ['exception' => $e]);
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
}
/**
* Serve the media files in the editor
*
* @return DataDownloadResponse|DataResponse
*
* @psalm-return DataDownloadResponse<200, string, array<never, never>>|DataResponse<404, '', array<never, never>>
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getMediaFile(string $mediaFileName, ?string $shareToken = null): DataResponse|DataDownloadResponse {
$documentId = $this->getDocument()->getId();
try {
if ($shareToken) {
$mediaFile = $this->attachmentService->getMediaFilePublic($documentId, $mediaFileName, $shareToken);
} else {
$userId = $this->getUserId();
$mediaFile = $this->attachmentService->getMediaFile($documentId, $mediaFileName, $userId);
}
return $mediaFile !== null
? new DataDownloadResponse(
$mediaFile->getContent(),
$mediaFile->getName(),
$this->getSecureMimeType($mediaFile->getMimeType())
)
: new DataResponse('', Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('getMediaFile error', ['exception' => $e]);
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
}
/**
* Serve the media files preview in the editor
* @return DataDownloadResponse|DataResponse|RedirectResponse
*/
#[NoAdminRequired]
#[PublicPage]
#[NoCSRFRequired]
#[RequireDocumentSessionOrUserOrShareToken]
public function getMediaFilePreview(string $mediaFileName, ?string $shareToken = null) {
$documentId = $this->getDocument()->getId();
try {
if ($shareToken) {
$preview = $this->attachmentService->getMediaFilePreviewPublic($documentId, $mediaFileName, $shareToken);
} else {
$userId = $this->getUserId();
$preview = $this->attachmentService->getMediaFilePreview($documentId, $mediaFileName, $userId);
}
if ($preview === null) {
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
if ($preview['type'] === 'file') {
return new DataDownloadResponse(
$preview['file']->getContent(),
$mediaFileName,
$this->getSecureMimeType($preview['file']->getMimeType())
);
} elseif ($preview['type'] === 'icon') {
return new RedirectResponse($preview['iconUrl']);
}
} catch (Exception $e) {
$this->logger->error('getMediaFilePreview error', ['exception' => $e]);
}
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
/**
* Allow all supported mimetypes
* Use mimetype detector for the other ones
*
* @param string $mimetype
* @return string
*/
private function getSecureMimeType(string $mimetype): string {
if (in_array($mimetype, self::IMAGE_MIME_TYPES)) {
return $mimetype;
}
return $this->mimeTypeDetector->getSecureMimeType($mimetype);
}
}
@@ -0,0 +1,15 @@
<?php
namespace OCA\Text\Controller;
use OCA\Text\Db\Document;
use OCA\Text\Db\Session;
interface ISessionAwareController {
public function getSession(): Session;
public function setSession(Session $session): void;
public function getDocument(): Document;
public function setDocument(Document $document): void;
public function getUserId(): string;
public function setUserId(string $userId): void;
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Text\Controller;
use OCA\Text\AppInfo\Application;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\TemplateResponse;
class NavigationController extends Controller {
/**
*
* @NoCSRFRequired
* @NoAdminRequired
*
* @return TemplateResponse
*/
public function navigate(): TemplateResponse {
return new TemplateResponse(Application::APP_NAME, 'main');
}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Text\Controller;
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Service\ApiService;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\PublicShareController;
use OCP\IRequest;
use OCP\ISession;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager as ShareManager;
use OCP\Share\IShare;
class PublicSessionController extends PublicShareController implements ISessionAwareController {
use TSessionAwareController;
private ?IShare $share = null;
public function __construct(
string $appName,
IRequest $request,
ISession $session,
private ShareManager $shareManager,
private ApiService $apiService
) {
parent::__construct($appName, $request, $session);
}
private function getShare(): IShare {
if ($this->share === null) {
throw new \Exception('Share has not been set yet');
}
return $this->share;
}
protected function getPasswordHash(): string {
return $this->getShare()->getPassword();
}
public function isValidToken(): bool {
try {
$this->share = $this->shareManager->getShareByToken($this->getToken());
return true;
} catch (ShareNotFound $e) {
return false;
}
}
protected function isPasswordProtected(): bool {
/** @psalm-suppress RedundantConditionGivenDocblockType */
return $this->getShare()->getPassword() !== null;
}
#[NoAdminRequired]
#[PublicPage]
public function create(string $token, string $file = null, ?string $guestName = null): DataResponse {
return $this->apiService->create(null, $file, $token, $guestName);
}
#[NoAdminRequired]
#[PublicPage]
public function close(int $documentId, int $sessionId, string $sessionToken): DataResponse {
return $this->apiService->close($documentId, $sessionId, $sessionToken);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function push(int $documentId, int $sessionId, string $sessionToken, int $version, array $steps, string $awareness, string $token): DataResponse {
return $this->apiService->push($this->getSession(), $this->getDocument(), $version, $steps, $awareness, $token);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function sync(string $token, int $version = 0): DataResponse {
return $this->apiService->sync($this->getSession(), $this->getDocument(), $version, $token);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function save(string $token, int $version = 0, string $autosaveContent = null, string $documentState = null, bool $force = false, bool $manualSave = false): DataResponse {
return $this->apiService->save($this->getSession(), $this->getDocument(), $version, $autosaveContent, $documentState, $force, $manualSave, $token);
}
/**
* @psalm-return DataResponse<int, array|null|object|scalar, array<string, mixed>>
*/
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function updateSession(string $guestName): DataResponse {
return $this->apiService->updateSession($this->getSession(), $guestName);
}
}
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Text\Controller;
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Service\ApiService;
use OCA\Text\Service\NotificationService;
use OCA\Text\Service\SessionService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\Attribute\UserRateLimit;
use OCP\AppFramework\Http\DataResponse;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
class SessionController extends ApiController implements ISessionAwareController {
use TSessionAwareController;
private bool $restoreUser = false;
private ?IUser $userToRestore = null;
public function __construct(
string $appName,
IRequest $request,
private ApiService $apiService,
private SessionService $sessionService,
private NotificationService $notificationService,
private IUserManager $userManager,
private IUserSession $userSession) {
parent::__construct($appName, $request);
}
#[NoAdminRequired]
public function create(int $fileId = null, string $file = null): DataResponse {
return $this->apiService->create($fileId, $file, null, null);
}
#[NoAdminRequired]
#[PublicPage]
public function close(int $documentId, int $sessionId, string $sessionToken): DataResponse {
return $this->apiService->close($documentId, $sessionId, $sessionToken);
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function push(int $version, array $steps, string $awareness): DataResponse {
try {
$this->loginSessionUser();
return $this->apiService->push($this->getSession(), $this->getDocument(), $version, $steps, $awareness);
} finally {
$this->restoreSessionUser();
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function sync(int $version = 0): DataResponse {
try {
$this->loginSessionUser();
return $this->apiService->sync($this->getSession(), $this->getDocument(), $version);
} finally {
$this->restoreSessionUser();
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
public function save(int $version = 0, string $autosaveContent = null, string $documentState = null, bool $force = false, bool $manualSave = false): DataResponse {
try {
$this->loginSessionUser();
return $this->apiService->save($this->getSession(), $this->getDocument(), $version, $autosaveContent, $documentState, $force, $manualSave);
} finally {
$this->restoreSessionUser();
}
}
#[NoAdminRequired]
#[PublicPage]
#[RequireDocumentSession]
#[UserRateLimit(limit: 5, period: 120)]
public function mention(string $mention): DataResponse {
if ($this->getSession()->isGuest() && !$this->sessionService->isUserInDocument($this->getDocument()->getId(), $mention)) {
return new DataResponse([], 403);
}
return new DataResponse($this->notificationService->mention($this->getDocument()->getId(), $mention));
}
private function loginSessionUser(): void {
$currentSession = $this->getSession();
if (!$this->userSession->isLoggedIn()) {
$user = $this->userManager->get($currentSession->getUserId());
if ($user !== null) {
$this->restoreUser = true;
$this->userToRestore = $this->userSession->getUser();
$this->userSession->setUser($user);
}
}
}
private function restoreSessionUser(): void {
if ($this->restoreUser) {
$this->userSession->setUser($this->userToRestore);
}
}
}
@@ -0,0 +1,59 @@
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Text\Controller;
use OCA\Text\AppInfo\Application;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\DataResponse;
use OCP\IConfig;
use OCP\IRequest;
class SettingsController extends Controller {
public const ACCEPTED_KEYS = [
'workspace_enabled'
];
public function __construct(string $appName, IRequest $request, private IConfig $config, private ?string $userId) {
parent::__construct($appName, $request);
}
/**
* @throws \OCP\PreConditionNotMetException
*
* @psalm-return DataResponse<200|400, array{workspace_enabled?: mixed, message?: 'Invalid config key'}, array<never, never>>
*/
#[NoAdminRequired]
public function updateConfig(string $key, int|string $value): DataResponse {
if (!in_array($key, self::ACCEPTED_KEYS, true)) {
return new DataResponse(['message' => 'Invalid config key'], Http::STATUS_BAD_REQUEST);
}
/** @psalm-suppress PossiblyNullArgument */
$this->config->setUserValue($this->userId, Application::APP_NAME, $key, (string)$value);
return new DataResponse([
$key => $value
]);
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace OCA\Text\Controller;
use OCA\Text\Db\Document;
use OCA\Text\Db\Session;
use OCA\Text\Exception\InvalidSessionException;
trait TSessionAwareController {
private ?Session $textSession = null;
private ?Document $document = null;
private ?string $userId = null;
public function setSession(?Session $session): void {
$this->textSession = $session;
}
public function setDocument(?Document $document): void {
$this->document = $document;
}
public function setUserId(?string $userId): void {
$this->userId = $userId;
}
public function getSession(): Session {
if ($this->textSession === null) {
throw new InvalidSessionException();
}
return $this->textSession;
}
public function getDocument(): Document {
if ($this->document === null) {
throw new InvalidSessionException();
}
return $this->document;
}
public function getUserId(): string {
if ($this->userId === null) {
throw new InvalidSessionException();
}
return $this->userId;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace OCA\Text\Controller;
use OCA\Text\Middleware\Attribute\RequireDocumentSession;
use OCA\Text\Service\SessionService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataResponse;
use OCP\Collaboration\Collaborators\ISearch;
use OCP\IRequest;
use OCP\IUserManager;
use OCP\Share\IShare;
class UserApiController extends ApiController implements ISessionAwareController {
use TSessionAwareController;
public function __construct(
string $appName,
IRequest $request,
private SessionService $sessionService,
private ISearch $collaboratorSearch,
private IUserManager $userManager
) {
parent::__construct($appName, $request);
}
#[PublicPage]
#[NoAdminRequired]
#[RequireDocumentSession]
public function index(string $filter = '', int $limit = 5): DataResponse {
$sessions = $this->sessionService->getAllSessions($this->getSession()->getDocumentId());
$users = [];
// Add joined users to the autocomplete list
foreach ($sessions as $session) {
$sessionUserId = $session['userId'];
if ($sessionUserId !== null && !isset($users[$sessionUserId])) {
$displayName = $this->userManager->getDisplayName($sessionUserId);
if ($displayName && stripos($displayName, $filter) !== false || stripos($sessionUserId, $filter) !== false) {
$users[$sessionUserId] = $displayName;
}
}
}
if (!$this->getSession()->isGuest()) {
// Add other users to the autocomplete list
[$result] = $this->collaboratorSearch->search($filter, [IShare::TYPE_USER], false, $limit, 0);
$userSearch = array_merge($result['users'], $result['exact']['users']);
foreach ($userSearch as ['label' => $label, 'value' => $value]) {
if (isset($value['shareWith'])) {
$id = $value['shareWith'];
$users[$id] = $label;
}
}
}
return new DataResponse($users);
}
}
@@ -0,0 +1,222 @@
<?php
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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/>.
*
*/
declare(strict_types=1);
/**
* @copyright Copyright (c) 2019 Julius Härtl <jus@bitgrid.net>
*
* @author Julius Härtl <jus@bitgrid.net>
*
* @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\Text\Controller;
use Exception;
use OCA\Text\AppInfo\Application;
use OCA\Text\DirectEditing\TextDocumentCreator;
use OCA\Text\Service\WorkspaceService;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\Constants;
use OCP\DirectEditing\IManager as IDirectEditingManager;
use OCP\DirectEditing\RegisterDirectEditorEvent;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IRequest;
use OCP\ISession;
use OCP\IURLGenerator;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;
class WorkspaceController extends OCSController {
public function __construct(
string $appName,
IRequest $request,
private IRootFolder $rootFolder,
private IManager $shareManager,
private IDirectEditingManager $directEditingManager,
private IURLGenerator $urlGenerator,
private WorkspaceService $workspaceService,
private IEventDispatcher $eventDispatcher,
private LoggerInterface $logger,
private ISession $session,
private ?string $userId
) {
parent::__construct($appName, $request);
}
/**
* Checks for available files in the current folder and returns required details to present
* the rich workspace
*/
#[NoAdminRequired]
public function folder(string $path = '/'): DataResponse {
/** */
try {
/** @psalm-suppress PossiblyNullArgument */
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$folder = $userFolder->get($path);
if ($folder instanceof Folder) {
$file = $this->workspaceService->getFile($folder);
if ($file === null) {
return new DataResponse([
'message' => 'No workspace file found',
'folder' => [
'permissions' => $folder->getPermissions()
]
], Http::STATUS_NOT_FOUND);
}
return new DataResponse([
'file' => [
'id' => $file->getId(),
'mimetype' => $file->getMimetype(),
'name' => $file->getName(),
'path' => $userFolder->getRelativePath($file->getPath())
],
'folder' => [
'permissions' => $folder->getPermissions()
]
]);
}
} catch (NotFoundException|NotPermittedException) {
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('Failed to get workspace file', ['exception' => $e]);
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
/**
* Checks for available files in the current folder and returns required details to present
* the rich workspace
* @api
*/
#[NoAdminRequired]
#[PublicPage]
public function publicFolder(string $shareToken, string $path = '/'): DataResponse {
try {
$share = $this->shareManager->getShareByToken($shareToken);
if (!($share->getPermissions() & Constants::PERMISSION_READ)) {
throw new ShareNotFound();
}
/** @psalm-suppress RedundantConditionGivenDocblockType */
if ($share->getPassword() !== null) {
$shareId = $this->session->get('public_link_authenticated');
if ($share->getId() !== $shareId) {
throw new ShareNotFound();
}
}
$shareNode = $share->getNode();
$node = $shareNode instanceof File ? $shareNode : $shareNode->get($path);
if ($node instanceof Folder) {
$file = $this->workspaceService->getFile($node);
if ($file === null) {
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
return new DataResponse([
'file' => [
'id' => $file->getId(),
'mimetype' => $file->getMimetype(),
'name' => $file->getName(),
'path' => $path . '/' . $file->getName()
]
]);
}
} catch (NotFoundException|ShareNotFound) {
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('Failed to get public workspace file', ['exception' => $e]);
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
#[NoAdminRequired]
public function direct(string $path): DataResponse {
$this->eventDispatcher->dispatchTyped(new RegisterDirectEditorEvent($this->directEditingManager));
try {
/** @psalm-suppress PossiblyNullArgument */
$folder = $this->rootFolder->getUserFolder($this->userId)->get($path);
if ($folder instanceof Folder) {
$file = $this->getFile($folder);
if ($file === null) {
$token = $this->directEditingManager->create($path . '/'. $this->workspaceService->getSupportedFilenames()[0], Application::APP_NAME, TextDocumentCreator::CREATOR_ID);
} else {
$token = $this->directEditingManager->open($path . '/'. $file->getName(), Application::APP_NAME);
}
return new DataResponse([
'url' => $this->urlGenerator->linkToRouteAbsolute('files.DirectEditingView.edit', ['token' => $token])
]);
}
} catch (Exception $e) {
$this->logger->error('Exception when creating a new file through direct editing', ['exception' => $e]);
return new DataResponse('Failed to create file', Http::STATUS_FORBIDDEN);
}
return new DataResponse(['message' => 'No workspace file found'], Http::STATUS_NOT_FOUND);
}
private function getFile(Folder $folder): ?File {
$file = null;
foreach ($this->workspaceService->getSupportedFilenames() as $filename) {
try {
$node = $folder->get($filename);
if ($node instanceof File) {
$file = $node;
}
} catch (NotFoundException) {
}
}
return $file;
}
}