Skip to content

Commit

Permalink
Catch and log error thrown while parsing dates from metadata
Browse files Browse the repository at this point in the history
Signed-off-by: Côme Chilliet <[email protected]>
  • Loading branch information
come-nc committed Dec 11, 2023
1 parent 38f560b commit 5c9bb54
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions lib/Listener/OriginalDateTimeMetadataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,15 @@
use OCP\EventDispatcher\IEventListener;
use OCP\Files\File;
use OCP\FilesMetadata\Event\MetadataLiveEvent;
use Psr\Log\LoggerInterface;

/**
* @template-implements IEventListener<MetadataLiveEvent>
*/
class OriginalDateTimeMetadataProvider implements IEventListener {
public function __construct() {
public function __construct(
private LoggerInterface $logger,
) {
}

public array $regexpToDateFormatMap = [
Expand All @@ -43,6 +46,27 @@ public function __construct() {
"/^([0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{4})/" => "Y-m-d-G-i-s",
];

private function dateToTimestamp(string $format, string $date, File $node): int|false {
try {
$dateTime = DateTime::createFromFormat($format, $date);
if ($dateTime !== false) {
return $dateTime->getTimestamp();
}
return false;
} catch (\Throwable $t) {
/* Date comes from user data and may trigger ValueError or DateRangeError */
$this->logger->warning(
'Failed to parse date {date} for file {path}',
[
'date' => $date,
'path' => $node->getPath(),
'exception' => $t,
]
);
return false;
}
}

public function handle(Event $event): void {
if (!($event instanceof MetadataLiveEvent)) {
return;
Expand All @@ -63,9 +87,9 @@ public function handle(Event $event): void {
// Try to use EXIF data.
if ($metadata->hasKey('photos-exif') && array_key_exists('DateTimeOriginal', $metadata->getArray('photos-exif'))) {
$rawDateTimeOriginal = $metadata->getArray('photos-exif')['DateTimeOriginal'];
$dateTimeOriginal = DateTime::createFromFormat("Y:m:d G:i:s", $rawDateTimeOriginal);
if ($dateTimeOriginal !== false) {
$metadata->setInt('photos-original_date_time', $dateTimeOriginal->getTimestamp(), true);
$timestampOriginal = $this->dateToTimestamp("Y:m:d G:i:s", $rawDateTimeOriginal, $node);
if ($timestampOriginal !== false) {
$metadata->setInt('photos-original_date_time', $timestampOriginal, true);
return;
}
}
Expand All @@ -80,9 +104,9 @@ public function handle(Event $event): void {
continue;
}

$dateTimeOriginal = DateTime::createFromFormat($format, $matches[1]);
if ($dateTimeOriginal !== false) {
$metadata->setInt('photos-original_date_time', $dateTimeOriginal->getTimestamp(), true);
$timestampOriginal = $this->dateToTimestamp($format, $matches[1], $node);
if ($timestampOriginal !== false) {
$metadata->setInt('photos-original_date_time', $timestampOriginal, true);
return;
}
}
Expand Down

0 comments on commit 5c9bb54

Please sign in to comment.