Skip to content

Commit

Permalink
Fix public link file creation
Browse files Browse the repository at this point in the history
Signed-off-by: Julius Härtl <[email protected]>
  • Loading branch information
juliusknorr committed Dec 29, 2021
1 parent 84b6a96 commit 368f4f6
Show file tree
Hide file tree
Showing 8 changed files with 232 additions and 136 deletions.
3 changes: 2 additions & 1 deletion appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@

['name' => 'document#createFromTemplate', 'url' => 'indexTemplate', 'verb' => 'GET'],
['name' => 'document#publicPage', 'url' => '/public', 'verb' => 'GET'],
['name' => 'document#create', 'url' => 'ajax/documents/create', 'verb' => 'POST'],

// external api access
['name' => 'document#extAppGetData', 'url' => '/ajax/extapp/data/{fileId}', 'verb' => 'POST'],
Expand Down Expand Up @@ -67,6 +66,8 @@
['name' => 'templates#delete', 'url' => '/template/{fileId}', 'verb' => 'DELETE'],
],
'ocs' => [
['name' => 'documentAPI#create', 'url' => '/api/v1/file', 'verb' => 'POST'],

['name' => 'OCS#createDirect', 'url' => '/api/v1/document', 'verb' => 'POST'],
['name' => 'OCS#createPublic', 'url' => '/api/v1/share', 'verb' => 'POST'],
['name' => 'OCS#createPublicFromInitiator', 'url' => '/api/v1/direct/share/initiator', 'verb' => 'POST'],
Expand Down
139 changes: 139 additions & 0 deletions lib/Controller/DocumentAPIController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php
/*
* @copyright Copyright (c) 2021 Julius Härtl <[email protected]>
*
* @author Julius Härtl <[email protected]>
*
* @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);

namespace OCA\Richdocuments\Controller;

use Exception;
use OCA\Richdocuments\AppInfo\Application;
use OCA\Richdocuments\Helper;
use OCA\Richdocuments\TemplateManager;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\IL10N;
use OCP\IRequest;
use OCP\Share\IManager;
use Psr\Log\LoggerInterface;
use Throwable;

class DocumentAPIController extends \OCP\AppFramework\OCSController {

private $rootFolder;
private $shareManager;
private $templateManager;
private $l10n;
private $logger;
private $userId;

public function __construct(IRequest $request, IRootFolder $rootFolder, IManager $shareManager, TemplateManager $templateManager, IL10N $l10n, LoggerInterface $logger, $userId) {
parent::__construct(Application::APPNAME, $request);
$this->rootFolder = $rootFolder;
$this->shareManager = $shareManager;
$this->templateManager = $templateManager;
$this->l10n = $l10n;
$this->logger = $logger;
$this->userId = $userId;
}

/**
* @NoAdminRequired
* @PublicPage
*/
public function create(string $mimeType, string $fileName, string $directoryPath = '/', string $shareToken = null): JSONResponse {
try {
if ($shareToken !== null) {
$share = $this->shareManager->getShareByToken($shareToken);
}

$rootFolder = $shareToken !== null ? $share->getNode() : $this->rootFolder->getUserFolder($this->userId);
$folder = $rootFolder->get($directoryPath);

if (!($folder instanceof Folder)) {
throw new Exception('Node is not a folder');
}
} catch (Throwable $e) {
$this->logger->error('Failed to create document', ['exception' => $e]);
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Cannot create document')
], Http::STATUS_BAD_REQUEST);
}

$basename = $this->l10n->t('New Document.odt');
switch ($mimeType) {
case 'application/vnd.oasis.opendocument.spreadsheet':
$basename = $this->l10n->t('New Spreadsheet.ods');
break;
case 'application/vnd.oasis.opendocument.presentation':
$basename = $this->l10n->t('New Presentation.odp');
break;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$basename = $this->l10n->t('New Document.docx');
break;
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
$basename = $this->l10n->t('New Spreadsheet.xlsx');
break;
case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
$basename = $this->l10n->t('New Presentation.pptx');
break;
default:
break;
}

if (!$fileName) {
$fileName = Helper::getNewFileName($folder, $basename);
}

if ($folder->nodeExists($fileName)) {
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('File already exists')
], Http::STATUS_BAD_REQUEST);
}

try {
$file = $folder->newFile($fileName);
$templateType = $this->templateManager->getTemplateTypeForExtension(pathinfo($fileName, PATHINFO_EXTENSION));
$empty = $this->templateManager->getEmpty($templateType);
$templateFile = array_shift($empty);
$file->putContent($this->templateManager->getEmptyFileContent($file->getExtension()));
if ($this->templateManager->isSupportedTemplateSource($templateFile->getExtension())) {
// Only use TemplateSource if supported filetype
$this->templateManager->setTemplateSource($file->getId(), $templateFile->getId());
}
} catch (Exception $e) {
$this->logger->error('Failed to create file from template', ['exception' => $e]);
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Not allowed to create document')
], Http::STATUS_BAD_REQUEST);
}
return new JSONResponse([
'status' => 'success',
'data' => \OCA\Files\Helper::formatFileInfo($file->getFileInfo())
]);
}
}
121 changes: 3 additions & 118 deletions lib/Controller/DocumentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,16 @@

namespace OCA\Richdocuments\Controller;

