Skip to content

Commit

Permalink
Merge branch '5.x' into 6.x
Browse files Browse the repository at this point in the history
  • Loading branch information
Davidmattei committed Jul 11, 2024
2 parents 6a2102b + 489d078 commit e5e78c7
Show file tree
Hide file tree
Showing 52 changed files with 3,430 additions and 3,238 deletions.
1 change: 1 addition & 0 deletions EMS/common-bundle/src/Helper/EmsFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ final class EmsFields
public const CONTENT_FILE_HASH_FIELD = 'sha1';
public const CONTENT_FILE_SIZE_FIELD = 'filesize';
public const CONTENT_FILE_NAME_FIELD = 'filename';
public const CONTENT_IMAGE_RESIZED_HASH_FIELD = '_image_resized_hash';
public const CONTENT_MIME_TYPE_FIELD_ = '_mime_type';
public const CONTENT_FILE_HASH_FIELD_ = '_hash';
public const CONTENT_FILE_ALGO_FIELD_ = '_algo';
Expand Down
9 changes: 7 additions & 2 deletions EMS/common-bundle/src/Storage/Processor/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -449,9 +449,14 @@ public static function getDefaults(): array
/**
* @param array<string, mixed> $fileField
*/
public static function extractHash(array $fileField, string $fileHashField = EmsFields::CONTENT_FILE_HASH_FIELD): string
public static function extractHash(array $fileField, string $fileHashField, string $processorType): string
{
return $fileField[EmsFields::CONTENT_FILE_HASH_FIELD_] ?? $fileField[$fileHashField] ?? 'processor';
$default = $fileField[EmsFields::CONTENT_FILE_HASH_FIELD_] ?? $fileField[$fileHashField] ?? 'processor';

return match ($processorType) {
EmsFields::ASSET_CONFIG_TYPE_IMAGE => $fileField[EmsFields::CONTENT_IMAGE_RESIZED_HASH_FIELD] ?? $default,
default => $default,
};
}

