Skip to content
Merged
Changes from all commits
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
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