Skip to content

Commit

Permalink
fix: Reset session if file rename changes mimetype from/to markdown
Browse files Browse the repository at this point in the history
For the event target file, we cannot use `getMimetype()` or
`getExtension()` as it's a node of type `NonExistingFile`.

Fixes: #5736

Signed-off-by: Jonas <jonas@freesources.org>
  • Loading branch information
mejo- committed Sep 11, 2024
1 parent c7264fc commit 380d5b9
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions lib/Listeners/BeforeNodeRenamedListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,23 @@

namespace OCA\Text\Listeners;

use Exception;
use OCA\Text\Service\AttachmentService;
use OCA\Text\Service\DocumentService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\Events\Node\BeforeNodeRenamedEvent;
use OCP\Files\File;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<Event|BeforeNodeRenamedEvent>
*/
class BeforeNodeRenamedListener implements IEventListener {
private AttachmentService $attachmentService;

public function __construct(AttachmentService $attachmentService) {
$this->attachmentService = $attachmentService;
public function __construct(
private readonly AttachmentService $attachmentService,
private readonly DocumentService $documentService,
private readonly LoggerInterface $logger) {
}

public function handle(Event $event): void {
Expand All @@ -30,10 +33,24 @@ public function handle(Event $event): void {
}
$source = $event->getSource();
$target = $event->getTarget();
if ($source instanceof File
&& $source->getMimeType() === 'text/markdown'
&& $target instanceof File
) {

if (!($source instanceof File && $target instanceof File)) {
return;
}

$sourceIsMarkdown = $source->getMimeType() === 'text/markdown';
$targetIsMarkdown = pathinfo($target->getPath(), PATHINFO_EXTENSION) === 'md'; // NonExistingFile has no `getMimetype()`

// Reset document state if mimetype changes from/to markdown as this means another editor is loaded
if ($sourceIsMarkdown xor $targetIsMarkdown) {
try {
$this->documentService->resetDocument($source->getId(), true);
} catch (Exception $e) {
$this->logger->error($e->getMessage(), ['exception' => $e]);
}
}

if ($sourceIsMarkdown) {
$this->attachmentService->moveAttachments($source, $target);
}
}
Expand Down

0 comments on commit 380d5b9

Please sign in to comment.