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

Use tmp folder to store temp uploaded logos in project admin form #2092

Draft
wants to merge 43 commits into
base: develop
Choose a base branch
from
Draft
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
42a13b6
feat: setup dockerized vue widget dev server
luistoptal Oct 6, 2024
9d32a07
chore: Merge branch 'develop' into new-feature/376-upload-update-proj…
luistoptal Oct 23, 2024
a257ae4
feat: mock image upload
luistoptal Oct 23, 2024
d10ab93
uppy widget is displayed in the ui
luistoptal Oct 25, 2024
f5f8ee9
display spinner while scripts load
luistoptal Oct 25, 2024
19c9c7e
renames controller and model variables to be more specific
luistoptal Oct 25, 2024
69e4e3f
feat: a11y uppy image loader
luistoptal Oct 25, 2024
5d2e114
feat: native inplementation
luistoptal Oct 25, 2024
f87f9b7
feat: custom image editor
luistoptal Oct 29, 2024
51ab59c
refactor: cleanup current implementation
luistoptal Oct 29, 2024
d19ad67
chore: comment feature and display upload button
luistoptal Oct 29, 2024
5e3f38f
feat: able to upload file and send data back to the client
luistoptal Oct 29, 2024
c04e70e
chore: restores actioncreate method to original functionality
luistoptal Oct 29, 2024
1edd8c0
feat: use write logo in project controller
luistoptal Oct 30, 2024
0103442
feat: setup logo cleanup on project delete and on logo upload
luistoptal Oct 30, 2024
b251bd9
feat: splits vue widget into components
luistoptal Oct 30, 2024
8a338dd
chore: cleanup logs and accept hidden input name
luistoptal Oct 30, 2024
f10940d
feat: tweak image editor flow and improve a11y
luistoptal Oct 30, 2024
f3a2930
feat: save logo in temp storage
luistoptal Oct 31, 2024
1376054
feat: project CRUD wroks with logo
luistoptal Nov 3, 2024
8af0f39
chore: delete logs
luistoptal Nov 3, 2024
47a83ab
feat: setup vue widget dev and prod
luistoptal Nov 3, 2024
7fbdf74
refactor: adds global error handling
luistoptal Nov 3, 2024
05a841d
feat: adds vue component unit testing
luistoptal Nov 4, 2024
fa90440
feat: validate image height before uploading
luistoptal Nov 4, 2024
6d3f072
chore: use production version of vue app
luistoptal Nov 4, 2024
a33135f
feat: tweak test scripts
luistoptal Nov 4, 2024
9110cae
feat: setup prod env
luistoptal Nov 4, 2024
7c863a4
refactor: cleanup vite app dev setup
luistoptal Nov 4, 2024
61cf404
chor: clean up readme
luistoptal Nov 4, 2024
14a144c
feat: separates form buttons from uppy widget
luistoptal Nov 5, 2024
d9dc59e
chore: reset env
luistoptal Nov 5, 2024
a15de36
fix: typo
luistoptal Nov 5, 2024
673784e
feat: adds e2e test of the logo upload flow
luistoptal Nov 5, 2024
1771019
feat: adds tests to readme
luistoptal Nov 5, 2024
aa43466
chore: expands readme
luistoptal Nov 5, 2024
5a15df3
chore: up log
luistoptal Nov 5, 2024
40f3224
chore: Merge branch 'develop' into new-feature/376-upload-update-proj…
luistoptal Nov 15, 2024
b6c936f
chore: cleans up
luistoptal Nov 15, 2024
3371083
feat: uses tmp folder to store temp uploaded logos in project admin form
luistoptal Nov 15, 2024
487fe6e
chore: remove excessive logs
luistoptal Nov 15, 2024
8ab6092
refactor: simplifies write logo fnc
luistoptal Nov 18, 2024
2bf354e
refactor: update and write tmp logo, set uppy debug to false
luistoptal Nov 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: project CRUD wroks with logo
luistoptal committed Nov 3, 2024

Verified

