🎉 Initial commit

This commit is contained in:
Marc Koch 2025-01-05 22:04:51 +01:00
commit fad27fe7f0
Signed by: marc
GPG Key ID: 12406554CFB028B9
19 changed files with 906 additions and 0 deletions

175
.gitignore vendored Normal file
View File

@ -0,0 +1,175 @@
# Created by https://www.toptal.com/developers/gitignore/api/django
# Edit at https://www.toptal.com/developers/gitignore?templates=django
### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py
db.sqlite3
db.sqlite3-journal
media
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
# in your Git repository. Update and uncomment the following line accordingly.
# <django-project-name>/staticfiles/
### Django.Python Stack ###
# Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
# Django stuff:
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# End of https://www.toptal.com/developers/gitignore/api/django

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

10
.idea/RoomBooking.iml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.12 (RoomBooking)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

20
.idea/dataSources.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="db" uuid="37a129b8-8038-4c13-bba8-73cf8fa77538">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/src/db.sqlite3</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
<libraries>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/xerial/sqlite-jdbc/3.45.1.0/sqlite-jdbc-3.45.1.0.jar</url>
</library>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar</url>
</library>
</libraries>
</data-source>
</component>
</project>

View File

@ -0,0 +1,76 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="HttpUrlsUsage" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredUrls">
<list>
<option value="http://localhost" />
<option value="http://127.0.0.1" />
<option value="http://0.0.0.0" />
<option value="http://www.w3.org/" />
<option value="http://json-schema.org/draft" />
<option value="http://java.sun.com/" />
<option value="http://xmlns.jcp.org/" />
<option value="http://javafx.com/javafx/" />
<option value="http://javafx.com/fxml" />
<option value="http://maven.apache.org/xsd/" />
<option value="http://maven.apache.org/POM/" />
<option value="http://www.springframework.org/schema/" />
<option value="http://www.springframework.org/tags" />
<option value="http://www.springframework.org/security/tags" />
<option value="http://www.thymeleaf.org" />
<option value="http://www.jboss.org/j2ee/schema/" />
<option value="http://www.jboss.com/xml/ns/" />
<option value="http://www.ibm.com/webservices/xsd" />
<option value="http://activemq.apache.org/schema/" />
<option value="http://schema.cloudfoundry.org/spring/" />
<option value="http://schemas.xmlsoap.org/" />
<option value="http://cxf.apache.org/schemas/" />
<option value="http://primefaces.org/ui" />
<option value="http://tiles.apache.org/" />
<option value="http://" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyCompatibilityInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ourVersions">
<value>
<list size="3">
<item index="0" class="java.lang.String" itemvalue="3.12" />
<item index="1" class="java.lang.String" itemvalue="3.11" />
<item index="2" class="java.lang.String" itemvalue="3.10" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="13">
<item index="0" class="java.lang.String" itemvalue="pandas" />
<item index="1" class="java.lang.String" itemvalue="PyPDF2" />
<item index="2" class="java.lang.String" itemvalue="drf-spectacular" />
<item index="3" class="java.lang.String" itemvalue="django-crispy-forms" />
<item index="4" class="java.lang.String" itemvalue="Django" />
<item index="5" class="java.lang.String" itemvalue="qrcode" />
<item index="6" class="java.lang.String" itemvalue="psycopg2" />
<item index="7" class="java.lang.String" itemvalue="django-active-link" />
<item index="8" class="java.lang.String" itemvalue="shortuuid" />
<item index="9" class="java.lang.String" itemvalue="uwsgi" />
<item index="10" class="java.lang.String" itemvalue="djangorestframework" />
<item index="11" class="java.lang.String" itemvalue="Pillow" />
<item index="12" class="java.lang.String" itemvalue="pyproject_hooks" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N813" />
</list>
</option>
</inspection_tool>
<inspection_tool class="ReassignedToPlainText" enabled="false" level="WARNING" enabled_by_default="false" />
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

10
.idea/misc.xml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.12 (RoomBooking)" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8 (tazPlease)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/RoomBooking.iml" filepath="$PROJECT_DIR$/.idea/RoomBooking.iml" />
</modules>
</component>
</project>

23
Dockerfile Normal file
View File

