Skip to content

Commit

Permalink
Started doing some code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
WilcoLouwerse committed Aug 13, 2024
1 parent 23e6cd5 commit 30859dd
Show file tree
Hide file tree
Showing 3 changed files with 206 additions and 50 deletions.
25 changes: 11 additions & 14 deletions lib/Controller/AttachmentsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private function checkUploadedFile(): JSONResponse|array
return new JSONResponse(data: ['error' => 'Please upload a file using key "_file" or give a "downloadUrl"'], statusCode: 400);
}

// Check for upload errors
// Check for upload errors.
if ($uploadedFile['error'] !== UPLOAD_ERR_OK) {
return new JSONResponse(data: ['error' => 'File upload error: '.$uploadedFile['error']], statusCode: 400);
}
Expand Down Expand Up @@ -218,7 +218,7 @@ private function handleFile(array $uploadedFile): JSONResponse|string
$this->fileService->createFolder(folderPath: "Publicaties/$publicationFolder");
$this->fileService->createFolder(folderPath: "Publicaties/$publicationFolder/Bijlagen");

// Save the uploaded file
// Save the uploaded file.
$filePath = "Publicaties/$publicationFolder/Bijlagen/" . $uploadedFile['name']; // Add a file version to the file name?
$created = $this->fileService->uploadFile(
content: file_get_contents(filename: $uploadedFile['tmp_name']),
Expand All @@ -234,7 +234,7 @@ private function handleFile(array $uploadedFile): JSONResponse|string


/**
* Adds information about the uploaded file to the appropriate Attachment fields.
* Adds information about the uploaded file to the appropriate Attachment fields. Inclusive share link.
*
* @param array $data The form-data fields and their values (/request body) that we are going to update before posting the Attachment.
* @param array $uploadedFile Information about the uploaded file from the request body.
Expand All @@ -245,7 +245,7 @@ private function handleFile(array $uploadedFile): JSONResponse|string
*/
private function AddFileInfoToData(array $data, array $uploadedFile, string $filePath): array
{
// Update Attachment data
// Update Attachment data.
$currentUser = $this->userSession->getUser();
$userId = $currentUser ? $currentUser->getUID() : 'Guest';
$data['reference'] = "$userId/$filePath";
Expand All @@ -255,7 +255,7 @@ private function AddFileInfoToData(array $data, array $uploadedFile, string $fil
$data['title'] = $explodedName[0];
$data['extension'] = end(array: $explodedName);

// Create ShareLink
// Create ShareLink.
$shareLink = $this->fileService->createShareLink(path: $filePath);
if (empty($data['accessUrl']) === true) {
$data['accessUrl'] = $shareLink;
Expand All @@ -277,9 +277,9 @@ private function AddFileInfoToData(array $data, array $uploadedFile, string $fil
public function create(ObjectService $objectService, ElasticSearchService $elasticSearchService): JSONResponse
{
$data = $this->request->getParams();
// Uploaded _file and downloadURL are mutually exclusive
// Uploaded _file and downloadURL are mutually exclusive.
if (empty($data['downloadUrl']) === true) {
// Check if a file was uploaded
// Check if a file was uploaded.
$uploadedFile = $this->checkUploadedFile();
if ($uploadedFile instanceof JSONResponse) {
return $uploadedFile;
Expand All @@ -293,17 +293,17 @@ public function create(ObjectService $objectService, ElasticSearchService $elast
}

if (empty($uploadedFile) === false) {
// Handle saving the uploaded file in NextCloud
// Handle saving the uploaded file in NextCloud.
$filePath = $this->handleFile(uploadedFile: $uploadedFile);
if ($filePath instanceof JSONResponse) {
return $filePath;
}

// Update Attachment data
// Update Attachment data, inclusive share link.
$data = $this->AddFileInfoToData(data: $data, uploadedFile: $uploadedFile, filePath: $filePath);
}

// Remove fields we should never post
// Remove fields we should never post.
unset($data['id']);
foreach($data as $key => $value) {
if(str_starts_with(haystack: $key, needle: '_')) {
Expand All @@ -328,7 +328,6 @@ public function create(ObjectService $objectService, ElasticSearchService $elast
config: $dbConfig
);

// get post from requests
return new JSONResponse($returnData);
}

Expand All @@ -341,7 +340,7 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear
{
$data = $this->request->getParams();

// Remove fields we should never post
// Remove fields we should never post.
unset($data['id']);
foreach($data as $key => $value) {
if(str_starts_with(haystack: $key, needle: '_')) {
Expand All @@ -368,7 +367,6 @@ public function update(string|int $id, ObjectService $objectService, ElasticSear
config: $dbConfig
);

// get post from requests
return new JSONResponse($returnData);
}

Expand Down Expand Up @@ -416,7 +414,6 @@ public function destroy(string|int $id, ObjectService $objectService, ElasticSea
config: $dbConfig
);

// get post from requests
return new JSONResponse($returnData);
}
}
117 changes: 84 additions & 33 deletions lib/Controller/PublicationsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,19 +219,77 @@ public function show(string|int $id, ObjectService $objectService): JSONResponse
}


/**
* Create/updates a file containing all metadata of a publication to NextCloud files, finds/creates a share link and returns it.
*
* @param string $filename The (tmp) filename of the file to store in NextCloud files.
* @param array $publication The publication data used to find/create the publication specific folder in NextCloud files.
*
* @return string|JSONResponse A share link url or an error JSONResponse.
* @throws Exception When a function reading or writing to NextCloud files goes wrong.
*/
private function saveFileToNextCloud(string $filename, array $publication): string|JSONResponse
{
// Create the Publicaties folder and the Publication specific folder.
$this->fileService->createFolder(folderPath: 'Publicaties');
$publicationFolder = $this->fileService->getPublicationFolderName(
publicationId: $publication['id'],
publicationTitle: $publication['title']
);
$this->fileService->createFolder(folderPath: "Publicaties/$publicationFolder");

// Save the file to NextCloud.
$filePath = "Publicaties/$publicationFolder/$filename";
$created = $this->fileService->updateFile(
content: file_get_contents(filename: $filename),
filePath: $filePath,
createNew: true
);

if ($created === false) {
return new JSONResponse(data: ['error' => "Failed to upload this file: $filePath to NextCloud"], statusCode: 500);
}

// Create ShareLink
$share = $this->fileService->findShare(path: $filePath);
if ($share !== null) {
$shareLink = $this->fileService->getShareLink($share);
} else {
$shareLink = $this->fileService->createShareLink(path: $filePath);
}

return $shareLink;
}


/**
* Creates a pdf file containing all metadata of the given publication.
*
* @param ObjectService $objectService The ObjectService, used to connect to a MongoDB database.
* @param string|int $id The id of a Publication we want to create / update a pdf file for.
* @param bool|null $download If we should return a download response (true = default) or only generate and save the file in NextCloud (false).
* @param array|null $publication If we already have a publication body prevent extra database requests by passing it along.
* @param array|null $options A few options for this function, "download" & "saveToNextCloud" can't be both false!
* "download" = If we should return a download response (true = default).
* "saveToNextCloud" = If we should create and save the file in NextCloud (true = default).
* "publication" = If we already have a publication body prevent extra database requests by passing it along.
*
* @return JSONResponse A JSONResponse ... todo
* @return JSONResponse A JSONResponse for downloading the pdf file. Or a JSONResponse containing a downloadUrl for a nextCloud file. Or an error response.
* @throws LoaderError|RuntimeError|SyntaxError|MpdfException|Exception
*/
private function createPublicationFile(ObjectService $objectService, string|int $id, ?bool $download = true, ?array $publication = null): JSONResponse
private function createPublicationFile(
ObjectService $objectService, string|int $id,
?array $options = [
'download' => true,
'saveToNextCloud' => true,
'publication' => null
]
): JSONResponse
{
if ($options['download'] === false && $options['saveToNextCloud'] === false) {
return new JSONResponse(data: ['error' => '$options "download" & "saveToNextCloud" for function
createPublicationFile should not be both set to false'], statusCode: 500);
}

$publication = $options['publication'] ?? null;
if ($publication === null) {
$jsonResponse = $this->show(id: $id, objectService: $objectService);
$publication = $jsonResponse->getData();
Expand Down Expand Up @@ -267,52 +325,41 @@ private function createPublicationFile(ObjectService $objectService, string|int
// Write HTML to PDF
$mpdf->WriteHTML(html: $html);

// Output to a file
$filename = "{$publication['title']}.pdf";
$mpdf->Output(name: $filename, dest: Destination::FILE);

// Create the Publicaties folder and the Publication specific folder.
$this->fileService->createFolder(folderPath: 'Publicaties');
$publicationFolder = $this->fileService->getPublicationFolderName(
publicationId: $publication['id'],
publicationTitle: $publication['title']
);
$this->fileService->createFolder(folderPath: "Publicaties/$publicationFolder");

// Save the uploaded file
$filePath = "Publicaties/$publicationFolder/$filename";
$this->fileService->deleteFile(filePath: $filePath);
$created = $this->fileService->uploadFile(
content: file_get_contents(filename: $filename),
filePath: $filePath
);

// Create ShareLink
$shareLink = $this->fileService->createShareLink(path: $filePath);
if (isset($options['saveToNextCloud']) === false || $options['saveToNextCloud'] === true) {
// Output to a file
$mpdf->Output(name: $filename, dest: Destination::FILE);

if ($created === false) {
return new JSONResponse(data: ['error' => "Failed to upload this file: $filePath to NextCloud"], statusCode: 500);
$shareLink = $this->saveFileToNextCloud(filename: $filename, publication: $publication);
if ($shareLink instanceof JSONResponse) {
return $shareLink;
}
}

if ($download === true) {
if (isset($options['download']) === false || $options['download'] === true) {
// Output directly to the browser
$mpdf->Output(name: $filename, dest: Destination::DOWNLOAD);
}

// Remove tmp folder
rmdir(directory: '/tmp/mpdf');

return new JSONResponse(['downloadUrl' => "$shareLink/download"], 200);
if (isset($options['saveToNextCloud']) === false || $options['saveToNextCloud'] === true) {
return new JSONResponse(['downloadUrl' => "$shareLink/download"], 200);
}
return new JSONResponse([], 200);
}


/**
* todo:
* Creates a ZIP archive containing a pdf file with all metadata of the publication for id = $id.
* Will also add all Attachments (Bijlagen) of this publication to this ZIP archive in a folder called 'Bijlagen'.
*
* @param ObjectService $objectService
* @param string|int $id
* @param ObjectService $objectService The ObjectService, used to connect to a MongoDB database.
* @param string|int $id The id of a Publication we want to download a ZIP archive for.
*
* @return JSONResponse
* @return JSONResponse A JSONResponse for downloading the ZIP archive. Or an error response.
* @throws LoaderError|MpdfException|RuntimeError|SyntaxError
*/
private function creatPublicationZip(ObjectService $objectService, string|int $id): JSONResponse
Expand All @@ -331,7 +378,11 @@ private function creatPublicationZip(ObjectService $objectService, string|int $i
}

// Update the publication .pdf file containing publication metadata.
$jsonResponse = $this->createPublicationFile(objectService: $objectService, id: $id, download: false, publication: $publication);
$jsonResponse = $this->createPublicationFile(objectService: $objectService, id: $id,
options: [
'download' => false,
'publication' => $publication
]);
$publicationFile = $jsonResponse->getData();
if (is_array($publicationFile) === true && isset($publicationFile['error']) === true) {
return new JSONResponse(data: $publicationFile, statusCode: $jsonResponse->getStatus());
Expand Down
Loading

0 comments on commit 30859dd

Please sign in to comment.