This commit is contained in:
2023-06-11 22:44:25 +02:00
parent cafb6bc755
commit a38909babd
10 changed files with 1735 additions and 88 deletions

131
.gitignore vendored Normal file
View File

@@ -0,0 +1,131 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

14
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,14 @@
stages:
- build
variables:
TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest
TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA
build:
stage: build
script:
- docker build -t $TAG_LATEST -t $TAG_COMMIT .
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
- docker push $TAG_COMMIT
- docker push $TAG_LATEST

29
Dockerfile Normal file
View File

@@ -0,0 +1,29 @@
# Verwende Python als Basisimage
FROM node:latest
# Setze Arbeitsverzeichnis
WORKDIR /usr/src/app
# Kopiere die package.json und package-lock.json in das Arbeitsverzeichnis
COPY package*.json ./
# Installiere die Abhängigkeiten
RUN npm install
# Kopiere den Quellcode in das Arbeitsverzeichnis
COPY ./src .
# Installiere Python
RUN apt-get update && apt-get install -y python3 python3-pip
# Installiere die Python-Abhängigkeiten
RUN pip3 install --no-cache-dir -r requirements.txt
# Setze den Port des Web-Servers
ENV WEB_PORT=80
# Öffne den Port des Web-Servers
EXPOSE $WEB_PORT
# Starte den Web-Server
CMD ["python", "server.js"]

103
README.md
View File

@@ -1,92 +1,19 @@
# BerichtExporter
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.lino3d.de/Lino/BerichTExporter.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.lino3d.de/Lino/BerichTExporter/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
```yaml
version: '3.7'
services:
berichtexporter:
image: registry.gitlab.lino3d.de:443/lino/berichtexporter/main:latest
restart: unless-stopped
ports:
- 80:80
environment:
- 'CALDAV_URL=https://example.com/calendars/' # URL to the caldav server
- 'CALDAV_USER=USERNAME' # Username for the caldav server
- 'CALDAV_PASSWORD=PASSWORD' # Password for the caldav server
- 'CALDAV_CALENDAR=CALENDARNAME' # Calendar name from the caldav server
# - WEB_PORT=80 # Port for the webserver (optional)
```

1324
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

7
package.json Normal file
View File

@@ -0,0 +1,7 @@
{
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"moment": "^2.29.4"
}
}

53
src/getCalendar.py Normal file
View File

