Removes dlbo onging qt5 development income folder
This commit is contained in:
16256 files changed
-3383918
No files matched your search
@@ -1,71 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS public.replays
|
||||
(
|
||||
name text COLLATE pg_catalog."default" NOT NULL,
|
||||
uuid text COLLATE pg_catalog."default" NOT NULL,
|
||||
created_by text COLLATE pg_catalog."default" NOT NULL,
|
||||
time_created bigint NOT NULL,
|
||||
CONSTRAINT replays_pkey PRIMARY KEY (uuid)
|
||||
)
|
||||
|
||||
TABLESPACE pg_default;
|
||||
|
||||
ALTER TABLE IF EXISTS public.replays
|
||||
OWNER to postgres;
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.users
|
||||
(
|
||||
id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
|
||||
username character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||
password character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||
CONSTRAINT users_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT users_username_key UNIQUE (username)
|
||||
)
|
||||
|
||||
TABLESPACE pg_default;
|
||||
|
||||
ALTER TABLE IF EXISTS public.users
|
||||
OWNER to postgres;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.tokens
|
||||
(
|
||||
id integer NOT NULL DEFAULT nextval('tokens_id_seq'::regclass),
|
||||
user_id integer,
|
||||
token character varying(255) COLLATE pg_catalog."default" NOT NULL,
|
||||
created_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
|
||||
expiry_date timestamp without time zone,
|
||||
CONSTRAINT tokens_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT tokens_token_key UNIQUE (token),
|
||||
CONSTRAINT tokens_user_id_fkey FOREIGN KEY (user_id)
|
||||
REFERENCES public.users (id) MATCH SIMPLE
|
||||
ON UPDATE NO ACTION
|
||||
ON DELETE CASCADE
|
||||
)
|
||||
|
||||
TABLESPACE pg_default;
|
||||
|
||||
ALTER TABLE IF EXISTS public.tokens
|
||||
OWNER to postgres;
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.spatial_ref_sys
|
||||
(
|
||||
srid integer NOT NULL,
|
||||
auth_name character varying(256) COLLATE pg_catalog."default",
|
||||
auth_srid integer,
|
||||
srtext character varying(2048) COLLATE pg_catalog."default",
|
||||
proj4text character varying(2048) COLLATE pg_catalog."default",
|
||||
CONSTRAINT spatial_ref_sys_pkey PRIMARY KEY (srid),
|
||||
CONSTRAINT spatial_ref_sys_srid_check CHECK (srid > 0 AND srid <= 998999)
|
||||
)
|
||||
|
||||
TABLESPACE pg_default;
|
||||
|
||||
ALTER TABLE IF EXISTS public.spatial_ref_sys
|
||||
OWNER to postgres;
|
||||
|
||||
REVOKE ALL ON TABLE public.spatial_ref_sys FROM PUBLIC;
|
||||
|
||||
GRANT SELECT ON TABLE public.spatial_ref_sys TO PUBLIC;
|
||||
|
||||
GRANT ALL ON TABLE public.spatial_ref_sys TO postgres;
|
||||
BIN
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
Binary file not shown.
Binary file not shown.
@@ -1,46 +0,0 @@
|
||||
# Getting Started with Create React App
|
||||
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.\
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.\
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.\
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.\
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.\
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
||||
@@ -1,13 +0,0 @@
|
||||
import globals from "globals";
|
||||
import pluginJs from "@eslint/js";
|
||||
import pluginReact from "eslint-plugin-react";
|
||||
|
||||
|
||||
/** @type {import('eslint').Linter.Config[]} */
|
||||
export default [
|
||||
{files: ["**/*.{js,mjs,cjs,jsx}"]},
|
||||
{files: ["**/*.js"], languageOptions: {sourceType: "script"}},
|
||||
{languageOptions: { globals: globals.browser }},
|
||||
pluginJs.configs.recommended,
|
||||
pluginReact.configs.flat.recommended,
|
||||
];
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@reduxjs/toolkit": "^2.3.0",
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"@types/jest": "^27.5.2",
|
||||
"@types/node": "^16.18.119",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"axios": "^1.7.7",
|
||||
"leaflet": "^1.9.4",
|
||||
"milsymbol": "^2.2.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-leaflet": "^4.2.1",
|
||||
"react-redux": "^9.1.2",
|
||||
"react-scripts": "5.0.1",
|
||||
"react-slider": "^2.0.6",
|
||||
"redux": "^5.0.1",
|
||||
"typescript": "^4.9.5",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
|
||||
"@eslint/js": "^9.14.0",
|
||||
"@types/leaflet": "^1.9.14",
|
||||
"@types/lodash": "^4.17.13",
|
||||
"@types/lodash.debounce": "^4.0.9",
|
||||
"@types/react-slider": "^1.3.6",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-plugin-react": "^7.37.2",
|
||||
"globals": "^15.12.0",
|
||||
"react-router-dom": "^6.27.0",
|
||||
"tailwindcss": "^3.4.14"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.8 KiB |
@@ -1,43 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>RME-Replay</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 9.4 KiB |
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
@@ -1,38 +0,0 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
render(<App />);
|
||||
const linkElement = screen.getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
|
||||
|
||||
import Dashboard from './pages/dashboard/Dashboard';
|
||||
import Login from './pages/loginpage/Login';
|
||||
import Replay from './pages/replaypage/Replay';
|
||||
import ProtectedRoute from './components/ProtectedRoute';
|
||||
import PublicRoute from './components/PublicRoute';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<Router>
|
||||
<div className="App">
|
||||
<Routes>
|
||||
<Route path="/login" element={<PublicRoute element={<Login />} />} />
|
||||
<Route path="/dashboard" element={<ProtectedRoute element={<Dashboard />} />} />
|
||||
<Route path="/" element={<Navigate to="/login" />} />
|
||||
<Route path="/replays/replay" element={<ProtectedRoute element={<Replay />} />} />
|
||||
</Routes>
|
||||
</div>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -1,39 +0,0 @@
|
||||
import axios from "axios"
|
||||
|
||||
export const LoginUser = async (username: string, password: string): Promise<boolean> => {
|
||||
try {
|
||||
const response = await axios.post("http://localhost:8080/login", {
|
||||
username: username,
|
||||
password: password,
|
||||
}, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
document.cookie = `token=${response.data.token}; path=/; Secure; SameSite=Strict`;
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const isAuthenticated = async (): Promise<boolean> => {
|
||||
const token = document.cookie.split('; ').find(row => row.startsWith('token='));
|
||||
|
||||
if (!token) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const response = await axios.get('http://localhost:8080/auth', {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token.split('=')[1]}`,
|
||||
},
|
||||
});
|
||||
return response.status === 200;
|
||||
} catch (error) {
|
||||
console.error('Authentication check failed:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import axios from "axios";
|
||||
import { Marker } from "../types/marker";
|
||||
|
||||
export const getBookmarks = async (replayId: string) => {
|
||||
try {
|
||||
const response = await axios.get<Marker[]>('http://localhost:8080/replays/replay/bookmark?replayId=' + replayId);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching bookmarks:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { GeoJson } from "../types/geojson";
|
||||
import axios from 'axios';
|
||||
import { ReplayInitialInfo } from '../types/replay';
|
||||
|
||||
export const getGeoObjects = async (replayId: string) => {
|
||||
try {
|
||||
const response = await axios.get<GeoJson[]>('http://localhost:8080/objects/replay?replayId=' + replayId);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching geoobjects:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const getInitialReplayInformation = async (replayId: string) => {
|
||||
try {
|
||||
const response = await axios.get<ReplayInitialInfo>('http://localhost:8080/objects/replayinit?replayId=' + replayId);
|
||||
console.log('Initial replay information:', response.data);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching initial replay information:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const getGeoObjectsInterval = async (replayId: string, min_timestamp: number, max_timestamp : number) => {
|
||||
try {
|
||||
const response = await axios.get<GeoJson[]>('http://localhost:8080/objects/replay?replayId=' + replayId + '&start=' + min_timestamp + '&end=' + max_timestamp);
|
||||
return response.data;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching geoobjects:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import axios from 'axios';
|
||||
import { Replay } from '../types/replay';
|
||||
|
||||
|
||||
export const getReplays = async (): Promise<Replay[]> => {
|
||||
try {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('token='))
|
||||
?.split('=')[1];
|
||||
const response = await axios.get<Replay[]>('http://localhost:8080/replays/user?token=' + token);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching replays:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteReplay = async (uuid: string): Promise<void> => {
|
||||
try {
|
||||
await axios.delete(`http://localhost:8080/replays/delete?replayId=${uuid}`);
|
||||
} catch (error) {
|
||||
console.error('Error deleting replay:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const getAvgLatLng = async (replayId: string): Promise<{ lat: number, lng: number }> => {
|
||||
try {
|
||||
const response = await axios.get<{ lat: number, lng: number }>(`http://localhost:8080/replays/replay/avg?replayId=${replayId}`);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching average LatLng:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
import { useEffect, useMemo, useState, FC } from 'react';
|
||||
import { MapContainer, TileLayer, Marker, Polyline, Polygon, Popup } from 'react-leaflet';
|
||||
import L from 'leaflet';
|
||||
|
||||
import icon from 'leaflet/dist/images/marker-icon.png';
|
||||
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
|
||||
import { GeoJson } from '../types/geojson';
|
||||
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import '../styles/map.css';
|
||||
import { getAvgLatLng } from '../api/replay';
|
||||
import { getIcon } from '../utils/markerSymbol';
|
||||
|
||||
// Standard-Icon für Leaflet
|
||||
const DefaultIcon = L.icon({
|
||||
iconUrl: icon,
|
||||
shadowUrl: iconShadow,
|
||||
iconSize: [25, 41],
|
||||
iconAnchor: [12.5, 41],
|
||||
});
|
||||
L.Marker.prototype.options.icon = DefaultIcon;
|
||||
|
||||
interface ReplayIdProps {
|
||||
geoJsons: GeoJson[];
|
||||
replayId: string;
|
||||
}
|
||||
|
||||
const StaticMap: FC<ReplayIdProps> = ({ geoJsons, replayId }) => {
|
||||
const [avgLatLng, setAvgLatLng] = useState<L.LatLng | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const iconCache = useMemo(() => new Map<string, L.Icon>(), []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchAvgLatLng = async () => {
|
||||
try {
|
||||
const avgLatLngResult = await getAvgLatLng(replayId);
|
||||
if (Array.isArray(avgLatLngResult) && avgLatLngResult.length > 0 && typeof avgLatLngResult[0].lat === 'number' && typeof avgLatLngResult[0].lng === 'number') {
|
||||
setAvgLatLng(new L.LatLng(avgLatLngResult[0].lat, avgLatLngResult[0].lng));
|
||||
} else {
|
||||
throw new Error('Invalid LatLng object');
|
||||
}
|
||||
setIsLoading(false);
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Abrufen von avgLatLng:', error);
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchAvgLatLng();
|
||||
}, [replayId]);
|
||||
|
||||
const tileLayer = useMemo(
|
||||
() => <TileLayer url="https://tile.openstreetmap.de/{z}/{x}/{y}.png" />,
|
||||
[]
|
||||
);
|
||||
|
||||
const icons = useMemo(() => {
|
||||
return geoJsons.map((marker) => {
|
||||
const { id, sidic } = marker.properties;
|
||||
const key = `${id}-${sidic}`;
|
||||
|
||||
// Prüfe, ob das Icon im Cache vorhanden ist
|
||||
if (!iconCache.has(key)) {
|
||||
iconCache.set(key, getIcon(marker));
|
||||
}
|
||||
|
||||
return iconCache.get(key)!; // Das "!" ist hier sicher, da wir garantiert vorher das Icon hinzufügen
|
||||
});
|
||||
}, [geoJsons, iconCache]);
|
||||
|
||||
const renderGeoJson = useMemo(() => {
|
||||
return geoJsons.map((marker, index) => {
|
||||
|
||||
const renderProperties = () => {
|
||||
return Object.entries(marker.properties).map(([key, value]) => (
|
||||
<p key={key}><strong>{key}:</strong> {value}</p>
|
||||
));
|
||||
};
|
||||
|
||||
|
||||
switch (marker.geometry.type) {
|
||||
case 'Point':
|
||||
return (
|
||||
<Marker
|
||||
key={index}
|
||||
position={marker.geometry.coordinates as L.LatLngExpression}
|
||||
icon={icons[index]}
|
||||
>
|
||||
<Popup>
|
||||
{renderProperties()}
|
||||
</Popup>
|
||||
</Marker>
|
||||
);
|
||||
case 'LineString':
|
||||
return (
|
||||
<Polyline
|
||||
key={index}
|
||||
positions={marker.geometry.coordinates as L.LatLngExpression[]}
|
||||
/>
|
||||
);
|
||||
case 'Polygon':
|
||||
return (
|
||||
<Polygon
|
||||
key={index}
|
||||
positions={marker.geometry.coordinates as L.LatLngExpression[][]}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
console.warn(`Unsupported geometry type: ${marker.geometry.type}`);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}, [geoJsons, icons]);
|
||||
|
||||
if (isLoading || !avgLatLng) {
|
||||
return (
|
||||
<div className="flex h-80vh items-center justify-center">
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MapContainer center={avgLatLng} zoom={13}>
|
||||
{tileLayer}
|
||||
{renderGeoJson}
|
||||
</MapContainer>
|
||||
);
|
||||
};
|
||||
|
||||
export default StaticMap;
|
||||
@@ -1,23 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Navigate } from 'react-router-dom';
|
||||
import { isAuthenticated } from '../api/auth';
|
||||
|
||||
const ProtectedRoute = ({ element }: { element: JSX.Element }) => {
|
||||
const [auth, setAuth] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
const authStatus = await isAuthenticated();
|
||||
setAuth(authStatus);
|
||||
};
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
if (auth === null) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
return auth ? element : <Navigate to="/login" />;
|
||||
};
|
||||
|
||||
export default ProtectedRoute;
|
||||
@@ -1,23 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Navigate } from 'react-router-dom';
|
||||
import { isAuthenticated } from '../api/auth';
|
||||
|
||||
const PublicRoute = ({ element }: { element: JSX.Element }) => {
|
||||
const [auth, setAuth] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
const authStatus = await isAuthenticated();
|
||||
setAuth(authStatus);
|
||||
};
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
if (auth === null) {
|
||||
return <div>Loading...</div>; // Oder ein anderes Lade-Element
|
||||
}
|
||||
|
||||
return auth ? <Navigate to="/dashboard" /> : element;
|
||||
};
|
||||
|
||||
export default PublicRoute;
|
||||
@@ -1,156 +0,0 @@
|
||||
import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react';
|
||||
import { GeoJson } from '../types/geojson';
|
||||
import debounce from 'lodash.debounce';
|
||||
|
||||
|
||||
interface CustomSliderProps {
|
||||
geoJsons: GeoJson[];
|
||||
setDisplayGeoJsons: React.Dispatch<React.SetStateAction<GeoJson[]>>;
|
||||
setOpenPopup: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
markerValue: number;
|
||||
minTimestamp: number;
|
||||
maxTimestamp: number;
|
||||
replayId: string;
|
||||
}
|
||||
|
||||
const CustomSlider: React.FC<CustomSliderProps> = ({
|
||||
geoJsons,
|
||||
setDisplayGeoJsons,
|
||||
setOpenPopup,
|
||||
markerValue,
|
||||
minTimestamp,
|
||||
maxTimestamp
|
||||
}) => {
|
||||
// State variables
|
||||
const [currentTimestamp, setCurrentTimestamp] = useState<number>(minTimestamp);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [playbackSpeed, setPlaybackSpeed] = useState(1);
|
||||
const [filterParty, setFilterParty] = useState<string | null>(null);
|
||||
|
||||
const intervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
// Worker Reference for background processing
|
||||
const workerRef = useRef<Worker | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
workerRef.current = new Worker(new URL('../utils/workers.ts', import.meta.url));
|
||||
return () => workerRef.current?.terminate();
|
||||
}, []);
|
||||
|
||||
// Debounced update function
|
||||
const debouncedUpdateGeoJsons = useMemo(() => {
|
||||
return debounce((timestamp: number) => {
|
||||
if (!workerRef.current) return;
|
||||
workerRef.current.postMessage({ geoJsons, timestamp, filterParty });
|
||||
}, 200);
|
||||
}, [geoJsons, filterParty]);
|
||||
|
||||
// Listen for worker messages
|
||||
useEffect(() => {
|
||||
if (!workerRef.current) return;
|
||||
|
||||
workerRef.current.onmessage = (e) => {
|
||||
setDisplayGeoJsons(e.data);
|
||||
};
|
||||
}, [setDisplayGeoJsons]);
|
||||
|
||||
// Handle timestamp and update GeoJSONs
|
||||
const handleSliderChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const timestamp = Number(event.target.value);
|
||||
setCurrentTimestamp(timestamp);
|
||||
debouncedUpdateGeoJsons(timestamp);
|
||||
};
|
||||
|
||||
// Toggle play/pause functionality
|
||||
const togglePlayback = () => {
|
||||
if (isPlaying) {
|
||||
clearInterval(intervalRef.current!);
|
||||
} else {
|
||||
intervalRef.current = setInterval(() => {
|
||||
setCurrentTimestamp((prev) => {
|
||||
const nextTimestamp = prev + 1000 * playbackSpeed;
|
||||
if (nextTimestamp >= maxTimestamp) {
|
||||
clearInterval(intervalRef.current!);
|
||||
setIsPlaying(false);
|
||||
return maxTimestamp;
|
||||
}
|
||||
debouncedUpdateGeoJsons(nextTimestamp);
|
||||
return nextTimestamp;
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
setIsPlaying((prev) => !prev);
|
||||
};
|
||||
|
||||
// Toggle playback speed
|
||||
const toggleSpeed = () => setPlaybackSpeed((prev) => (prev === 1 ? 2 : 1));
|
||||
|
||||
// Handle filter change
|
||||
const handleFilterChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
setFilterParty(event.target.value || null);
|
||||
};
|
||||
|
||||
// Return early if no data
|
||||
if (!geoJsons.length) return <div>Loading...</div>;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 p-4 bg-white shadow-md rounded-lg">
|
||||
{/* Slider */}
|
||||
<div>
|
||||
<input
|
||||
type="range"
|
||||
value={currentTimestamp}
|
||||
onChange={handleSliderChange}
|
||||
min={minTimestamp}
|
||||
max={maxTimestamp}
|
||||
step={1000}
|
||||
className="w-full h-2 appearance-none rounded-lg bg-gray-200 outline-none cursor-pointer transition-all focus:ring-2 focus:ring-blue-500"
|
||||
style={{
|
||||
background: `linear-gradient(to right, #3182ce ${((currentTimestamp - minTimestamp) / (maxTimestamp - minTimestamp)) * 100}%, #e5e7eb ${((currentTimestamp - minTimestamp) / (maxTimestamp - minTimestamp)) * 100}%)`,
|
||||
}}
|
||||
/>
|
||||
<div className="mt-2 text-center text-gray-700 text-lg font-medium">
|
||||
{new Date(currentTimestamp).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Playback Controls */}
|
||||
<div className="flex justify-center gap-4">
|
||||
<button
|
||||
onClick={togglePlayback}
|
||||
className="px-6 py-2 bg-blue-500 text-white font-semibold rounded-lg shadow hover:bg-blue-600 transition-all"
|
||||
>
|
||||
{isPlaying ? 'Pause' : 'Play'}
|
||||
</button>
|
||||
<button
|
||||
onClick={toggleSpeed}
|
||||
className="px-6 py-2 bg-green-500 text-white font-semibold rounded-lg shadow hover:bg-green-600 transition-all"
|
||||
>
|
||||
{playbackSpeed === 1 ? 'Speed Up' : 'Slow Down'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setOpenPopup(true)}
|
||||
className="px-6 py-2 bg-red-500 text-white font-semibold rounded-lg shadow hover:bg-red-600 transition-all"
|
||||
>
|
||||
Open Dialogue
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Filter Dropdown */}
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="text-gray-700 font-medium">Filter by Party:</label>
|
||||
<select
|
||||
value={filterParty || ''}
|
||||
onChange={handleFilterChange}
|
||||
className="px-4 py-2 bg-gray-100 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
>
|
||||
<option value="">No Filter</option>
|
||||
<option value="Blue">Blue</option>
|
||||
<option value="Red">Red</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomSlider;
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
interface ActionButtonProps {
|
||||
color: 'blue' | 'red' | 'yellow';
|
||||
onClick: () => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const ActionButton: React.FC<ActionButtonProps> = ({ color, onClick, children }) => {
|
||||
const colors = {
|
||||
blue: 'bg-blue-500 hover:bg-blue-700',
|
||||
red: 'bg-red-500 hover:bg-red-700',
|
||||
yellow: 'bg-yellow-500 hover:bg-yellow-700',
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={`${colors[color]} text-white font-medium py-2 px-4 rounded transition-all`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
interface TableHeaderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
const TableHeader: React.FC<TableHeaderProps> = ({ children }) => (
|
||||
<th className="py-3 px-4 text-left font-medium">{children}</th>
|
||||
);
|
||||
|
||||
export default TableHeader;
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Replay } from "../../types/replay";
|
||||
import { ActionButton } from "./ActionButton";
|
||||
|
||||
interface ReplayRowProps {
|
||||
replay: Replay;
|
||||
onView: (uuid: string) => void;
|
||||
onDelete: (uuid: string) => void;
|
||||
}
|
||||
|
||||
const ReplayRow: React.FC<ReplayRowProps> = ({ replay, onView, onDelete }) => {
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
|
||||
const openDialog = () => setIsDialogOpen(true);
|
||||
const closeDialog = () => setIsDialogOpen(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<tr className="border-b hover:bg-gray-100">
|
||||
<td className="py-3 px-4">{replay.name}</td>
|
||||
<td className="py-3 px-4">{replay.uuid}</td>
|
||||
<td className="py-3 px-4">{replay.created_by}</td>
|
||||
<td className="py-3 px-4">{new Date(replay.time_created * 1000).toLocaleString()}</td>
|
||||
<td className="py-3 px-4 flex gap-2">
|
||||
<ActionButton color="blue" onClick={() => onView(replay.uuid)}>
|
||||
View
|
||||
</ActionButton>
|
||||
<ActionButton color="red" onClick={() => onDelete(replay.uuid)}>
|
||||
Delete
|
||||
</ActionButton>
|
||||
<ActionButton color="yellow" onClick={() => openDialog()}>
|
||||
Details
|
||||
</ActionButton>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
{isDialogOpen && (
|
||||
<div className="fixed inset-0 flex items-center justify-center z-50 bg-gray-900 bg-opacity-50">
|
||||
<div className="bg-white rounded-lg shadow-lg p-8 max-w-md w-full z-10">
|
||||
<h2 className="text-2xl font-semibold text-gray-800 mb-4">Replay Details</h2>
|
||||
<div className="space-y-2 text-gray-700">
|
||||
<p><strong className="font-medium">Name:</strong> {replay.name}</p>
|
||||
<p><strong className="font-medium">UUID:</strong> {replay.uuid}</p>
|
||||
<p><strong className="font-medium">Created By:</strong> {replay.created_by}</p>
|
||||
<p><strong className="font-medium">Time Created:</strong> {new Date(replay.time_created * 1000).toLocaleString()}</p>
|
||||
</div>
|
||||
<div className="mt-6 flex justify-end">
|
||||
<ActionButton color="red" onClick={closeDialog}>
|
||||
Close
|
||||
</ActionButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
export default ReplayRow;
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
import { Replay } from "../../types/replay";
|
||||
import TableHeader from "./ReplayHeader";
|
||||
import ReplayRow from "./ReplayRow";
|
||||
|
||||
interface ReplayTableProps {
|
||||
replays: Replay[];
|
||||
onView: (uuid: string) => void;
|
||||
onDelete: (uuid: string) => void;
|
||||
}
|
||||
|
||||
const ReplayTable: React.FC<ReplayTableProps> = ({ replays, onView, onDelete }) => {
|
||||
return (
|
||||
<table className="min-w-full bg-white">
|
||||
<thead className="bg-gray-200 text-gray-700">
|
||||
<tr>
|
||||
<TableHeader>NAME</TableHeader>
|
||||
<TableHeader>UUID</TableHeader>
|
||||
<TableHeader>CREATED BY </TableHeader>
|
||||
<TableHeader>TIME CREATED</TableHeader>
|
||||
<TableHeader>ACTIONS</TableHeader>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{replays.map((replay) => (
|
||||
<ReplayRow
|
||||
key={replay.uuid}
|
||||
replay={replay}
|
||||
onView={onView}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
};
|
||||
|
||||
export default ReplayTable;
|
||||
@@ -1,3 +0,0 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -1,36 +0,0 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import { Provider } from 'react-redux';
|
||||
|
||||
import App from './App';
|
||||
|
||||
import userReducer from './store/UserSlice';
|
||||
import mapReducer from './store/MapSlice';
|
||||
import './index.css';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement
|
||||
);
|
||||
|
||||
const store = configureStore (
|
||||
{
|
||||
reducer: {
|
||||
user: userReducer,
|
||||
map: mapReducer,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
root.render(
|
||||
<Provider store={store}>
|
||||
<App />
|
||||
</Provider>
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
|
||||
|
Before Width: | Height: | Size: 2.6 KiB |
@@ -1,53 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { deleteReplay, getAvgLatLng, getReplays } from "../../api/replay";
|
||||
import { setAvgLatLng } from "../../store/MapSlice";
|
||||
import ReplayTable from "../../components/dashboard/ReplayTable";
|
||||
import { Replay } from "../../types/replay";
|
||||
|
||||
const Dashboard: React.FC = () => {
|
||||
const [replays, setReplays] = useState<Replay[]>([]);
|
||||
const dispatch = useDispatch();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchReplays = async () => {
|
||||
const data = await getReplays();
|
||||
setReplays(data);
|
||||
};
|
||||
fetchReplays();
|
||||
}, []);
|
||||
|
||||
const handleViewReplay = async (uuid: string) => {
|
||||
const avgLatLng = await getAvgLatLng(uuid);
|
||||
dispatch(setAvgLatLng(avgLatLng));
|
||||
navigate(`/replays/replay?replayId=${uuid}`);
|
||||
};
|
||||
|
||||
const handleDeleteReplay = async (uuid: string) => {
|
||||
await deleteReplay(uuid);
|
||||
const updatedReplays = await getReplays();
|
||||
setReplays(updatedReplays);
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="container mx-auto p-6">
|
||||
<header className="mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-800">Replay Dashboard</h1>
|
||||
<p className="text-gray-600">Manage your Replays</p>
|
||||
<p className="text-gray-600"></p>
|
||||
</header>
|
||||
|
||||
<section className="overflow-x-auto bg-white shadow-md rounded-lg">
|
||||
<ReplayTable
|
||||
replays={replays}
|
||||
onView={handleViewReplay}
|
||||
onDelete={handleDeleteReplay}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
@@ -1,54 +0,0 @@
|
||||
// src/pages/loginpage/Login.tsx
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { LoginUser } from '../../api/auth';
|
||||
|
||||
const Login = () => {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogin = () => {
|
||||
LoginUser(username, password).then((success) => {
|
||||
if (success) {
|
||||
navigate('/dashboard');
|
||||
} else {
|
||||
alert('Login failed');
|
||||
}
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-100">
|
||||
<div className="w-full max-w-md p-8 space-y-6 bg-white rounded shadow-md">
|
||||
<h2 className="text-2xl font-bold text-center">Login</h2>
|
||||
<div className="space-y-4">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-600"
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full px-4 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-600"
|
||||
/>
|
||||
<button
|
||||
onClick={handleLogin}
|
||||
className="w-full px-4 py-2 font-bold text-white bg-blue-600 rounded hover:bg-blue-700"
|
||||
>
|
||||
Login
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
@@ -1,100 +0,0 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
|
||||
import StaticMap from "../../components/Map";
|
||||
import CustomSlider from "../../components/Slider";
|
||||
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { GeoJson } from "../../types/geojson";
|
||||
import { getInitialReplayInformation } from "../../api/geojson";
|
||||
import { Marker } from "../../types/marker";
|
||||
import { getBookmarks } from "../../api/bookmark";
|
||||
|
||||
const Replay: React.FC = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const [geoJsons, setGeoJsons] = useState<GeoJson[]>([]);
|
||||
const [displayGeoJsons, setDisplayGeoJsons] = useState<GeoJson[]>([]);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [openPopup, setOpenPopup] = useState<boolean>(false);
|
||||
const [markers, setMarkers] = useState<Marker[]>([]);
|
||||
const [sliderValue, setSliderValue] = useState<number>(0);
|
||||
const [minTimestamp, setMinTimestamp] = useState<number>(0);
|
||||
const [maxTimestamp, setMaxTimestamp] = useState<number>(0);
|
||||
|
||||
const replayId = searchParams.get("replayId");
|
||||
useEffect(() => {
|
||||
const fetchGeoObjects = async () => {
|
||||
try {
|
||||
const geoObjects = await getInitialReplayInformation(replayId || "");
|
||||
setGeoJsons(geoObjects.geojsons);
|
||||
setMinTimestamp(Number(geoObjects.timestamps.min_timestamp));
|
||||
setMaxTimestamp(Number(geoObjects.timestamps.max_timestamp));
|
||||
setIsLoading(false);
|
||||
} catch (error) {
|
||||
console.error("Error fetching geo objects:", error);
|
||||
} finally {
|
||||
}
|
||||
};
|
||||
fetchGeoObjects();
|
||||
}, [replayId]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchBookmarks = async () => {
|
||||
try {
|
||||
const markers = await getBookmarks(replayId || "");
|
||||
setMarkers(markers);
|
||||
} catch (error) {
|
||||
console.error("Error fetching bookmarks:", error);
|
||||
}
|
||||
};
|
||||
fetchBookmarks();
|
||||
}, [replayId]);
|
||||
|
||||
return (
|
||||
<div className="h-[100%]">
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center items-center h-full">
|
||||
Loading...
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<StaticMap geoJsons={displayGeoJsons} replayId={replayId || ""} />
|
||||
<div className="w-full z-100 h-[20vh]">
|
||||
{openPopup && (
|
||||
<div className="absolute top-0 left-0 w-[30%] h-full bg-white bg-opacity-90 z-10">
|
||||
<div className="flex justify-between items-center p-2">
|
||||
<h2 className="text-lg font-bold">Marker Dialog</h2>
|
||||
<button onClick={() => setOpenPopup(false)}>Close</button>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
{markers.map(marker => (
|
||||
<div key={marker.id} className="flex justify-between items-center p-2 border-b">
|
||||
<div>{marker.name}</div>
|
||||
<div>{new Date(marker.timestamp).toLocaleString()}</div>
|
||||
<button
|
||||
className="bg-blue-500 text-white rounded-lg px-2 py-1"
|
||||
onClick={() => setSliderValue(marker.timestamp)} // Update the slider value
|
||||
>
|
||||
Show on Map
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<CustomSlider
|
||||
geoJsons={geoJsons}
|
||||
setDisplayGeoJsons={setDisplayGeoJsons}
|
||||
setOpenPopup={setOpenPopup}
|
||||
markerValue={sliderValue}
|
||||
minTimestamp={minTimestamp}
|
||||
maxTimestamp={maxTimestamp}
|
||||
replayId={replayId || ""}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Replay;
|
||||
@@ -1 +0,0 @@
|
||||
/// <reference types="react-scripts" />
|
||||
@@ -1,15 +0,0 @@
|
||||
import { ReportHandler } from 'web-vitals';
|
||||
|
||||
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
|
||||
if (onPerfEntry && onPerfEntry instanceof Function) {
|
||||
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
|
||||
getCLS(onPerfEntry);
|
||||
getFID(onPerfEntry);
|
||||
getFCP(onPerfEntry);
|
||||
getLCP(onPerfEntry);
|
||||
getTTFB(onPerfEntry);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default reportWebVitals;
|
||||
@@ -1,5 +0,0 @@
|
||||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom';
|
||||
@@ -1,16 +0,0 @@
|
||||
import { createSlice } from "@reduxjs/toolkit";
|
||||
|
||||
const mapSlice = createSlice({
|
||||
name: 'map',
|
||||
initialState: { avgLatLng : { lat: 0, lng: 0 } },
|
||||
reducers: {
|
||||
setAvgLatLng(state, action) {
|
||||
state.avgLatLng = action.payload;
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
export const { setAvgLatLng } = mapSlice.actions
|
||||
|
||||
export default mapSlice.reducer
|
||||
@@ -1,24 +0,0 @@
|
||||
import { createSlice } from "@reduxjs/toolkit";
|
||||
import { User } from '../types/user';
|
||||
|
||||
const user = {
|
||||
name: ''
|
||||
} as User;
|
||||
|
||||
const userSlice = createSlice({
|
||||
name: 'user',
|
||||
initialState: user ? user : null,
|
||||
reducers: {
|
||||
setUser(state, action) {
|
||||
if(user) {
|
||||
if (state) {
|
||||
state.name = action.payload.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const { setUser } = userSlice.actions
|
||||
|
||||
export default userSlice.reducer
|
||||
@@ -1,29 +0,0 @@
|
||||
/* /home/nino-pinzer/devel/Arbeit/rme-playback/frontend/src/styles/map.css */
|
||||
|
||||
.leaflet-container {
|
||||
width: 100%;
|
||||
height: 80vh;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.leaflet-control {
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.leaflet-popup-content-wrapper {
|
||||
font-size: 14px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.leaflet-popup-tip-container {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.leaflet-popup-content {
|
||||
margin: 8px;
|
||||
}
|
||||
|
||||
.leaflet-marker-icon {
|
||||
z-index: 500;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { LatLngExpression, Point } from "leaflet";
|
||||
|
||||
export type GeoJson = {
|
||||
type: "Feature";
|
||||
geometry: {
|
||||
type: "Point" | "LineString" | "Polygon";
|
||||
coordinates: LatLngExpression | LatLngExpression[] | LatLngExpression[][];
|
||||
};
|
||||
properties: {
|
||||
[key: string]: any;
|
||||
};
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
export interface Marker {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
timestamp: number;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { GeoJson } from "./geojson";
|
||||
|
||||
export type Replay = {
|
||||
name: string;
|
||||
uuid: string;
|
||||
created_by: string;
|
||||
time_created: number;
|
||||
};
|
||||
|
||||
|
||||
export type ReplayInitialInfo = {
|
||||
timestamps: {
|
||||
min_timestamp: number;
|
||||
max_timestamp: number;
|
||||
},
|
||||
geojsons: GeoJson[]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
export interface User {
|
||||
name: string;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
export const findMinMax = (timestamps: number[]) => {
|
||||
let minTimestamp = Number.POSITIVE_INFINITY;
|
||||
let maxTimestamp = Number.NEGATIVE_INFINITY;
|
||||
|
||||
for (const timestamp of timestamps) {
|
||||
if (timestamp < minTimestamp) {
|
||||
minTimestamp = timestamp;
|
||||
}
|
||||
if (timestamp > maxTimestamp) {
|
||||
maxTimestamp = timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
return { minTimestamp, maxTimestamp };
|
||||
};
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import ms from 'milsymbol';
|
||||
import { GeoJson } from '../types/geojson';
|
||||
import L from 'leaflet';
|
||||
|
||||
export const getIcon = (marker : GeoJson) => {
|
||||
const symbolOptions: ms.SymbolOptions = {
|
||||
size: 35,
|
||||
sidc: marker.properties.sidic,
|
||||
dtg: marker.properties.dtg || "1054",
|
||||
// additionalInformation: marker.properties.additionalInformation || marker.properties.id,
|
||||
// location: marker.properties.location || "Location",
|
||||
// direction: marker.properties.direction || "Direction",
|
||||
// speed: marker.properties.speed || "Speed",
|
||||
uniqueDesignation: marker.properties.uniqueDesignation || "1",
|
||||
// type: marker.properties.type || "Type",
|
||||
// altitudeDepth: marker.properties.altitudeDepth || "Altitude/Depth",
|
||||
// quantity: marker.properties.quantity || "Quantity",
|
||||
// equipmentTeardownTime: marker.properties.equipmentTeardownTime || "Equipment Teardown Time",
|
||||
// commonIdentifier: marker.properties.commonIdentifier || "Common Identifier",
|
||||
};
|
||||
|
||||
const symbol = new ms.Symbol(symbolOptions);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
const dimensions = symbol.getSize();
|
||||
|
||||
canvas.width = dimensions.width;
|
||||
canvas.height = dimensions.height;
|
||||
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
ctx.drawImage(symbol.asCanvas(), 0, 0, canvas.width, canvas.height);
|
||||
}
|
||||
|
||||
const iconUrl = canvas.toDataURL();
|
||||
|
||||
return L.icon({
|
||||
iconUrl: iconUrl,
|
||||
iconSize: [dimensions.width, dimensions.height], // Dynamische Größe verwenden
|
||||
iconAnchor: [dimensions.width / 2, dimensions.height / 2],
|
||||
});
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
export {};
|
||||
|
||||
onmessage = function (e) {
|
||||
const { geoJsons, timestamp, filterParty } = e.data;
|
||||
|
||||
const latestById = geoJsons.reduce((acc: { [x: string]: any; }, geoJson: { properties: { id: any; timestamp: any; }; }) => {
|
||||
const { id, timestamp: geoJsonTimestamp } = geoJson.properties;
|
||||
const time = new Date(geoJsonTimestamp).getTime();
|
||||
|
||||
if (time <= timestamp && (!acc[id] || new Date(acc[id].properties.timestamp).getTime() < time)) {
|
||||
acc[id] = geoJson;
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const result = filterParty
|
||||
? (Object.values(latestById) as { properties: any }[]).filter(({ properties }) => properties.parties === filterParty)
|
||||
: Object.values(latestById);
|
||||
|
||||
postMessage(result);
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
"./src/**/*.{js,jsx,ts,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
project(restapi LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_AUTORCC ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core HttpServer Sql Network)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core HttpServer Sql Network)
|
||||
|
||||
add_executable(restapi
|
||||
src/main.cpp
|
||||
|
||||
src/include/objectMethods.h
|
||||
src/include/apiroutes.h
|
||||
src/include/types.h
|
||||
|
||||
src/include/isValidGeoJsonObject.h
|
||||
src/include/dbConnection.h
|
||||
|
||||
config/db_config.json
|
||||
config/private.key
|
||||
config/server.crt
|
||||
|
||||
src/include/dbQuery.h
|
||||
|
||||
src/include/isValidReplayObject.h
|
||||
|
||||
|
||||
src/include/replayMethods.h
|
||||
|
||||
src/include/authMethods.h
|
||||
src/include/setupSslCertificate.h
|
||||
|
||||
)
|
||||
target_link_libraries(restapi Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::HttpServer Qt${QT_VERSION_MAJOR}::Sql Qt${QT_VERSION_MAJOR}::Network)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS restapi
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"host": "localhost",
|
||||
"port" : 5432,
|
||||
"dbname" : "rme_playback",
|
||||
"user" : "postgres",
|
||||
"password" : "postgres"
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
-----BEGIN CERTIFICATE REQUEST-----
|
||||
MIIC9zCCAd8CAQAwgZkxCzAJBgNVBAYTAkRFMRYwFAYDVQQIDA1OaWVkZXJzYWNo
|
||||
c2VuMQ8wDQYDVQQHDAZCcmVtZW4xDDAKBgNVBAoMA1JNRTEMMAoGA1UECwwDUk1F
|
||||
MRIwEAYDVQQDDAlsb2NhbGhvc3QxMTAvBgkqhkiG9w0BCQEWIk5pbm8tcGFzY2Fs
|
||||
LnBpbnplckByaGVpbm1ldGFsbC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
|
||||
ggEKAoIBAQDkOG9Ci/XVwsXWAiCJYzdGQpvGqZluht1SdegTTTaJB0ok+utYOB1+
|
||||
3AiFjUQQm+lvoOcKW/NqFjDkK6CDkpTJLu6pyLAn+dCkPzQqLKXFMvono/JtEB9G
|
||||
+MT3HlQb2Ds5UuYnQ3KfMTUOKNrlM+8scj49EqikC7VlRE6YsE4/qtOs1bxhTyig
|
||||
C90gCNUmYsMNCeTG7zcsyVApI6mnnO1X7JdcyhsmyPnZ9YMzxRJNlDArI5FYJojM
|
||||
eFMYXuucS634vPhcAYQRFQtrG8e98/HjAWI9k3gzF4zeULctuT1bEjLA+sc4bZy9
|
||||
MQqGxHIvOLkxyhVYD1gyM0F2Tkbg85ZhAgMBAAGgGDAWBgkqhkiG9w0BCQcxCQwH
|
||||
Uk1FMjAyNDANBgkqhkiG9w0BAQsFAAOCAQEAXMyiKr5Mdt1Y1SriIQvDrEczU+xF
|
||||
7PpU8RqE5/Ir/ZMJ8o16RhEFhGAygvP4208pdXWy2/zC6LofdFvi/mx1kEqZLk9E
|
||||
vjfECB7NGDHHI/dC1dydMLu6SwBGqufj5zEGR+kBA06KwrzTwflxLN87DtKLYPzj
|
||||
STs4/LK6RgsfdtlkAhsfOk2XkYRdWi5DLim8KjnC51HD3rheWCgRgiIW1+rBGjRC
|
||||
0Jz/v1nPy9P+v0tPBN5uuLrmTCDNsTQTPh5L3c3DcA2uI9H1Uyu2mZcN+CYkDLAw
|
||||
X9yFlYnF3VNQCaemPnzE4vReQ/RU9mn6TZdgblFRsstgWQvvO9poAvde5g==
|
||||
-----END CERTIFICATE REQUEST-----
|
||||
@@ -1,28 +0,0 @@
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkOG9Ci/XVwsXW
|
||||
AiCJYzdGQpvGqZluht1SdegTTTaJB0ok+utYOB1+3AiFjUQQm+lvoOcKW/NqFjDk
|
||||
K6CDkpTJLu6pyLAn+dCkPzQqLKXFMvono/JtEB9G+MT3HlQb2Ds5UuYnQ3KfMTUO
|
||||
KNrlM+8scj49EqikC7VlRE6YsE4/qtOs1bxhTyigC90gCNUmYsMNCeTG7zcsyVAp
|
||||
I6mnnO1X7JdcyhsmyPnZ9YMzxRJNlDArI5FYJojMeFMYXuucS634vPhcAYQRFQtr
|
||||
G8e98/HjAWI9k3gzF4zeULctuT1bEjLA+sc4bZy9MQqGxHIvOLkxyhVYD1gyM0F2
|
||||
Tkbg85ZhAgMBAAECggEADuTT9f7WU1X7vUS0ROMRt2cfbW6iEcGBbiE9vQy782Nj
|
||||
ZlhtxXscCaxobfbTK1ZRfLR+f4GSuCislid2uT92sE58yt3LCUDXafCqAdqaEu2J
|
||||
v86GQrHbqLERgaMcEBkjfFE5rfRL5bG7aaom5vBlunvWLfwqv1H4S5ySmIphAOyQ
|
||||
iNURCtIEElGZbuG8rvByxF7ZAplWStXuNUPcRN0Vs3Lm3CuaTO5UP9hYZ40+rikl
|
||||
oOOQUB/6r8i+LRKUcU7MfEDkF9g3iklWDt8NuuBuL9Pc00ARamQa7pTRFWe+q+0V
|
||||
qjsDmkU25SGyGwAIRknoxnDzc96cajltnwW7J0K6JQKBgQD0bVhiILRICaADCvL5
|
||||
OXMp1+JlYN++Mul0AXIY8vP77rSEFTsNYaNGhHDs7GXjasD8Uxo0dplux6Gs59uS
|
||||
Ob19n8dfzof0P+KTvtZLaIyRCFxbs4U5SEKWTtE37agoiCgwFMSOxKy68N4JXHqL
|
||||
nFTFHnoLRo4D4k2IehVeIeOfuwKBgQDvBqa4Spjolo+KU5+r4Z2OBozeipxwDB3t
|
||||
Ul28eevEbY1o/NT/A4nTw9riD7pExMnCDqw3Xt7BU/DtjDnBqMA9c98hKFxy/yxX
|
||||
dWCvCPWXETq+aD5y9rY8+AUdEyA4Vm4ijnupj6gm6PWd0vOxZz6/67R7gSGLVCgN
|
||||
HU0R3gO6kwKBgQDRw6FNHUn6ZKA43EWm0sHdkBMP87IwdVraHn9/n8j5VWL/04SJ
|
||||
OFi6JOEQwtOx9qTGJr9fdMS6SIKcc6KA/CJ91AhzVThhyg21w9n+fyvbL7SrUgYs
|
||||
IbJbciqk98UPe8IZeUkySOD/0cSLfh0BAVnSjRQp5xPri2QEktkRnr3NDwKBgFoX
|
||||
ybNg+q2AQm5DAsYIbhhgQ6yF1l0tVAJlr0shMUqCeHCAC9BrBwI4qkHW58CP4/Qv
|
||||
D553NcLs3rzKw+JIttzy1cFrsxztLUtxxJV07QyZw+iM5izy7NGiMls5IEXb3ftM
|
||||
dTP+H8U6vYlVP+E4JyCzuP1sOLaJa+c1ih0X75PdAoGBANQQg7XkwflQvduccbpO
|
||||
KfsDOIL0NWsHaqGIhm25ufYqCjdZ7LM4LH+T6BF+6vYteAM6zQOJ4d0j9yYVLHbd
|
||||
tb1ct2RPnrebHsN0HLx5iibJDafOe3+Xb9d7J8MVKi5dXnw8bPZdit5znbqSdc5W
|
||||
FWqhdokOEYyvVxOLEhpnNfY0
|
||||
-----END PRIVATE KEY-----
|
||||
@@ -1,22 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDuzCCAqMCFACAK0wopGGeRcujdgfkW0zX6sF6MA0GCSqGSIb3DQEBCwUAMIGZ
|
||||
MQswCQYDVQQGEwJERTEWMBQGA1UECAwNTmllZGVyc2FjaHNlbjEPMA0GA1UEBwwG
|
||||
QnJlbWVuMQwwCgYDVQQKDANSTUUxDDAKBgNVBAsMA1JNRTESMBAGA1UEAwwJbG9j
|
||||
YWxob3N0MTEwLwYJKoZIhvcNAQkBFiJOaW5vLXBhc2NhbC5waW56ZXJAcmhlaW5t
|
||||
ZXRhbGwuY29tMB4XDTI0MTEyMjA3MTg0N1oXDTI1MTEyMjA3MTg0N1owgZkxCzAJ
|
||||
BgNVBAYTAkRFMRYwFAYDVQQIDA1OaWVkZXJzYWNoc2VuMQ8wDQYDVQQHDAZCcmVt
|
||||
ZW4xDDAKBgNVBAoMA1JNRTEMMAoGA1UECwwDUk1FMRIwEAYDVQQDDAlsb2NhbGhv
|
||||
c3QxMTAvBgkqhkiG9w0BCQEWIk5pbm8tcGFzY2FsLnBpbnplckByaGVpbm1ldGFs
|
||||
bC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkOG9Ci/XVwsXW
|
||||
AiCJYzdGQpvGqZluht1SdegTTTaJB0ok+utYOB1+3AiFjUQQm+lvoOcKW/NqFjDk
|
||||
K6CDkpTJLu6pyLAn+dCkPzQqLKXFMvono/JtEB9G+MT3HlQb2Ds5UuYnQ3KfMTUO
|
||||
KNrlM+8scj49EqikC7VlRE6YsE4/qtOs1bxhTyigC90gCNUmYsMNCeTG7zcsyVAp
|
||||
I6mnnO1X7JdcyhsmyPnZ9YMzxRJNlDArI5FYJojMeFMYXuucS634vPhcAYQRFQtr
|
||||
G8e98/HjAWI9k3gzF4zeULctuT1bEjLA+sc4bZy9MQqGxHIvOLkxyhVYD1gyM0F2
|
||||
Tkbg85ZhAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAJVr7rwP6gnl47S90JnjIfUS
|
||||
swIN3FAgr2z348FZKaU7fqlZz2uVcU6yrDseqEkf3lDdRAsYs9iV0psXWObD353V
|
||||
Afj0tSH85JikRLbGFnIOlDJ4Dhf577pSnS25wamQZWJ1Z9rME1SmwbdGBYFWwCu5
|
||||
bl7ffi64j+iEIt0/B634WeugkPW8GpN2v9M0JJTNWxrF0CTf4ulXRdYJJ7M8xEt8
|
||||
4ajNV5MmxRJfiMgtsrTJQM+ayghT6URkkm17bzUcTjxIoQZAE2zSiEqdlEXAK+v/
|
||||
GEjICExe642J/6OPcS3BZKDOn5DqQZl8TMGum7SZpg3ycqqqcvD8oKG7cp0LWCo=
|
||||
-----END CERTIFICATE-----
|
||||
Whitespace-only changes.
@@ -1,129 +0,0 @@
|
||||
#ifndef APIROUTES_H
|
||||
#define APIROUTES_H
|
||||
|
||||
#include "authMethods.h"
|
||||
#include "dbConnection.h"
|
||||
#include "objectMethods.h"
|
||||
#include "replayMethods.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QString>
|
||||
#include <QJsonDocument>
|
||||
#include <QHttpServerResponse>
|
||||
#include <qhttpserver.h>
|
||||
#include <qjsonobject.h>
|
||||
|
||||
// Loggt die HTTP-Anfragen
|
||||
void logRequest(const QHttpServerRequest &request) {
|
||||
const auto method = request.method();
|
||||
const QString url = request.url().toString();
|
||||
|
||||
qDebug() << "Request received:"
|
||||
<< "Method:" << method
|
||||
<< "URL:" << url;
|
||||
|
||||
}
|
||||
|
||||
// Fügt CORS-Routen hinzu
|
||||
void addCorsRoutes(QHttpServer &server) {
|
||||
const QStringList corsRoutes = {
|
||||
"/objects", "/objects/replayinit", "/objects/replay",
|
||||
"/replays", "/replays/delete", "/replays/user",
|
||||
"/login", "/auth", "/replays/replay/avg",
|
||||
"/bookmark", "/replays/replay/bookmark"
|
||||
};
|
||||
|
||||
auto handleOptionsRequest = [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
QHttpServerResponse response("");
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
};
|
||||
|
||||
for (const auto &route : corsRoutes) {
|
||||
server.route(route, QHttpServerRequest::Method::Options, handleOptionsRequest);
|
||||
}
|
||||
}
|
||||
|
||||
// Fügt API-Routen hinzu
|
||||
void addApiRoutes(QHttpServer &server) {
|
||||
// Stellt sicher, dass die Datenbank verbunden und initialisiert ist
|
||||
QSqlDatabase db = connectToDb();
|
||||
initializeDatabase(db);
|
||||
|
||||
// Routenregistrierungen
|
||||
server.route("/objects", QHttpServerRequest::Method::Post, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return ObjectMethods::postObjects(request);
|
||||
});
|
||||
|
||||
server.route("/objects/replayinit", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return ObjectMethods::getReplayInitInformation(request);
|
||||
});
|
||||
|
||||
server.route("/objects/replay", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return ObjectMethods::getGeoObjectsInterval(request);
|
||||
});
|
||||
|
||||
server.route("/replays", QHttpServerRequest::Method::Post, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return postReplays(request);
|
||||
});
|
||||
|
||||
server.route("/replays", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return getAllReplays(request);
|
||||
});
|
||||
|
||||
server.route("/replays/delete", QHttpServerRequest::Method::Delete, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return deleteReplay(request);
|
||||
});
|
||||
|
||||
server.route("/replays/replay", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return getSingleReplay(request);
|
||||
});
|
||||
|
||||
server.route("/replays/replay/bookmark", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return ObjectMethods::getBookmarks(request);
|
||||
});
|
||||
|
||||
server.route("/replays/user", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return getUserReplays(request);
|
||||
});
|
||||
|
||||
server.route("/bookmark", QHttpServerRequest::Method::Post, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return ObjectMethods::postBookmark(request);
|
||||
});
|
||||
|
||||
server.route("/login", QHttpServerRequest::Method::Post, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return loginUser(request);
|
||||
});
|
||||
|
||||
server.route("/auth", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return authUser(request);
|
||||
});
|
||||
|
||||
server.route("/replays/replay/avg", QHttpServerRequest::Method::Get, [](const QHttpServerRequest &request) {
|
||||
logRequest(request);
|
||||
return getAvg(request);
|
||||
});
|
||||
}
|
||||
|
||||
// Hauptfunktion zum Einrichten der API-Routen und CORS-Policy
|
||||
void setupApiRoutes(QHttpServer &server) {
|
||||
addApiRoutes(server);
|
||||
addCorsRoutes(server);
|
||||
}
|
||||
|
||||
#endif // APIROUTES_H
|
||||
@@ -1,161 +0,0 @@
|
||||
#ifndef AUTHMETHODS_H
|
||||
#define AUTHMETHODS_H
|
||||
|
||||
#include <qhttpserverrequest.h>
|
||||
#include <qhttpserverresponse.h>
|
||||
#include <qcryptographichash.h>
|
||||
#include <qjsondocument.h>
|
||||
#include <QJsonObject>
|
||||
#include <qsqldatabase.h>
|
||||
#include <qsqlerror.h>
|
||||
#include <qsqlquery.h>
|
||||
#include <QUuid>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
|
||||
QString hashPassword(const QString &password) {
|
||||
return QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256).toHex());
|
||||
}
|
||||
|
||||
QString generateToken() {
|
||||
return QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
}
|
||||
|
||||
QHttpServerResponse login(const QJsonObject &json) {
|
||||
QString username = json["username"].toString();
|
||||
QString password = json["password"].toString();
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
query.prepare(QString("SELECT id, password FROM public.users WHERE username = '%1'").arg(username));
|
||||
|
||||
if (!query.exec() || !query.next()) {
|
||||
QHttpServerResponse response("Invalid username or password", QHttpServerResponse::StatusCode::Unauthorized);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
QString hashedPassword = query.value("password").toString();
|
||||
|
||||
if (hashedPassword != hashPassword(password)) {
|
||||
QHttpServerResponse response("Invalid username or password", QHttpServerResponse::StatusCode::Unauthorized);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
QString token = generateToken();
|
||||
int userId = query.value("id").toInt();
|
||||
QDateTime expiryDate = QDateTime::currentDateTimeUtc().addSecs(24 * 3600);
|
||||
|
||||
query.prepare("INSERT INTO public.tokens (user_id, token, expiry_date) VALUES (:user_id, :token, :expiry_date)");
|
||||
query.bindValue(":user_id", userId);
|
||||
query.bindValue(":token", token);
|
||||
query.bindValue(":expiry_date", expiryDate);
|
||||
|
||||
if (!query.exec()) {
|
||||
qDebug() << "Error inserting token";
|
||||
QHttpServerResponse response("Token generation failed", QHttpServerResponse::StatusCode::InternalServerError);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
QJsonObject jsonResponse;
|
||||
jsonResponse["token"] = token;
|
||||
QByteArray responseBody = QJsonDocument(jsonResponse).toJson();
|
||||
|
||||
QHttpServerResponse response(responseBody, QHttpServerResponse::StatusCode::Ok);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse loginUser(const QHttpServerRequest &request) {
|
||||
auto body = request.body();
|
||||
QJsonDocument jsonRequest = QJsonDocument::fromJson(body);
|
||||
qDebug() << jsonRequest;
|
||||
|
||||
if (!jsonRequest.isObject()) {
|
||||
QHttpServerResponse response("Invalid Request!", QHttpServerResponse::StatusCode::BadRequest);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
return login(jsonRequest.object());
|
||||
}
|
||||
|
||||
|
||||
QHttpServerResponse checkAuth(const QString &token) {
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
QSqlQuery query(db);
|
||||
|
||||
query.prepare(QString("SELECT user_id, expiry_date FROM tokens WHERE token = :token"));
|
||||
query.bindValue(":token", token);
|
||||
|
||||
if (!query.exec() || !query.next()) {
|
||||
QHttpServerResponse response("Invalid token", QHttpServerResponse::StatusCode::Unauthorized);
|
||||
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
QDateTime expiryDate = query.value("expiry_date").toDateTime();
|
||||
if (QDateTime::currentDateTimeUtc() > expiryDate) {
|
||||
QHttpServerResponse response("Token expired", QHttpServerResponse::StatusCode::Unauthorized);
|
||||
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
QJsonObject jsonResponse;
|
||||
jsonResponse["status"] = "Authenticated";
|
||||
QHttpServerResponse response(QJsonDocument(jsonResponse).toJson(), QHttpServerResponse::StatusCode::Ok);
|
||||
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse authUser(const QHttpServerRequest &request) {
|
||||
QList<QPair<QByteArray, QByteArray>> headers = request.headers();
|
||||
QString token;
|
||||
|
||||
for (const auto &header : headers) {
|
||||
if (header.first.toLower() == "authorization") {
|
||||
QString authHeader = QString::fromUtf8(header.second);
|
||||
if (authHeader.startsWith("Bearer ")) {
|
||||
token = authHeader.mid(7);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (token.isEmpty()) {
|
||||
QHttpServerResponse response("No token provided", QHttpServerResponse::StatusCode::Unauthorized);
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
||||
return response;
|
||||
}
|
||||
|
||||
return checkAuth(token);
|
||||
}
|
||||
|
||||
#endif // AUTHMETHODS_H
|
||||
@@ -1,202 +0,0 @@
|
||||
#ifndef DBCONNECTION_H
|
||||
#define DBCONNECTION_H
|
||||
|
||||
#include <QDebug>
|
||||
#include <QSqlDatabase>
|
||||
#include <QFile>
|
||||
#include <QSqlError>
|
||||
#include <QSqlQuery>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QDir>
|
||||
#include <QCoreApplication>
|
||||
|
||||
QSqlDatabase connectToDb() {
|
||||
QString path = QDir::cleanPath(QCoreApplication::applicationDirPath() + QDir::separator() + "../../config" + QDir::separator() + "db_config.json");
|
||||
|
||||
QFile inFile(path);
|
||||
|
||||
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
qDebug() << "Kann die Datei nicht öffnen:" << inFile.errorString();
|
||||
}
|
||||
|
||||
QByteArray data = inFile.readAll();
|
||||
inFile.close();
|
||||
|
||||
QJsonParseError errorPtr;
|
||||
|
||||
QJsonDocument doc = QJsonDocument::fromJson(data, &errorPtr);
|
||||
|
||||
if (doc.isNull()) {
|
||||
qDebug() << "Parse failed";
|
||||
}
|
||||
|
||||
QJsonObject rootObj = doc.object();
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
|
||||
|
||||
db.setHostName(rootObj.value("host").toString());
|
||||
db.setPort(rootObj.value("port").toInt());
|
||||
db.setDatabaseName(rootObj.value("dbname").toString());
|
||||
db.setUserName(rootObj.value("user").toString());
|
||||
db.setPassword(rootObj.value("password").toString());
|
||||
|
||||
if (!db.open()) {
|
||||
qDebug() << "Datenbankverbindung konnte nicht hergestellt werden";
|
||||
return db;
|
||||
}
|
||||
|
||||
qDebug() << "Datenbankverbindung wurde hergestellt";
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
QMap<QString, QString> getTableCreationQueries() {
|
||||
QMap<QString, QString> tableQueries;
|
||||
tableQueries["extensions"] = R"(
|
||||
CREATE EXTENSION IF NOT EXISTS postgis;
|
||||
)";
|
||||
|
||||
tableQueries["geojson-seq"] =R"(
|
||||
CREATE SEQUENCE geojson_objects_id_seq;
|
||||
)";
|
||||
// Tabelle für Benutzer
|
||||
tableQueries["users"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password TEXT NOT NULL
|
||||
)
|
||||
)";
|
||||
|
||||
// Tabelle für Tokens
|
||||
tableQueries["tokens"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL,
|
||||
token TEXT NOT NULL,
|
||||
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
expiry_date TIMESTAMP WITHOUT TIME ZONE NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
)
|
||||
)";
|
||||
|
||||
// Tabelle für Replays
|
||||
tableQueries["replays"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS replays (
|
||||
uuid TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
created_by INT NOT NULL,
|
||||
time_created BIGINT,
|
||||
FOREIGN KEY (created_by) REFERENCES groups(id) ON DELETE CASCADE
|
||||
)
|
||||
)";
|
||||
|
||||
// Tabelle für Gruppen
|
||||
tableQueries["groups"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE
|
||||
)
|
||||
)";
|
||||
|
||||
// Tabelle für die Zuordnung von Benutzern zu Gruppen
|
||||
tableQueries["user_groups"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS user_groups (
|
||||
user_id INT NOT NULL,
|
||||
group_id INT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, group_id)
|
||||
)
|
||||
)";
|
||||
|
||||
// Tabelle für die Zuordnung von Replays zu Gruppen
|
||||
tableQueries["group_replays"] = R"(
|
||||
CREATE TABLE IF NOT EXISTS group_replays (
|
||||
group_id INT NOT NULL,
|
||||
replay_uuid TEXT NOT NULL,
|
||||
FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (replay_uuid) REFERENCES replays(uuid) ON DELETE CASCADE,
|
||||
PRIMARY KEY (group_id, replay_uuid)
|
||||
)
|
||||
)";
|
||||
|
||||
// Root-User erstellen (falls nicht bereits vorhanden)
|
||||
tableQueries["root_user"] = R"(
|
||||
INSERT INTO users (username, password)
|
||||
VALUES ('root', '4813494d137e1631bba301d5acab6e7bb7aa74ce1185d456565ef51d737677b2')
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
)";
|
||||
|
||||
// Root-Gruppe erstellen (falls nicht bereits vorhanden)
|
||||
tableQueries["root_group"] = R"(
|
||||
INSERT INTO groups (name)
|
||||
VALUES ('Root')
|
||||
ON CONFLICT (name) DO NOTHING
|
||||
)";
|
||||
|
||||
// Root-User der Root-Gruppe zuordnen
|
||||
tableQueries["root_user_group"] = R"(
|
||||
INSERT INTO user_groups (user_id, group_id)
|
||||
SELECT u.id, g.id
|
||||
FROM users u, groups g
|
||||
WHERE u.username = 'root' AND g.name = 'Root'
|
||||
ON CONFLICT (user_id, group_id) DO NOTHING
|
||||
)";
|
||||
|
||||
return tableQueries;
|
||||
}
|
||||
|
||||
bool initializeDatabase(QSqlDatabase db) {
|
||||
if (!db.isOpen()) {
|
||||
qDebug() << "Die Datenbank ist nicht geöffnet.";
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery setupQuery(db);
|
||||
if (!setupQuery.exec(R"(
|
||||
CREATE TABLE IF NOT EXISTS executed_queries (
|
||||
query_name TEXT PRIMARY KEY
|
||||
);
|
||||
)")) {
|
||||
qDebug() << "Fehler beim Erstellen der Tabelle executed_queries:" << setupQuery.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
QStringList executionOrder = {
|
||||
"extensions", "geojson_seq", "users", "tokens", "replays",
|
||||
"groups", "user_groups", "group_replays", "root_group",
|
||||
"root_user", "root_user_group"
|
||||
};
|
||||
|
||||
QMap<QString, QString> tableQueries = getTableCreationQueries();
|
||||
|
||||
for (const QString& key : executionOrder) {
|
||||
QSqlQuery checkQuery(db);
|
||||
checkQuery.prepare("SELECT 1 FROM executed_queries WHERE query_name = :queryName");
|
||||
checkQuery.bindValue(":queryName", key);
|
||||
|
||||
if (!checkQuery.exec() || !checkQuery.next()) {
|
||||
QSqlQuery execQuery(db);
|
||||
if (!execQuery.exec(tableQueries[key])) {
|
||||
qDebug() << "Fehler beim Ausführen der Query für" << key << ":" << execQuery.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery insertQuery(db);
|
||||
insertQuery.prepare("INSERT INTO executed_queries (query_name) VALUES (:queryName)");
|
||||
insertQuery.bindValue(":queryName", key);
|
||||
if (!insertQuery.exec()) {
|
||||
qDebug() << "Fehler beim Einfügen in executed_queries:" << insertQuery.lastError().text();
|
||||
}
|
||||
|
||||
qDebug() << "Query für" << key << "erfolgreich ausgeführt.";
|
||||
}
|
||||
}
|
||||
|
||||
qDebug() << "Datenbank wurde erfolgreich initialisiert.";
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,444 +0,0 @@
|
||||
#ifndef DBQUERY_H
|
||||
#define DBQUERY_H
|
||||
|
||||
#include <qjsonobject.h>
|
||||
#include <qdebug.h>
|
||||
#include <qsqldatabase.h>
|
||||
#include <qsqlquery.h>
|
||||
|
||||
#include "types.h"
|
||||
|
||||
#include <qjsondocument.h>
|
||||
#include <QSqlError>
|
||||
#include <QUuid>
|
||||
#include <QDateTime>
|
||||
|
||||
bool insertGeoObjectToDb(const QJsonObject &obj) {
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if(!db.isOpen()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
QJsonObject propertiesObj = obj["properties"].toObject();
|
||||
QJsonObject geoJsonObj = obj["geometry"].toObject();
|
||||
|
||||
QString replayId = propertiesObj["replay_id"].toString();
|
||||
qint64 timestamp = propertiesObj["timestamp"].toInteger();
|
||||
|
||||
QString properties = QString::fromUtf8(QJsonDocument(propertiesObj).toJson());
|
||||
QString geoJson = QString::fromUtf8(QJsonDocument(geoJsonObj).toJson());
|
||||
|
||||
query.prepare(QString("INSERT INTO %1.geojson_objects (properties, geom, timestamp) VALUES (:properties, ST_GeomFromGeoJson(:geoJson), :timestamp)").arg(replayId));
|
||||
|
||||
query.bindValue(":properties", properties);
|
||||
query.bindValue(":geoJson", geoJson);
|
||||
query.bindValue(":timestamp", timestamp);
|
||||
|
||||
if(!query.exec()) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
QJsonArray getGeoObjectsIntervallFromDb(const QString &replayId, const QString &start_timestamp, const QString &end_timestamp) {
|
||||
QJsonArray array;
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if (!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
query.prepare(QString(
|
||||
"SELECT properties, ST_AsGeoJSON(geom) as geojson "
|
||||
"FROM %1.geojson_objects "
|
||||
"WHERE timestamp BETWEEN :start_timestamp AND :end_timestamp "
|
||||
"ORDER BY timestamp ASC"
|
||||
).arg(replayId));
|
||||
|
||||
// Werte binden
|
||||
query.bindValue(":start_timestamp", start_timestamp);
|
||||
query.bindValue(":end_timestamp", end_timestamp);
|
||||
|
||||
// Query ausführen
|
||||
if (!query.exec()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
// Ergebnisse verarbeiten
|
||||
while (query.next()) {
|
||||
GeoJSONFeature feature;
|
||||
|
||||
QJsonObject geometry = QJsonDocument::fromJson(query.value("geojson").toByteArray()).object();
|
||||
QJsonObject properties = QJsonDocument::fromJson(query.value("properties").toByteArray()).object();
|
||||
|
||||
feature.properties = properties;
|
||||
feature.geometry = geometry;
|
||||
|
||||
array.append(feature.toJson());
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
QJsonObject getReplayInitInformationsFromDb(const QString &replayId) {
|
||||
QJsonObject result;
|
||||
QJsonObject timestamps;
|
||||
QJsonArray geojsons;
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if (!db.isOpen()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
// Abrufen von min_timestamp und max_timestamp
|
||||
if (query.exec(QString("SELECT MIN(timestamp) as min_timestamp, MAX(timestamp) as max_timestamp FROM %1.geojson_objects").arg(replayId))) {
|
||||
if (query.next()) {
|
||||
timestamps["min_timestamp"] = query.value("min_timestamp").toString();
|
||||
timestamps["max_timestamp"] = query.value("max_timestamp").toString();
|
||||
}
|
||||
}
|
||||
|
||||
// Abrufen der GeoJSON-Objekte
|
||||
if (query.exec(QString("SELECT properties, ST_AsGeoJSON(geom) as geojson FROM %1.geojson_objects WHERE timestamp BETWEEN (SELECT MIN(timestamp) FROM %1.geojson_objects) AND (SELECT MIN(timestamp) FROM %1.geojson_objects) + 300000;").arg(replayId))) {
|
||||
while (query.next()) {
|
||||
GeoJSONFeature feature;
|
||||
|
||||
QJsonObject geometry = QJsonDocument::fromJson(query.value("geojson").toByteArray()).object();
|
||||
QJsonObject properties = QJsonDocument::fromJson(query.value("properties").toByteArray()).object();
|
||||
|
||||
feature.properties = properties;
|
||||
feature.geometry = geometry;
|
||||
|
||||
geojsons.append(feature.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
// Ergebnis zusammensetzen
|
||||
result["timestamps"] = timestamps;
|
||||
result["geojsons"] = geojsons;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool insertReplayToDb(const QJsonObject &obj) {
|
||||
QString uuid = "r" + QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
uuid = uuid.replace("-", "_");
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
QString replayName = obj["name"].toString();
|
||||
int createdBy = obj["created_by"].toInt();
|
||||
|
||||
uint now = std::chrono::duration_cast<std::chrono::seconds> (std::chrono::system_clock::now().time_since_epoch()).count();
|
||||
|
||||
if(!db.isOpen()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("CREATE SCHEMA IF NOT EXISTS %1;").arg(uuid))) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!query.exec(QString("CREATE TABLE IF NOT EXISTS %1.geojson_objects(id integer NOT NULL DEFAULT nextval('geojson_objects_id_seq'::regclass),properties jsonb, geom geometry(Geometry,4326),timestamp BIGINT, CONSTRAINT geojson_objects_pkey PRIMARY KEY (id))").arg(uuid))) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!query.exec(QString("CREATE TABLE IF NOT EXISTS %1.marker(id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, timestamp BIGINT NOT NULL)").arg(uuid))) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
query.prepare(QString("INSERT INTO public.replays VALUES (:uuid, :name, :created_by, :time_created);"));
|
||||
|
||||
query.bindValue(":name", replayName);
|
||||
query.bindValue(":uuid", uuid);
|
||||
query.bindValue(":created_by", createdBy);
|
||||
query.bindValue(":time_created", now);
|
||||
|
||||
if(!query.exec()) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
query.prepare(QString("INSERT INTO group_replays (group_id, replay_uuid) VALUES (:group_id, :replay_uuid)"));
|
||||
|
||||
query.bindValue(":group_id", createdBy);
|
||||
query.bindValue(":replay_uuid", uuid);
|
||||
|
||||
if(!query.exec()) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QJsonArray getReplaysfromDb() {
|
||||
QJsonArray array;
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if(!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("SELECT * FROM public.replays ORDER BY uuid ASC"))) {
|
||||
return array;
|
||||
}
|
||||
while(query.next()) {
|
||||
QJsonObject obj;
|
||||
|
||||
obj["name"] = query.value("name").toString();
|
||||
obj["uuid"] = query.value("uuid").toString();
|
||||
obj["created_by"] = query.value("created_by").toString();
|
||||
obj["time_created"] = query.value("time_created").toString();
|
||||
|
||||
array.append(obj);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
QJsonArray getReplayfromDb(const QString &replayId) {
|
||||
QJsonArray array;
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
if(!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("SELECT * FROM public.replays WHERE uuid = '%1' " ).arg(replayId))) {
|
||||
qDebug() << query.lastError().text();
|
||||
return array;
|
||||
}
|
||||
|
||||
while(query.next()) {
|
||||
QJsonObject obj;
|
||||
|
||||
obj["name"] = query.value("name").toString();
|
||||
obj["uuid"] = query.value("uuid").toString();
|
||||
obj["created_by"] = query.value("created_by").toString();
|
||||
obj["time_created"] = query.value("time_created").toString();
|
||||
|
||||
array.append(obj);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
QJsonArray getUserReplaysfromDb(const QString &token) {
|
||||
QJsonArray array;
|
||||
QString userId;
|
||||
QString groupId;
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
if(!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
// 1. Hole den user_id für das gegebene Token
|
||||
query.prepare("SELECT user_id FROM public.tokens WHERE token = :token");
|
||||
query.bindValue(":token", token);
|
||||
|
||||
if (!query.exec()) {
|
||||
qDebug() << "Query execution failed:" << query.lastError().text();
|
||||
return array;
|
||||
}
|
||||
|
||||
if (query.next()) {
|
||||
userId = query.value("user_id").toString();
|
||||
} else {
|
||||
qDebug() << "No user found for token:" << token;
|
||||
return array;
|
||||
}
|
||||
|
||||
// 2. Finde die Gruppe, der der Benutzer angehört
|
||||
query.prepare("SELECT group_id FROM public.user_groups WHERE user_id = :user_id");
|
||||
query.bindValue(":user_id", userId);
|
||||
|
||||
if (!query.exec()) {
|
||||
qDebug() << "Query execution failed to find group for user:" << query.lastError().text();
|
||||
return array;
|
||||
}
|
||||
|
||||
if (query.next()) {
|
||||
groupId = query.value("group_id").toString();
|
||||
} else {
|
||||
qDebug() << "No group found for user:" << userId;
|
||||
return array;
|
||||
}
|
||||
|
||||
// 3. Hole alle replays, die der Gruppe zugeordnet sind
|
||||
query.prepare("SELECT replay_uuid FROM public.group_replays WHERE group_id = :group_id");
|
||||
query.bindValue(":group_id", groupId);
|
||||
|
||||
if (!query.exec()) {
|
||||
qDebug() << "Query execution failed to get replays for group:" << query.lastError().text();
|
||||
return array;
|
||||
}
|
||||
|
||||
// 4. Hole die vollständigen Informationen für jedes Replay
|
||||
while (query.next()) {
|
||||
QString replayUuid = query.value("replay_uuid").toString();
|
||||
|
||||
// Finde die Replay-Daten anhand der UUID
|
||||
QSqlQuery replayQuery(db);
|
||||
replayQuery.prepare("SELECT * FROM public.replays WHERE uuid = :uuid");
|
||||
replayQuery.bindValue(":uuid", replayUuid);
|
||||
|
||||
if (!replayQuery.exec()) {
|
||||
qDebug() << "Query execution failed to get replay details:" << replayQuery.lastError().text();
|
||||
continue; // Falls das Replay nicht gefunden wird, überspringe es
|
||||
}
|
||||
|
||||
if (replayQuery.next()) {
|
||||
QJsonObject obj;
|
||||
|
||||
obj["name"] = replayQuery.value("name").toString();
|
||||
obj["uuid"] = replayQuery.value("uuid").toString();
|
||||
obj["created_by"] = replayQuery.value("created_by").toInt();
|
||||
obj["time_created"] = replayQuery.value("time_created").toString();
|
||||
|
||||
array.append(obj);
|
||||
}
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
|
||||
bool deleteReplayFromDb(const QString &replayId, QString &error) {
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
|
||||
if(!db.isOpen()) {
|
||||
error = "Database connection went wrong";
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("DELETE FROM public.replays WHERE uuid = '%1' ").arg(replayId))) {
|
||||
qDebug() << query.lastError().text();
|
||||
error = "Deleting replay from public.replay went wrong";
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!query.exec(QString("DROP SCHEMA if exists %1 cascade;").arg(replayId))) {
|
||||
qDebug() << query.lastError().text();
|
||||
error = "Droping replay Schema went wrong";
|
||||
return false;
|
||||
}
|
||||
error = "Successful replay delete";
|
||||
return true;
|
||||
}
|
||||
QJsonArray getAvgLatLng(const QString &replayId, QString &error) {
|
||||
QJsonArray array;
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
if(!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("SELECT AVG(ST_X(geom::geometry)) AS avg_longitude, AVG(ST_Y(geom::geometry)) AS avg_latitude FROM %1.geojson_objects").arg(replayId))) {
|
||||
qDebug() << query.lastError().text();
|
||||
return array;
|
||||
}
|
||||
|
||||
while(query.next()) {
|
||||
QJsonObject obj;
|
||||
|
||||
obj["lat"] = query.value("avg_longitude").toDouble();
|
||||
obj["lng"] = query.value("avg_latitude").toDouble();
|
||||
|
||||
array.append(obj);
|
||||
|
||||
}
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
bool insertBookmark(const QJsonObject &obj) {
|
||||
|
||||
qDebug() << obj["name"].toString();
|
||||
qDebug() << obj["description"].toString();
|
||||
qDebug() << obj["timestamp"].toInteger();
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if(!db.isOpen()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
|
||||
QString replayId = obj["uuid"].toString();
|
||||
qint64 timestamp = obj["timestamp"].toInteger();
|
||||
QString name = obj["name"].toString();
|
||||
QString description = obj["description"].toString();
|
||||
|
||||
query.prepare(QString("INSERT INTO %1.marker (name, description, timestamp) VALUES (:name, :description, :timestamp)").arg(replayId));
|
||||
|
||||
query.bindValue(":name", name);
|
||||
query.bindValue(":description", description);
|
||||
query.bindValue(":timestamp", timestamp);
|
||||
|
||||
if(!query.exec()) {
|
||||
qDebug() << query.lastError().text();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QJsonArray getBookmarkFromDB(const QString &replayId) {
|
||||
QJsonArray array;
|
||||
|
||||
QSqlDatabase db = QSqlDatabase::database();
|
||||
|
||||
if(!db.isOpen()) {
|
||||
return array;
|
||||
}
|
||||
|
||||
QSqlQuery query(db);
|
||||
|
||||
if(!query.exec(QString("SELECT * FROM %1.marker ORDER BY timestamp DESC").arg(replayId))) {
|
||||
return array;
|
||||
}
|
||||
|
||||
while(query.next()) {
|
||||
QJsonObject obj;
|
||||
|
||||
obj["name"] = query.value("name").toString();
|
||||
obj["description"] = query.value("description").toString();
|
||||
obj["timestamp"] = query.value("timestamp").toLongLong();
|
||||
|
||||
array.append(obj);
|
||||
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#endif // DBQUERY_H
|
||||
@@ -1,38 +0,0 @@
|
||||
#ifndef ISVALIDGEOJSONOBJECT_H
|
||||
#define ISVALIDGEOJSONOBJECT_H
|
||||
|
||||
#include <qjsonobject.h>
|
||||
#include <qjsonarray.h>
|
||||
|
||||
bool isValidGeoJSONFeature(const QJsonObject &json, QString &error) {
|
||||
|
||||
if(!json.contains("type") || json["type"].toString() != "Feature") {
|
||||
error = "Invalid GeoJson: 'type', must be 'Feature'";
|
||||
return false;
|
||||
}
|
||||
|
||||
if(!json.contains("geometry") || !json["geometry"].isObject()) {
|
||||
error = "Invalid GeoJSON: 'geometry' field is missing or not an object";
|
||||
return false;
|
||||
}
|
||||
|
||||
QJsonObject geometry = json["geometry"].toObject();
|
||||
|
||||
if(!geometry.contains("coordinates") || !geometry["coordinates"].isArray()) {
|
||||
error = "Invalid GeoJSON: 'geometry.coordinates' must be an an array or is missing";
|
||||
return false;
|
||||
}
|
||||
|
||||
QJsonArray coordinates = geometry["coordinates"].toArray();
|
||||
|
||||
if(json.contains("properties") && !json["properties"].isObject()) {
|
||||
error = "InvalidGeoJSON: 'properties must be an object";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
error = "GeoJSON is valid and successfully added to database ";
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // ISVALIDGEOJSONOBJECT_H
|
||||
@@ -1,17 +0,0 @@
|
||||
#ifndef ISVALIDREPLAYOBJECT_H
|
||||
#define ISVALIDREPLAYOBJECT_H
|
||||
|
||||
#include <qjsonobject.h>
|
||||
|
||||
bool isValidReplayObject(const QJsonObject &json, QString &error) {
|
||||
if(!json.contains("name") || !json.contains("created_by")) {
|
||||
error = "Replay is missing something -> name || location || created_by";
|
||||
return false;
|
||||
}
|
||||
|
||||
error = "Replay is valid and successfully created";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif // ISVALIDREPLAYOBJECT_H
|
||||
@@ -1,127 +0,0 @@
|
||||
#ifndef OBJECTMETHODS_H
|
||||
#define OBJECTMETHODS_H
|
||||
|
||||
#include <qhttpserverresponse.h>
|
||||
#include <qsqldatabase.h>
|
||||
|
||||
#include "dbQuery.h"
|
||||
#include "isValidGeoJsonObject.h"
|
||||
#include "types.h"
|
||||
|
||||
#include <qhttpserverrequest.h>
|
||||
#include <qjsondocument.h>
|
||||
#include <qjsonobject.h>
|
||||
#include <QDebug>
|
||||
#include <qjsonarray.h>
|
||||
|
||||
namespace ObjectMethods {
|
||||
|
||||
// Set common response headers for CORS and content-type
|
||||
void setCommonHeaders(QHttpServerResponse &response) {
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
// Handle errors and return a response with a specific status code
|
||||
QHttpServerResponse createErrorResponse(const QString &errorMessage, QHttpServerResponse::StatusCode statusCode) {
|
||||
QHttpServerResponse response(errorMessage, statusCode);
|
||||
setCommonHeaders(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
// Validate and insert GeoJSON feature into the database
|
||||
QHttpServerResponse handleGeoJSONFeature(const QJsonObject &jsonObj) {
|
||||
QString error;
|
||||
GeoJSONFeature geoJsonObj = geoJsonObj.fromJson(jsonObj);
|
||||
|
||||
if (!isValidGeoJSONFeature(geoJsonObj.toJson(), error)) {
|
||||
return createErrorResponse(error, QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
insertGeoObjectToDb(geoJsonObj.toJson());
|
||||
return QHttpServerResponse(QString(), QHttpServerResponse::StatusCode::Ok);
|
||||
}
|
||||
|
||||
QHttpServerResponse postObjects(const QHttpServerRequest &request) {
|
||||
auto body = request.body();
|
||||
QJsonDocument jsonRequest = QJsonDocument::fromJson(body);
|
||||
|
||||
if (!jsonRequest.isObject() && !jsonRequest.isArray()) {
|
||||
return createErrorResponse("Invalid JSON", QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
// Handle single object or an array of objects
|
||||
if (jsonRequest.isObject()) {
|
||||
return handleGeoJSONFeature(jsonRequest.object());
|
||||
} else if (jsonRequest.isArray()) {
|
||||
for (const QJsonValue &obj : jsonRequest.array()) {
|
||||
if (obj.isObject()) {
|
||||
QHttpServerResponse response = handleGeoJSONFeature(obj.toObject());
|
||||
if (response.statusCode() == QHttpServerResponse::StatusCode::BadRequest) {
|
||||
return response; // Return error response immediately if one is found
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return QHttpServerResponse(QString(), QHttpServerResponse::StatusCode::Ok);
|
||||
}
|
||||
|
||||
QHttpServerResponse getGeoObjectsInterval(const QHttpServerRequest &request) {
|
||||
if (!request.query().hasQueryItem("replayId") || !request.query().hasQueryItem("start") || !request.query().hasQueryItem("end")) {
|
||||
return createErrorResponse("Query param is missing", QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
QString replayId = request.query().queryItemValue("replayId");
|
||||
QString start_timestamp = request.query().queryItemValue("start");
|
||||
QString end_timestamp = request.query().queryItemValue("end");
|
||||
|
||||
QJsonArray array = getGeoObjectsIntervallFromDb(replayId, start_timestamp, end_timestamp);
|
||||
|
||||
QHttpServerResponse response(array, QHttpServerResponse::StatusCode::Ok);
|
||||
setCommonHeaders(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse getReplayInitInformation(const QHttpServerRequest &request) {
|
||||
if (!request.query().hasQueryItem("replayId")) {
|
||||
return createErrorResponse("replayId is missing", QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
QJsonObject obj = getReplayInitInformationsFromDb(request.query().queryItemValue("replayId"));
|
||||
QHttpServerResponse response(obj, QHttpServerResponse::StatusCode::Ok);
|
||||
setCommonHeaders(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse postBookmark(const QHttpServerRequest &request) {
|
||||
auto body = request.body();
|
||||
QJsonDocument jsonRequest = QJsonDocument::fromJson(body);
|
||||
QString error;
|
||||
|
||||
if (jsonRequest["name"].isNull() || jsonRequest["timestamp"].isNull()) {
|
||||
error = "values are missing";
|
||||
return createErrorResponse(error, QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
insertBookmark(jsonRequest.object());
|
||||
QHttpServerResponse response(error, QHttpServerResponse::StatusCode::Ok);
|
||||
setCommonHeaders(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse getBookmarks(const QHttpServerRequest &request) {
|
||||
if (!request.query().hasQueryItem("replayId")) {
|
||||
return createErrorResponse("replayId is missing", QHttpServerResponse::StatusCode::BadRequest);
|
||||
}
|
||||
|
||||
QJsonArray array = getBookmarkFromDB(request.query().queryItemValue("replayId"));
|
||||
|
||||
QHttpServerResponse response(array, QHttpServerResponse::StatusCode::Ok);
|
||||
setCommonHeaders(response);
|
||||
return response;
|
||||
}
|
||||
|
||||
} // namespace ObjectMethods
|
||||
|
||||
#endif // OBJECTMETHODS_H
|
||||
@@ -1,129 +0,0 @@
|
||||
#ifndef REPLAYMETHODS_H
|
||||
#define REPLAYMETHODS_H
|
||||
|
||||
#include <qhttpserverrequest.h>
|
||||
#include <qhttpserverresponse.h>
|
||||
#include <qjsonarray.h>
|
||||
#include <qjsondocument.h>
|
||||
#include "dbQuery.h"
|
||||
#include "isValidReplayObject.h"
|
||||
|
||||
namespace {
|
||||
const QByteArray ACCESS_CONTROL_ALLOW_ORIGIN = "*";
|
||||
const QByteArray CONTENT_TYPE_JSON = "application/json";
|
||||
|
||||
QHttpServerResponse createBadRequestResponse(const QString& message) {
|
||||
QHttpServerResponse response(message, QHttpServerResponder::StatusCode::BadRequest);
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Origin"), ACCESS_CONTROL_ALLOW_ORIGIN);
|
||||
response.setHeader(QByteArray("Content-Type"), CONTENT_TYPE_JSON);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse createOkResponse(const QJsonArray& array) {
|
||||
QHttpServerResponse response(array, QHttpServerResponder::StatusCode::Ok);
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Origin"), ACCESS_CONTROL_ALLOW_ORIGIN);
|
||||
response.setHeader(QByteArray("Content-Type"), CONTENT_TYPE_JSON);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse createOkResponse(const QString& message) {
|
||||
QHttpServerResponse response(message, QHttpServerResponder::StatusCode::Ok);
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Origin"), ACCESS_CONTROL_ALLOW_ORIGIN);
|
||||
response.setHeader(QByteArray("Content-Type"), CONTENT_TYPE_JSON);
|
||||
return response;
|
||||
}
|
||||
|
||||
QHttpServerResponse createInternalErrorResponse(const QString& error) {
|
||||
QHttpServerResponse response(error, QHttpServerResponder::StatusCode::InternalServerError);
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Origin"), ACCESS_CONTROL_ALLOW_ORIGIN);
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Methods"), QByteArray("GET, POST, DELETE, OPTIONS"));
|
||||
response.setHeader(QByteArray("Access-Control-Allow-Headers"), QByteArray("Content-Type, Authorization"));
|
||||
return response;
|
||||
}
|
||||
|
||||
bool hasReplayId(const QHttpServerRequest &request) {
|
||||
return request.query().hasQueryItem("replayId");
|
||||
}
|
||||
|
||||
bool hasToken(const QHttpServerRequest &request) {
|
||||
return request.query().hasQueryItem("token");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
QHttpServerResponse getSingleReplay(const QHttpServerRequest &request) {
|
||||
if (!hasReplayId(request)) {
|
||||
return createBadRequestResponse("replayId is missing");
|
||||
}
|
||||
|
||||
return createOkResponse(getReplayfromDb(request.query().queryItemValue("replayId")));
|
||||
}
|
||||
|
||||
QHttpServerResponse getAllReplays(const QHttpServerRequest &request) {
|
||||
return createOkResponse(getReplaysfromDb());
|
||||
}
|
||||
|
||||
QHttpServerResponse getUserReplays(const QHttpServerRequest &request) {
|
||||
if (!hasToken(request)) {
|
||||
return createBadRequestResponse("token is missing");
|
||||
}
|
||||
|
||||
return createOkResponse(getUserReplaysfromDb(request.query().queryItemValue("token")));
|
||||
}
|
||||
|
||||
QHttpServerResponse postReplays(const QHttpServerRequest &request) {
|
||||
auto body = request.body();
|
||||
QJsonDocument jsonRequest = QJsonDocument::fromJson(body);
|
||||
|
||||
if (!jsonRequest.isObject() && !jsonRequest.isArray()) {
|
||||
return createBadRequestResponse("Invalid JSON");
|
||||
}
|
||||
|
||||
QString error;
|
||||
if (jsonRequest.isObject()) {
|
||||
QJsonObject jsonObj = jsonRequest.object();
|
||||
if (!isValidReplayObject(jsonObj, error)) {
|
||||
return createBadRequestResponse(error);
|
||||
}
|
||||
insertReplayToDb(jsonObj);
|
||||
} else if (jsonRequest.isArray()) {
|
||||
for (const QJsonValue &obj : jsonRequest.array()) {
|
||||
if (obj.isObject()) {
|
||||
QJsonObject jsonObj = obj.toObject();
|
||||
if (!isValidReplayObject(jsonObj, error)) {
|
||||
return createBadRequestResponse(error);
|
||||
}
|
||||
insertReplayToDb(jsonObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createOkResponse("Replays added successfully");
|
||||
}
|
||||
|
||||
QHttpServerResponse deleteReplay(const QHttpServerRequest &request) {
|
||||
if (!hasReplayId(request)) {
|
||||
return createBadRequestResponse("replayId is missing");
|
||||
}
|
||||
|
||||
QString replayId = request.query().queryItemValue("replayId");
|
||||
QString error;
|
||||
|
||||
if (!deleteReplayFromDb(replayId, error)) {
|
||||
return createInternalErrorResponse(error);
|
||||
}
|
||||
|
||||
return createOkResponse("Replay deleted successfully");
|
||||
}
|
||||
|
||||
QHttpServerResponse getAvg(const QHttpServerRequest &request) {
|
||||
if (!hasReplayId(request)) {
|
||||
return createBadRequestResponse("replayId is missing");
|
||||
}
|
||||
|
||||
QString error;
|
||||
QJsonArray array = getAvgLatLng(request.query().queryItemValue("replayId"), error);
|
||||
return createOkResponse(array);
|
||||
}
|
||||
|
||||
#endif // REPLAYMETHODS_H
|
||||
@@ -1,32 +0,0 @@
|
||||
#ifndef SETUPSSLCERTIFICATE_H
|
||||
#define SETUPSSLCERTIFICATE_H
|
||||
#include <QCoreApplication>
|
||||
#include <qdir.h>
|
||||
#include <qsslconfiguration.h>
|
||||
#include <qsslkey.h>
|
||||
|
||||
QSslConfiguration setupSslCertificate() {
|
||||
QSslConfiguration sslConfiguration;
|
||||
|
||||
QString cert = QDir::cleanPath(QCoreApplication::applicationDirPath() + QDir::separator() + "../../config" + QDir::separator() + "server.crt");
|
||||
QString key = QDir::cleanPath(QCoreApplication::applicationDirPath() + QDir::separator() + "../../config" + QDir::separator() + "private.key");
|
||||
|
||||
QFile certFile(cert);
|
||||
QFile keyFile(key);
|
||||
|
||||
if (!certFile.open(QIODevice::ReadOnly) || !keyFile.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open certificate or key file";
|
||||
return sslConfiguration;
|
||||
}
|
||||
|
||||
QSslCertificate certificate(&certFile, QSsl::Pem);
|
||||
QSslKey privateKey(&keyFile, QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey, "RME2024");
|
||||
|
||||
sslConfiguration.setLocalCertificate(certificate);
|
||||
sslConfiguration.setPrivateKey(privateKey);
|
||||
sslConfiguration.setProtocol(QSsl::TlsV1_2);
|
||||
|
||||
return sslConfiguration;
|
||||
}
|
||||
|
||||
#endif // SETUPSSLCERTIFICATE_H
|
||||
@@ -1,35 +0,0 @@
|
||||
#ifndef TYPES_H
|
||||
#define TYPES_H
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
|
||||
struct GeoJSONFeature {
|
||||
QJsonObject geometry;
|
||||
QJsonObject properties;
|
||||
|
||||
QJsonObject toJson() const {
|
||||
QJsonObject feature;
|
||||
|
||||
feature["type"] = "Feature";
|
||||
feature["geometry"] = geometry;
|
||||
feature["properties"] = properties;
|
||||
|
||||
return feature;
|
||||
}
|
||||
|
||||
static GeoJSONFeature fromJson(const QJsonObject &json) {
|
||||
GeoJSONFeature feature;
|
||||
|
||||
if(json["type"] == "Feature") {
|
||||
|
||||
feature.geometry = json["geometry"].toObject();
|
||||
feature.properties = json["properties"].toObject();
|
||||
}
|
||||
|
||||
return feature;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // TYPES_H
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
#include "include/apiroutes.h"
|
||||
// #include "include/setupSslCertificate.h"
|
||||
#include <QCoreApplication>
|
||||
#include <qhttpserver.h>
|
||||
#include <QTcpServer>
|
||||
#include <QtSql/QSqlDatabase>
|
||||
#include <QSslConfiguration>
|
||||
#include <QSslCertificate>
|
||||
#include <QSslKey>
|
||||
#include <QFile>
|
||||
#include <QDir>
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QCoreApplication a(argc, argv);
|
||||
|
||||
QHttpServer server;
|
||||
qDebug() << hashPassword("root");
|
||||
// server.sslSetup(setupSslCertificate()); -> Ssl Certificate einfügen
|
||||
|
||||
setupApiRoutes(server);
|
||||
|
||||
const auto port = server.listen(QHostAddress::Any, 8080);
|
||||
|
||||
if (!port) {
|
||||
qDebug() << "Server failed to listen on port" << port;
|
||||
return 0;
|
||||
}
|
||||
qDebug() << "Server started on Port " << port;
|
||||
|
||||
return a.exec();
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
project(simulator VERSION 0.1 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_AUTORCC ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets Qml Location Network)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Qml Location Network)
|
||||
|
||||
set(PROJECT_SOURCES
|
||||
main.cpp
|
||||
mainwindow.cpp
|
||||
mainwindow.h
|
||||
mainwindow.ui
|
||||
)
|
||||
|
||||
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
|
||||
qt_add_executable(simulator
|
||||
MANUAL_FINALIZATION
|
||||
${PROJECT_SOURCES}
|
||||
main.qrc
|
||||
markerhelper.h markerhelper.cpp
|
||||
replayhelper.h replayhelper.cpp
|
||||
bookmarkhelper.h bookmarkhelper.cpp
|
||||
|
||||
|
||||
|
||||
|
||||
)
|
||||
# Define target properties for Android with Qt 6 as:
|
||||
# set_property(TARGET simulator APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR
|
||||
# ${CMAKE_CURRENT_SOURCE_DIR}/android)
|
||||
# For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation
|
||||
else()
|
||||
if(ANDROID)
|
||||
add_library(simulator SHARED
|
||||
${PROJECT_SOURCES}
|
||||
)
|
||||
# Define properties for Android with Qt 5 after find_package() calls as:
|
||||
# set(ANDROID_PACKAGE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/android")
|
||||
else()
|
||||
add_executable(simulator
|
||||
${PROJECT_SOURCES}
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
target_link_libraries(simulator PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Qml Qt${QT_VERSION_MAJOR}::Location Qt${QT_VERSION_MAJOR}::Network
|
||||
)
|
||||
|
||||
# Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1.
|
||||
# If you are developing for iOS or macOS you should consider setting an
|
||||
# explicit, fixed bundle identifier manually though.
|
||||
if(${QT_VERSION} VERSION_LESS 6.1.0)
|
||||
set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.simulator)
|
||||
endif()
|
||||
set_target_properties(simulator PROPERTIES
|
||||
${BUNDLE_ID_OPTION}
|
||||
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
||||
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
||||
MACOSX_BUNDLE TRUE
|
||||
WIN32_EXECUTABLE TRUE
|
||||
)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS simulator
|
||||
BUNDLE DESTINATION .
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
)
|
||||
|
||||
if(QT_VERSION_MAJOR EQUAL 6)
|
||||
qt_finalize_executable(simulator)
|
||||
endif()
|
||||
@@ -1,19 +0,0 @@
|
||||
import QtQuick 2.0
|
||||
import markerHelper 1.0
|
||||
import replayHelper 1.0
|
||||
import bookmarkHelper 1.0
|
||||
Item {
|
||||
MarkerHelper {
|
||||
id: markerHelper
|
||||
}
|
||||
ReplayHelper {
|
||||
id: replayHelper
|
||||
}
|
||||
BookmarkHelper {
|
||||
id: bookmarkHelper
|
||||
}
|
||||
|
||||
property BookmarkHelper bookmarkHelper : bookmarkHelper
|
||||
property ReplayHelper replayHelper : replayHelper
|
||||
property MarkerHelper markerHelper : markerHelper
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
import QtQuick
|
||||
import QtPositioning
|
||||
import QtLocation
|
||||
import QtQuick.Controls
|
||||
|
||||
Rectangle {
|
||||
id: mapContainer
|
||||
width: parent.width * 3 / 4
|
||||
height: parent.height
|
||||
|
||||
property real bookmarkTimestamp: 0
|
||||
|
||||
|
||||
function statusGen() {
|
||||
var random = Math.random();
|
||||
var status;
|
||||
|
||||
if (random < 0.01) {
|
||||
status = 'damaged';
|
||||
} else if (random < 0.10) {
|
||||
status = 'destroyed';
|
||||
} else {
|
||||
status = 'fully_capable';
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
function partieGen() {
|
||||
var random = Math.random();
|
||||
var status;
|
||||
|
||||
if (random < 0.33) {
|
||||
status = 'Red';
|
||||
} else {
|
||||
status = 'Blue';
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
|
||||
function createMarker() {
|
||||
var centerLat = 53.5200;
|
||||
var centerLng = 9.4050;
|
||||
var latRange = 0.1; // Beschränke auf ±0.1 Grad um centerLat
|
||||
var lngRange = 0.1; // Beschränke auf ±0.1 Grad um centerLng
|
||||
|
||||
for (var i = 1; i <= 200; i++) {
|
||||
var lat = centerLat + (Math.random() * latRange * 2 - latRange);
|
||||
var lng = centerLng + (Math.random() * lngRange * 2 - lngRange);
|
||||
|
||||
|
||||
var component = Qt.createComponent("marker.qml");
|
||||
var sprite = component.createObject(map, {
|
||||
"lat": lat,
|
||||
"lng": lng
|
||||
});
|
||||
logic.markerHelper.postObject(replay_uuid, i, lng, lat, statusGen(), partieGen());
|
||||
markers.push(sprite);
|
||||
}
|
||||
return markers;
|
||||
}
|
||||
|
||||
|
||||
Timer {
|
||||
id: moveTimer
|
||||
interval: 1000 // Move every second
|
||||
repeat: true
|
||||
onTriggered: {
|
||||
for (var i = 0 ; i < markers.length; i++) {
|
||||
|
||||
var newLat = markers[i].lat + (Math.random() * 0.01 - 0.005)
|
||||
var newLng = markers[i].lng + (Math.random() * 0.01 - 0.005)
|
||||
|
||||
markers[i].lat = newLat
|
||||
markers[i].lng = newLng
|
||||
|
||||
logic.markerHelper.postObject(replay_uuid, i+1, newLng, newLat, statusGen(), partieGen())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Plugin {
|
||||
id: mapPlugin
|
||||
name: "osm"
|
||||
PluginParameter {
|
||||
name: "osm.mapping.custom.host"
|
||||
value: "https://tile.openstreetmap.de/"
|
||||
}
|
||||
}
|
||||
|
||||
Map {
|
||||
id: map
|
||||
anchors.fill: parent
|
||||
plugin: mapPlugin
|
||||
center: QtPositioning.coordinate(53.5200, 9.4050) // Berlin
|
||||
zoomLevel: 14
|
||||
z: 1
|
||||
|
||||
property geoCoordinate startCentroid
|
||||
property var markers: []
|
||||
|
||||
PinchHandler {
|
||||
id: pinch
|
||||
target: null
|
||||
onActiveChanged: if (active) {
|
||||
map.startCentroid = map.toCoordinate(
|
||||
pinch.centroid.position, false)
|
||||
}
|
||||
onScaleChanged: delta => {
|
||||
map.zoomLevel += Math.log2(delta)
|
||||
map.alignCoordinateToPoint(
|
||||
map.startCentroid, pinch.centroid.position)
|
||||
}
|
||||
onRotationChanged: {} // Deaktiviert Rotation
|
||||
grabPermissions: PointerHandler.TakeOverForbidden
|
||||
}
|
||||
|
||||
DragHandler {
|
||||
id: drag
|
||||
target: map
|
||||
onTranslationChanged: delta => map.pan(-delta.x, -delta.y)
|
||||
}
|
||||
|
||||
activeMapType: supportedMapTypes[supportedMapTypes.length - 1]
|
||||
|
||||
Button {
|
||||
text: "Start Simulation"
|
||||
width: parent.width
|
||||
z: 10
|
||||
onClicked: {
|
||||
var sprites = createMarker()
|
||||
|
||||
for (var i = 0; i < sprites.length; i++) {
|
||||
map.addMapItem(sprites[i])
|
||||
}
|
||||
|
||||
moveTimer.start()
|
||||
}
|
||||
}
|
||||
|
||||
Button {
|
||||
text: "Add Lesezeichen"
|
||||
width: parent.width
|
||||
z:10
|
||||
y:25
|
||||
onClicked: {
|
||||
bookmarkTimestamp = Date.now();
|
||||
bookmarkDialog.open();
|
||||
}
|
||||
}
|
||||
}
|
||||
Dialog {
|
||||
id: bookmarkDialog
|
||||
title: "Add Lesezeichen"
|
||||
modal: true
|
||||
standardButtons: Dialog.Ok | Dialog.Cancel
|
||||
|
||||
Column {
|
||||
spacing: 10
|
||||
padding: 20
|
||||
|
||||
TextField {
|
||||
id: nameField
|
||||
placeholderText: "Name"
|
||||
}
|
||||
|
||||
TextArea {
|
||||
id: descriptionField
|
||||
placeholderText: "Description"
|
||||
}
|
||||
}
|
||||
|
||||
onAccepted: {
|
||||
var name = nameField.text;
|
||||
var description = descriptionField.text;
|
||||
logic.bookmarkHelper.postBookmark(replay_uuid, name, description, bookmarkTimestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
|
||||
Rectangle {
|
||||
id: replaySidebar
|
||||
width: parent.width * 1 / 4
|
||||
height: parent.height
|
||||
|
||||
Column {
|
||||
anchors.fill: parent
|
||||
spacing: 10
|
||||
padding: 10
|
||||
|
||||
Button {
|
||||
text: "Add Replay"
|
||||
onClicked: {
|
||||
addItemDialog.open()
|
||||
}
|
||||
width: parent.width - 20
|
||||
}
|
||||
|
||||
ListView {
|
||||
id: listView
|
||||
width: parent.width - 20
|
||||
height: parent.height
|
||||
model: itemList
|
||||
|
||||
delegate: Item {
|
||||
width: listView.width
|
||||
height: 40
|
||||
|
||||
Rectangle {
|
||||
id: background
|
||||
color: model.selected ? "lightblue" : "white" // Change color if selected
|
||||
anchors.fill: parent
|
||||
border.color: "gray"
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
onClicked: {
|
||||
// Deselect all items first
|
||||
for (var i = 0; i < itemList.count; i++) {
|
||||
itemList.setProperty(i, "selected",
|
||||
false) // Deselect
|
||||
}
|
||||
// Select the clicked item
|
||||
model.selected = true // Select this item
|
||||
console.log(model.uuid)
|
||||
replay_uuid = model.uuid // Assuming replay_uuid is declared elsewhere
|
||||
|
||||
for (var j = 0; j < markers.length; j++) {
|
||||
markers[j].visible = false // Unsichtbar machen
|
||||
markers[j].parent = null // Parent entfernen
|
||||
markers[j].destroy() // Objekt zerstören
|
||||
}
|
||||
markers = [] // Leere das Marker-Array
|
||||
}
|
||||
}
|
||||
}
|
||||
Button {
|
||||
text: "Delete"
|
||||
width: 80
|
||||
padding: 10
|
||||
anchors.verticalCenter: parent.verticalCenter
|
||||
anchors.right: parent.right
|
||||
background: Rectangle {
|
||||
color: "red"
|
||||
}
|
||||
|
||||
onClicked: {
|
||||
logic.replayHelper.deleteReplay(model.uuid)
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: model.name
|
||||
color: "black"
|
||||
anchors.centerIn: parent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Component.onCompleted: {
|
||||
logic.replayHelper.fetchReplays()
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: logic.replayHelper
|
||||
|
||||
function onReplaysFetched(replays) {
|
||||
itemList.clear()
|
||||
for (var i = 0; i < replays.length; i++) {
|
||||
itemList.append({
|
||||
"name": replays[i].name,
|
||||
"uuid": replays[i].uuid,
|
||||
"time_created": replays[i].time_created,
|
||||
"selected": false
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
#include "bookmarkhelper.h"
|
||||
#include <QDebug>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <qeventloop.h>
|
||||
#include <qqmlengine.h>
|
||||
#include <QNetworkReply>
|
||||
|
||||
BookmarkHelper::BookmarkHelper() {}
|
||||
|
||||
void BookmarkHelper::postBookmark(QString uuid, QString name, QString description, qint64 timestamp) {
|
||||
QNetworkRequest request;
|
||||
|
||||
request.setUrl(QUrl("http://localhost:8080/bookmark"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
// SSL-Konfiguration ohne Überprüfung des Zertifikats
|
||||
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
|
||||
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
request.setSslConfiguration(sslConfig);
|
||||
|
||||
QJsonObject obj;
|
||||
|
||||
obj["uuid"] = uuid;
|
||||
obj["name"] = name;
|
||||
obj["description"] = description;
|
||||
obj["timestamp"] = timestamp;
|
||||
|
||||
QJsonDocument jsonDoc(obj);
|
||||
QByteArray jsonData = jsonDoc.toJson();
|
||||
|
||||
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
|
||||
|
||||
QNetworkReply *reply = manager->post(request, jsonData);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, [reply, this] {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray response = reply->readAll();
|
||||
} else {
|
||||
qDebug() << "Error sending Replay:" << reply->errorString();
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef BOOKMARKHELPER_H
|
||||
#define BOOKMARKHELPER_H
|
||||
|
||||
#include <qnetworkaccessmanager.h>
|
||||
#include <qobject.h>
|
||||
|
||||
class BookmarkHelper : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
BookmarkHelper();
|
||||
|
||||
Q_INVOKABLE void postBookmark(QString uuid, QString name, QString description, qint64 timestamp);
|
||||
|
||||
private:
|
||||
QNetworkAccessManager *m_manager;
|
||||
};
|
||||
|
||||
#endif // BOOKMARKHELPER_H
|
||||
@@ -1,26 +0,0 @@
|
||||
#include "bookmarkhelper.h"
|
||||
#include "markerhelper.h"
|
||||
#include "replayhelper.h"
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QApplication>
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QApplication a(argc, argv);
|
||||
|
||||
qmlRegisterType<MarkerHelper>("markerHelper", 1, 0, "MarkerHelper");
|
||||
qmlRegisterType<ReplayHelper>("replayHelper", 1, 0, "ReplayHelper");
|
||||
qmlRegisterType<BookmarkHelper>("bookmarkHelper", 1,0, "BookmarkHelper");
|
||||
|
||||
QQmlApplicationEngine engine;
|
||||
|
||||
QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &a, [] () { QCoreApplication::exit(-1); }, Qt::QueuedConnection);
|
||||
|
||||
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
|
||||
|
||||
if(engine.rootObjects().isEmpty()) {
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
return a.exec();
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
|
||||
Window {
|
||||
id: window
|
||||
visible: true
|
||||
width: 1920
|
||||
height: 1080
|
||||
title: "RME-Simulator"
|
||||
|
||||
property string replay_uuid: ""
|
||||
property var markers: []
|
||||
|
||||
Logic {
|
||||
id: logic
|
||||
}
|
||||
ListModel {
|
||||
id: itemList
|
||||
}
|
||||
Rectangle {
|
||||
id: main
|
||||
width: parent.width
|
||||
height: parent.height
|
||||
visible: true
|
||||
Dialog {
|
||||
id: addItemDialog
|
||||
title: "Add New Replay"
|
||||
modal: true
|
||||
standardButtons: Dialog.Ok | Dialog.Cancel
|
||||
|
||||
Column {
|
||||
spacing: 10
|
||||
padding: 10
|
||||
Label {
|
||||
text: "Enter Replay Name:"
|
||||
}
|
||||
TextField {
|
||||
id: replayNameField
|
||||
width: 200
|
||||
placeholderText: "Replay Name"
|
||||
}
|
||||
}
|
||||
|
||||
onAccepted: {
|
||||
if(replayNameField.text !== "") {
|
||||
itemList.append({"name": replayNameField.text})
|
||||
logic.replayHelper.createReplay(replayNameField.text);
|
||||
replayNameField.text = ""
|
||||
}
|
||||
}
|
||||
Connections {
|
||||
target: logic.replayHelper
|
||||
|
||||
function onReplayCreated() {
|
||||
logic.replayHelper.fetchReplays(); // Fetch the updated list of replays
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SideBar_Component {
|
||||
id: sidebar
|
||||
anchors.left: parent.left
|
||||
}
|
||||
|
||||
Map_Component {
|
||||
id: map
|
||||
anchors.right: parent.right
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<RCC>
|
||||
<qresource prefix="/">
|
||||
<file>main.qml</file>
|
||||
<file>mss-symbol.png</file>
|
||||
<file>marker.qml</file>
|
||||
<file>Logic.qml</file>
|
||||
<file>Map_Component.qml</file>
|
||||
<file>SideBar_Component.qml</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -1,14 +0,0 @@
|
||||
#include "mainwindow.h"
|
||||
#include "./ui_mainwindow.h"
|
||||
|
||||
MainWindow::MainWindow(QWidget *parent)
|
||||
: QMainWindow(parent)
|
||||
, ui(new Ui::MainWindow)
|
||||
{
|
||||
ui->setupUi(this);
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
delete ui;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
#ifndef MAINWINDOW_H
|
||||
#define MAINWINDOW_H
|
||||
|
||||
#include <QMainWindow>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
namespace Ui {
|
||||
class MainWindow;
|
||||
}
|
||||
QT_END_NAMESPACE
|
||||
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
MainWindow(QWidget *parent = nullptr);
|
||||
~MainWindow();
|
||||
|
||||
private:
|
||||
Ui::MainWindow *ui;
|
||||
};
|
||||
#endif // MAINWINDOW_H
|
||||
@@ -1,31 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>MainWindow</class>
|
||||
<widget class="QMainWindow" name="MainWindow">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>600</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>MainWindow</string>
|
||||
</property>
|
||||
<widget class="QWidget" name="centralwidget"/>
|
||||
<widget class="QMenuBar" name="menubar">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>23</height>
|
||||
</rect>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusbar"/>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
@@ -1,22 +0,0 @@
|
||||
import QtQuick 2.0
|
||||
import QtPositioning 5.12
|
||||
import QtLocation 5.12
|
||||
|
||||
MapQuickItem{
|
||||
property double lat: 0
|
||||
property double lng: 0
|
||||
|
||||
id: mapMarker
|
||||
anchorPoint.x: image.width/2
|
||||
anchorPoint.y: image.height/2
|
||||
|
||||
sourceItem: Image {
|
||||
id: image
|
||||
source: "mss-symbol.png"
|
||||
width: 250 / 4
|
||||
height: 150 / 4
|
||||
}
|
||||
coordinate: QtPositioning.coordinate(lat,lng)
|
||||
onLatChanged: coordinate.latitude = lat
|
||||
onLngChanged: coordinate.longitude = lng
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
#include "markerhelper.h"
|
||||
#include <QDebug>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <qeventloop.h>
|
||||
#include <qqmlengine.h>
|
||||
#include <QNetworkReply>
|
||||
MarkerHelper::MarkerHelper() {
|
||||
m_manager = new QNetworkAccessManager(this);
|
||||
}
|
||||
void MarkerHelper::startSimulation(QString replayId) {
|
||||
|
||||
}
|
||||
void MarkerHelper::postObject(QString replayId,int id, double lat, double lng, QString status, QString partie) {
|
||||
// Erstelle das GeoJSON-Objekt
|
||||
QString sidic;
|
||||
|
||||
if(status == "damaged") {
|
||||
sidic = "10061000001212000000"; // SIDIC CODE FOR SMYBOL ( DAMAGED )
|
||||
} else if (status == "destroyed") {
|
||||
sidic = "10031500001202000000"; // SIDIC CODE FOR SMYBOL ( DESTROYED )
|
||||
} else if (status == "fully_capable") {
|
||||
sidic = "30031020000000000000"; // SIDIC CODE FOR SYMBOL ( FULLY_CAPALE )
|
||||
}
|
||||
|
||||
QJsonObject geoJson;
|
||||
geoJson.insert("type", "Feature");
|
||||
|
||||
QJsonObject geometry;
|
||||
geometry.insert("type", "Point");
|
||||
|
||||
QJsonArray coordinates;
|
||||
coordinates.append(lng);
|
||||
coordinates.append(lat);
|
||||
geometry.insert("coordinates", coordinates);
|
||||
|
||||
QJsonObject properties;
|
||||
properties.insert("id", id);
|
||||
properties.insert("timestamp", QDateTime::currentMSecsSinceEpoch());
|
||||
properties.insert("replay_id", replayId);
|
||||
properties.insert("parties", partie);
|
||||
properties.insert("sidic", sidic);
|
||||
|
||||
geoJson.insert("properties", properties);
|
||||
geoJson.insert("geometry", geometry);
|
||||
|
||||
QJsonDocument jsonDoc(geoJson);
|
||||
QByteArray jsonData = jsonDoc.toJson();
|
||||
|
||||
QNetworkRequest request;
|
||||
|
||||
request.setUrl(QUrl("http://localhost:8080/objects"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
|
||||
|
||||
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
request.setSslConfiguration(sslConfig);
|
||||
|
||||
QNetworkReply *reply = m_manager->post(request, jsonData);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, [reply] {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray response = reply->readAll();
|
||||
// Verarbeite die Antwort
|
||||
} else {
|
||||
qDebug() << "Error sending GeoJSON:" << reply->errorString();
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef MARKERHELPER_H
|
||||
#define MARKERHELPER_H
|
||||
|
||||
#include <qnetworkaccessmanager.h>
|
||||
#include <qobject.h>
|
||||
class MarkerHelper : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
MarkerHelper();
|
||||
|
||||
Q_INVOKABLE void postObject(QString replayId, int id, double lat, double lng, QString status, QString partie);
|
||||
Q_INVOKABLE void startSimulation(QString replayId);
|
||||
|
||||
private:
|
||||
QNetworkAccessManager *m_manager;
|
||||
};
|
||||
|
||||
#endif // MARKERHELPER_H
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 796 B |
@@ -1,104 +0,0 @@
|
||||
#include "replayhelper.h"
|
||||
#include <qjsonarray.h>
|
||||
#include <qjsondocument.h>
|
||||
#include <qjsonobject.h>
|
||||
#include <qnetworkaccessmanager.h>
|
||||
#include <qnetworkreply.h>
|
||||
#include <qnetworkrequest.h>
|
||||
|
||||
ReplayHelper::ReplayHelper() {
|
||||
connect(&m_manager, &QNetworkAccessManager::finished, this, &ReplayHelper::onReplaysFetched);
|
||||
}
|
||||
|
||||
QJsonArray ReplayHelper::replays() {
|
||||
return m_replays;
|
||||
}
|
||||
|
||||
void ReplayHelper::fetchReplays() {
|
||||
QUrl url("http://localhost:8080/replays");
|
||||
QNetworkRequest request(url);
|
||||
// SSL-Konfiguration ohne Überprüfung des Zertifikats
|
||||
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
|
||||
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
request.setSslConfiguration(sslConfig);
|
||||
m_manager.get(request);
|
||||
}
|
||||
|
||||
void ReplayHelper::onReplaysFetched(QNetworkReply * reply) {
|
||||
if(reply->error() != QNetworkReply::NoError) {
|
||||
qWarning() << "Fehler beim Abrufen der Replays";
|
||||
reply->deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
QByteArray responseData = reply->readAll();
|
||||
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
|
||||
|
||||
m_replays = QJsonArray();
|
||||
|
||||
for(int i = 0; i < jsonDoc.array().size(); i++) {
|
||||
m_replays.append(jsonDoc.array()[i]);
|
||||
}
|
||||
|
||||
emit replaysFetched(m_replays);
|
||||
emit replaysChanged();
|
||||
}
|
||||
void ReplayHelper::createReplay(QString name) {
|
||||
QNetworkRequest request;
|
||||
|
||||
request.setUrl(QUrl("http://localhost:8080/replays"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
|
||||
|
||||
// SSL-Konfiguration ohne Überprüfung des Zertifikats
|
||||
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
|
||||
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
request.setSslConfiguration(sslConfig);
|
||||
|
||||
QJsonObject obj;
|
||||
|
||||
obj["name"] = name;
|
||||
obj["created_by"] = 1;
|
||||
|
||||
QJsonDocument jsonDoc(obj);
|
||||
QByteArray jsonData = jsonDoc.toJson();
|
||||
|
||||
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
|
||||
|
||||
QNetworkReply *reply = manager->post(request, jsonData);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, [reply, this] {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray response = reply->readAll();
|
||||
emit replayCreated();
|
||||
fetchReplays(); // Lädt die aktualisierte Liste erneut
|
||||
} else {
|
||||
qDebug() << "Error sending Replay:" << reply->errorString();
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
emit replayCreated();
|
||||
}
|
||||
|
||||
void ReplayHelper::deleteReplay(QString replayId) {
|
||||
QNetworkRequest request;
|
||||
|
||||
request.setUrl(QUrl("http://localhost:8080/replays/delete?replayId=" + replayId));
|
||||
|
||||
QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
|
||||
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
|
||||
request.setSslConfiguration(sslConfig);
|
||||
|
||||
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
|
||||
|
||||
QNetworkReply *reply = manager->deleteResource(request);
|
||||
|
||||
connect(reply, &QNetworkReply::finished, [reply, this] {
|
||||
if (reply->error() == QNetworkReply::NoError) {
|
||||
QByteArray response = reply->readAll();
|
||||
fetchReplays();
|
||||
} else {
|
||||
qDebug() << "Error sending Replay:" << reply->errorString();
|
||||
}
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
#ifndef REPLAYHELPER_H
|
||||
#define REPLAYHELPER_H
|
||||
|
||||
#include <qjsonarray.h>
|
||||
#include <qnetworkaccessmanager.h>
|
||||
#include <qobject.h>
|
||||
class ReplayHelper : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ReplayHelper();
|
||||
|
||||
Q_INVOKABLE QJsonArray replays();
|
||||
Q_INVOKABLE void fetchReplays();
|
||||
Q_INVOKABLE void createReplay(QString name);
|
||||
Q_INVOKABLE void deleteReplay(QString replayId);
|
||||
signals:
|
||||
void replaysChanged();
|
||||
void replaysFetched(const QJsonArray &replays);
|
||||
void replayCreated();
|
||||
private slots:
|
||||
void onReplaysFetched(QNetworkReply * reply);
|
||||
|
||||
private:
|
||||
QNetworkAccessManager m_manager;
|
||||
QJsonArray m_replays;
|
||||
};
|
||||
|
||||
#endif // REPLAYHELPER_H
|
||||
Reference in new issue
Block a user