@ -0,0 +1,23 @@
FROM python:3.12-slim-bookworm
LABEL authors="Marc Koch"
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY src/ ./
COPY requirements.txt .
COPY README.md index.md
RUN pip install --no-cache-dir -r requirements.txt
RUN groupadd -r app-user && useradd -r -g app-user app-user && \
chown -R app-user:app-user /app
USER app-user
EXPOSE 8000
CMD ["nanodjango", "serve", "booking.py"]
#CMD ["nanodjango", "run", "booking.py"]

73
LICENSE.md Normal file
View File

@ -0,0 +1,73 @@
Apache License, Version 2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks.
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

60
README.md Normal file
View File

@ -0,0 +1,60 @@
Room Booking
---
This application allows you to create an event in a room booking calendar via a
REST API.
## Setup
If you see this page, the application is already running.
You will have to create users, API keys and calendars
via [admin interface](/admin).
## Usage
A full documentation of the API is available at [`/api/docs/`](/api/docs).
Authentication is done via a Bearer token in the `Authorization` header.
### Create an event
To create an event, you need to send a POST request to `/api/{calendar}/events/`
with the following JSON payload:
```json
{
"name": "Event Title",
"start": "2025-01-02T12:00:00",
"end": "2025-01-02T13:00:00"
}
```
Curl example:
```bash
curl -s \
-H "Authorization: Bearer secrettoken" \
-H "Content-Type: application/json" \
-d "{\"name\": \"Test-Event\", \"start\": \"$(date --iso-8601=minutes)\", \"end\": \"$(date --iso-8601=minutes -d '+2 hours')\"}" \
localhost:8000/api/test-kalender/event
```
The response will contain the event ID:
```json
{"id": "4zx3QAFzoxV3vaZSKGaH2S"}
```
### Delete an event
To delete an event, you need to send a DELETE request to `/api/{calendar}/events/{event_id}`.
Curl example:
```bash
curl -s -X DELETE \
-H "Authorization: Bearer secrettoken" \
-H "Content-Type: application/json" \
localhost:8000/api/test-kalender/event/4zx3QAFzoxV3vaZSKGaH2S
```
The response will be empty but the status code will be `204`.

15
docker-compose.yaml Normal file
View File

@ -0,0 +1,15 @@
---
services:
app:
image: git.extrasolar.space/marc/room-booking.git:latest
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
- app-data:/app
env_file: .env
volumes:
app-data:

35
requirements.txt Normal file
View File

@ -0,0 +1,35 @@
annotated-types==0.7.0
arrow==1.3.0
asgiref==3.8.1
attrs==24.3.0
black==24.10.0
certifi==2024.12.14
charset-normalizer==3.4.1
click==8.1.8
Django==5.1.4
django-ninja==1.3.0
gunicorn==23.0.0
h11==0.14.0
ics==0.7.2
idna==3.10
isort==5.13.2
Markdown==3.7
mypy-extensions==1.0.0
nanodjango==0.9.2
packaging==24.2
pathspec==0.12.1
platformdirs==4.3.6
pydantic==2.10.4
pydantic_core==2.27.2
python-dateutil==2.9.0.post0
requests==2.32.3
shortuuid==1.0.13
six==1.17.0
sqlparse==0.5.3
TatSu==5.12.2
types-python-dateutil==2.9.0.20241206
typing_extensions==4.12.2
urllib3==2.3.0
uvicorn==0.34.0
validators==0.34.0
whitenoise==6.8.2

1
src/.dockerignore Normal file
View File

@ -0,0 +1 @@
db.*

278
src/booking.py Normal file
View File

