Add frontend and backend files

This commit is contained in:
Léo Carpentier 2022-02-09 13:56:34 +02:00
parent cf7aee71a2
commit 32ea3f5031
27 changed files with 30853 additions and 0 deletions

8
.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
.env
.overnodebundle
*.old
node/node_modules
nginx-react/node_modules
nginx-react/build
.vscode
dummyEmitter

5
backend/.dockerignore Normal file
View File

@ -0,0 +1,5 @@
./node_modules
./build
.git
*.md
.gitignore

View File

@ -1 +1,16 @@
# pull official node image
FROM node
# define /app as working directory
WORKDIR /app
# copy package.json and package-lock.json to /app
COPY package.json /app
COPY package-lock.json /app
# install node dependencies
RUN npm install
COPY . /app
# launch node server
ENTRYPOINT node server.js

3181
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
backend/package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js",
"build": "cd frontend && npm install && npm run build"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.2",
"minio": "^7.0.26",
"mongodb": "^4.3.1"
}
}

93
backend/server.js Normal file
View File

@ -0,0 +1,93 @@
const { MongoClient } = require("mongodb");
const express = require('express');
const minio = require('minio');
/*============== VARIABLE DECLARATION ==============*/
// Mongo set-up variables
const mongoEndpoint = process.env.ME_CONFIG_MONGODB_SERVER;
const mongoPort = parseInt(process.env.ME_CONFIG_MONGODB_PORT);
const mongoDatabase = process.env.ME_CONFIG_MONGODB_DB;
const mongoCollection = process.env.ME_CONFIG_MONGODB_COLLECTION;
// Minio set-up variables
const minioEndpoint = process.env.MINIO_ENDPOINT;
const minioBucket = process.env.MINIO_BUCKET;
const minioPort = parseInt(process.env.MINIO_SERVING_PORT);
const minioKey = process.env.MINIO_ACCESS_KEY;
const minioSecret = process.env.MINIO_SECRET_KEY;
// Stream set-up variables
let changeStream;
const options = { fullDocument: "updateLookup" };
const pipeline = [];
const PORT = process.env.PORT || 3002;
// Create Mongo client
const MONGO_URI = `mongodb://${mongoEndpoint}:${mongoPort}`;
const mongoClient = new MongoClient(MONGO_URI);
/*============== CODE ==============*/
async function run() {
console.log('server.js has been launched')
const app = express();
// Configuring mongoDB connection
await mongoClient.connect();
const database = mongoClient.db(mongoDatabase);
const collection = database.collection(mongoCollection);
// Notify connection
console.log(`Connection established with Mongo Database at ${MONGO_URI}`);
// Opening event listener on the database
changeStream = collection.watch(pipeline, options);
console.log("Started watching changes in database");
app.get('/events', async function (request, response) {
let eventArray = [];
let minioClient = new minio.Client({
endPoint: minioEndpoint,
port: minioPort,
useSSL: false,
accessKey: minioKey,
secretKey: minioSecret
});
// notifies GET requests
console.log('/events was requested');
// Setting the header to event-stream for Server Sent Events (Eventsource)
const header = { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive' }
response.writeHead(200, "OK", header);
response.write('Connection established \n\n');
// Triggers callback on every change in collection set up
changeStream.on("change", data => {
// Retrieves modified document on the db and stores it
let document = JSON.stringify(data.fullDocument);
eventArray = [document, ...eventArray];
// Fetch screenshot if there is one
if (data.fullDocument.screenshot_count) {
minioClient.presignedUrl('GET', minioBucket, `${data.fullDocument.camera}/${data.fullDocument._id}/1.jpg`, 60 * 60, (err, presignedUrl) => {
if (err) { return console.log(err) };
const realURL = JSON.stringify({ picUrl: presignedUrl });
eventArray = [realURL, ...eventArray];
})
}
// sends updated array
response.write(`data: [${[...eventArray]}]\n\n`);
});
});
app.listen(PORT);
console.log(`Server listening at 127.0.0.1:${PORT}`);
}
run().catch(console.dir);

5
frontend/.dockerignore Normal file
View File

@ -0,0 +1,5 @@
./node_modules
./build
.git
*.md
.gitignore

View File

@ -1,5 +1,39 @@
# pull official base image
FROM node AS builder
# set working directory
WORKDIR /app
# install app dependencies
#copies package.json and package-lock.json to Docker environment
COPY package.json ./
# Installs all node packages
RUN npm install
# Copies everything over to Docker environment
COPY . ./
RUN npm run build
#Stage 2
#######################################
#pull the official nginx:1.19.0 base image
FROM nginx
#copies React to the container directory
# Set working directory to nginx resources directory
WORKDIR /usr/share/nginx/html
# Remove default nginx static resources
RUN rm -rf ./*
RUN apt-get install bash
# Copies configuration files
COPY ./default.conf /etc/nginx/conf.d/default.conf
# Copies static resources from builder stage
COPY --from=builder /app/build .
# Containers run nginx with global directives and daemon off
ENTRYPOINT ["nginx", "-g", "daemon off;"]

70
frontend/README.md Normal file
View File

@ -0,0 +1,70 @@
# 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 your browser.
The page will reload when you make changes.\
You may 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/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

27179
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
frontend/package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.1",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"web-vitals": "^2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3002",
"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"
]
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,43 @@
<!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>React App</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>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"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"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,3 @@
body {
background-color: #eafaf9;
}

View File

@ -0,0 +1,32 @@
import React, { useState, useEffect } from 'react';
import './App.css';
import EventList from '../eventList/EventList.js';
function App(props) {
const [events, setEvents] = useState(['EventLog']); // initialises Event state
const [sse, setSse] = useState(new EventSource('/events', { withCredentials: true})) // creates eventSource listener
useEffect(() => {
sse.onerror = (e) => {
console.error();
sse.close();
}
sse.onmessage = (e) => {
// parses received data from string to JSON
const message = JSON.parse(e.data);
// initialises a new array with updated server-side event array
const newEvents = [...message];
// sets the updated event array as state
setEvents(newEvents);
};
});
return <EventList data={events} />
}
export default App;

View File

@ -0,0 +1,18 @@
.eventDiv {
background-color: aliceblue;
border: 2px solid #26A69A;
border-radius: 15px;
text-align: left;
padding: 5px;
max-width: fit-content;
font-family: apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
color: #092a26;
margin: 7px 0px;
}
.eventPic {
border-radius: 15px;
border: 1px groove #d5f6f2;
max-width:100%;
max-height:100%;
}

View File

@ -0,0 +1,13 @@
import React from "react";
import "./Event.css";
function Event(props) {
return (
<div className="eventDiv">
{props.data.picUrl? <img className="eventPic" src={props.data.picUrl}></img> : JSON.stringify(props.data)}
</div>
);
}
export default Event;

View File

@ -0,0 +1,11 @@
.eventListUl {
background-color: #c1f1ec;
max-width: 50%;
padding: 5px;
border: 5px solid #26A69A;
border-radius: 5px;
}
.eventListLi {
list-style: none;
}

View File

@ -0,0 +1,18 @@
import React from 'react';
import Event from '../event/Event.js';
import './EventList.css';
function EventList(props) {
console.log(`FROM LIST: ${props.data}`);
return (
<ul className="eventListUl">
{props.data.map((event) => {
return <li className="eventListLi"><Event data={event} /></li>
})}
</ul>
)
}
export default EventList;

3
frontend/src/index.css Normal file
View File

@ -0,0 +1,3 @@
body {
}

17
frontend/src/index.js Normal file
View File

@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/app/App.js';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// 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();

View File

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
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;

View File

@ -0,0 +1,5 @@
// 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';