@@ -0,0 +1,53 @@
import datetime
from caldav.davclient import DAVClient
import argparse
import html
# Parse command-line arguments
parser = argparse.ArgumentParser(description='Retrieve events from a CalDAV calendar.')
parser.add_argument('url', type=str, help='Server URL')
parser.add_argument('user', type=str, help='Username')
parser.add_argument('password', type=str, help='Password')
parser.add_argument('calendar', type=str, help='Calendar name')
parser.add_argument('start_date', type=str, help='Start date (dd.mm.yyyy)')
parser.add_argument('end_date', type=str, help='End date (dd.mm.yyyy)')
args = parser.parse_args()
# Create a DAV client
client = DAVClient(args.url, username=args.user, password=args.password)
# Find the calendar by its name ('myCalendar' in this case)
principal = client.principal()
calendars = principal.calendars()
calendar = None
for cal in calendars:
if cal.name == args.calendar:
calendar = cal
break
if calendar:
# Set the start and end timestamps
start = datetime.datetime.strptime(args.start_date, "%d.%m.%Y")
end = datetime.datetime.strptime(args.end_date, "%d.%m.%Y")
start = start.replace(hour=0, minute=0, second=0)
end = end.replace(hour=23, minute=59, second=59)
results = calendar.date_search(start, end)
# Store events in a list
events = []
for result in results:
event = result.instance.vevent
summary = event.summary.value if event.summary else None
start_time = event.dtstart.value.strftime("%d.%m.%Y %H:%M:%S")
events.append((start_time, summary))
# Sort the events by start time
events.sort(key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y %H:%M:%S"))
# Print the sorted events
for summary in events:
print('-', summary[1])
else:
print('Calendar not found.')

1
src/requirements.txt Normal file
View File

@@ -0,0 +1 @@
caldav

86
src/server.js Normal file
View File

@@ -0,0 +1,86 @@
const express = require('express');
const path = require('path');
const app = express();
const { spawnSync } = require('child_process');
const moment = require('moment');
// Befehl für die Skriptausführung
const command = process.platform === 'win32' ? 'python' : 'python3';
// Pfad zum Kalender-Skript
const scriptPath = path.resolve(__dirname, 'getCalendar.py');
// Definiere den Port, auf dem der Webserver lauschen soll
const webPort = process.env.WEB_PORT || 3000;
const templates = path.join(__dirname, 'templates');
// Stelle den Pfad zum "views" Verzeichnis ein
app.set('views', templates);
// Verwende EJS als Vorlagen-Engine
app.set('view engine', 'ejs');
// Funktion zum Formatieren des Datums
function formatDate(date) {
const day = date.getDate().toString().padStart(2, '0');
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const year = date.getFullYear();
return `${day}.${month}.${year}`;
}
// Funktion zum Erstellen der Liste der letzten 50 Wochen
function getLast50Weeks() {
let currentWeek = moment().startOf('isoWeek');
const last50Weeks = [];
for (let i = 0; i < 50; i++) {
const startOfWeek = currentWeek.clone().format('DD.MM.YYYY');
const endOfWeek = currentWeek.clone().add(6, 'days').format('DD.MM.YYYY');
last50Weeks.push(startOfWeek + " - " + endOfWeek);
currentWeek.subtract(7, 'days');
}
return last50Weeks;
}
function convertToJsEscape(str) {
return str.replace(/[\u00A0-\u9999]/g, function (match) {
return '\\u' + ('0000' + match.charCodeAt(0).toString(16)).slice(-4);
});
}
function getCalendarEntries(week) {
const weekDate = getLast50Weeks()[week];
const [startDateStr, endDateStr] = weekDate.split(" - ");
// Argumente für das Kalender-Skript
const args = [
process.env.CALDAV_URL,
process.env.CALDAV_USER,
process.env.CALDAV_PASSWORD,
process.env.CALDAV_CALENDAR,
startDateStr,
endDateStr
];
// Skript ausführen und Output in einer Variable speichern
const result = spawnSync(command, [scriptPath, ...args], { encoding: 'utf-8' });
console.log(convertToJsEscape(result.stdout.toString('utf-8')));
return result.stdout;
}
// Definiere eine Route für die Startseite
app.get('/', (req, res) => {
res.render('index', { options:getLast50Weeks() });
});
// Definiere eine Route für die Ausgabe der Daten
app.get('/getreport', (req, res) => {
res.send(getCalendarEntries(req.query.week));
});
// Starte den Server und lass ihn auf Port 3000 lauschen
app.listen(webPort, () => {
console.log('Webserver läuft auf Port', webPort);
});

75
src/templates/index.ejs Normal file
View File

@@ -0,0 +1,75 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BerichtExporter</title>
<style>
body {
font-family: 'Roboto', sans-serif;
font-size: 16px;
background-color: #f5f5f5;
}
.selector {
margin-top: 10px;
margin-bottom: 10px;
}
.selector select {
height: 30px;
font-size: 16px;
}
.selector button {
font-size: 16px;
height: 30px;
margin-left: 10px;
}
#export-textarea {
font-size: 16px;
width: 90%;
resize: none;
overflow-y: hidden;
}
</style>
</head>
<body>
<h1>BerichtExporter</h1>
<div class="selector">
<select id="week-list">
<% options.forEach((element, index) => { %>
<option value="<%= index %>"><%= element %></option>
<% }); %>
</select>
<button id="export-button" onclick="exportReport()">Export</button>
</div>
<textarea id="export-textarea" readonly></textarea>
<script>
const exportTextarea = document.getElementById('export-textarea');
const weekList = document.getElementById('week-list');
function exportReport() {
const week = weekList.value;
fetch('/getreport?week=' + week)
.then(response => {
if (response.ok) {
return response.text();
} else {
exportTextarea.value = 'Error while fetching report';
throw new Error('Error while fetching report');
}
}).then(text => {
exportTextarea.value = text;
exportTextarea.style.height = exportTextarea.scrollHeight + "px";
}).catch(error => {
exportTextarea.value = 'Error while fetching report';
console.error(error);
});
}
</script>
</body>
</html>