Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Next Next commit
manual backport of #2426, refs #2411, Improve image attachment manage…
…ment

Signed-off-by: Julien Veyssier <[email protected]>
  • Loading branch information
Julien Veyssier committed May 24, 2022
commit c44751edc28faf397f3209b24d11647559fb3017
2 changes: 1 addition & 1 deletion cypress/integration/images.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const checkImage = (documentId, imageName, imageId, index) => {
cy.log('Check the image is visible and well formed', { documentId, imageName, imageId, index, encodedName })
return new Cypress.Promise((resolve, reject) => {
cy.get('#editor [data-component="image-view"]')
.filter('[data-src="text://image?imageFileName=' + encodedName + '"]')
.filter('[data-src=".attachments.' + documentId + '/' + encodedName + '"]')
.find('.image__view') // wait for load finish
.within(($el) => {
// keep track that we have created this image in the attachment dir
Expand Down
26 changes: 22 additions & 4 deletions lib/Service/ImageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ public function uploadImage(int $documentId, string $newFileName, $newFileResour
$savedFile = $saveDir->newFile($fileName, $newFileResource);
return [
'name' => $fileName,
'dirname' => $saveDir->getName(),
'id' => $savedFile->getId(),
'documentId' => $textFile->getId(),
];
Expand Down Expand Up @@ -183,6 +184,7 @@ public function uploadImagePublic(?int $documentId, string $newFileName, $newFil
$savedFile = $saveDir->newFile($fileName, $newFileResource);
return [
'name' => $fileName,
'dirname' => $saveDir->getName(),
'id' => $savedFile->getId(),
'documentId' => $textFile->getId(),
];
Expand Down Expand Up @@ -227,6 +229,7 @@ private function copyImageFile(File $imageFile, Folder $saveDir, File $textFile)
// get file type and name
return [
'name' => $fileName,
'dirname' => $saveDir->getName(),
'id' => $targetFile->getId(),
'documentId' => $textFile->getId(),
];
Expand Down Expand Up @@ -457,7 +460,7 @@ public function cleanupAttachments(int $fileId): int {
$attachmentsByName[$attNode->getName()] = $attNode;
}

$contentAttachmentNames = $this->getAttachmentNamesFromContent($textFile->getContent());
$contentAttachmentNames = $this->getAttachmentNamesFromContent($textFile->getContent(), $fileId);

$toDelete = array_diff(array_keys($attachmentsByName), $contentAttachmentNames);
foreach ($toDelete as $name) {
Expand All @@ -476,20 +479,35 @@ public function cleanupAttachments(int $fileId): int {
* @param string $content
* @return array
*/
public static function getAttachmentNamesFromContent(string $content): array {
$matches = [];
public static function getAttachmentNamesFromContent(string $content, int $fileId): array {
$oldMatches = [];
preg_match_all(
// simple version with .+ between the brackets
// '/\!\[.+\]\(text:\/\/image\?[^)]*imageFileName=([^)&]+)\)/',
// complex version of php-markdown
// matches ![ANY_CONSIDERED_CORRECT_BY_PHP-MARKDOWN](text://image?ANYTHING&imageFileName=FILE_NAME) and captures FILE_NAME
'/\!\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[\])*\])*\])*\])*\])*\])*\]\(text:\/\/image\?[^)]*imageFileName=([^)&]+)\)/',
$content,
$oldMatches,
PREG_SET_ORDER
);
$oldNames = array_map(static function (array $match) {
return urldecode($match[1]);
}, $oldMatches);

$matches = [];
// matches ![ANY_CONSIDERED_CORRECT_BY_PHP-MARKDOWN](.attachments.DOCUMENT_ID/ANY_FILE_NAME) and captures FILE_NAME
preg_match_all(
'/\!\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[(?>[^\[\]]+|\[\])*\])*\])*\])*\])*\])*\]\(\.attachments\.'.$fileId.'\/([^)&]+)\)/',
$content,
$matches,
PREG_SET_ORDER
);
return array_map(static function (array $match) {
$names = array_map(static function (array $match) {
return urldecode($match[1]);
}, $matches);

return array_merge($names, $oldNames);
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/components/EditorWrapper.vue
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ export default {
}

return this.$syncService.uploadImage(file).then((response) => {
this.insertAttachmentImage(response.data?.name, response.data?.id, position)
this.insertAttachmentImage(response.data?.name, response.data?.id, position, response.data?.dirname)
}).catch((error) => {
console.error(error)
showError(error?.response?.data?.error)
Expand All @@ -625,18 +625,18 @@ export default {
insertImagePath(imagePath) {
this.uploadingImages = true
this.$syncService.insertImageFile(imagePath).then((response) => {
this.insertAttachmentImage(response.data?.name, response.data?.id)
this.insertAttachmentImage(response.data?.name, response.data?.id, null, response.data?.dirname)
}).catch((error) => {
console.error(error)
showError(error?.response?.data?.error)
}).then(() => {
this.uploadingImages = false
})
},
insertAttachmentImage(name, fileId, position = null) {
insertAttachmentImage(name, fileId, position = null, dirname = '') {
// inspired by the fixedEncodeURIComponent function suggested in
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
const src = 'text://image?imageFileName='
const src = dirname + '/'
+ encodeURIComponent(name).replace(/[!'()*]/g, (c) => {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
Expand Down
118 changes: 76 additions & 42 deletions src/nodes/ImageView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ export default {
loaded: false,
failed: false,
showIcons: false,
imageUrl: null,
}
},
computed: {
Expand All @@ -151,39 +152,6 @@ export default {
})
}
},
imageUrl() {
if (this.src.startsWith('text://')) {
const documentId = this.currentSession?.documentId
const sessionId = this.currentSession?.id
const sessionToken = this.currentSession?.token
const imageFileName = getQueryVariable(this.src, 'imageFileName')
if (getCurrentUser() || !this.token) {
return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}',
{
documentId,
sessionId,
sessionToken,
imageFileName,
})
} else {
return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}&shareToken={shareToken}',
{
documentId,
sessionId,
sessionToken,
imageFileName,
shareToken: this.token,
})
}
}
if (this.isRemoteUrl || this.isPreviewUrl || this.isDataUrl) {
return this.src
}
if (this.hasPreview && this.mime !== 'image/gif') {
return this.previewUrl
}
return this.davUrl
},
isRemoteUrl() {
return this.src.startsWith('http://')
|| this.src.startsWith('https://')
Expand All @@ -195,6 +163,9 @@ export default {
isDataUrl() {
return this.src.startsWith('data:')
},
isDirectUrl() {
return (this.isRemoteUrl || this.isPreviewUrl || this.isDataUrl)
},
basename() {
return decodeURI(this.src.split('?')[0])
},
Expand Down Expand Up @@ -280,18 +251,59 @@ export default {
this.loaded = true
return
}
const img = new Image()
img.onload = () => {
this.imageLoaded = true
}
img.onerror = () => {
this.init().catch((e) => {
this.onImageLoadFailure()
})
},
methods: {
async init() {
if (this.src.startsWith('text://')) {
const imageFileName = getQueryVariable(this.src, 'imageFileName')
return this.loadImage(this.getTextApiUrl(imageFileName))
}
if (this.src.startsWith(`.attachments.${this.currentSession?.documentId}/`)) {
const imageFileName = decodeURIComponent(this.src.replace(`.attachments.${this.currentSession?.documentId}/`, '').split('?')[0])
return this.loadImage(this.getTextApiUrl(imageFileName))
}
if (this.isDirectUrl) {
return this.loadImage(this.src)
}
if (this.hasPreview && this.mime !== 'image/gif') {
return this.loadImage(this.previewUrl)
}
// if it starts with '.attachments.1234/'
if (this.src.match(/^\.attachments\.\d+\//)) {
// try the webdav url
return this.loadImage(this.davUrl).catch((e) => {
// try the attachment API
const imageFileName = decodeURIComponent(this.src.replace(/\.attachments\.\d+\//, '').split('?')[0])
const textApiUrl = this.getTextApiUrl(imageFileName)
return this.loadImage(textApiUrl).then(() => {
// TODO if attachment works, rewrite the url with correct document ID
})
})
}
this.loadImage(this.davUrl)
},
async loadImage(imageUrl) {
return new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => {
this.imageUrl = imageUrl
this.imageLoaded = true
resolve()
}
img.onerror = (e) => {
reject(e)
}
img.src = imageUrl
})
},
onImageLoadFailure() {
this.failed = true
this.imageLoaded = false
this.loaded = true
}
img.src = this.imageUrl
},
methods: {
},
updateAlt() {
this.alt = this.$refs.altInput.value
},
Expand All @@ -301,6 +313,28 @@ export default {
this.editor.commands.scrollIntoView()
})
},
getTextApiUrl(imageFileName) {
const documentId = this.currentSession?.documentId
const sessionId = this.currentSession?.id
const sessionToken = this.currentSession?.token
if (getCurrentUser() || !this.token) {
return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}',
{
documentId,
sessionId,
sessionToken,
imageFileName,
})
}
return generateUrl('/apps/text/image?documentId={documentId}&sessionId={sessionId}&sessionToken={sessionToken}&imageFileName={imageFileName}&shareToken={shareToken}',
{
documentId,
sessionId,
sessionToken,
imageFileName,
shareToken: this.token,
})
},
},
}
</script>
Expand Down
87 changes: 0 additions & 87 deletions src/tests/nodes/ImageView.spec.js

This file was deleted.

Loading