@ -0,0 +1,278 @@
import os
import secrets
from datetime import datetime
from pathlib import Path
from uuid import UUID
import markdown
import requests
import shortuuid
from django.core.validators import URLValidator
from django.db import models
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from ics import Calendar as ICS_Calendar, Event as ICS_Event
from nanodjango import Django
from shortuuid.django_fields import ShortUUIDField
DJANGO_SECRET_KEY = os.getenv("DJANGO_SECRET_KEY") \
if os.getenv("DJANGO_SECRET_KEY") \
else secrets.token_hex(40) if os.getenv("DEBUG") else None
DEBUG = os.getenv("DEBUG")
BASE_DIR = Path(__file__).resolve().parent
# Check if all required values are set
if not DJANGO_SECRET_KEY and not DEBUG:
print("DJANGO_SECRET_KEY is not set")
exit(1)
# Initialise nanodjango
app = Django(
SECRET_KEY=DJANGO_SECRET_KEY,
TIME_ZONE=os.getenv("TIME_ZONE", "Europe/Berlin"),
ALLOWED_HOSTS=["localhost"] + [host for host in
os.getenv("ALLOWED_HOSTS", "").split(",")],
DEBUG=DEBUG,
TEMPLATES_DIR=BASE_DIR / "templates",
STATICFILES_DIRS=[
BASE_DIR / "static",
],
)
# Import ninja after nanodjango has been initialised to avoid this error:
# https://github.com/vitalik/django-ninja/issues/1169
from ninja import NinjaAPI, ModelSchema
from ninja.security import HttpBearer, django_auth
from ninja.errors import HttpError
@app.admin
class Calendar(models.Model):
"""
A calendar model to store events.
"""
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100, editable=False)
url = models.URLField(validators=[URLValidator])
calendar_password = models.CharField(max_length=29)
users = models.ManyToManyField(app.settings.AUTH_USER_MODEL,
related_name='calendars')
def save(self, *args, **kwargs):
self.url = self.url.rstrip("/")
self.name = self.get_name()
return super().save(*args, **kwargs)
def get_name(self):
return self.url.split("/")[-1]
@property
def username(self):
return self.url.split("/")[-2]
def __str__(self):
return self.name
@app.admin(ordering=("start", "end", "name"))
class Event(models.Model):
"""
Event model to store events in a calendar and send them to a CalDAV server.
"""
id = ShortUUIDField(primary_key=True, editable=False, unique=True,
default=shortuuid.uuid)
calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE,
related_name='events')
name = models.CharField(max_length=100)
path = models.CharField(max_length=200, editable=False)
start = models.DateTimeField()
end = models.DateTimeField()
ics = models.TextField(blank=True)
sent = models.DateTimeField(blank=True, null=True, editable=False)
cancelled = models.DateTimeField(blank=True, null=True, editable=False)
def save(self, *args, **kwargs):
self.path = f"{self.calendar.url}/{self.uuid}"
self.ics = self.create_ics()
# Send the event to the CalDAV server if it has not been cancelled yet
if not self.cancelled:
try:
self.send()
except requests.HTTPError as e:
raise HttpError(401, str(e))
return super().save(*args, **kwargs)
def delete(self, *args, **kwargs):
if self.sent:
self.cancel()
return super().delete(*args, **kwargs)
def send(self):
"""
Sends a PUT request to the CalDAV server to create the event.
:return:
"""
request = requests.put(
self.path,
headers={"Content-Type": "text/calendar; charset=utf-8"},
data=bytes(self.ics, 'utf-8'),
auth=(self.calendar.username, self.calendar.calendar_password),
timeout=10,
)
request.raise_for_status()
self.sent = datetime.now(tz=timezone.get_current_timezone())
def cancel(self):
"""
Sends a DELETE request to the CalDAV server to cancel the event.
:return:
"""
try:
request = requests.delete(
self.path,
headers={"Content-Type": "text/calendar; charset=utf-8"},
auth=(self.calendar.username, self.calendar.calendar_password),
timeout=10,
)
request.raise_for_status()
except requests.HTTPError as e:
raise HttpError(e.response.status_code, str(e))
self.cancelled = datetime.now(tz=timezone.get_current_timezone())
self.save()
def create_ics(self) -> str:
"""
Create ics string
:return:
"""
c = ICS_Calendar()
e = ICS_Event()
e.uid = self.uuid.__str__()
e.name = self.name
e.begin = self.start
e.end = self.end
c.events.add(e)
return c.serialize()
@property
def uuid(self) -> UUID:
return shortuuid.decode(self.id.__str__())
def __str__(self):
string = f"{self.id} - {self.name} - ({self.start:%Y-%m-%d %H:%M} - {self.end:%Y-%m-%d %H:%M})"
return string if not self.cancelled else f"{string} - CANCELLED"
@app.admin(readonly_fields = ('key',))
class APIKey(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(app.settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='api_keys')
key = models.CharField(max_length=80, unique=True, editable=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@classmethod
def generate_key(cls):
return secrets.token_hex(40)
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super().save(*args, **kwargs)
def authenticate(self, request, api_key):
if api_key == self.key:
return api_key
def __str__(self):
return f"{self.user.username}: {self.key[:4]:*<76}"
class AuthBearer(HttpBearer):
def authenticate(self, request, token):
return APIKey.objects.filter(key=token).first()
class EventSchemaIn(ModelSchema):
class Meta:
model = Event
fields = ["name", "start", "end"]
class EventSchemaOut(ModelSchema):
class Meta:
model = Event
fields = ["id"]
# Initialising a separate ninja API instead of using nanodjango's app.ninja
# instance allows us to access the ninja.security classes defined in the ninja
# package.
api = NinjaAPI(auth=[AuthBearer(), django_auth])
def get_user(request) -> app.settings.AUTH_USER_MODEL:
"""
Get the user either from the request or from the API key.
:param request:
:return:
"""
return request.user if not request.user.is_anonymous \
else APIKey.objects.get(key=request.auth.key).user
def get_markdown():
"""
Get the markdown content from the index.md file.
:return:
"""
with open(BASE_DIR / "index.md") as f:
md = markdown.Markdown(extensions=["fenced_code"])
return md.convert(f.read())
@api.get("/info")
def info(request):
if request.user.is_anonymous:
user = APIKey.objects.get(key=request.auth.key).user
else:
user = request.user
return {"user": str(user),
"rooms": [room.name for room in user.rooms.all()]}
@api.post("/{calendar}/event", response={201: EventSchemaOut})
def create_event(request, calendar: str, event: EventSchemaIn):
user = get_user(request)
cal = get_object_or_404(Calendar, name=calendar)
if user not in cal.users.all():
raise HttpError(401,
f"User not authorised to create event in calendar '{cal.name}'")
event = Event.objects.create(calendar=cal, **event.dict())
return 201, event
@api.delete("/{calendar}/event/{event_id}", response={204: None})
def delete_event(request, calendar: str, event_id: str):
user = get_user(request)
cal = get_object_or_404(Calendar, name=calendar)
if user not in cal.users.all():
raise HttpError(401,
f"User not authorised to delete event in calendar '{cal.name}'")
event = get_object_or_404(Event, id=event_id)
event.cancel()
return 204, None
app.route("api/", include=api.urls)
@app.route("/")
def home(request):
return render(request, "index.html", {
"content": get_markdown(),
})

View File

@ -0,0 +1,90 @@
# Generated by Django 5.1.4 on 2025-01-05 20:44
import django.core.validators
import django.db.models.deletion
import shortuuid.django_fields
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="APIKey",
fields=[
("id", models.AutoField(primary_key=True, serialize=False)),
("key", models.CharField(editable=False, max_length=80, unique=True)),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="api_keys",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Calendar",
fields=[
("id", models.AutoField(primary_key=True, serialize=False)),
("name", models.CharField(editable=False, max_length=100)),
(
"url",
models.URLField(validators=[django.core.validators.URLValidator]),
),
("calendar_password", models.CharField(max_length=29)),
(
"users",
models.ManyToManyField(
related_name="calendars", to=settings.AUTH_USER_MODEL
),
),
],
),
migrations.CreateModel(
name="Event",
fields=[
(
"id",
shortuuid.django_fields.ShortUUIDField(
alphabet=None,
editable=False,
length=22,
max_length=22,
prefix="",
primary_key=True,
serialize=False,
unique=True,
),
),
("name", models.CharField(max_length=100)),
("path", models.CharField(editable=False, max_length=200)),
("start", models.DateTimeField()),
("end", models.DateTimeField()),
("ics", models.TextField(blank=True)),
("sent", models.DateTimeField(blank=True, editable=False, null=True)),
(
"cancelled",
models.DateTimeField(blank=True, editable=False, null=True),
),
(
"calendar",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="events",
to="booking.calendar",
),
),
],
),
]

View File

4
src/static/style.css Normal file
View File

@ -0,0 +1,4 @@
.container {
width: 90%;
margin: 3em auto;
}

14
src/templates/index.html Normal file
View File

@ -0,0 +1,14 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Room Booking</title>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
<div class="container">
{{ content | safe }}
</div>
</body>
</html>