use OCA\Richdocuments\AppInfo\Application;
use OCA\Richdocuments\Events\BeforeFederationRedirectEvent;
use OCA\Richdocuments\Service\FederationService;
use OCA\Richdocuments\Service\InitialStateService;
use OCA\Richdocuments\TemplateManager;
use OCA\Richdocuments\TokenManager;
use \OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Http\RedirectResponse;
use OCP\Constants;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\GenericFileException;
use OCP\Files\IRootFolder;
use OCP\Files\Node;
use OCP\Files\NotFoundException;
Expand All @@ -36,18 +33,14 @@
use \OCP\AppFramework\Http\FeaturePolicy;
use \OCP\AppFramework\Http\TemplateResponse;
use \OCA\Richdocuments\AppConfig;
use \OCA\Richdocuments\Helper;
use OCP\ISession;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OC\Files\Type\TemplateManager;

class DocumentController extends Controller {

/** @var string */
private $uid;
/** @var IL10N */
private $l10n;
/** @var IConfig */
private $config;
/** @var AppConfig */
Expand All @@ -62,36 +55,30 @@ class DocumentController extends Controller {
private $session;
/** @var IRootFolder */
private $rootFolder;
/** @var \OCA\Richdocuments\TemplateManager */
/** @var TemplateManager */
private $templateManager;
/** @var FederationService */
private $federationService;
/** @var InitialStateService */
private $initialState;

const ODT_TEMPLATE_PATH = '/emptyTemplates/odttemplate.odt';


public function __construct(
$appName,
IRequest $request,
IConfig $config,
AppConfig $appConfig,
IL10N $l10n,
IManager $shareManager,
TokenManager $tokenManager,
IRootFolder $rootFolder,
ISession $session,
$UserId,
ILogger $logger,
\OCA\Richdocuments\TemplateManager $templateManager,
TemplateManager $templateManager,
FederationService $federationService,
Helper $helper,
InitialStateService $initialState
) {
parent::__construct($appName, $request);
$this->uid = $UserId;
$this->l10n = $l10n;
$this->config = $config;
$this->appConfig = $appConfig;
$this->shareManager = $shareManager;
Expand Down Expand Up @@ -501,108 +488,6 @@ public function remote($shareToken, $remoteServer, $remoteServerToken, $filePath
return new TemplateResponse('core', '403', [], 'guest');
}

/**
* @NoAdminRequired
*
* @param string $mimetype
* @param string $filename
* @param string $dir
* @return JSONResponse
* @throws NotPermittedException
* @throws GenericFileException
*/
public function create($mimetype,
$filename,
$dir = '/'){

$root = $this->rootFolder->getUserFolder($this->uid);
try {
/** @var Folder $folder */
$folder = $root->get($dir);
} catch (NotFoundException $e) {
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Cannot create document')
], Http::STATUS_BAD_REQUEST);
}

if (!($folder instanceof Folder)) {
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Cannot create document')
], Http::STATUS_BAD_REQUEST);
}

$basename = $this->l10n->t('New Document.odt');
switch ($mimetype) {
case 'application/vnd.oasis.opendocument.spreadsheet':
$basename = $this->l10n->t('New Spreadsheet.ods');
break;
case 'application/vnd.oasis.opendocument.presentation':
$basename = $this->l10n->t('New Presentation.odp');
break;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
$basename = $this->l10n->t('New Document.docx');
break;
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
$basename = $this->l10n->t('New Spreadsheet.xlsx');
break;
case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
$basename = $this->l10n->t('New Presentation.pptx');
break;
default:
// to be safe
$mimetype = 'application/vnd.oasis.opendocument.text';
break;
}

if (!$filename){
$filename = Helper::getNewFileName($folder, $basename);
}

if ($folder->nodeExists($filename)) {
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Document already exists')
], Http::STATUS_BAD_REQUEST);
}

try {
$file = $folder->newFile($filename);
} catch (NotPermittedException $e) {
return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Not allowed to create document')
], Http::STATUS_BAD_REQUEST);
}

$content = '';
if (class_exists(TemplateManager::class)){
$manager = \OC_Helper::getFileTemplateManager();
$content = $manager->getTemplate($mimetype);
}

if (!$content){
// FIXME: see if this is used,
$content = file_get_contents(dirname(dirname(__DIR__)) . self::ODT_TEMPLATE_PATH);
}

if ($content) {
$file->putContent($content);

return new JSONResponse([
'status' => 'success',
'data' => \OCA\Files\Helper::formatFileInfo($file->getFileInfo())
]);
}


return new JSONResponse([
'status' => 'error',
'message' => $this->l10n->t('Cannot create document')
]);
}

private function renderErrorPage($message) {
$params = [
'errors' => [['error' => $message]]
Expand Down
18 changes: 18 additions & 0 deletions lib/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,24 @@ private function filterTemplates($templates, $type = null) {
});
}

public function getTemplateTypeForExtension(string $extension): ?string {
switch ($extension) {
case 'odt':
case 'docx':
return 'document';
case 'ods':
case 'xlsx':
return 'spreadsheet';
case 'odp':
case 'pptx':
return 'presentation';
case 'odg':
return 'drawing';
}

return null;
}

public function getEmpty($type = null) {
$folder = $this->getEmptyTemplateDir();

Expand Down
1 change: 1 addition & 0 deletions src/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,7 @@ $(document).ready(function() {

if (shouldAskForGuestName()) {
PostMessages.sendPostMessage('parent', 'loading')
PostMessages.sendPostMessage('parent', 'NC_ShowNamePicker')
$('#documents-content').guestNamePicker()
} else {
documentsMain.initSession()
Expand Down
Loading

0 comments on commit 368f4f6

Please sign in to comment.