Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add missing functions for fetching subobjects and result statistics #105

Open
wants to merge 7 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
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
132 changes: 132 additions & 0 deletions lib/Db/File.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

namespace OCA\OpenRegister\Db;

use DateTime;
use JsonSerializable;
use OCP\AppFramework\Db\Entity;
use OCP\IURLGenerator;

class File extends Entity implements JsonSerializable
{
protected ?string $uuid = null;
protected ?string $filename = null;
protected ?string $downloadUrl = null;
protected ?string $shareUrl = null;
protected ?string $accessUrl = null;
protected ?string $extension = null;
protected ?string $checksum = null;
protected ?int $source = null;
protected ?string $userId = null;
protected ?string $base64 = null;
protected ?string $filePath = null;
protected ?DateTime $created = null;
protected ?DateTime $updated = null;

public function __construct() {
$this->addType('uuid', 'string');
$this->addType('filename', 'string');
$this->addType('downloadUrl', 'string');
$this->addType('shareUrl', 'string');
$this->addType('accessUrl', 'string');
$this->addType('extension', 'string');
$this->addType('checksum', 'string');
$this->addType('source', 'int');
$this->addType('userId', 'string');
$this->addType('created', 'datetime');
$this->addType('updated', 'datetime');
}

public function getJsonFields(): array
{
return array_keys(
array_filter($this->getFieldTypes(), function ($field) {
return $field === 'json';
})
);
}

public function hydrate(array $object): self
{
$jsonFields = $this->getJsonFields();

foreach ($object as $key => $value) {
if (in_array($key, $jsonFields) === true && $value === []) {
$value = [];
}

$method = 'set'.ucfirst($key);

try {
$this->$method($value);
} catch (\Exception $exception) {
// ("Error writing $key");
}
}

return $this;
}

public function jsonSerialize(): array
{
return [
'id' => $this->id,
'uuid' => $this->uuid,
'filename' => $this->filename,
'downloadUrl' => $this->downloadUrl,
'shareUrl' => $this->shareUrl,
'accessUrl' => $this->accessUrl,
'extension' => $this->extension,
'checksum' => $this->checksum,
'source' => $this->source,
'userId' => $this->userId,
'created' => isset($this->created) ? $this->created->format('c') : null,
'updated' => isset($this->updated) ? $this->updated->format('c') : null,
];
}

public static function getSchema(IURLGenerator $IURLGenerator): string {
return json_encode([
'$id' => $IURLGenerator->getBaseUrl().'/apps/openconnector/api/files/schema',
'$schema' => 'https://json-schema.org/draft/2020-12/schema',
'type' => 'object',
'required' => [
],
'properties' => [
'filename' => [
'type' => 'string',
'minLength' => 1,
'maxLength' => 255
],
'downloadUrl' => [
'type' => 'string',
'format' => 'uri',
],
'shareUrl' => [
'type' => 'string',
'format' => 'uri',
],
'accessUrl' => [
'type' => 'string',
'format' => 'uri',
],
'extension' => [
'type' => 'string',
'maxLength' => 10,
],
'checksum' => [
'type' => 'string',
],
'source' => [
'type' => 'number',
],
'userId' => [
'type' => 'string',
],
'base64' => [
'type' => 'string'
]
]
]);
}
}
141 changes: 141 additions & 0 deletions lib/Db/FileMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php

namespace OCA\OpenRegister\Db;

use DateTime;
use OCA\OpenRegister\Db\File;
use OCP\AppFramework\Db\Entity;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use Symfony\Component\Uid\Uuid;

class FileMapper extends QBMapper
{
public function __construct(IDBConnection $db)
{
parent::__construct($db, 'openregister_files');
}

public function find(int $id): File
{
$qb = $this->db->getQueryBuilder();

$qb->select('*')
->from('openregister_files')
->where(
$qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))
);

return $this->findEntity(query: $qb);
}

public function findAll(?int $limit = null, ?int $offset = null, ?array $filters = [], ?array $searchConditions = [], ?array $searchParams = []): array
{
$qb = $this->db->getQueryBuilder();

$qb->select('*')
->from('openregister_files')
->setMaxResults($limit)
->setFirstResult($offset);

foreach ($filters as $filter => $value) {
$filter = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $filter));
if ($value === 'IS NOT NULL') {
$qb->andWhere($qb->expr()->isNotNull($filter));
} elseif ($value === 'IS NULL') {
$qb->andWhere($qb->expr()->isNull($filter));
} else {
$qb->andWhere($qb->expr()->eq($filter, $qb->createNamedParameter($value)));
}
}

if (empty($searchConditions) === false) {
$qb->andWhere('(' . implode(' OR ', $searchConditions) . ')');
foreach ($searchParams as $param => $value) {
$qb->setParameter($param, $value);
}
}

return $this->findEntities(query: $qb);
}

/**
* @inheritDoc
*
* @param \OCA\OpenRegister\Db\File|Entity $entity
* @return \OCA\OpenRegister\Db\File
* @throws \OCP\DB\Exception
*/
public function insert(File|Entity $entity): File
{
// Set created and updated fields
$entity->setCreated(new DateTime());
$entity->setUpdated(new DateTime());

if($entity->getUuid() === null) {
$entity->setUuid(Uuid::v4());
}

return parent::insert($entity);
}