/**
Expand Down
2 changes: 1 addition & 1 deletion EMS/common-bundle/src/Storage/Processor/Processor.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function __construct(
*/
public function resolveAndGetResponse(Request $request, array $fileField, array $configArray = [], bool $immutableRoute = false): Response
{
$hash = Config::extractHash($fileField);
$hash = Config::extractHash($fileField, EmsFields::CONTENT_FILE_HASH_FIELD, \strval($configArray[EmsFields::ASSET_CONFIG_TYPE] ?? 'none'));
$filename = Config::extractFilename($fileField, $configArray);
$mimetype = Config::extractMimetype($fileField, $configArray, $filename);
$mimeType = $this->overwriteMimeType($mimetype, $configArray);
Expand Down
2 changes: 1 addition & 1 deletion EMS/common-bundle/src/Twig/AssetRuntime.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public function assetPath(array $fileField, array $assetConfig = [], string $rou
{
$config = $assetConfig;

$hash = Config::extractHash($fileField, $fileHashField);
$hash = Config::extractHash($fileField, $fileHashField, \strval($assetConfig[EmsFields::ASSET_CONFIG_TYPE] ?? 'none'));
$filename = Config::extractFilename($fileField, $config, $filenameField, $mimeTypeField);
$mimeType = Config::extractMimetype($fileField, $config, $filename, $mimeTypeField);
$referenceType = Config::extractUrlType($fileField, $referenceType);
Expand Down
44 changes: 42 additions & 2 deletions EMS/core-bundle/assets/js/EmsListeners.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import PickFileFromServer from './module/pickFileFromServer';
import FileUploader from "@elasticms/file-uploader";
import Datatables from "./module/datatables";
import {tooltipDataLinks} from "./helper/tooltip";
import {resizeImage} from "./helper/resizeImage";


export default class EmsListeners {
Expand Down Expand Up @@ -273,11 +274,41 @@ export default class EmsListeners {
}
}

_resizeImage(fileHandler, container, previewUrl){
const self = this;
const mainDiv = $(container);
const metaFields = (typeof mainDiv.data('meta-fields') !== 'undefined');
const contentInput = mainDiv.find(".content");
const resizedImageHashInput = mainDiv.find(".resized-image-hash");
const previewLink = mainDiv.find(".img-responsive");

resizeImage(this.hashAlgo, this.initUpload, fileHandler).then((response) => {
if (null === response) {
$(resizedImageHashInput).val('')
previewLink.attr('src', previewUrl);
} else {
$(resizedImageHashInput).val(response.hash)
previewLink.attr('src', response.url);
}
}).catch((errorMessage) => {
console.error(errorMessage)
$(resizedImageHashInput).val('')
previewLink.attr('src', previewUrl);
}).finally(() => {
if(metaFields && $(contentInput).length) {
self.fileDataExtrator(container);
}
else if(typeof self.onChangeCallback === "function"){
self.onChangeCallback();
}
})
}

initFileUploader(fileHandler, container){
const mainDiv = $(container);
const metaFields = (typeof mainDiv.data('meta-fields') !== 'undefined');
const sha1Input = mainDiv.find(".sha1");
const resizedImageHashInput = mainDiv.find(".resized-image-hash");
const typeInput = mainDiv.find(".type");
const nameInput = mainDiv.find(".name");
const progressBar = mainDiv.find(".progress-bar");
Expand Down Expand Up @@ -306,6 +337,7 @@ export default class EmsListeners {
emsListener: this,
onHashAvailable: function(hash, type, name){
$(sha1Input).val(hash);
$(resizedImageHashInput).val('');
$(assetHashSignature).empty().append(hash);
$(typeInput).val(type);
$(nameInput).val(name);
Expand All @@ -329,14 +361,17 @@ export default class EmsListeners {
},
onUploaded: function(assetUrl, previewUrl){
viewButton.attr('href', assetUrl);
previewLink.attr('src', previewUrl);
viewButton.removeClass("disabled");
clearButton.removeClass("disabled");
previewTab.removeClass('hidden');
uploadTab.addClass('hidden');


if(metaFields && $(contentInput).length) {
const imageTypes = ['image/png','image/jpeg','image/webp']
if(imageTypes.includes(fileHandler.type)) {
self._resizeImage(fileHandler, container, previewUrl);
}
else if(metaFields && $(contentInput).length) {
self.fileDataExtrator(container);
}
else if(typeof self.onChangeCallback === "function"){
Expand All @@ -353,6 +388,7 @@ export default class EmsListeners {
$(progressNumber).html('Error code : '+code);
}
$(sha1Input).val('');
$(resizedImageHashInput).val('');
$(assetHashSignature).empty();
$(typeInput).val('');
$(nameInput).val('');
Expand Down Expand Up @@ -432,6 +468,7 @@ export default class EmsListeners {
onAssetData(row, data){
const mainDiv = $(row);
const sha1Input = mainDiv.find(".sha1");
const resizedImageHashInput = mainDiv.find(".resized-image-hash");
const metaFields = (typeof mainDiv.data('meta-fields') !== 'undefined');
const typeInput = mainDiv.find(".type");
const nameInput = mainDiv.find(".name");
Expand All @@ -447,6 +484,7 @@ export default class EmsListeners {
const uploadTab = mainDiv.find(".asset-upload-tab");
const previewLink = mainDiv.find(".img-responsive");
sha1Input.val(data.sha1);
resizedImageHashInput.val('');
assetHashSignature.empty().append(data.sha1);
typeInput.val(data.mimetype);
nameInput.val(data.filename);
Expand Down Expand Up @@ -486,6 +524,7 @@ export default class EmsListeners {
target.find(".clear-asset-button").click(function() {
const parent = $(this).closest('.file-uploader-row');
const sha1Input = $(parent).find(".sha1");
const resizedImageHashInput = $(parent).find(".resized-image-hash");
const typeInput = $(parent).find(".type");
const nameInput = $(parent).find(".name");
const progressBar = $(parent).find(".progress-bar");
Expand All @@ -502,6 +541,7 @@ export default class EmsListeners {

$(parent).find(".file-uploader-input").val('');
sha1Input.val('');
resizedImageHashInput.val('');
assetHashSignature.empty();
typeInput.val('');
nameInput.val('');
Expand Down
17 changes: 15 additions & 2 deletions EMS/core-bundle/assets/js/component/mediaLibrary.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ajaxModal from "./../helper/ajaxModal";
import ProgressBar from "../helper/progressBar";
import FileUploader from "@elasticms/file-uploader";
import {resizeImage} from "../helper/resizeImage";

export default class MediaLibrary {
id;
Expand Down Expand Up @@ -607,7 +608,7 @@ export default class MediaLibrary {
this.#elements.listUploads.appendChild(liUpload);

this._getFileHash(file, progressBar)
.then((fileHash) => this._createFile(file, fileHash))
.then((fileHash) => this._resizeImage(file, fileHash))
.then(() => {
progressBar.status('Finished');
setTimeout(() => {
Expand All @@ -626,12 +627,24 @@ export default class MediaLibrary {
});
});
}
async _createFile(file, fileHash) {
async _resizeImage(file, fileHash) {
resizeImage(this.#options.hashAlgo, this.#options.urlInitUpload, file).then((response) => {
if (null === response) {
this._createFile(file, fileHash)
} else {
this._createFile(file, fileHash, response.hash)
}
}).catch(() => {
this._createFile(file, fileHash)
})
}
async _createFile(file, fileHash, resizedHash = null) {
const formData = new FormData();
formData.append('name', file.name);
formData.append('filesize', file.size);
formData.append('fileMimetype', file.type);
formData.append('fileHash', fileHash);
formData.append('fileResizedHash', resizedHash);

const path = this.#activeFolderId ? `/add-file/${this.#activeFolderId}` : '/add-file';
await this._post(path, formData, true)
Expand Down
97 changes: 97 additions & 0 deletions EMS/core-bundle/assets/js/helper/resizeImage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
'use strict'

import FileUploader from '@elasticms/file-uploader'

async function resizeImage(hashAlgo, initUpload, fileHandler) {
return new Promise((resolve, reject) => {
const imageTypes = ['image/png','image/jpeg','image/webp']
if (!imageTypes.includes(fileHandler.type)) {
resolve(null)
}

let fileHash = null
const reader = new FileReader()
const imageMaxSize = document.body.dataset.imageMaxSize
reader.onload = function (e) {
const image = new Image()
image.onload = function (imageEvent) {
const canvas = document.createElement('canvas')
let width = image.width
let height = image.height
if (width <= imageMaxSize && height <= imageMaxSize) {
resolve(null)
}
if (width > height) {
if (width > imageMaxSize) {
height = Math.round(height * imageMaxSize / width)
width = imageMaxSize
}
} else {
if (height > imageMaxSize) {
width = Math.round(width * imageMaxSize / height)
height = imageMaxSize
}
}
canvas.width = width
canvas.height = height
canvas.getContext('2d').drawImage(image, 0, 0, width, height)
const dataUrl = canvas.toDataURL(fileHandler.type)
const resizedImage = dataUrlToBlob(dataUrl)
let basename = fileHandler.name
let extension = ''
if(basename.lastIndexOf('.') !== -1) {
extension = basename.substring(basename.lastIndexOf("."))
basename = basename.substring(0, basename.lastIndexOf("."))
}
resizedImage.name = `${basename}_${width}x${height}${extension}`

const resizedImageUploader = new FileUploader({
file: resizedImage,
algo: hashAlgo,
initUrl: initUpload,
emsListener: self,
onHashAvailable: function(hash){
fileHash = hash
},
onUploaded: function(assetUrl, previewUrl){
resolve({
hash: fileHash,
url: previewUrl,
})
},
onError: function(message, code){
reject(`Error ${code} during upload of resized image with message: ${message}`)
},
})
}
image.src = e.target.result
}
reader.readAsDataURL(fileHandler)
})
}

function dataUrlToBlob(dataUrl) {
const BASE64_MARKER = ';base64,'
if (dataUrl.indexOf(BASE64_MARKER) === -1) {
const parts = dataUrl.split(',')
const contentType = parts[0].split(':')[1]
const raw = parts[1]

return new Blob([raw], {type: contentType})
}

const parts = dataUrl.split(BASE64_MARKER)
const contentType = parts[0].split(':')[1]
const raw = window.atob(parts[1])
const rawLength = raw.length

const uInt8Array = new Uint8Array(rawLength)

for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i)
}

return new Blob([uInt8Array], {type: contentType})
}

export { resizeImage, dataUrlToBlob }
Loading

0 comments on commit e5e78c7

Please sign in to comment.