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

Layer upload (GeoTIFF and zipped SHP) #137

Merged
merged 5 commits into from
Nov 11, 2022
Merged
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
7 changes: 7 additions & 0 deletions assets/fallbackConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ var shogunApplicationConfig = {
]
}
},
geoserver: {
base: '/geoserver',
upload: {
workspace: 'SHOGUN',
limit: 200000000, // ~200MB
}
},
models: [
'Application',
'Layer',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@

.left-toolbar {
padding: 0 0 10px 0;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
}

Expand Down
330 changes: 316 additions & 14 deletions src/Component/GeneralEntity/GeneralEntityRoot/GeneralEntityRoot.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,97 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, {
useCallback,
useEffect,
useMemo,
useState
} from 'react';

import {
useNavigate,
useLocation,
matchPath,
Link
} from 'react-router-dom';
import { useHotkeys } from 'react-hotkeys-hook';
import { Button, PageHeader, Form, notification } from 'antd';

import {
useHotkeys
} from 'react-hotkeys-hook';

import {
Button,
PageHeader,
Form,
notification,
Upload
} from 'antd';

import {
FormOutlined,
SaveOutlined,
UndoOutlined,
UploadOutlined
} from '@ant-design/icons';

import {
RcFile,
UploadChangeParam
} from 'antd/lib/upload';
import {
UploadFile
} from 'antd/lib/upload/interface';

import {
UploadRequestOption
} from 'rc-upload/lib/interface';

import {
NamePath
} from 'rc-field-form/lib/interface';

import _isEmpty from 'lodash/isEmpty';

import { ControllerUtil } from '../../../Controller/ControllerUtil';
import { FormOutlined, SaveOutlined, UndoOutlined } from '@ant-design/icons';
import { GenericEntityController } from '../../../Controller/GenericEntityController';
import Logger from '@terrestris/base-util/dist/Logger';
import { NamePath } from 'rc-field-form/lib/interface';
import {
useTranslation
} from 'react-i18next';
import i18next from 'i18next';

import {
getBearerTokenHeader
} from '@terrestris/shogun-util/dist/security/getBearerTokenHeader';
import BaseEntity from '@terrestris/shogun-util/dist/model/BaseEntity';
import config from 'shogunApplicationConfig';
import GeneralEntityForm, { FormConfig } from '../GeneralEntityForm/GeneralEntityForm';
import GeneralEntityTable, { TableConfig } from '../GeneralEntityTable/GeneralEntityTable';
import Logger from '@terrestris/base-util/dist/Logger';

import {
ControllerUtil
} from '../../../Controller/ControllerUtil';
import {
GenericEntityController
} from '../../../Controller/GenericEntityController';
import GeneralEntityForm, {
FormConfig
} from '../GeneralEntityForm/GeneralEntityForm';
import GeneralEntityTable, {
TableConfig
} from '../GeneralEntityTable/GeneralEntityTable';
import useSHOGunAPIClient from '../../../Hooks/useSHOGunAPIClient';
import TranslationUtil from '../../../Util/TranslationUtil';

import { useTranslation } from 'react-i18next';
import config from 'shogunApplicationConfig';

import './GeneralEntityRoot.less';

import i18next from 'i18next';
import TranslationUtil from '../../../Util/TranslationUtil';
type LayerUploadOptions = {
baseUrl: string;
workspace: string;
storeName: string;
layerName: string;
file: RcFile;
};

type LayerUploadResponse = {
layerName: string;
workspace: string;
baseUrl: string;
};

export type GeneralEntityConfigType<T extends BaseEntity> = {
i18n: FormTranslations;
Expand Down Expand Up @@ -68,6 +134,7 @@ export function GeneralEntityRoot<T extends BaseEntity>({
const [formValid, setFormValid] = useState<boolean>(true);
const [isGridLoading, setGridLoading] = useState<boolean>(false);
const [isSaving, setIsSaving] = useState<boolean>(false);
const [isUploadingFile, setIsUploadingFile] = useState<boolean>(false);

const [form] = Form.useForm();
const client = useSHOGunAPIClient();
Expand Down Expand Up @@ -227,6 +294,217 @@ export function GeneralEntityRoot<T extends BaseEntity>({
}
};

const onBeforeFileUpload = (file: RcFile) => {
// TODO: Complete quality check
// 1. Check for file size. What should the limit be? Format dependent?
// 2. Check if the selected file format is valid
// 3. Check if the file is not broken/corrupted
// 4. Other checks
LukasLohoff marked this conversation as resolved.
Show resolved Hide resolved
const maxSize = config.geoserver?.upload?.limit || '200000000';
const fileType = file.type;
const fileSize = file.size;

// 1. Check file size
if (fileSize > maxSize) {
notification.error({
message: t('GeneralEntityRoot.upload.error.message', {
entity: TranslationUtil.getTranslationFromConfig(entityName, i18n)
}),
description: t('GeneralEntityRoot.upload.error.descriptionSize', {
maxSize: maxSize / 1000000
})
});

return false;
}

// 2. Check file format
const supportedFormats = ['application/zip', 'image/tiff'];
if (!supportedFormats.includes(fileType)) {
notification.error({
message: t('GeneralEntityRoot.upload.error.message', {
entity: TranslationUtil.getTranslationFromConfig(entityName, i18n)
}),
description: t('GeneralEntityRoot.upload.error.descriptionFormat', {
supportedFormats: supportedFormats.join(', ')
})
});

return false;
}

return true;
};

const uploadGeoTiff = async (options: LayerUploadOptions): Promise<void> => {
const {
baseUrl,
workspace,
storeName,
layerName,
file
} = options;

const url = `${baseUrl}/rest/workspaces/${workspace}/coveragestores/` +
`${storeName}/file.geotiff?coverageName=${layerName}`;

const response = await fetch(url, {
method: 'PUT',
headers: {
...getBearerTokenHeader(client?.getKeycloak()),
'Content-Type': 'image/tiff'
},
body: file
});

if (!response.ok) {
throw new Error('No successful response while uploading the file');
}
};

const uploadShapeZip = async (options: LayerUploadOptions): Promise<void> => {
const {
baseUrl,
workspace,
storeName,
layerName,
file
} = options;

const url = `${baseUrl}/rest/workspaces/${workspace}/datastores/` +
`${storeName}/file.shp?configure=none`;

const response = await fetch(url, {
method: 'PUT',
headers: {
...getBearerTokenHeader(client?.getKeycloak()),
'Content-Type': 'application/zip'
},
body: file
});

if (!response.ok) {
throw new Error('No successful response while uploading the file');
}

const featureTypeUrl = `${baseUrl}/rest/workspaces/${workspace}/datastores/${storeName}/featuretypes`;

const featureTypeResponse = await fetch(featureTypeUrl, {
method: 'POST',
headers: {
...getBearerTokenHeader(client?.getKeycloak()),
'Content-Type': 'application/json'
},
body: JSON.stringify({
featureType: {
enabled: true,
name: layerName,
nativeName: file.name.split('.')[0],
title: layerName
}
})
});

if (!featureTypeResponse.ok) {
throw new Error('No successful response while creating the featuretype');
}
};

const onFileUploadAction = async (options: UploadRequestOption<LayerUploadResponse>) => {
const {
onError,
onSuccess,
file
} = options;

const splittedFileName = (file as RcFile).name.split('.');
const fileType = (file as RcFile).type;
const geoServerBaseUrl = config.geoserver?.base || '/geoserver';
const workspace = config.geoserver?.upload?.workspace || 'SHOGUN';
const layerName = `${splittedFileName[0]}_${Date.now()}`.toUpperCase();

const uploadData = {
file: file as RcFile,
baseUrl: geoServerBaseUrl,
workspace: workspace,
storeName: layerName,
layerName: layerName
};

try {
if (fileType === 'image/tiff') {
await uploadGeoTiff(uploadData);
}

if (fileType === 'application/zip') {
await uploadShapeZip(uploadData);
}

onSuccess({
baseUrl: geoServerBaseUrl,
workspace: workspace,
layerName: layerName
});
} catch (error) {
onError({
name: 'UploadError',
message: error.message
});
}
};

const onFileUploadChange = async(info: UploadChangeParam<UploadFile<LayerUploadResponse>>) => {
const file = info.file;

if (file.status === 'uploading') {
setIsUploadingFile(true);
}

if (file.status === 'done') {
await client.layer().add({
name: file.response.layerName,
type: 'TILEWMS',
clientConfig: {
hoverable: false
},
sourceConfig: {
url: `${file.response.baseUrl}/ows?`,
layerNames: `${file.response.workspace}:${file.response.layerName}`,
useBearerToken: true
}
});

// Refresh the list
fetchEntities();

// Finally, show success message
setIsUploadingFile(false);

notification.success({
message: t('GeneralEntityRoot.upload.success.message', {
entity: TranslationUtil.getTranslationFromConfig(entityName, i18n)
}),
description: t('GeneralEntityRoot.upload.success.description', {
fileName: file.fileName,
layerName: file.response.layerName
}),
});
} else if (file.status === 'error') {
setIsUploadingFile(false);

Logger.error(file.error);

notification.error({
message: t('GeneralEntityRoot.upload.error.message', {
entity: TranslationUtil.getTranslationFromConfig(entityName, i18n)
}),
description: t('GeneralEntityRoot.upload.error.description', {
fileName: file.fileName
})
});
}
};

/**
* Shortcut: Save entity form when ctrl+s is pressed.
*/
Expand Down Expand Up @@ -297,6 +575,30 @@ export function GeneralEntityRoot<T extends BaseEntity>({
})}
</Button>
</Link>
{/* Upload only available for layer entities */}
{entityType === 'layer' && (
<Upload
customRequest={onFileUploadAction}
accept='image/tiff,application/zip'
maxCount={1}
showUploadList={false}
beforeUpload={onBeforeFileUpload}
onChange={onFileUploadChange}
>
<Button
type="primary"
key="upload"
icon={<UploadOutlined />}
loading={isUploadingFile}
disabled={isUploadingFile}
>
{t('GeneralEntityRoot.upload.button', {
context: i18next.language,
entity: TranslationUtil.getTranslationFromConfig(entityName, i18n)
})}
</Button>
</Upload>
)}
</div>
<GeneralEntityTable
i18n={i18n}
Expand Down
Loading