/**
* @inheritDoc
*
* @param \OCA\OpenRegister\Db\File|Entity $entity
* @return \OCA\OpenRegister\Db\File
* @throws \OCP\DB\Exception
*/
public function update(File|Entity $entity): File
{
// Set updated field
$entity->setUpdated(new DateTime());

return parent::update($entity);
}

public function createFromArray(array $object): File
{
$obj = new File();
$obj->hydrate($object);
// Set uuid
if ($obj->getUuid() === null){
$obj->setUuid(Uuid::v4());
}
return $this->insert(entity: $obj);
}

public function updateFromArray(int $id, array $object): File
{
$obj = $this->find($id);
$obj->hydrate($object);

// Set or update the version
$version = explode('.', $obj->getVersion());
$version[2] = (int)$version[2] + 1;
$obj->setVersion(implode('.', $version));

return $this->update($obj);
}

/**
* Get the total count of all call logs.
*
* @return int The total number of call logs in the database.
*/
public function getTotalCallCount(): int
{
$qb = $this->db->getQueryBuilder();

// Select count of all logs
$qb->select($qb->createFunction('COUNT(*) as count'))
->from('openregister_files');

$result = $qb->execute();
$row = $result->fetch();

// Return the total count
return (int)$row['count'];
}
}
24 changes: 23 additions & 1 deletion lib/Db/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,28 @@ public function getSchemaObject(IURLGenerator $urlGenerator): object
foreach ($data['properties'] as $title => $property) {
// Remove empty fields with array_filter().
$data['properties'][$title] = array_filter($property);

if($property['type'] === 'file') {
$data['properties'][$title] = ['$ref' => $urlGenerator->getBaseUrl().'/apps/openregister/api/files/schema'];
}
if($property['type'] === 'oneOf') {
unset($data['properties'][$title]['type']);
$data['properties'][$title]['oneOf'] = array_map(
callback: function (array $item) use ($urlGenerator) {
if($item['type'] === 'file') {
unset($item['type']);
$item['$ref'] = $urlGenerator->getBaseUrl().'/apps/openregister/api/files/schema';
}

return $item;
},
array: $property['oneOf']);
}
if($property['type'] === 'array'
&& isset($property['items']['type']) === true
&& $property['items']['type'] === 'oneOf') {
unset($data['properties'][$title]['items']['type']);
}
}

unset($data['id'], $data['uuid'], $data['summary'], $data['archive'], $data['source'],
Expand All @@ -141,7 +163,7 @@ public function getSchemaObject(IURLGenerator $urlGenerator): object

// Validator needs this specific $schema
$data['$schema'] = 'https://json-schema.org/draft/2020-12/schema';
$data['$id'] = $urlGenerator->getAbsoluteURL($urlGenerator->linkToRoute('openregister.Schemas.show', ['id' => $this->getUuid()]));
$data['$id'] = $urlGenerator->getAbsoluteURL($urlGenerator->linkToRoute('openregister.Schemas.show', ['id' => $this->getId()]));

return json_decode(json_encode($data));
}
Expand Down
70 changes: 70 additions & 0 deletions lib/Migration/Version1Date20241216094112.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\OpenRegister\Migration;

use Closure;
use Doctrine\DBAL\Types\Types;
use OCP\DB\ISchemaWrapper;
use OCP\Migration\IOutput;
use OCP\Migration\SimpleMigrationStep;

/**
* FIXME Auto-generated migration step: Please modify to your needs!
*/
class Version1Date20241216094112 extends SimpleMigrationStep {

/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
*/
public function preSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
}

/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
* @return null|ISchemaWrapper
*/
public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper {
/** @var ISchemaWrapper $schema */
$schema = $schemaClosure();

if($schema->hasTable('openregister_files') === false) {
$table = $schema->createTable('openregister_files');
$table->addColumn(name: 'id', typeName: Types::BIGINT, options: ['autoincrement' => true, 'notnull' => true, 'length' => 255]);
$table->addColumn(name: 'uuid', typeName: Types::STRING, options: ['notnull' => true, 'length' => 255]);
$table->addColumn(name: 'filename', typeName: Types::STRING, options: ['notnull' => false, 'length' => 255]);
$table->addColumn(name: 'download_url', typeName: Types::STRING, options: ['notnull' => false, 'length' => 1023]);
$table->addColumn(name: 'share_url', typeName: Types::STRING, options: ['notnull' => false, 'length' => 1023]);
$table->addColumn(name: 'access_url', typeName: Types::STRING, options: ['notnull' => false, 'length' => 1023]);
$table->addColumn(name: 'extension', typeName: Types::STRING, options: ['notnull' => false, 'length' => 255]);
$table->addColumn(name: 'checksum', typeName: Types::STRING, options: ['notnull' => false, 'length' => 255]);
$table->addColumn(name: 'source', typeName: Types::INTEGER, options: ['notnull' => false, 'length' => 255]);
$table->addColumn(name: 'user_id', typeName: Types::STRING, options: ['notnull' => false, 'length' => 255]);
$table->addColumn(name: 'created', typeName: Types::DATETIME_IMMUTABLE, options: ['notnull' => true, 'length' => 255]);
$table->addColumn(name: 'updated', typeName: Types::DATETIME_MUTABLE, options: ['notnull' => true, 'length' => 255]);
$table->addColumn(name: 'file_path', typeName: Types::STRING);

$table->setPrimaryKey(['id']);
}

return $schema;
}

/**
* @param IOutput $output
* @param Closure(): ISchemaWrapper $schemaClosure
* @param array $options
*/
public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $options): void {
}
}
Loading
Loading