This commit was signed with the committer’s verified signature.
commit 1376054f5c03b35dc75109c6408f41baf27cb299
216 changes: 159 additions & 57 deletions protected/controllers/AdminProjectController.php
Original file line number Diff line number Diff line change
@@ -25,7 +25,7 @@ public function accessRules()
{
return array(
array('allow', // admin only
'actions'=>array('admin','delete','index','view','create','update','uploadLogo'),
'actions'=>array('admin','delete','index','view','create','update','uploadTempLogo'),
'roles'=>array('admin'),
),
array('deny', // deny all users
@@ -51,92 +51,192 @@ public function actionView($id)
*/
public function actionCreate()
{
$model=new Project;
Yii::log("actionCreate: Starting project creation", "info");
$model = new Project;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

if(isset($_POST['Project']))
{
Yii::log("actionCreate: POST data received - " . print_r($_POST['Project'], true), "info");
$model->attributes=$_POST['Project'];
// save logo in permanent storage
$model->writeLogo(Yii::$app->cloudStore, Yii::$app->params['environment'] . '/' . 'images/projects/' . $model->getUuid(), $model->logo_image);
if($model->save())
$storage = Yii::$app->cloudStore;
$tempImageLocation = $model->image_location;
$model->image_location = null;

Yii::log("actionCreate: Project attributes - " . print_r($model->attributes, true), "info");
Yii::log("actionCreate: Temp image location - " . $tempImageLocation, "info");

if($model->save()) {
Yii::log("actionCreate: Project saved successfully with ID " . $model->id, "info");
// first we need to get the project id, and then we create the logo path deterministically
if ($tempImageLocation) {
Yii::log("actionCreate: Processing temp image at " . $tempImageLocation, "info");
// get file from url and save it in project folder (instance dependent, deterministic path)
$logoUrl = $model->writeLogoFromUrl($storage, $tempImageLocation);
Yii::log("actionCreate: Logo URL after writeLogoFromUrl - " . ($logoUrl ?: 'null'), "info");
$tempLogoPath = str_replace(Project::getStorageBasePath() . '/', '', $tempImageLocation);
$tempDirectory = dirname($tempLogoPath);

// delete file from payload url (it's always temp url)
if ($storage->has($tempLogoPath)) {
Yii::log("actionCreate: Attempting to delete temp file at " . $tempLogoPath, "info");
if ($storage->deleteDir($tempDirectory)) {
Yii::log("actionCreate: Deleted temp dir " . $tempDirectory, "info");
} else {
Yii::log("actionCreate: Failed to delete temp dir " . $tempDirectory, "warning");
}
} else {
Yii::log("actionCreate: Temp image not found at " . $tempImageLocation, "warning");
}

if ($logoUrl) {
Yii::log("actionCreate: Updating project with new logo URL - " . $logoUrl, "info");
// Update only the image_location and skip validation of other fields
$model->image_location = $logoUrl;
// Use updateByPk to bypass validation
Project::model()->updateByPk($model->id, array('image_location' => $logoUrl));
Yii::log("actionCreate: Project updated with logo URL successfully", "info");
}
}
$this->redirect(array('view','id'=>$model->id));
} else {
Yii::log("actionCreate: Failed to save project - " . print_r($model->getErrors(), true), "error");
}
}

$this->render('create',array(
'model'=>$model,
));
}

/**
* Make a JSON response with the given code, message, and payload.
* @param int $code The HTTP status code.
* @param string $message The message to include in the response.
* @param array $payload Additional data to include in the response.
*/
private function makeResponse($code, $message, $payload = []) {
$success = $code < 400;
header('Content-Type: application/json');
http_response_code($code);
echo CJSON::encode(array_merge([
'success' => $success,
'message' => $message,
], $payload));
Yii::app()->end();
}

/**
* Upload a logo image
*/
public function actionUploadLogo() {
// $existingLogoUrl = Yii::app()->request->getQuery('existingLogoUrl');
public function actionUploadTempLogo() {
Yii::log("actionUploadTempLogo: ", "info");
if (!isset($_FILES['logo_image'])) {
$this->makeResponse(400, 'Invalid request. No file was uploaded.');
}

$uploadedLogo = CUploadedFile::getInstanceByName('logo_image');
// get multipart data file from request
$uploadedLogoFile = CUploadedFile::getInstanceByName('logo_image');

if ($uploadedLogo->getSize() > 1_000_000) {
if ($uploadedLogoFile->getSize() > 1_000_000) {
$message = 'Invalid request. Logo image size should be less than 1MB';
Yii::app()->user->setFlash('updateError', $message);
$this->makeResponse(400, $message);
}

$random_uuid = Uuid::uuid4()->toString();
$temp_logo_dir = Yii::$app->params['environment'] . '/images/projects/temp/' . $random_uuid;
$image_location = Project::writeLogo(Yii::$app->cloudStore, $temp_logo_dir, $uploadedLogo);
// no need to delete logs from temp directory, that can be done with cron job
$storage = Yii::$app->cloudStore;

// save file to temp folder
if ($uploadedLogoFile) {
$image_location = Project::writeLogoFromFile($storage, Project::getTempLogoPath(), $uploadedLogoFile);
}

if (!$image_location) {
$message = 'Failed to save your logo image';
Yii::app()->user->setFlash('updateError', $message);
$this->makeResponse(500, $message);
}

// return temp file url
$this->makeResponse(200, 'Logo uploaded successfully', [
'image_location' => $image_location
]);
}

/**
* Make a JSON response with the given code, message, and payload.
* @param int $code The HTTP status code.
* @param string $message The message to include in the response.
* @param array $payload Additional data to include in the response.
*/
private function makeResponse($code, $message, $payload = []) {
$success = $code < 400;
header('Content-Type: application/json');
http_response_code($code);
echo CJSON::encode(array_merge([
'success' => $success,
'message' => $message,
], $payload));
Yii::app()->end();
}

/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
Yii::log("actionUpdate: Starting update for project ID: $id", "info");
$model = $this->loadModel($id);
Yii::log("actionUpdate: Loaded model with name: " . $model->name, "info");

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);

if(isset($_POST['Project']))
{
$model->attributes=$_POST['Project'];
if($model->save())
Yii::log("actionUpdate: Processing POST data for project", "info");
$prevAttributes = $model->attributes;
$newAttributes = $_POST['Project'];
Yii::log("actionUpdate: Previous image_location: " . $prevAttributes['image_location'], "info");
Yii::log("actionUpdate: New image_location: " . $newAttributes['image_location'], "info");

$model->attributes = $newAttributes;
$storage = Yii::$app->cloudStore;

// if there is a logo url and it's different from the previous one
if ($model->image_location && $model->image_location !== $prevAttributes['image_location']) {
Yii::log("actionUpdate: Detected logo change, processing new logo", "info");

// Delete old logo if it exists
if ($prevAttributes['image_location']) {
$oldPath = str_replace(Project::getStorageBasePath() . '/', '', $prevAttributes['image_location']);
$oldDir = dirname($oldPath);
if ($storage->has($oldPath)) {
$deleteResult = $storage->deleteDir($oldDir);
Yii::log("actionUpdate: Old logo deletion result: " . ($deleteResult ? 'success' : 'failed'), "info");
} else {
Yii::log("actionUpdate: Old logo file not found at: " . $oldPath, "warning");
}
}

// save new file
$logoUrl = $model->writeLogoFromUrl($storage, $model->image_location);
Yii::log("actionUpdate: New logo URL: " . ($logoUrl ?: 'failed to generate'), "info");
if ($logoUrl) {
$model->image_location = $logoUrl;
} else {
Yii::log("actionUpdate: Failed to write new logo from URL", "error");
}

// TODO refactor into helper function
$tempImageLocation = $newAttributes['image_location'];
$tempLogoPath = str_replace(Project::getStorageBasePath() . '/', '', $tempImageLocation);
$tempDirectory = dirname($tempLogoPath);

// delete temp file
if ($storage->has($tempLogoPath)) {
Yii::log("actionCreate: Attempting to delete temp file at " . $tempLogoPath, "info");
if ($storage->deleteDir($tempDirectory)) {
Yii::log("actionCreate: Deleted temp dir " . $tempDirectory, "info");
} else {
Yii::log("actionCreate: Failed to delete temp dir " . $tempDirectory, "warning");
}
} else {
Yii::log("actionCreate: Temp image not found at " . $tempImageLocation, "warning");
}
}

// NOTE I think saving the model will trigger validation and thus fail if the URL or name are left unchanged
if($model->save()) {
Yii::log("actionUpdate: Successfully saved project changes", "info");
$this->redirect(array('view','id'=>$model->id));
} else {
Yii::log("actionUpdate: Failed to save project changes. Errors: " . print_r($model->getErrors(), true), "error");
}
}

$this->render('update',array(
@@ -151,36 +251,38 @@ public function actionUpdate($id)
*/
public function actionDelete($id)
{
Yii::log("delete: $id");
$storageBasePath = ''; // 'https://' . self::BUCKET
Yii::log("actionDelete: Starting deletion process for project ID: $id", "info");

if(Yii::app()->request->isPostRequest)
{
Yii::log("actionDelete: Received valid POST request", "info");

// we only allow deletion via POST request
$model = $this->loadModel($id);
$logoUrl = $model->image_location;
$logoPath = str_replace($storageBasePath . '/', '', $logoUrl);

// I expected YII_ENV_DEV to be true but it's not defined, so using a hardcoded temporary approach for now so app does not crash each time
// $isTester = false;
// if ($isTester) {
// Yii::log("actionDelete: Tester environment, skipping actual delete", "info");
// } else {
// }
if (Yii::$app->cloudStore->delete($logoPath)) {
Yii::log("actionDelete: Deleted logo image" . $logoPath . " for project ". $id, "info");
} else {
// fail silently
Yii::log("actionDelete: Failed to delete logo image" . $logoPath . " for project ". $id, "error");
}
Yii::log("actionDelete: Loaded project model with name: " . $model->name, "info");

$model->delete();
try {
if($model->delete()) {
Yii::log("actionDelete: Successfully deleted project with ID: $id", "info");
} else {
Yii::log("actionDelete: Failed to delete project. Errors: " . print_r($model->getErrors(), true), "error");
}
} catch(\Exception $e) {
Yii::log("actionDelete: Exception while deleting project: " . $e->getMessage(), "error");
throw $e;
}

// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
if(!isset($_GET['ajax'])) {
$redirectUrl = isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin');
Yii::log("actionDelete: Redirecting to: " . print_r($redirectUrl, true), "info");
$this->redirect($redirectUrl);
}
}
else
else {
Yii::log("actionDelete: Invalid request method - must be POST", "error");
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
}

/**
Loading