diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8a923ae --- /dev/null +++ b/.env.example @@ -0,0 +1,47 @@ +# 🌐 Frontend +PUBLIC_SERVER_URL=http://server:8000 # PLEASE DON'T CHANGE :) - Should be the service name of the backend with port 8000, even if you change the port in the backend service. Only change if you are using a custom more complex setup. +ORIGIN=http://localhost:8015 +BODY_SIZE_LIMIT=Infinity +FRONTEND_PORT=8015 + +# 🐘 PostgreSQL Database +PGHOST=db +POSTGRES_DB=database +POSTGRES_USER=adventure +POSTGRES_PASSWORD=changeme123 + +# 🔒 Django Backend +SECRET_KEY=changeme123 +DJANGO_ADMIN_USERNAME=admin +DJANGO_ADMIN_PASSWORD=admin +DJANGO_ADMIN_EMAIL=admin@example.com +PUBLIC_URL=http://localhost:8016 # Match the outward port, used for the creation of image urls +CSRF_TRUSTED_ORIGINS=http://localhost:8016,http://localhost:8015 +DEBUG=False +FRONTEND_URL=http://localhost:8015 # Used for email generation. This should be the url of the frontend +BACKEND_PORT=8016 + +# Optional: use Google Maps integration +# https://adventurelog.app/docs/configuration/google_maps_integration.html +# GOOGLE_MAPS_API_KEY=your_google_maps_api_key + +# Optional: disable registration +# https://adventurelog.app/docs/configuration/disable_registration.html +DISABLE_REGISTRATION=False +# DISABLE_REGISTRATION_MESSAGE=Registration is disabled for this instance of AdventureLog. + +# Optional: Use email +# https://adventurelog.app/docs/configuration/email.html +# EMAIL_BACKEND=email +# EMAIL_HOST=smtp.gmail.com +# EMAIL_USE_TLS=True +# EMAIL_PORT=587 +# EMAIL_USE_SSL=False +# EMAIL_HOST_USER=user +# EMAIL_HOST_PASSWORD=password +# DEFAULT_FROM_EMAIL=user@example.com + +# Optional: Use Umami for analytics +# https://adventurelog.app/docs/configuration/analytics.html +# PUBLIC_UMAMI_SRC=https://cloud.umami.is/script.js # If you are using the hosted version of Umami +# PUBLIC_UMAMI_WEBSITE_ID= \ No newline at end of file diff --git a/.github/.docker-compose-database.yml b/.github/.docker-compose-database.yml new file mode 100644 index 0000000..aa187bd --- /dev/null +++ b/.github/.docker-compose-database.yml @@ -0,0 +1,16 @@ +services: + db: + image: postgis/postgis:15-3.3 + container_name: adventurelog-db + restart: unless-stopped + ports: + - "127.0.0.1:5432:5432" + environment: + POSTGRES_DB: database + POSTGRES_USER: adventure + POSTGRES_PASSWORD: changeme123 + volumes: + - postgres_data:/var/lib/postgresql/data/ + +volumes: + postgres_data: diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..ca0f2f6 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @seanmorley15 \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..80c427d --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: seanmorley15 +buy_me_a_coffee: seanmorley15 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dac7165 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Detailed bug reports help me diagnose and fix bugs quicker! Thanks! +title: "[BUG]" +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Docker Compose** +If the issue is related to deployment and docker, please post an **obfuscated** (remove secrets and confidential information) version of your compose file. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/deployment-issue.md b/.github/ISSUE_TEMPLATE/deployment-issue.md new file mode 100644 index 0000000..fcc8228 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/deployment-issue.md @@ -0,0 +1,15 @@ +--- +name: Deployment Issue +about: Request help deploying AdventureLog on your machine. The more details, the + better I can help! +title: "[DEPLOYMENT]" +labels: deployment +assignees: '' + +--- + +## Explain your issue + +## Provide an **obfuscated** `docker-compose.yml` + +## Provide any necessary logs from the containers and browser diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..696e895 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for AdventureLog +title: "[REQUEST]" +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/backend-beta.yml b/.github/workflows/backend-beta.yml new file mode 100644 index 0000000..a02bbaf --- /dev/null +++ b/.github/workflows/backend-beta.yml @@ -0,0 +1,46 @@ +name: Upload beta backend image to GHCR and Docker Hub + +on: + push: + branches: + - development + paths: + - "backend/**" + +env: + IMAGE_NAME: "adventurelog-backend" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./backend diff --git a/.github/workflows/backend-latest.yml b/.github/workflows/backend-latest.yml new file mode 100644 index 0000000..5351d9d --- /dev/null +++ b/.github/workflows/backend-latest.yml @@ -0,0 +1,46 @@ +name: Upload latest backend image to GHCR and Docker Hub + +on: + push: + branches: + - main + paths: + - "backend/**" + +env: + IMAGE_NAME: "adventurelog-backend" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: '${{ github.repository_owner }}' + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:latest -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:latest ./backend diff --git a/.github/workflows/backend-release.yml b/.github/workflows/backend-release.yml new file mode 100644 index 0000000..696f8b5 --- /dev/null +++ b/.github/workflows/backend-release.yml @@ -0,0 +1,43 @@ +name: Upload the tagged release backend image to GHCR and Docker Hub + +on: + release: + types: [released] + +env: + IMAGE_NAME: "adventurelog-backend" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:${{ github.event.release.tag_name }} -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:${{ github.event.release.tag_name }} ./backend diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml new file mode 100644 index 0000000..0ce9d7c --- /dev/null +++ b/.github/workflows/backend-test.yml @@ -0,0 +1,64 @@ +name: Test Backend + +permissions: + contents: read + +on: + pull_request: + paths: + - 'backend/server/**' + - '.github/workflows/backend-test.yml' + push: + paths: + - 'backend/server/**' + - '.github/workflows/backend-test.yml' + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: set up python 3.12 + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: install dependencies + run: | + sudo apt update -q + sudo apt install -y -q \ + python3-gdal + + - name: start database + run: | + docker compose -f .github/.docker-compose-database.yml up -d + + - name: install python libreries + working-directory: backend/server + run: | + pip install -r requirements.txt + + - name: run server + working-directory: backend/server + env: + PGHOST: "127.0.0.1" + PGDATABASE: "database" + PGUSER: "adventure" + PGPASSWORD: "changeme123" + SECRET_KEY: "changeme123" + DJANGO_ADMIN_USERNAME: "admin" + DJANGO_ADMIN_PASSWORD: "admin" + DJANGO_ADMIN_EMAIL: "admin@example.com" + PUBLIC_URL: "http://localhost:8000" + CSRF_TRUSTED_ORIGINS: "http://localhost:5173,http://localhost:8000" + DEBUG: "True" + FRONTEND_URL: "http://localhost:5173" + run: | + python manage.py migrate + python manage.py runserver & + + - name: wait for backend to boot + run: > + curl -fisS --retry 60 --retry-delay 1 --retry-all-errors + http://localhost:8000/ diff --git a/.github/workflows/cdn-beta.yml b/.github/workflows/cdn-beta.yml new file mode 100644 index 0000000..d5c2c85 --- /dev/null +++ b/.github/workflows/cdn-beta.yml @@ -0,0 +1,46 @@ +name: Upload beta CDN image to GHCR and Docker Hub + +on: + push: + branches: + - development + paths: + - "cdn/**" + +env: + IMAGE_NAME: "adventurelog-cdn" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./cdn diff --git a/.github/workflows/cdn-latest.yml b/.github/workflows/cdn-latest.yml new file mode 100644 index 0000000..376ede9 --- /dev/null +++ b/.github/workflows/cdn-latest.yml @@ -0,0 +1,46 @@ +name: Upload latest CDN image to GHCR and Docker Hub + +on: + push: + branches: + - main + paths: + - "cdn/**" + +env: + IMAGE_NAME: "adventurelog-cdn" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:latest -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:latest ./cdn diff --git a/.github/workflows/cdn-release.yml b/.github/workflows/cdn-release.yml new file mode 100644 index 0000000..2bba9af --- /dev/null +++ b/.github/workflows/cdn-release.yml @@ -0,0 +1,43 @@ +name: Upload the tagged release CDN image to GHCR and Docker Hub + +on: + release: + types: [released] + +env: + IMAGE_NAME: "adventurelog-cdn" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:${{ github.event.release.tag_name }} -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:${{ github.event.release.tag_name }} ./cdn diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml deleted file mode 100644 index e890bfc..0000000 --- a/.github/workflows/docker-image.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Upload Docker image to GHCR - -on: - push: - branches: - - main - paths: - - "backend/**" - -env: - IMAGE_NAME: "adventurelog-backend" - -jobs: - upload: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - - name: Login to GitHub Container Registry - uses: docker/login-action@v1 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.ACCESS_TOKEN }} - - - name: Build Docker image - run: docker build -t $IMAGE_NAME:latest ./backend - - - name: Tag Docker image - run: docker tag $IMAGE_NAME:latest ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME:latest - - - name: Push Docker image to GHCR - run: docker push ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME:latest diff --git a/.github/workflows/frontend-beta.yml b/.github/workflows/frontend-beta.yml new file mode 100644 index 0000000..29597ae --- /dev/null +++ b/.github/workflows/frontend-beta.yml @@ -0,0 +1,46 @@ +name: Upload beta frontend image to GHCR and Docker Hub + +on: + push: + branches: + - development + paths: + - "frontend/**" + +env: + IMAGE_NAME: "adventurelog-frontend" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:beta -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:beta ./frontend diff --git a/.github/workflows/frontend-latest.yml b/.github/workflows/frontend-latest.yml index a0a7602..a74ae2f 100644 --- a/.github/workflows/frontend-latest.yml +++ b/.github/workflows/frontend-latest.yml @@ -1,11 +1,11 @@ -name: Upload Docker image to GHCR +name: Upload latest frontend image to GHCR and Docker Hub on: push: branches: - main paths: - - 'frontend/**' + - "frontend/**" env: IMAGE_NAME: "adventurelog-frontend" @@ -24,11 +24,23 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.ACCESS_TOKEN }} - - name: Build Docker image - run: docker build -t $IMAGE_NAME:latest ./frontend + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: '${{ github.repository_owner }}' - - name: Tag Docker image - run: docker tag $IMAGE_NAME:latest ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME:latest - - - name: Push Docker image to GHCR - run: docker push ghcr.io/${{ github.repository_owner }}/$IMAGE_NAME:latest + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:latest -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:latest ./frontend diff --git a/.github/workflows/frontend-release.yml b/.github/workflows/frontend-release.yml new file mode 100644 index 0000000..bb7fc6b --- /dev/null +++ b/.github/workflows/frontend-release.yml @@ -0,0 +1,43 @@ +name: Upload tagged release frontend image to GHCR and Docker Hub + +on: + release: + types: [released] + +env: + IMAGE_NAME: "adventurelog-frontend" + +jobs: + upload: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Login to GitHub Container Registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.ACCESS_TOKEN }} + + - name: Login to Docker Hub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: set lower case owner name + run: | + echo "REPO_OWNER=${OWNER,,}" >>${GITHUB_ENV} + env: + OWNER: "${{ github.repository_owner }}" + + - name: Build Docker images + run: docker buildx build --platform linux/amd64,linux/arm64 --push -t ghcr.io/$REPO_OWNER/$IMAGE_NAME:${{ github.event.release.tag_name }} -t ${{ secrets.DOCKERHUB_USERNAME }}/$IMAGE_NAME:${{ github.event.release.tag_name }} ./frontend diff --git a/.github/workflows/frontend-test.yml b/.github/workflows/frontend-test.yml new file mode 100644 index 0000000..73d9b24 --- /dev/null +++ b/.github/workflows/frontend-test.yml @@ -0,0 +1,32 @@ +name: Test Frontend + +permissions: + contents: read + +on: + pull_request: + paths: + - "frontend/**" + - ".github/workflows/frontend-test.yml" + push: + paths: + - "frontend/**" + - ".github/workflows/frontend-test.yml" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: install dependencies + working-directory: frontend + run: npm i + + - name: build frontend + working-directory: frontend + run: npm run build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..090b681 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +# Ignore everything in the .venv folder +.venv/ +.vscode/settings.json +.pnpm-store/ +.env diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..8777355 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "lokalise.i18n-ally", + "svelte.svelte-vscode" + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..80fe952 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,40 @@ +{ + "git.ignoreLimitWarning": true, + "i18n-ally.localesPaths": [ + "frontend/src/locales", + "backend/server/backend/lib/python3.12/site-packages/allauth/locale", + "backend/server/backend/lib/python3.12/site-packages/dj_rest_auth/locale", + "backend/server/backend/lib/python3.12/site-packages/rest_framework/locale", + "backend/server/backend/lib/python3.12/site-packages/rest_framework_simplejwt/locale", + "backend/server/backend/lib/python3.12/site-packages/django/conf/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/messages", + "backend/server/backend/lib/python3.12/site-packages/allauth/templates/account/messages", + "backend/server/backend/lib/python3.12/site-packages/allauth/templates/mfa/messages", + "backend/server/backend/lib/python3.12/site-packages/allauth/templates/socialaccount/messages", + "backend/server/backend/lib/python3.12/site-packages/allauth/templates/usersessions/messages", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/admindocs/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/auth/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/admin/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/contenttypes/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/flatpages/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/humanize/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/gis/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/redirects/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/postgres/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/sessions/locale", + "backend/server/backend/lib/python3.12/site-packages/django/contrib/sites/locale", + "backend/server/backend/lib/python3.12/site-packages/rest_framework/templates/rest_framework/docs/langs" + ], + "i18n-ally.keystyle": "nested", + "i18n-ally.keysInUse": [ + "navbar.themes.dim", + "navbar.themes.northernLights", + "navbar.themes.aqua", + "navbar.themes.aestheticDark", + "navbar.themes.aestheticLight", + "navbar.themes.forest", + "navbar.themes.night", + "navbar.themes.dark", + "navbar.themes.light" + ] +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c980b88..7b49b3d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,91 +1,50 @@ # Contributing to AdventureLog -When contributing to this repository, please first discuss the change you wish to make via issue, -email, or any other method with the owners of this repository before making a change. - -Please note we have a code of conduct, please follow it in all your interactions with the project. +We’re excited to have you contribute to AdventureLog! To ensure that this community remains welcoming and productive for all users and developers, please follow this simple Code of Conduct. ## Pull Request Process -1. Please make sure you create an issue first for your change so you can link any pull requests to this issue. There should be a clear relationship between pull requests and issues. -2. Update the README.md with details of changes to the interface, this includes new environment - variables, exposed ports, useful file locations and container parameters. -3. Increase the version numbers in any examples files and the README.md to the new version that this - Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). -4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you - do not have permission to do that, you may request the second reviewer to merge it for you. +1. **Open an Issue First**: Discuss any changes or features you plan to implement by opening an issue. This helps to clarify your idea and ensures there’s a shared understanding. +2. **Document Changes**: If your changes impact the user interface, add new environment variables, or introduce new container configurations, make sure to update the documentation accordingly. The documentation is located in the `documentation` folder. +3. **Pull Request**: Submit a pull request with your changes. Make sure to reference the issue you opened in the description. ## Code of Conduct ### Our Pledge -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. +At AdventureLog, we are committed to creating a community that fosters adventure, exploration, and innovation. We encourage diverse participation and strive to maintain a space where everyone feels welcome to contribute, regardless of their background or experience level. We ask that you contribute with respect and kindness, making sure to prioritize collaboration and mutual growth. ### Our Standards -Examples of behavior that contributes to creating a positive environment -include: +In order to maintain a positive environment, we encourage the following behaviors: -- Using welcoming and inclusive language -- Being respectful of differing viewpoints and experiences -- Gracefully accepting constructive criticism -- Focusing on what is best for the community -- Showing empathy towards other community members +- **Inclusivity**: Use welcoming and inclusive language that fosters collaboration across all perspectives and experiences. +- **Respect**: Respect differing opinions and engage with empathy, understanding that each person’s perspective is valuable. +- **Constructive Feedback**: Offer feedback that helps improve the project and allows contributors to grow from it. +- **Adventure Spirit**: Bring the same sense of curiosity, discovery, and positivity that drives AdventureLog into all interactions with the community. -Examples of unacceptable behavior by participants include: +Examples of unacceptable behavior include: -- The use of sexualized language or imagery and unwelcome sexual attention or - advances -- Trolling, insulting/derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or electronic - address, without explicit permission -- Other conduct which could reasonably be considered inappropriate in a - professional setting +- Personal attacks, trolling, or any form of harassment. +- Insensitive or discriminatory language, including sexualized comments or imagery. +- Spamming or misusing project spaces for personal gain. +- Publishing or using others’ private information without permission. +- Anything else that could be seen as disrespectful or unprofessional in a collaborative environment. ### Our Responsibilities -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. +As maintainers of AdventureLog, we are committed to enforcing this Code of Conduct and taking corrective action when necessary. This may involve moderating comments, pulling code, or banning users who engage in harmful behaviors. -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. +We strive to foster a community that balances open collaboration with respect for all contributors. ### Scope -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. +This Code of Conduct applies in all spaces related to AdventureLog. This includes our GitHub repository, discussions, documentation, social media accounts, and events—both online and in person. ### Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at [INSERT EMAIL ADDRESS]. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. +If you experience or witness unacceptable behavior, please report it to the project team at `contact@adventurelog.app`. All reports will be confidential and handled swiftly. The maintainers will investigate the issue and take appropriate action as needed. ### Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ +This Code of Conduct is inspired by the [Contributor Covenant](http://contributor-covenant.org), version 1.4, and adapted to fit the unique spirit of AdventureLog. diff --git a/LICENSE b/LICENSE index e72bfdd..792a64f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,190 +1,207 @@ + AdventureLog: Self-hostable travel tracker and trip planner. + Copyright (C) 2023-2025 Sean Morley + Contact: contact@seanmorley.com + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. Preamble - The GNU General Public License is a free, copyleft license for +The GNU General Public License is a free, copyleft license for software and other kinds of works. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the +software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to +any other work released this way by its authors. You can apply it to your programs, too. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. - For example, if you distribute copies of such a program, whether +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they know their rights. - Developers that use the GNU GPL protect your rights with two steps: +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. - Some devices are designed to deny users access to install or run +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we +use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we +products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. - Finally, every program is threatened constantly by software patents. +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that +make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. - The precise terms and conditions for copying, distribution and +The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS - 0. Definitions. +0. Definitions. - "This License" refers to version 3 of the GNU General Public License. +"This License" refers to version 3 of the GNU General Public License. - "Copyright" also means copyright-like laws that apply to other kinds of +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. - To "modify" a work means to copy from or adapt all or part of the work +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the +exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. - A "covered work" means either the unmodified Program or a work based +A "covered work" means either the unmodified Program or a work based on the Program. - To "propagate" a work means to do anything with it that, without +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, +computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - An interactive user interface displays "Appropriate Legal Notices" +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If +work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - 1. Source Code. +1. Source Code. - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source form of a work. - A "Standard Interface" means an interface that either is an official +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - The "System Libraries" of an executable work include anything, other +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A +implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - The "Corresponding Source" for a work in object code form means all +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's +control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source +which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - The Corresponding Source need not include anything that users +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - The Corresponding Source for a work in source code form is that +The Corresponding Source for a work in source code form is that same work. - 2. Basic Permissions. +2. Basic Permissions. - All rights granted under this License are granted for the term of +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your +content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - You may make, run and propagate covered works that you do not +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose +in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works +not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. +3. Protecting Users' Legal Rights From Anti-Circumvention Law. - No covered work shall be deemed part of an effective technological +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - When you convey a covered work, you waive any legal power to forbid +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or @@ -192,9 +209,9 @@ modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - 4. Conveying Verbatim Copies. +4. Conveying Verbatim Copies. - You may convey verbatim copies of the Program's source code as you +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any @@ -202,12 +219,12 @@ non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - You may charge any price or no price for each copy that you convey, +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - 5. Conveying Modified Source Versions. +5. Conveying Modified Source Versions. - You may convey a work based on the Program, or the modifications to +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: @@ -232,19 +249,19 @@ terms of section 4, provided that you also meet all of these conditions: interfaces that do not display Appropriate Legal Notices, your work need not make them do so. - A compilation of a covered work with other separate and independent +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work +beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - 6. Conveying Non-Source Forms. +6. Conveying Non-Source Forms. - You may convey a covered work in object code form under the terms +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: @@ -290,75 +307,75 @@ in one of these ways: Source of the work are being offered to the general public at no charge under subsection 6d. - A separable portion of the object code, whose source code is excluded +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - A "User Product" is either (1) a "consumer product", which means any +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product +actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - "Installation Information" for a User Product means any methods, +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must +a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - If you convey an object code work under this section in, or with, or +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply +by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - The requirement to provide Installation Information does not include a +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a +the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - Corresponding Source conveyed, and Installation Information provided, +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - 7. Additional Terms. +7. Additional Terms. - "Additional permissions" are terms that supplement the terms of this +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions +that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - When you convey a copy of a covered work, you may at your option +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - Notwithstanding any other provision of this License, for material you +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: @@ -385,74 +402,74 @@ that material) supplement the terms of this License with terms: any liability that these contractual assumptions directly impose on those licensors and authors. - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains +restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - If you add terms to a covered work in accord with this section, you +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - Additional terms, permissive or non-permissive, may be stated in the +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - 8. Termination. +8. Termination. - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - However, if you cease all violation of this License, then your +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - Moreover, your license from a particular copyright holder is +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - Termination of your rights under this section does not terminate the +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently +this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - 9. Acceptance Not Required for Having Copies. +9. Acceptance Not Required for Having Copies. - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, +to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - 10. Automatic Licensing of Downstream Recipients. +10. Automatic Licensing of Downstream Recipients. - Each time you convey a covered work, the recipient automatically +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible +propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - An "entity transaction" is a transaction transferring control of an +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered +organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could @@ -460,43 +477,43 @@ give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - 11. Patents. +11. Patents. - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". - A contributor's "essential patent claims" are all patent claims +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For +consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - Each contributor grants you a non-exclusive, worldwide, royalty-free +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - In the following three paragraphs, a "patent license" is any express +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a +sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - If you convey a covered work, knowingly relying on a patent license, +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, @@ -504,13 +521,13 @@ then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - If, pursuant to or in connection with a single transaction or +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify @@ -518,10 +535,10 @@ or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - A patent license is "discriminatory" if it does not include within +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered +specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying @@ -533,73 +550,73 @@ for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - Nothing in this License shall be construed as excluding or limiting +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - 12. No Surrender of Others' Freedom. +12. No Surrender of Others' Freedom. - If conditions are imposed on you (whether by court order, agreement or +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a +excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - 13. Use with the GNU Affero General Public License. +13. Use with the GNU Affero General Public License. - Notwithstanding any other provision of this License, you have +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this +combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. - 14. Revised Versions of this License. +14. Revised Versions of this License. - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - Each version is given a distinguishing version number. If the +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the +Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. - If the Program specifies that a proxy can decide which future +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - 15. Disclaimer of Warranty. +15. Disclaimer of Warranty. - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - 16. Limitation of Liability. +16. Limitation of Liability. - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE @@ -609,9 +626,9 @@ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - 17. Interpretation of Sections 15 and 16. +17. Interpretation of Sections 15 and 16. - If the disclaimer of warranty and limitation of liability provided +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the @@ -619,56 +636,3 @@ Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file diff --git a/README.md b/README.md index a4c61ed..73aa31b 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,150 @@ -# AdventureLog: Embark, Explore, Remember. 🌍 +
-_**⚠️ AdventureLog is in early development and is not recommended for production use until version 1.0!**_ + logo +

AdventureLog

+ +

+ The ultimate travel companion for the modern-day explorer. +

+ +

+ View Demo + · + Documentation + · + Discord + · + Support 💖 +

+
-### _"Never forget an adventure with AdventureLog - Your ultimate travel companion!"_ +
---- + -# Installation +# Table of Contents -# Docker 🐋 +- [About the Project](#-about-the-project) + - [Screenshots](#-screenshots) + - [Tech Stack](#-tech-stack) + - [Features](#-features) +- [Roadmap](#-roadmap) +- [Contributing](#-contributing) +- [License](#-license) +- [Contact](#-contact) +- [Acknowledgements](#-acknowledgements) -Docker is the preferred way to run AdventureLog on your local machine. It is a lightweight containerization technology that allows you to run applications in isolated environments called containers. -**Note**: This guide mainly focuses on installation with a linux based host machine, but the steps are similar for other operating systems. + -## Prerequisites +## ⭐ About the Project -- Docker installed on your machine/server. You can learn how to download it [here](https://docs.docker.com/engine/install/). +Starting from a simple idea of tracking travel locations (called adventures), AdventureLog has grown into a full-fledged travel companion. With AdventureLog, you can log your adventures, keep track of where you've been on the world map, plan your next trip collaboratively, and share your experiences with friends and family. -## Getting Started +AdventureLog was created to solve a problem: the lack of a modern, open-source, user-friendly travel companion. Many existing travel apps are either too complex, too expensive, or too closed-off to be useful for the average traveler. AdventureLog aims to be the opposite: simple, beautiful, and open to everyone. -Get the `docker-compose.yml` file from the AdventureLog repository. You can download it from [here](https://github.com/seanmorley15/AdventureLog/blob/main/docker-compose.yml) or run this command to download it directly to your machine: + -```bash -wget https://raw.githubusercontent.com/seanmorley15/AdventureLog/main/docker-compose.yml -``` +### 📷 Screenshots -## Configuration +
+ Adventures +

Displays the adventures you have visited and the ones you plan to embark on. You can also filter and sort the adventures.

+ Adventure Details +

Shows specific details about an adventure, including the name, date, location, description, and rating.

+ Edit Modal + Adventure Details +

View all of your adventures on a map, with the ability to filter by visit status and add new ones by click on the map

+ Dashboard +

Displays a summary of your adventures, including your world travel stats.

+ Itinerary +

Plan your adventures and travel itinerary with a list of activities and a map view. View your trip in a variety of ways, including an itinerary list, a map view, and a calendar view.

+ Countries +

Lists all the countries you have visited and plan to visit, with the ability to filter by visit status.

+ Regions +

Displays the regions for a specific country, includes a map view to visually select regions.

+
-Here is a summary of the configuration options available in the `docker-compose.yml` file: + - +### 🚀 Tech Stack -### Frontend Container (web) +
+ Client + +
-| Name | Required | Description | Default Value | -| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| `PUBLIC_SERVER_URL` | Yes | What the frontend SSR server uses to connect to the backend. | http://server:8000 | -| `ORIGIN` | Sometimes | Not needed if using HTTPS. If not, set it to the domain of what you will acess the app from. | http://localhost:8080 | -| `BODY_SIZE_LIMIT` | Yes | Used to set the maximum upload size to the server. Should be changed to prevent someone from uploading too much! Custom values must be set in **kiliobytes**. | Infinity | +
+ Server + +
+ -### Backend Container (server) +### 🎯 Features -| Name | Required | Description | Default Value | -| ----------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -------------------- | -| `PGHOST` | Yes | Databse host. | db | -| `PGDATABASE` | Yes | Database. | database | -| `PGUSER` | Yes | Database user. | adventure | -| `PGPASSWORD` | Yes | Database password. | changeme123 | -| `DJANGO_ADMIN_USERNAME` | Yes | Default username. | admin | -| `DJANGO_ADMIN_PASSWORD` | Yes | Default password, change after inital login. | admin | -| `DJANGO_ADMIN_EMAIL` | Yes | Default user's email. | admin@example.com | -| `PUBLIC_URL` | Yes | This is the publically accessible url to the **nginx** container. You should be able to acess nginx from this url where you access your app. | http://127.0.0.1:81 | -| `CSRF_TRUSTED_ORIGINS` | Yes | Need to be changed to the orgins where you use your backend server and frontend. These values are comma seperated. | Needs to be changed. | +- **Track Your Adventures** 🌍: Log your adventures and keep track of where you've been on the world map. + - Adventures can store a variety of information, including the location, date, and description. + - Adventures can be sorted into custom categories for easy organization. + - Adventures can be marked as private or public, allowing you to share your adventures with friends and family. + - Keep track of the countries and regions you've visited with the world travel book. +- **Plan Your Next Trip** 📃: Take the guesswork out of planning your next adventure with an easy-to-use itinerary planner. + - Itineraries can be created for any number of days and can include multiple destinations. + - Itineraries include many planning features like flight information, notes, checklists, and links to external resources. + - Itineraries can be shared with friends and family for collaborative planning. +- **Share Your Experiences** 📸: Share your adventures with friends and family and collaborate on trips together. + - Adventures and itineraries can be shared via a public link or directly with other AdventureLog users. + - Collaborators can view and edit shared itineraries (collections), making planning a breeze. -### Proxy Container (nginx) Configuration + -In order to use media files in a production environment, you need to configure the `nginx` container to serve the media files. The container is already in the docker compose file but you need to do a few things to make it work. +## 🧭 Roadmap -1. Create a directory called `proxy` in the same directory as the `docker-compose.yml` file. -2. Create a file called `nginx.conf` in the `proxy` directory. -3. Add the following configuration to the `nginx.conf` file: +The AdventureLog Roadmap can be found [here](https://github.com/users/seanmorley15/projects/5) -```nginx -server { - listen 80; - server_name localhost; + - location /media/ { - alias /app/media/; - } -} -``` +## 👋 Contributing -## Running the Containers + + + -To start the containers, run the following command: +Contributions are always welcome! -```bash -docker compose up -d -``` +See `contributing.md` for ways to get started. -Enjoy AdventureLog! 🎉 + -# About AdventureLog +## 📃 License -AdventureLog is a Svelte Kit and Django application that utilizes a PostgreSQL database. Users can log the adventures they have experienced, as well as plan future ones. Key features include: +Distributed under the GNU General Public License v3.0. See `LICENSE` for more information. -- Logging past adventures with fields like name, date, location, description, and rating. -- Planning future adventures with similar fields. -- Tagging different activity types for better organization. -- Viewing countries, regions, and marking visited regions. + -AdventureLog aims to be your ultimate travel companion, helping you document your adventures and plan new ones effortlessly. +## 🤝 Contact -AdventureLog is licensed under the GNU General Public License v3.0. +Sean Morley - [website](https://seanmorley.com) - -## Roadmap 🛣️ +## 💎 Acknowledgements -- Improved mobile device support -- Password reset functionality -- Improved error handling -- Handling of adventure cards with variable width --> +- Logo Design by [nordtektiger](https://github.com/nordtektiger) +- WorldTravel Dataset [dr5hn/countries-states-cities-database](https://github.com/dr5hn/countries-states-cities-database) + +### Top Supporters 💖 + +- [Veymax](https://x.com/veymax) +- [nebriv](https://github.com/nebriv) +- [Victor Butler](https://x.com/victor_butler) diff --git a/backend/AUTHORS b/backend/AUTHORS deleted file mode 100644 index c5ba2ed..0000000 --- a/backend/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -http://github.com/iMerica/dj-rest-auth/contributors diff --git a/backend/Dockerfile b/backend/Dockerfile index a093cdf..b3f41b7 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,32 +1,60 @@ -# Dockerfile +# Use the official Python slim image as the base image +FROM python:3.13-slim -FROM python:3.10-slim - -LABEL Developers="Sean Morley" +# Metadata labels for the AdventureLog image +LABEL maintainer="Sean Morley" \ + version="v0.10.0" \ + description="AdventureLog — the ultimate self-hosted travel companion." \ + org.opencontainers.image.title="AdventureLog" \ + org.opencontainers.image.description="AdventureLog is a self-hosted travel companion that helps you plan, track, and share your adventures." \ + org.opencontainers.image.version="v0.10.0" \ + org.opencontainers.image.authors="Sean Morley" \ + org.opencontainers.image.url="https://raw.githubusercontent.com/seanmorley15/AdventureLog/refs/heads/main/brand/banner.png" \ + org.opencontainers.image.source="https://github.com/seanmorley15/AdventureLog" \ + org.opencontainers.image.vendor="Sean Morley" \ + org.opencontainers.image.created="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \ + org.opencontainers.image.licenses="GPL-3.0" # Set environment variables -ENV PYTHONDONTWRITEBYTECODE 1 -ENV PYTHONUNBUFFERED 1 +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 # Set the working directory WORKDIR /code -# Install system dependencies +# Install system dependencies (Nginx included) RUN apt-get update \ - && apt-get install -y git postgresql-client \ - && apt-get clean + && apt-get install -y git postgresql-client gdal-bin libgdal-dev nginx supervisor \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY ./server/requirements.txt /code/ -RUN pip install --upgrade pip -RUN pip install -r requirements.txt +RUN pip install --upgrade pip \ + && pip install -r requirements.txt + +# Create necessary directories +RUN mkdir -p /code/static /code/media +# RUN mkdir -p /code/staticfiles /code/media # Copy the Django project code into the Docker image COPY ./server /code/ -RUN python3 manage.py collectstatic --verbosity 2 +# Copy Nginx configuration +COPY ./nginx.conf /etc/nginx/nginx.conf + +# Copy Supervisor configuration +COPY ./supervisord.conf /etc/supervisor/conf.d/supervisord.conf + +# Collect static files +RUN python3 manage.py collectstatic --noinput --verbosity 2 # Set the entrypoint script COPY ./entrypoint.sh /code/entrypoint.sh RUN chmod +x /code/entrypoint.sh -ENTRYPOINT ["/code/entrypoint.sh"] \ No newline at end of file + +# Expose ports for NGINX and Gunicorn +EXPOSE 80 8000 + +# Command to start Supervisor (which starts Nginx and Gunicorn) +CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"] diff --git a/backend/LICENSE b/backend/LICENSE deleted file mode 100644 index 42a0292..0000000 --- a/backend/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 iMerica https://github.com/iMerica/ - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/backend/MANIFEST.in b/backend/MANIFEST.in deleted file mode 100644 index c2d4208..0000000 --- a/backend/MANIFEST.in +++ /dev/null @@ -1,5 +0,0 @@ -include AUTHORS -include LICENSE -include MANIFEST.in -include README.md -graft dj_rest_auth diff --git a/backend/README.md b/backend/README.md deleted file mode 100644 index 349b7be..0000000 --- a/backend/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# AdventureLog Django Backend -A demo of a possible AdventureLog 2.0 version using Django as the backend with a REST API. - -Based of django-rest-framework and dj-rest-auth. \ No newline at end of file diff --git a/backend/entrypoint.sh b/backend/entrypoint.sh index b72181b..1031cb1 100644 --- a/backend/entrypoint.sh +++ b/backend/entrypoint.sh @@ -1,10 +1,32 @@ #!/bin/bash # Function to check PostgreSQL availability -check_postgres() { - PGPASSWORD=$PGPASSWORD psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -c '\q' >/dev/null 2>&1 +# Helper to get the first non-empty environment variable +get_env() { + for var in "$@"; do + value="${!var}" + if [ -n "$value" ]; then + echo "$value" + return + fi + done } +check_postgres() { + local db_host + local db_user + local db_name + local db_pass + + db_host=$(get_env PGHOST) + db_user=$(get_env PGUSER POSTGRES_USER) + db_name=$(get_env PGDATABASE POSTGRES_DB) + db_pass=$(get_env PGPASSWORD POSTGRES_PASSWORD) + + PGPASSWORD="$db_pass" psql -h "$db_host" -U "$db_user" -d "$db_name" -c '\q' >/dev/null 2>&1 +} + + # Wait for PostgreSQL to become available until check_postgres; do >&2 echo "PostgreSQL is unavailable - sleeping" @@ -13,25 +35,57 @@ done >&2 echo "PostgreSQL is up - continuing..." +# run sql commands +# psql -h "$PGHOST" -U "$PGUSER" -d "$PGDATABASE" -f /app/backend/init-postgis.sql + # Apply Django migrations python manage.py migrate -# Check for default data -python manage.py worldtravel-seed - -# Create superuser if environment variables are set -if [ -n "$DJANGO_ADMIN_USERNAME" ] && [ -n "$DJANGO_ADMIN_PASSWORD" ]; then +# Create superuser if environment variables are set and there are no users present at all. +if [ -n "$DJANGO_ADMIN_USERNAME" ] && [ -n "$DJANGO_ADMIN_PASSWORD" ] && [ -n "$DJANGO_ADMIN_EMAIL" ]; then echo "Creating superuser..." python manage.py shell << EOF from django.contrib.auth import get_user_model +from allauth.account.models import EmailAddress + User = get_user_model() + +# Check if the user already exists if not User.objects.filter(username='$DJANGO_ADMIN_USERNAME').exists(): - User.objects.create_superuser('$DJANGO_ADMIN_USERNAME', '$DJANGO_ADMIN_EMAIL', '$DJANGO_ADMIN_PASSWORD') + # Create the superuser + superuser = User.objects.create_superuser( + username='$DJANGO_ADMIN_USERNAME', + email='$DJANGO_ADMIN_EMAIL', + password='$DJANGO_ADMIN_PASSWORD' + ) print("Superuser created successfully.") + + # Create the EmailAddress object for AllAuth + EmailAddress.objects.create( + user=superuser, + email='$DJANGO_ADMIN_EMAIL', + verified=True, + primary=True + ) + print("EmailAddress object created successfully for AllAuth.") else: print("Superuser already exists.") EOF fi -# Start Django server -python manage.py runserver 0.0.0.0:8000 + +# Sync the countries and world travel regions +# Sync the countries and world travel regions +python manage.py download-countries +if [ $? -eq 137 ]; then + >&2 echo "WARNING: The download-countries command was interrupted. This is likely due to lack of memory allocated to the container or the host. Please try again with more memory." + exit 1 +fi + +cat /code/adventurelog.txt + +# Start Gunicorn in foreground +exec gunicorn main.wsgi:application \ + --bind [::]:8000 \ + --workers 2 \ + --timeout 120 diff --git a/backend/nginx.conf b/backend/nginx.conf new file mode 100644 index 0000000..23dba44 --- /dev/null +++ b/backend/nginx.conf @@ -0,0 +1,42 @@ +worker_processes 1; +events { + worker_connections 1024; +} +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 65; + client_max_body_size 100M; + # The backend is running in the same container, so reference localhost + upstream django { + server 127.0.0.1:8000; # Use localhost to point to Gunicorn running internally + } + server { + listen 80; + server_name localhost; + location / { + proxy_pass http://django; # Forward to the upstream block + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + location /static/ { + alias /code/staticfiles/; # Serve static files directly + } + # Serve protected media files with X-Accel-Redirect + location /protectedMedia/ { + internal; # Only internal requests are allowed + alias /code/media/; # This should match Django MEDIA_ROOT + try_files $uri =404; # Return a 404 if the file doesn't exist + + # Security headers for all protected files + add_header Content-Security-Policy "default-src 'self'; script-src 'none'; object-src 'none'; base-uri 'none'" always; + add_header X-Content-Type-Options nosniff always; + add_header X-Frame-Options SAMEORIGIN always; + add_header X-XSS-Protection "1; mode=block" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + } + } +} \ No newline at end of file diff --git a/backend/server/.env.example b/backend/server/.env.example index ea63047..2c93208 100644 --- a/backend/server/.env.example +++ b/backend/server/.env.example @@ -7,4 +7,30 @@ SECRET_KEY='pleasechangethisbecauseifyoudontitwillbeverybadandyouwillgethackedin PUBLIC_URL='http://127.0.0.1:8000' -DEBUG=True \ No newline at end of file +DEBUG=True + +FRONTEND_URL='http://localhost:3000' + +EMAIL_BACKEND='console' + +# EMAIL_BACKEND='email' +# EMAIL_HOST='smtp.gmail.com' +# EMAIL_USE_TLS=False +# EMAIL_PORT=587 +# EMAIL_USE_SSL=True +# EMAIL_HOST_USER='user' +# EMAIL_HOST_PASSWORD='password' +# DEFAULT_FROM_EMAIL='user@example.com' + +# GOOGLE_MAPS_API_KEY='key' + + +# ------------------- # +# For Developers to start a Demo Database +# docker run --name adventurelog-development -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=admin -e POSTGRES_DB=adventurelog -p 5432:5432 -d postgis/postgis:15-3.3 + +# PGHOST='localhost' +# PGDATABASE='adventurelog' +# PGUSER='admin' +# PGPASSWORD='admin' +# ------------------- # \ No newline at end of file diff --git a/backend/server/demo/__init__.py b/backend/server/achievements/__init__.py similarity index 100% rename from backend/server/demo/__init__.py rename to backend/server/achievements/__init__.py diff --git a/backend/server/achievements/admin.py b/backend/server/achievements/admin.py new file mode 100644 index 0000000..af087ce --- /dev/null +++ b/backend/server/achievements/admin.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from allauth.account.decorators import secure_admin_login +from achievements.models import Achievement, UserAchievement + +admin.autodiscover() +admin.site.login = secure_admin_login(admin.site.login) + +admin.site.register(Achievement) +admin.site.register(UserAchievement) \ No newline at end of file diff --git a/backend/server/achievements/apps.py b/backend/server/achievements/apps.py new file mode 100644 index 0000000..2a635e2 --- /dev/null +++ b/backend/server/achievements/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class AchievementsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'achievements' diff --git a/documentation/docs/Usage/manage-docs-versions.md b/backend/server/achievements/management/__init__.py similarity index 100% rename from documentation/docs/Usage/manage-docs-versions.md rename to backend/server/achievements/management/__init__.py diff --git a/documentation/docs/Usage/translate-your-site.md b/backend/server/achievements/management/commands/__init__.py similarity index 100% rename from documentation/docs/Usage/translate-your-site.md rename to backend/server/achievements/management/commands/__init__.py diff --git a/backend/server/achievements/management/commands/achievement-seed.py b/backend/server/achievements/management/commands/achievement-seed.py new file mode 100644 index 0000000..7713e88 --- /dev/null +++ b/backend/server/achievements/management/commands/achievement-seed.py @@ -0,0 +1,66 @@ +import json +from django.core.management.base import BaseCommand +from achievements.models import Achievement + +US_STATE_CODES = [ + 'US-AL', 'US-AK', 'US-AZ', 'US-AR', 'US-CA', 'US-CO', 'US-CT', 'US-DE', + 'US-FL', 'US-GA', 'US-HI', 'US-ID', 'US-IL', 'US-IN', 'US-IA', 'US-KS', + 'US-KY', 'US-LA', 'US-ME', 'US-MD', 'US-MA', 'US-MI', 'US-MN', 'US-MS', + 'US-MO', 'US-MT', 'US-NE', 'US-NV', 'US-NH', 'US-NJ', 'US-NM', 'US-NY', + 'US-NC', 'US-ND', 'US-OH', 'US-OK', 'US-OR', 'US-PA', 'US-RI', 'US-SC', + 'US-SD', 'US-TN', 'US-TX', 'US-UT', 'US-VT', 'US-VA', 'US-WA', 'US-WV', + 'US-WI', 'US-WY' +] + +ACHIEVEMENTS = [ + { + "name": "First Adventure", + "key": "achievements.first_adventure", + "type": "adventure_count", + "description": "Log your first adventure!", + "condition": {"type": "adventure_count", "value": 1}, + }, + { + "name": "Explorer", + "key": "achievements.explorer", + "type": "adventure_count", + "description": "Log 10 adventures.", + "condition": {"type": "adventure_count", "value": 10}, + }, + { + "name": "Globetrotter", + "key": "achievements.globetrotter", + "type": "country_count", + "description": "Visit 5 different countries.", + "condition": {"type": "country_count", "value": 5}, + }, + { + "name": "American Dream", + "key": "achievements.american_dream", + "type": "country_count", + "description": "Visit all 50 states in the USA.", + "condition": {"type": "country_count", "items": US_STATE_CODES}, + } +] + + + + +class Command(BaseCommand): + help = "Seeds the database with predefined achievements" + + def handle(self, *args, **kwargs): + for achievement_data in ACHIEVEMENTS: + achievement, created = Achievement.objects.update_or_create( + name=achievement_data["name"], + defaults={ + "description": achievement_data["description"], + "condition": json.dumps(achievement_data["condition"]), + "type": achievement_data["type"], + "key": achievement_data["key"], + }, + ) + if created: + self.stdout.write(self.style.SUCCESS(f"✅ Created: {achievement.name}")) + else: + self.stdout.write(self.style.WARNING(f"🔄 Updated: {achievement.name}")) diff --git a/backend/server/achievements/models.py b/backend/server/achievements/models.py new file mode 100644 index 0000000..c23bb31 --- /dev/null +++ b/backend/server/achievements/models.py @@ -0,0 +1,34 @@ +import uuid +from django.db import models +from django.contrib.auth import get_user_model + +User = get_user_model() + +VALID_ACHIEVEMENT_TYPES = [ + "adventure_count", + "country_count", +] + +class Achievement(models.Model): + """Stores all possible achievements""" + name = models.CharField(max_length=255, unique=True) + key = models.CharField(max_length=255, unique=True, default='achievements.other') # Used for frontend lookups, e.g. "achievements.first_adventure" + type = models.CharField(max_length=255, choices=[(tag, tag) for tag in VALID_ACHIEVEMENT_TYPES], default='adventure_count') # adventure_count, country_count, etc. + description = models.TextField() + icon = models.ImageField(upload_to="achievements/", null=True, blank=True) + condition = models.JSONField() # Stores rules like {"type": "adventure_count", "value": 10} + + def __str__(self): + return self.name + +class UserAchievement(models.Model): + """Tracks which achievements a user has earned""" + user = models.ForeignKey(User, on_delete=models.CASCADE) + achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE) + earned_at = models.DateTimeField(auto_now_add=True) + + class Meta: + unique_together = ("user", "achievement") # Prevent duplicates + + def __str__(self): + return f"{self.user.username} - {self.achievement.name}" diff --git a/backend/server/achievements/tests.py b/backend/server/achievements/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/backend/server/achievements/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/backend/server/achievements/views.py b/backend/server/achievements/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/backend/server/achievements/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/backend/server/adventurelog.txt b/backend/server/adventurelog.txt new file mode 100644 index 0000000..229c771 --- /dev/null +++ b/backend/server/adventurelog.txt @@ -0,0 +1,7 @@ + █████╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗████████╗██╗ ██╗██████╗ ███████╗██╗ ██████╗ ██████╗ +██╔══██╗██╔══██╗██║ ██║██╔════╝████╗ ██║╚══██╔══╝██║ ██║██╔══██╗██╔════╝██║ ██╔═══██╗██╔════╝ +███████║██║ ██║██║ ██║█████╗ ██╔██╗ ██║ ██║ ██║ ██║██████╔╝█████╗ ██║ ██║ ██║██║ ███╗ +██╔══██║██║ ██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║ ██║ ██║ ██║██╔══██╗██╔══╝ ██║ ██║ ██║██║ ██║ +██║ ██║██████╔╝ ╚████╔╝ ███████╗██║ ╚████║ ██║ ╚██████╔╝██║ ██║███████╗███████╗╚██████╔╝╚██████╔╝ +╚═╝ ╚═╝╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ +“The world is full of wonderful things you haven't seen yet. Don't ever give up on the chance of seeing them.” - J.K. Rowling diff --git a/backend/server/adventures/admin.py b/backend/server/adventures/admin.py index 9291219..e23fa15 100644 --- a/backend/server/adventures/admin.py +++ b/backend/server/adventures/admin.py @@ -1,28 +1,53 @@ import os from django.contrib import admin from django.utils.html import mark_safe -from .models import Adventure, Collection -from worldtravel.models import Country, Region, VisitedRegion +from .models import Adventure, Checklist, ChecklistItem, Collection, Transportation, Note, AdventureImage, Visit, Category, Attachment, Lodging +from worldtravel.models import Country, Region, VisitedRegion, City, VisitedCity +from allauth.account.decorators import secure_admin_login + +admin.autodiscover() +admin.site.login = secure_admin_login(admin.site.login) + +@admin.action(description="Trigger geocoding") +def trigger_geocoding(modeladmin, request, queryset): + count = 0 + for adventure in queryset: + try: + adventure.save() # Triggers geocoding logic in your model + count += 1 + except Exception as e: + modeladmin.message_user(request, f"Error geocoding {adventure}: {e}", level='error') + modeladmin.message_user(request, f"Geocoding triggered for {count} adventures.", level='success') + class AdventureAdmin(admin.ModelAdmin): - list_display = ('name', 'type', 'user_id', 'date', 'is_public', 'image_display') - list_filter = ('type', 'user_id', 'is_public') + list_display = ('name', 'get_category', 'get_visit_count', 'user_id', 'is_public') + list_filter = ( 'user_id', 'is_public') + search_fields = ('name',) + readonly_fields = ('city', 'region', 'country') + actions = [trigger_geocoding] - def image_display(self, obj): - if obj.image: - public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/') - public_url = public_url.replace("'", "") - return mark_safe(f' bool: + try: + socket.gethostbyname(hostname) + return True + except socket.error: + return False + +def reverse_geocode(lat, lon, user): + if getattr(settings, 'GOOGLE_MAPS_API_KEY', None): + return reverse_geocode_google(lat, lon, user) + return reverse_geocode_osm(lat, lon, user) + +def reverse_geocode_osm(lat, lon, user): + url = f"https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat={lat}&lon={lon}" + headers = {'User-Agent': 'AdventureLog Server'} + connect_timeout = 1 + read_timeout = 5 + + if not is_host_resolvable("nominatim.openstreetmap.org"): + return {"error": "DNS resolution failed"} + + try: + response = requests.get(url, headers=headers, timeout=(connect_timeout, read_timeout)) + response.raise_for_status() + data = response.json() + return extractIsoCode(user, data) + except Exception: + return {"error": "An internal error occurred while processing the request"} + +def reverse_geocode_google(lat, lon, user): + api_key = settings.GOOGLE_MAPS_API_KEY + + # Updated to use the new Geocoding API endpoint (this one is still supported) + # The Geocoding API is separate from Places API and still uses the old format + url = "https://maps.googleapis.com/maps/api/geocode/json" + params = {"latlng": f"{lat},{lon}", "key": api_key} + + try: + response = requests.get(url, params=params) + response.raise_for_status() + data = response.json() + + if data.get("status") != "OK": + return {"error": "Geocoding failed"} + + # Convert Google schema to Nominatim-style for extractIsoCode + first_result = data.get("results", [])[0] + result_data = { + "name": first_result.get("formatted_address"), + "address": _parse_google_address_components(first_result.get("address_components", [])) + } + return extractIsoCode(user, result_data) + except Exception: + return {"error": "An internal error occurred while processing the request"} + +def _parse_google_address_components(components): + parsed = {} + country_code = None + state_code = None + + for comp in components: + types = comp.get("types", []) + long_name = comp.get("long_name") + short_name = comp.get("short_name") + + if "country" in types: + parsed["country"] = long_name + country_code = short_name + parsed["ISO3166-1"] = short_name + if "administrative_area_level_1" in types: + parsed["state"] = long_name + state_code = short_name + if "administrative_area_level_2" in types: + parsed["county"] = long_name + if "locality" in types: + parsed["city"] = long_name + if "sublocality" in types: + parsed["town"] = long_name + + # Build composite ISO 3166-2 code like US-ME + if country_code and state_code: + parsed["ISO3166-2-lvl1"] = f"{country_code}-{state_code}" + + return parsed \ No newline at end of file diff --git a/backend/server/adventures/managers.py b/backend/server/adventures/managers.py new file mode 100644 index 0000000..4a12194 --- /dev/null +++ b/backend/server/adventures/managers.py @@ -0,0 +1,17 @@ +from django.db import models +from django.db.models import Q + +class AdventureManager(models.Manager): + def retrieve_adventures(self, user, include_owned=False, include_shared=False, include_public=False): + query = Q() + + if include_owned: + query |= Q(user_id=user) + + if include_shared: + query |= Q(collections__shared_with=user) + + if include_public: + query |= Q(is_public=True) + + return self.filter(query).distinct() diff --git a/backend/server/adventures/middleware.py b/backend/server/adventures/middleware.py index af54b68..fae6b0b 100644 --- a/backend/server/adventures/middleware.py +++ b/backend/server/adventures/middleware.py @@ -1,13 +1,40 @@ -class AppVersionMiddleware: +from django.conf import settings +from django.utils.deprecation import MiddlewareMixin +import os + +class OverrideHostMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): - # Process request (if needed) + public_url = os.getenv('PUBLIC_URL', None) + if public_url: + # Extract host and scheme + scheme, host = public_url.split("://") + request.META['HTTP_HOST'] = host + request.META['wsgi.url_scheme'] = scheme + + # Set X-Forwarded-Proto for Django + request.META['HTTP_X_FORWARDED_PROTO'] = scheme + response = self.get_response(request) - - # Add custom header to response - # Replace with your app version - response['X-AdventureLog-Version'] = '1.0.0' - return response + +class XSessionTokenMiddleware(MiddlewareMixin): + def process_request(self, request): + session_token = request.headers.get('X-Session-Token') + if session_token: + request.COOKIES[settings.SESSION_COOKIE_NAME] = session_token + +class DisableCSRFForSessionTokenMiddleware(MiddlewareMixin): + def process_request(self, request): + if 'X-Session-Token' in request.headers: + setattr(request, '_dont_enforce_csrf_checks', True) + +class DisableCSRFForMobileLoginSignup(MiddlewareMixin): + def process_request(self, request): + is_mobile = request.headers.get('X-Is-Mobile', '').lower() == 'true' + is_login_or_signup = request.path in ['/auth/browser/v1/auth/login', '/auth/browser/v1/auth/signup'] + if is_mobile and is_login_or_signup: + setattr(request, '_dont_enforce_csrf_checks', True) + \ No newline at end of file diff --git a/backend/server/adventures/migrations/0009_alter_adventure_image.py b/backend/server/adventures/migrations/0001_adventure_image.py similarity index 75% rename from backend/server/adventures/migrations/0009_alter_adventure_image.py rename to backend/server/adventures/migrations/0001_adventure_image.py index 7c204e9..6906db4 100644 --- a/backend/server/adventures/migrations/0009_alter_adventure_image.py +++ b/backend/server/adventures/migrations/0001_adventure_image.py @@ -1,4 +1,4 @@ -# Generated by Django 5.0.6 on 2024-07-18 15:06 +# Generated by Django 5.0.8 on 2024-08-15 23:20 import django_resized.forms from django.db import migrations @@ -7,11 +7,11 @@ from django.db import migrations class Migration(migrations.Migration): dependencies = [ - ('adventures', '0008_collection_description'), + ('adventures', 'migrate_images'), ] operations = [ - migrations.AlterField( + migrations.AddField( model_name='adventure', name='image', field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='WEBP', keep_meta=True, null=True, quality=75, scale=None, size=[1920, 1080], upload_to='images/'), diff --git a/backend/server/adventures/migrations/0001_initial.py b/backend/server/adventures/migrations/0001_initial.py index 5dc1b49..4b0082c 100644 --- a/backend/server/adventures/migrations/0001_initial.py +++ b/backend/server/adventures/migrations/0001_initial.py @@ -1,6 +1,10 @@ -# Generated by Django 5.0.6 on 2024-06-28 01:01 +# Generated by Django 5.0.8 on 2024-08-11 13:37 import django.contrib.postgres.fields +import django.db.models.deletion +import django_resized.forms +import uuid +from django.conf import settings from django.db import migrations, models @@ -9,23 +13,109 @@ class Migration(migrations.Migration): initial = True dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ + migrations.CreateModel( + name='Checklist', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('date', models.DateField(blank=True, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='ChecklistItem', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('is_checked', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('checklist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='adventures.checklist')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='Collection', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('description', models.TextField(blank=True, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('start_date', models.DateField(blank=True, null=True)), + ('end_date', models.DateField(blank=True, null=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('is_archived', models.BooleanField(default=False)), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.AddField( + model_name='checklist', + name='collection', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection'), + ), migrations.CreateModel( name='Adventure', fields=[ - ('id', models.AutoField(primary_key=True, serialize=False)), - ('type', models.CharField(max_length=100)), + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('type', models.CharField(choices=[('visited', 'Visited'), ('planned', 'Planned'), ('lodging', 'Lodging'), ('dining', 'Dining')], max_length=100)), ('name', models.CharField(max_length=200)), ('location', models.CharField(blank=True, max_length=200, null=True)), ('activity_types', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=100), blank=True, null=True, size=None)), ('description', models.TextField(blank=True, null=True)), ('rating', models.FloatField(blank=True, null=True)), ('link', models.URLField(blank=True, null=True)), - ('image', models.ImageField(blank=True, null=True, upload_to='images/')), + ('image', django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='WEBP', keep_meta=True, null=True, quality=75, scale=None, size=[1920, 1080], upload_to='images/')), ('date', models.DateField(blank=True, null=True)), - ('trip_id', models.IntegerField(blank=True, null=True)), + ('is_public', models.BooleanField(default=False)), + ('longitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('latitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')), + ], + ), + migrations.CreateModel( + name='Note', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('content', models.TextField(blank=True, null=True)), + ('links', django.contrib.postgres.fields.ArrayField(base_field=models.URLField(), blank=True, null=True, size=None)), + ('date', models.DateField(blank=True, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='Transportation', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('type', models.CharField(choices=[('car', 'Car'), ('plane', 'Plane'), ('train', 'Train'), ('bus', 'Bus'), ('boat', 'Boat'), ('bike', 'Bike'), ('walking', 'Walking'), ('other', 'Other')], max_length=100)), + ('name', models.CharField(max_length=200)), + ('description', models.TextField(blank=True, null=True)), + ('rating', models.FloatField(blank=True, null=True)), + ('link', models.URLField(blank=True, null=True)), + ('date', models.DateTimeField(blank=True, null=True)), + ('flight_number', models.CharField(blank=True, max_length=100, null=True)), + ('from_location', models.CharField(blank=True, max_length=200, null=True)), + ('to_location', models.CharField(blank=True, max_length=200, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] diff --git a/backend/server/adventures/migrations/0002_adventureimage.py b/backend/server/adventures/migrations/0002_adventureimage.py new file mode 100644 index 0000000..bf80832 --- /dev/null +++ b/backend/server/adventures/migrations/0002_adventureimage.py @@ -0,0 +1,27 @@ +# Generated by Django 5.0.8 on 2024-08-15 23:17 + +import django.db.models.deletion +import django_resized.forms +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='AdventureImage', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('image', django_resized.forms.ResizedImageField(crop=None, force_format='WEBP', keep_meta=True, quality=75, scale=None, size=[1920, 1080], upload_to='images/')), + ('adventure', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='adventures.adventure')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/backend/server/adventures/migrations/0002_alter_adventureimage_adventure.py b/backend/server/adventures/migrations/0002_alter_adventureimage_adventure.py new file mode 100644 index 0000000..b03c3ad --- /dev/null +++ b/backend/server/adventures/migrations/0002_alter_adventureimage_adventure.py @@ -0,0 +1,19 @@ +# Generated by Django 5.0.8 on 2024-08-15 23:31 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0001_adventure_image'), + ] + + operations = [ + migrations.AlterField( + model_name='adventureimage', + name='adventure', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='adventures.adventure'), + ), + ] diff --git a/backend/server/adventures/migrations/0002_initial.py b/backend/server/adventures/migrations/0002_initial.py deleted file mode 100644 index 2518d14..0000000 --- a/backend/server/adventures/migrations/0002_initial.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 5.0.6 on 2024-06-28 01:01 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - initial = True - - dependencies = [ - ('adventures', '0001_initial'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name='adventure', - name='user_id', - field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), - ), - ] diff --git a/backend/server/adventures/migrations/0011_adventure_updated_at.py b/backend/server/adventures/migrations/0003_adventure_end_date.py similarity index 50% rename from backend/server/adventures/migrations/0011_adventure_updated_at.py rename to backend/server/adventures/migrations/0003_adventure_end_date.py index d04e34a..a04bbdb 100644 --- a/backend/server/adventures/migrations/0011_adventure_updated_at.py +++ b/backend/server/adventures/migrations/0003_adventure_end_date.py @@ -1,4 +1,4 @@ -# Generated by Django 5.0.6 on 2024-07-19 12:55 +# Generated by Django 5.0.8 on 2024-08-18 16:16 from django.db import migrations, models @@ -6,13 +6,13 @@ from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ - ('adventures', '0010_adventure_created_at_collection_created_at'), + ('adventures', '0002_alter_adventureimage_adventure'), ] operations = [ migrations.AddField( model_name='adventure', - name='updated_at', - field=models.DateTimeField(auto_now=True), + name='end_date', + field=models.DateField(blank=True, null=True), ), ] diff --git a/backend/server/adventures/migrations/0004_transportation_end_date.py b/backend/server/adventures/migrations/0004_transportation_end_date.py new file mode 100644 index 0000000..04f3b57 --- /dev/null +++ b/backend/server/adventures/migrations/0004_transportation_end_date.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2024-08-19 20:04 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0003_adventure_end_date'), + ] + + operations = [ + migrations.AddField( + model_name='transportation', + name='end_date', + field=models.DateTimeField(blank=True, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0005_collection_shared_with.py b/backend/server/adventures/migrations/0005_collection_shared_with.py new file mode 100644 index 0000000..c3ee3ac --- /dev/null +++ b/backend/server/adventures/migrations/0005_collection_shared_with.py @@ -0,0 +1,20 @@ +# Generated by Django 5.0.8 on 2024-09-02 13:21 + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0004_transportation_end_date'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='collection', + name='shared_with', + field=models.ManyToManyField(blank=True, related_name='shared_with', to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/backend/server/adventures/migrations/0005_remove_adventure_trip_id_trip_adventure_trip.py b/backend/server/adventures/migrations/0005_remove_adventure_trip_id_trip_adventure_trip.py deleted file mode 100644 index 43f80e7..0000000 --- a/backend/server/adventures/migrations/0005_remove_adventure_trip_id_trip_adventure_trip.py +++ /dev/null @@ -1,37 +0,0 @@ -# Generated by Django 5.0.6 on 2024-07-09 16:49 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('adventures', '0004_adventure_latitude_adventure_longitude'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.RemoveField( - model_name='adventure', - name='trip_id', - ), - migrations.CreateModel( - name='Trip', - fields=[ - ('id', models.AutoField(primary_key=True, serialize=False)), - ('name', models.CharField(max_length=200)), - ('type', models.CharField(max_length=100)), - ('location', models.CharField(blank=True, max_length=200, null=True)), - ('date', models.DateField(blank=True, null=True)), - ('is_public', models.BooleanField(default=False)), - ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), - ], - ), - migrations.AddField( - model_name='adventure', - name='trip', - field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.trip'), - ), - ] diff --git a/backend/server/adventures/migrations/0006_alter_adventure_link.py b/backend/server/adventures/migrations/0006_alter_adventure_link.py new file mode 100644 index 0000000..1a78820 --- /dev/null +++ b/backend/server/adventures/migrations/0006_alter_adventure_link.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2024-09-17 14:18 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0005_collection_shared_with'), + ] + + operations = [ + migrations.AlterField( + model_name='adventure', + name='link', + field=models.URLField(blank=True, max_length=2083, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0006_alter_adventure_type_alter_trip_type.py b/backend/server/adventures/migrations/0006_alter_adventure_type_alter_trip_type.py deleted file mode 100644 index 34e44f9..0000000 --- a/backend/server/adventures/migrations/0006_alter_adventure_type_alter_trip_type.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 5.0.6 on 2024-07-09 16:58 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('adventures', '0005_remove_adventure_trip_id_trip_adventure_trip'), - ] - - operations = [ - migrations.AlterField( - model_name='adventure', - name='type', - field=models.CharField(choices=[('visited', 'Visited'), ('planned', 'Planned'), ('featured', 'Featured')], max_length=100), - ), - migrations.AlterField( - model_name='trip', - name='type', - field=models.CharField(choices=[('visited', 'Visited'), ('planned', 'Planned'), ('featured', 'Featured')], max_length=100), - ), - ] diff --git a/backend/server/adventures/migrations/0007_remove_adventure_trip_alter_adventure_type_and_more.py b/backend/server/adventures/migrations/0007_remove_adventure_trip_alter_adventure_type_and_more.py deleted file mode 100644 index 6210249..0000000 --- a/backend/server/adventures/migrations/0007_remove_adventure_trip_alter_adventure_type_and_more.py +++ /dev/null @@ -1,42 +0,0 @@ -# Generated by Django 5.0.6 on 2024-07-15 12:57 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('adventures', '0006_alter_adventure_type_alter_trip_type'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.RemoveField( - model_name='adventure', - name='trip', - ), - migrations.AlterField( - model_name='adventure', - name='type', - field=models.CharField(choices=[('visited', 'Visited'), ('planned', 'Planned')], max_length=100), - ), - migrations.CreateModel( - name='Collection', - fields=[ - ('id', models.AutoField(primary_key=True, serialize=False)), - ('name', models.CharField(max_length=200)), - ('is_public', models.BooleanField(default=False)), - ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), - ], - ), - migrations.AddField( - model_name='adventure', - name='collection', - field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection'), - ), - migrations.DeleteModel( - name='Trip', - ), - ] diff --git a/backend/server/adventures/migrations/0007_visit_model.py b/backend/server/adventures/migrations/0007_visit_model.py new file mode 100644 index 0000000..8197c08 --- /dev/null +++ b/backend/server/adventures/migrations/0007_visit_model.py @@ -0,0 +1,32 @@ +# Generated by Django 5.0.8 on 2024-09-23 18:06 + +import django.db.models.deletion +import uuid +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0006_alter_adventure_link'), + ] + + operations = [ + migrations.AlterField( + model_name='adventure', + name='type', + field=models.CharField(choices=[('general', 'General 🌍'), ('Outdoor', 'Outdoor 🏞️'), ('lodging', 'Lodging 🛌'), ('dining', 'Dining 🍽️'), ('activity', 'Activity 🏄'), ('attraction', 'Attraction 🎢'), ('shopping', 'Shopping 🛍️'), ('nightlife', 'Nightlife 🌃'), ('event', 'Event 🎉'), ('transportation', 'Transportation 🚗'), ('culture', 'Culture 🎭'), ('water_sports', 'Water Sports 🚤'), ('hiking', 'Hiking 🥾'), ('wildlife', 'Wildlife 🦒'), ('historical_sites', 'Historical Sites 🏛️'), ('music_concerts', 'Music & Concerts 🎶'), ('fitness', 'Fitness 🏋️'), ('art_museums', 'Art & Museums 🎨'), ('festivals', 'Festivals 🎪'), ('spiritual_journeys', 'Spiritual Journeys 🧘\u200d♀️'), ('volunteer_work', 'Volunteer Work 🤝'), ('other', 'Other')], default='general', max_length=100), + ), + migrations.CreateModel( + name='Visit', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('start_date', models.DateField(blank=True, null=True)), + ('end_date', models.DateField(blank=True, null=True)), + ('notes', models.TextField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('adventure', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='visits', to='adventures.adventure')), + ], + ), + ] diff --git a/backend/server/adventures/migrations/0008_collection_description.py b/backend/server/adventures/migrations/0008_collection_description.py deleted file mode 100644 index 8decb03..0000000 --- a/backend/server/adventures/migrations/0008_collection_description.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 5.0.6 on 2024-07-15 13:05 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('adventures', '0007_remove_adventure_trip_alter_adventure_type_and_more'), - ] - - operations = [ - migrations.AddField( - model_name='collection', - name='description', - field=models.TextField(blank=True, null=True), - ), - ] diff --git a/backend/server/adventures/migrations/0008_remove_date_field.py b/backend/server/adventures/migrations/0008_remove_date_field.py new file mode 100644 index 0000000..0260097 --- /dev/null +++ b/backend/server/adventures/migrations/0008_remove_date_field.py @@ -0,0 +1,28 @@ +# Generated by Django 5.0.8 on 2024-09-23 18:06 + +import django.db.models.deletion +import uuid +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', 'migrate_visits_categories'), + ('adventures', 'migrate_images'), + ] + + operations = [ + migrations.RemoveField( + model_name='adventure', + name='date', + ), + migrations.RemoveField( + model_name='adventure', + name='end_date', + ), + migrations.RemoveField( + model_name='adventure', + name='image', + ), + ] diff --git a/backend/server/adventures/migrations/0009_alter_adventure_type.py b/backend/server/adventures/migrations/0009_alter_adventure_type.py new file mode 100644 index 0000000..72178f9 --- /dev/null +++ b/backend/server/adventures/migrations/0009_alter_adventure_type.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2024-09-30 00:33 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0008_remove_date_field'), + ] + + operations = [ + migrations.AlterField( + model_name='adventure', + name='type', + field=models.CharField(choices=[('general', 'General 🌍'), ('outdoor', 'Outdoor 🏞️'), ('lodging', 'Lodging 🛌'), ('dining', 'Dining 🍽️'), ('activity', 'Activity 🏄'), ('attraction', 'Attraction 🎢'), ('shopping', 'Shopping 🛍️'), ('nightlife', 'Nightlife 🌃'), ('event', 'Event 🎉'), ('transportation', 'Transportation 🚗'), ('culture', 'Culture 🎭'), ('water_sports', 'Water Sports 🚤'), ('hiking', 'Hiking 🥾'), ('wildlife', 'Wildlife 🦒'), ('historical_sites', 'Historical Sites 🏛️'), ('music_concerts', 'Music & Concerts 🎶'), ('fitness', 'Fitness 🏋️'), ('art_museums', 'Art & Museums 🎨'), ('festivals', 'Festivals 🎪'), ('spiritual_journeys', 'Spiritual Journeys 🧘\u200d♀️'), ('volunteer_work', 'Volunteer Work 🤝'), ('other', 'Other')], default='general', max_length=100), + ), + ] diff --git a/backend/server/adventures/migrations/0010_adventure_created_at_collection_created_at.py b/backend/server/adventures/migrations/0010_adventure_created_at_collection_created_at.py deleted file mode 100644 index 949ad10..0000000 --- a/backend/server/adventures/migrations/0010_adventure_created_at_collection_created_at.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by Django 5.0.6 on 2024-07-18 19:27 - -import django.utils.timezone -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ('adventures', '0009_alter_adventure_image'), - ] - - operations = [ - migrations.AddField( - model_name='adventure', - name='created_at', - field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), - preserve_default=False, - ), - migrations.AddField( - model_name='collection', - name='created_at', - field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), - preserve_default=False, - ), - ] diff --git a/backend/server/adventures/migrations/0010_collection_link.py b/backend/server/adventures/migrations/0010_collection_link.py new file mode 100644 index 0000000..85a5341 --- /dev/null +++ b/backend/server/adventures/migrations/0010_collection_link.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2024-10-08 03:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0009_alter_adventure_type'), + ] + + operations = [ + migrations.AddField( + model_name='collection', + name='link', + field=models.URLField(blank=True, max_length=2083, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0011_category_adventure_category.py b/backend/server/adventures/migrations/0011_category_adventure_category.py new file mode 100644 index 0000000..6413454 --- /dev/null +++ b/backend/server/adventures/migrations/0011_category_adventure_category.py @@ -0,0 +1,34 @@ +# Generated by Django 5.0.8 on 2024-11-14 04:30 + +from django.conf import settings +import django.db.models.deletion +import uuid +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0010_collection_link'), + ] + + operations = [ + migrations.CreateModel( + name='Category', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('display_name', models.CharField(max_length=200)), + ('icon', models.CharField(default='🌍', max_length=200)), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name_plural': 'Categories', + }, + ), + migrations.AddField( + model_name='adventure', + name='category', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.category'), + ), + ] diff --git a/backend/server/adventures/migrations/0012_migrate_types_to_categories.py b/backend/server/adventures/migrations/0012_migrate_types_to_categories.py new file mode 100644 index 0000000..8aea132 --- /dev/null +++ b/backend/server/adventures/migrations/0012_migrate_types_to_categories.py @@ -0,0 +1,59 @@ +from django.db import migrations + +def migrate_categories(apps, schema_editor): + # Use the historical models + Adventure = apps.get_model('adventures', 'Adventure') + Category = apps.get_model('adventures', 'Category') + + ADVENTURE_TYPES = { + 'general': ('General', '🌍'), + 'outdoor': ('Outdoor', '🏞️'), + 'lodging': ('Lodging', '🛌'), + 'dining': ('Dining', '🍽️'), + 'activity': ('Activity', '🏄'), + 'attraction': ('Attraction', '🎢'), + 'shopping': ('Shopping', '🛍️'), + 'nightlife': ('Nightlife', '🌃'), + 'event': ('Event', '🎉'), + 'transportation': ('Transportation', '🚗'), + 'culture': ('Culture', '🎭'), + 'water_sports': ('Water Sports', '🚤'), + 'hiking': ('Hiking', '🥾'), + 'wildlife': ('Wildlife', '🦒'), + 'historical_sites': ('Historical Sites', '🏛️'), + 'music_concerts': ('Music & Concerts', '🎶'), + 'fitness': ('Fitness', '🏋️'), + 'art_museums': ('Art & Museums', '🎨'), + 'festivals': ('Festivals', '🎪'), + 'spiritual_journeys': ('Spiritual Journeys', '🧘‍♀️'), + 'volunteer_work': ('Volunteer Work', '🤝'), + 'other': ('Other', '❓'), + } + + adventures = Adventure.objects.all() + for adventure in adventures: + # Access the old 'type' field using __dict__ because it's not in the model anymore + old_type = adventure.__dict__.get('type') + if old_type in ADVENTURE_TYPES: + category, created = Category.objects.get_or_create( + name=old_type, + user_id=adventure.user_id, + defaults={ + 'display_name': ADVENTURE_TYPES[old_type][0], + 'icon': ADVENTURE_TYPES[old_type][1], + } + ) + adventure.category = category + adventure.save() + else: + print(f"Unknown type: {old_type}") + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0011_category_adventure_category'), + ] + + operations = [ + migrations.RunPython(migrate_categories), + ] \ No newline at end of file diff --git a/backend/server/adventures/migrations/0013_remove_adventure_type_alter_adventure_category.py b/backend/server/adventures/migrations/0013_remove_adventure_type_alter_adventure_category.py new file mode 100644 index 0000000..d52f950 --- /dev/null +++ b/backend/server/adventures/migrations/0013_remove_adventure_type_alter_adventure_category.py @@ -0,0 +1,23 @@ +# Generated by Django 5.0.8 on 2024-11-14 04:51 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0012_migrate_types_to_categories'), + ] + + operations = [ + migrations.RemoveField( + model_name='adventure', + name='type', + ), + migrations.AlterField( + model_name='adventure', + name='category', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='adventures.category'), + ), + ] diff --git a/backend/server/adventures/migrations/0014_alter_category_unique_together.py b/backend/server/adventures/migrations/0014_alter_category_unique_together.py new file mode 100644 index 0000000..79b0bdf --- /dev/null +++ b/backend/server/adventures/migrations/0014_alter_category_unique_together.py @@ -0,0 +1,19 @@ +# Generated by Django 5.0.8 on 2024-11-17 21:43 + +from django.conf import settings +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0013_remove_adventure_type_alter_adventure_category'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AlterUniqueTogether( + name='category', + unique_together={('name', 'user_id')}, + ), + ] diff --git a/backend/server/adventures/migrations/0015_transportation_destination_latitude_and_more.py b/backend/server/adventures/migrations/0015_transportation_destination_latitude_and_more.py new file mode 100644 index 0000000..7971839 --- /dev/null +++ b/backend/server/adventures/migrations/0015_transportation_destination_latitude_and_more.py @@ -0,0 +1,33 @@ +# Generated by Django 5.0.8 on 2024-12-19 17:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0014_alter_category_unique_together'), + ] + + operations = [ + migrations.AddField( + model_name='transportation', + name='destination_latitude', + field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True), + ), + migrations.AddField( + model_name='transportation', + name='destination_longitude', + field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True), + ), + migrations.AddField( + model_name='transportation', + name='origin_latitude', + field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True), + ), + migrations.AddField( + model_name='transportation', + name='origin_longitude', + field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0016_alter_adventureimage_image.py b/backend/server/adventures/migrations/0016_alter_adventureimage_image.py new file mode 100644 index 0000000..a226fe1 --- /dev/null +++ b/backend/server/adventures/migrations/0016_alter_adventureimage_image.py @@ -0,0 +1,20 @@ +# Generated by Django 5.0.8 on 2025-01-01 21:40 + +import adventures.models +import django_resized.forms +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0015_transportation_destination_latitude_and_more'), + ] + + operations = [ + migrations.AlterField( + model_name='adventureimage', + name='image', + field=django_resized.forms.ResizedImageField(crop=None, force_format='WEBP', keep_meta=True, quality=75, scale=None, size=[1920, 1080], upload_to=adventures.models.PathAndRename('images/')), + ), + ] diff --git a/backend/server/adventures/migrations/0017_adventureimage_is_primary.py b/backend/server/adventures/migrations/0017_adventureimage_is_primary.py new file mode 100644 index 0000000..9a920a3 --- /dev/null +++ b/backend/server/adventures/migrations/0017_adventureimage_is_primary.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2025-01-03 04:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0016_alter_adventureimage_image'), + ] + + operations = [ + migrations.AddField( + model_name='adventureimage', + name='is_primary', + field=models.BooleanField(default=False), + ), + ] diff --git a/backend/server/adventures/migrations/0018_attachment.py b/backend/server/adventures/migrations/0018_attachment.py new file mode 100644 index 0000000..f41c44b --- /dev/null +++ b/backend/server/adventures/migrations/0018_attachment.py @@ -0,0 +1,26 @@ +# Generated by Django 5.0.8 on 2025-01-19 00:39 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0017_adventureimage_is_primary'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Attachment', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('file', models.FileField(upload_to='attachments/')), + ('adventure', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='adventures.adventure')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/backend/server/adventures/migrations/0019_alter_attachment_file.py b/backend/server/adventures/migrations/0019_alter_attachment_file.py new file mode 100644 index 0000000..bb48fae --- /dev/null +++ b/backend/server/adventures/migrations/0019_alter_attachment_file.py @@ -0,0 +1,19 @@ +# Generated by Django 5.0.8 on 2025-01-19 22:17 + +import adventures.models +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0018_attachment'), + ] + + operations = [ + migrations.AlterField( + model_name='attachment', + name='file', + field=models.FileField(upload_to=adventures.models.PathAndRename('attachments/')), + ), + ] diff --git a/backend/server/adventures/migrations/0020_attachment_name.py b/backend/server/adventures/migrations/0020_attachment_name.py new file mode 100644 index 0000000..4773250 --- /dev/null +++ b/backend/server/adventures/migrations/0020_attachment_name.py @@ -0,0 +1,19 @@ +# Generated by Django 5.0.8 on 2025-01-19 22:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0019_alter_attachment_file'), + ] + + operations = [ + migrations.AddField( + model_name='attachment', + name='name', + field=models.CharField(default='', max_length=200), + preserve_default=False, + ), + ] diff --git a/backend/server/adventures/migrations/0021_alter_attachment_name.py b/backend/server/adventures/migrations/0021_alter_attachment_name.py new file mode 100644 index 0000000..93b7eb3 --- /dev/null +++ b/backend/server/adventures/migrations/0021_alter_attachment_name.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.8 on 2025-01-19 22:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0020_attachment_name'), + ] + + operations = [ + migrations.AlterField( + model_name='attachment', + name='name', + field=models.CharField(blank=True, max_length=200, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0022_hotel.py b/backend/server/adventures/migrations/0022_hotel.py new file mode 100644 index 0000000..56a6097 --- /dev/null +++ b/backend/server/adventures/migrations/0022_hotel.py @@ -0,0 +1,39 @@ +# Generated by Django 5.0.8 on 2025-02-02 15:36 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0021_alter_attachment_name'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Hotel', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('description', models.TextField(blank=True, null=True)), + ('rating', models.FloatField(blank=True, null=True)), + ('link', models.URLField(blank=True, max_length=2083, null=True)), + ('check_in', models.DateTimeField(blank=True, null=True)), + ('check_out', models.DateTimeField(blank=True, null=True)), + ('reservation_number', models.CharField(blank=True, max_length=100, null=True)), + ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9, null=True)), + ('latitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('longitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('location', models.CharField(blank=True, max_length=200, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/backend/server/adventures/migrations/0023_lodging_delete_hotel.py b/backend/server/adventures/migrations/0023_lodging_delete_hotel.py new file mode 100644 index 0000000..44e502c --- /dev/null +++ b/backend/server/adventures/migrations/0023_lodging_delete_hotel.py @@ -0,0 +1,43 @@ +# Generated by Django 5.0.8 on 2025-02-08 01:50 + +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0022_hotel'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Lodging', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('name', models.CharField(max_length=200)), + ('type', models.CharField(choices=[('hotel', 'Hotel'), ('hostel', 'Hostel'), ('resort', 'Resort'), ('bnb', 'Bed & Breakfast'), ('campground', 'Campground'), ('cabin', 'Cabin'), ('apartment', 'Apartment'), ('house', 'House'), ('villa', 'Villa'), ('motel', 'Motel'), ('other', 'Other')], default='other', max_length=100)), + ('description', models.TextField(blank=True, null=True)), + ('rating', models.FloatField(blank=True, null=True)), + ('link', models.URLField(blank=True, max_length=2083, null=True)), + ('check_in', models.DateTimeField(blank=True, null=True)), + ('check_out', models.DateTimeField(blank=True, null=True)), + ('reservation_number', models.CharField(blank=True, max_length=100, null=True)), + ('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9, null=True)), + ('latitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('longitude', models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True)), + ('location', models.CharField(blank=True, max_length=200, null=True)), + ('is_public', models.BooleanField(default=False)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('collection', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='adventures.collection')), + ('user_id', models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.DeleteModel( + name='Hotel', + ), + ] diff --git a/backend/server/adventures/migrations/0024_alter_attachment_file.py b/backend/server/adventures/migrations/0024_alter_attachment_file.py new file mode 100644 index 0000000..e63bb0e --- /dev/null +++ b/backend/server/adventures/migrations/0024_alter_attachment_file.py @@ -0,0 +1,19 @@ +# Generated by Django 5.0.8 on 2025-03-17 01:15 + +import adventures.models +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0023_lodging_delete_hotel'), + ] + + operations = [ + migrations.AlterField( + model_name='attachment', + name='file', + field=models.FileField(upload_to=adventures.models.PathAndRename('attachments/'), validators=[adventures.models.validate_file_extension]), + ), + ] diff --git a/backend/server/adventures/migrations/0025_alter_visit_end_date_alter_visit_start_date.py b/backend/server/adventures/migrations/0025_alter_visit_end_date_alter_visit_start_date.py new file mode 100644 index 0000000..668e968 --- /dev/null +++ b/backend/server/adventures/migrations/0025_alter_visit_end_date_alter_visit_start_date.py @@ -0,0 +1,23 @@ +# Generated by Django 5.0.8 on 2025-03-17 21:41 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0024_alter_attachment_file'), + ] + + operations = [ + migrations.AlterField( + model_name='visit', + name='end_date', + field=models.DateTimeField(blank=True, null=True), + ), + migrations.AlterField( + model_name='visit', + name='start_date', + field=models.DateTimeField(blank=True, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0026_visit_timezone.py b/backend/server/adventures/migrations/0026_visit_timezone.py new file mode 100644 index 0000000..f0642dd --- /dev/null +++ b/backend/server/adventures/migrations/0026_visit_timezone.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.11 on 2025-05-10 14:53 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0025_alter_visit_end_date_alter_visit_start_date'), + ] + + operations = [ + migrations.AddField( + model_name='visit', + name='timezone', + field=models.CharField(blank=True, choices=[('Africa/Abidjan', 'Africa/Abidjan'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('Africa/Algiers', 'Africa/Algiers'), ('Africa/Asmera', 'Africa/Asmera'), ('Africa/Bamako', 'Africa/Bamako'), ('Africa/Bangui', 'Africa/Bangui'), ('Africa/Banjul', 'Africa/Banjul'), ('Africa/Bissau', 'Africa/Bissau'), ('Africa/Blantyre', 'Africa/Blantyre'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Africa/Cairo', 'Africa/Cairo'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Dakar', 'Africa/Dakar'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Africa/Douala', 'Africa/Douala'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('Africa/Freetown', 'Africa/Freetown'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Africa/Harare', 'Africa/Harare'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Africa/Juba', 'Africa/Juba'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Africa/Kigali', 'Africa/Kigali'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Africa/Lagos', 'Africa/Lagos'), ('Africa/Libreville', 'Africa/Libreville'), ('Africa/Lome', 'Africa/Lome'), ('Africa/Luanda', 'Africa/Luanda'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Africa/Malabo', 'Africa/Malabo'), ('Africa/Maputo', 'Africa/Maputo'), ('Africa/Maseru', 'Africa/Maseru'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Africa/Nairobi', 'Africa/Nairobi'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Africa/Niamey', 'Africa/Niamey'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/Windhoek', 'Africa/Windhoek'), ('America/Adak', 'America/Adak'), ('America/Anchorage', 'America/Anchorage'), ('America/Anguilla', 'America/Anguilla'), ('America/Antigua', 'America/Antigua'), ('America/Araguaina', 'America/Araguaina'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('America/Aruba', 'America/Aruba'), ('America/Asuncion', 'America/Asuncion'), ('America/Bahia', 'America/Bahia'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Barbados', 'America/Barbados'), ('America/Belem', 'America/Belem'), ('America/Belize', 'America/Belize'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Boa_Vista', 'America/Boa_Vista'), ('America/Bogota', 'America/Bogota'), ('America/Boise', 'America/Boise'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('America/Campo_Grande', 'America/Campo_Grande'), ('America/Cancun', 'America/Cancun'), ('America/Caracas', 'America/Caracas'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayenne', 'America/Cayenne'), ('America/Cayman', 'America/Cayman'), ('America/Chicago', 'America/Chicago'), ('America/Chihuahua', 'America/Chihuahua'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('America/Cordoba', 'America/Cordoba'), ('America/Costa_Rica', 'America/Costa_Rica'), ('America/Creston', 'America/Creston'), ('America/Cuiaba', 'America/Cuiaba'), ('America/Curacao', 'America/Curacao'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('America/Dawson', 'America/Dawson'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Denver', 'America/Denver'), ('America/Detroit', 'America/Detroit'), ('America/Dominica', 'America/Dominica'), ('America/Edmonton', 'America/Edmonton'), ('America/Eirunepe', 'America/Eirunepe'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('America/Fortaleza', 'America/Fortaleza'), ('America/Glace_Bay', 'America/Glace_Bay'), ('America/Godthab', 'America/Godthab'), ('America/Goose_Bay', 'America/Goose_Bay'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Grenada', 'America/Grenada'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Guatemala', 'America/Guatemala'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Guyana', 'America/Guyana'), ('America/Halifax', 'America/Halifax'), ('America/Havana', 'America/Havana'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Inuvik', 'America/Inuvik'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Jamaica', 'America/Jamaica'), ('America/Jujuy', 'America/Jujuy'), ('America/Juneau', 'America/Juneau'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Kralendijk', 'America/Kralendijk'), ('America/La_Paz', 'America/La_Paz'), ('America/Lima', 'America/Lima'), ('America/Los_Angeles', 'America/Los_Angeles'), ('America/Louisville', 'America/Louisville'), ('America/Lower_Princes', 'America/Lower_Princes'), ('America/Maceio', 'America/Maceio'), ('America/Managua', 'America/Managua'), ('America/Manaus', 'America/Manaus'), ('America/Marigot', 'America/Marigot'), ('America/Martinique', 'America/Martinique'), ('America/Matamoros', 'America/Matamoros'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Mendoza', 'America/Mendoza'), ('America/Menominee', 'America/Menominee'), ('America/Merida', 'America/Merida'), ('America/Metlakatla', 'America/Metlakatla'), ('America/Mexico_City', 'America/Mexico_City'), ('America/Miquelon', 'America/Miquelon'), ('America/Moncton', 'America/Moncton'), ('America/Monterrey', 'America/Monterrey'), ('America/Montevideo', 'America/Montevideo'), ('America/Montserrat', 'America/Montserrat'), ('America/Nassau', 'America/Nassau'), ('America/New_York', 'America/New_York'), ('America/Nome', 'America/Nome'), ('America/Noronha', 'America/Noronha'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Ojinaga', 'America/Ojinaga'), ('America/Panama', 'America/Panama'), ('America/Paramaribo', 'America/Paramaribo'), ('America/Phoenix', 'America/Phoenix'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Porto_Velho', 'America/Porto_Velho'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('America/Recife', 'America/Recife'), ('America/Regina', 'America/Regina'), ('America/Resolute', 'America/Resolute'), ('America/Rio_Branco', 'America/Rio_Branco'), ('America/Santarem', 'America/Santarem'), ('America/Santiago', 'America/Santiago'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Scoresbysund', 'America/Scoresbysund'), ('America/Sitka', 'America/Sitka'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('America/St_Johns', 'America/St_Johns'), ('America/St_Kitts', 'America/St_Kitts'), ('America/St_Lucia', 'America/St_Lucia'), ('America/St_Thomas', 'America/St_Thomas'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Swift_Current', 'America/Swift_Current'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('America/Thule', 'America/Thule'), ('America/Tijuana', 'America/Tijuana'), ('America/Toronto', 'America/Toronto'), ('America/Tortola', 'America/Tortola'), ('America/Vancouver', 'America/Vancouver'), ('America/Whitehorse', 'America/Whitehorse'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Yakutat', 'America/Yakutat'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Asia/Aden', 'Asia/Aden'), ('Asia/Almaty', 'Asia/Almaty'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Asia/Bahrain', 'Asia/Bahrain'), ('Asia/Baku', 'Asia/Baku'), ('Asia/Bangkok', 'Asia/Bangkok'), ('Asia/Barnaul', 'Asia/Barnaul'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Asia/Brunei', 'Asia/Brunei'), ('Asia/Calcutta', 'Asia/Calcutta'), ('Asia/Chita', 'Asia/Chita'), ('Asia/Colombo', 'Asia/Colombo'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Dhaka', 'Asia/Dhaka'), ('Asia/Dili', 'Asia/Dili'), ('Asia/Dubai', 'Asia/Dubai'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Asia/Gaza', 'Asia/Gaza'), ('Asia/Hebron', 'Asia/Hebron'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('Asia/Hovd', 'Asia/Hovd'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Asia/Jakarta', 'Asia/Jakarta'), ('Asia/Jayapura', 'Asia/Jayapura'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Kabul', 'Asia/Kabul'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Karachi', 'Asia/Karachi'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Asia/Kuching', 'Asia/Kuching'), ('Asia/Kuwait', 'Asia/Kuwait'), ('Asia/Macau', 'Asia/Macau'), ('Asia/Magadan', 'Asia/Magadan'), ('Asia/Makassar', 'Asia/Makassar'), ('Asia/Manila', 'Asia/Manila'), ('Asia/Muscat', 'Asia/Muscat'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Oral', 'Asia/Oral'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('Asia/Qatar', 'Asia/Qatar'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Asia/Saigon', 'Asia/Saigon'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Asia/Seoul', 'Asia/Seoul'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Singapore', 'Asia/Singapore'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Asia/Taipei', 'Asia/Taipei'), ('Asia/Tashkent', 'Asia/Tashkent'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Asia/Tehran', 'Asia/Tehran'), ('Asia/Thimphu', 'Asia/Thimphu'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Atlantic/Azores', 'Atlantic/Azores'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('Atlantic/Canary', 'Atlantic/Canary'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Australia/Darwin', 'Australia/Darwin'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Hobart', 'Australia/Hobart'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Australia/Perth', 'Australia/Perth'), ('Australia/Sydney', 'Australia/Sydney'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Europe/Andorra', 'Europe/Andorra'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Europe/Athens', 'Europe/Athens'), ('Europe/Belgrade', 'Europe/Belgrade'), ('Europe/Berlin', 'Europe/Berlin'), ('Europe/Bratislava', 'Europe/Bratislava'), ('Europe/Brussels', 'Europe/Brussels'), ('Europe/Bucharest', 'Europe/Bucharest'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Europe/Dublin', 'Europe/Dublin'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Europe/Helsinki', 'Europe/Helsinki'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Europe/Jersey', 'Europe/Jersey'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Kirov', 'Europe/Kirov'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Europe/London', 'Europe/London'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Europe/Madrid', 'Europe/Madrid'), ('Europe/Malta', 'Europe/Malta'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Europe/Minsk', 'Europe/Minsk'), ('Europe/Monaco', 'Europe/Monaco'), ('Europe/Moscow', 'Europe/Moscow'), ('Europe/Oslo', 'Europe/Oslo'), ('Europe/Paris', 'Europe/Paris'), ('Europe/Podgorica', 'Europe/Podgorica'), ('Europe/Prague', 'Europe/Prague'), ('Europe/Riga', 'Europe/Riga'), ('Europe/Rome', 'Europe/Rome'), ('Europe/Samara', 'Europe/Samara'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('Europe/Saratov', 'Europe/Saratov'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Europe/Skopje', 'Europe/Skopje'), ('Europe/Sofia', 'Europe/Sofia'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Europe/Tirane', 'Europe/Tirane'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Europe/Vatican', 'Europe/Vatican'), ('Europe/Vienna', 'Europe/Vienna'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Zurich', 'Europe/Zurich'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Indian/Chagos', 'Indian/Chagos'), ('Indian/Christmas', 'Indian/Christmas'), ('Indian/Cocos', 'Indian/Cocos'), ('Indian/Comoro', 'Indian/Comoro'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('Indian/Mahe', 'Indian/Mahe'), ('Indian/Maldives', 'Indian/Maldives'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Indian/Mayotte', 'Indian/Mayotte'), ('Indian/Reunion', 'Indian/Reunion'), ('Pacific/Apia', 'Pacific/Apia'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Pacific/Easter', 'Pacific/Easter'), ('Pacific/Efate', 'Pacific/Efate'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('Pacific/Guam', 'Pacific/Guam'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway'), ('Pacific/Nauru', 'Pacific/Nauru'), ('Pacific/Niue', 'Pacific/Niue'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Pacific/Palau', 'Pacific/Palau'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Pacific/Truk', 'Pacific/Truk'), ('Pacific/Wake', 'Pacific/Wake'), ('Pacific/Wallis', 'Pacific/Wallis')], max_length=50, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0027_transportation_end_timezone_and_more.py b/backend/server/adventures/migrations/0027_transportation_end_timezone_and_more.py new file mode 100644 index 0000000..6331225 --- /dev/null +++ b/backend/server/adventures/migrations/0027_transportation_end_timezone_and_more.py @@ -0,0 +1,23 @@ +# Generated by Django 5.0.11 on 2025-05-10 15:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0026_visit_timezone'), + ] + + operations = [ + migrations.AddField( + model_name='transportation', + name='end_timezone', + field=models.CharField(blank=True, choices=[('Africa/Abidjan', 'Africa/Abidjan'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('Africa/Algiers', 'Africa/Algiers'), ('Africa/Asmera', 'Africa/Asmera'), ('Africa/Bamako', 'Africa/Bamako'), ('Africa/Bangui', 'Africa/Bangui'), ('Africa/Banjul', 'Africa/Banjul'), ('Africa/Bissau', 'Africa/Bissau'), ('Africa/Blantyre', 'Africa/Blantyre'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Africa/Cairo', 'Africa/Cairo'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Dakar', 'Africa/Dakar'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Africa/Douala', 'Africa/Douala'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('Africa/Freetown', 'Africa/Freetown'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Africa/Harare', 'Africa/Harare'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Africa/Juba', 'Africa/Juba'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Africa/Kigali', 'Africa/Kigali'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Africa/Lagos', 'Africa/Lagos'), ('Africa/Libreville', 'Africa/Libreville'), ('Africa/Lome', 'Africa/Lome'), ('Africa/Luanda', 'Africa/Luanda'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Africa/Malabo', 'Africa/Malabo'), ('Africa/Maputo', 'Africa/Maputo'), ('Africa/Maseru', 'Africa/Maseru'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Africa/Nairobi', 'Africa/Nairobi'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Africa/Niamey', 'Africa/Niamey'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/Windhoek', 'Africa/Windhoek'), ('America/Adak', 'America/Adak'), ('America/Anchorage', 'America/Anchorage'), ('America/Anguilla', 'America/Anguilla'), ('America/Antigua', 'America/Antigua'), ('America/Araguaina', 'America/Araguaina'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('America/Aruba', 'America/Aruba'), ('America/Asuncion', 'America/Asuncion'), ('America/Bahia', 'America/Bahia'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Barbados', 'America/Barbados'), ('America/Belem', 'America/Belem'), ('America/Belize', 'America/Belize'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Boa_Vista', 'America/Boa_Vista'), ('America/Bogota', 'America/Bogota'), ('America/Boise', 'America/Boise'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('America/Campo_Grande', 'America/Campo_Grande'), ('America/Cancun', 'America/Cancun'), ('America/Caracas', 'America/Caracas'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayenne', 'America/Cayenne'), ('America/Cayman', 'America/Cayman'), ('America/Chicago', 'America/Chicago'), ('America/Chihuahua', 'America/Chihuahua'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('America/Cordoba', 'America/Cordoba'), ('America/Costa_Rica', 'America/Costa_Rica'), ('America/Creston', 'America/Creston'), ('America/Cuiaba', 'America/Cuiaba'), ('America/Curacao', 'America/Curacao'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('America/Dawson', 'America/Dawson'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Denver', 'America/Denver'), ('America/Detroit', 'America/Detroit'), ('America/Dominica', 'America/Dominica'), ('America/Edmonton', 'America/Edmonton'), ('America/Eirunepe', 'America/Eirunepe'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('America/Fortaleza', 'America/Fortaleza'), ('America/Glace_Bay', 'America/Glace_Bay'), ('America/Godthab', 'America/Godthab'), ('America/Goose_Bay', 'America/Goose_Bay'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Grenada', 'America/Grenada'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Guatemala', 'America/Guatemala'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Guyana', 'America/Guyana'), ('America/Halifax', 'America/Halifax'), ('America/Havana', 'America/Havana'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Inuvik', 'America/Inuvik'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Jamaica', 'America/Jamaica'), ('America/Jujuy', 'America/Jujuy'), ('America/Juneau', 'America/Juneau'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Kralendijk', 'America/Kralendijk'), ('America/La_Paz', 'America/La_Paz'), ('America/Lima', 'America/Lima'), ('America/Los_Angeles', 'America/Los_Angeles'), ('America/Louisville', 'America/Louisville'), ('America/Lower_Princes', 'America/Lower_Princes'), ('America/Maceio', 'America/Maceio'), ('America/Managua', 'America/Managua'), ('America/Manaus', 'America/Manaus'), ('America/Marigot', 'America/Marigot'), ('America/Martinique', 'America/Martinique'), ('America/Matamoros', 'America/Matamoros'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Mendoza', 'America/Mendoza'), ('America/Menominee', 'America/Menominee'), ('America/Merida', 'America/Merida'), ('America/Metlakatla', 'America/Metlakatla'), ('America/Mexico_City', 'America/Mexico_City'), ('America/Miquelon', 'America/Miquelon'), ('America/Moncton', 'America/Moncton'), ('America/Monterrey', 'America/Monterrey'), ('America/Montevideo', 'America/Montevideo'), ('America/Montserrat', 'America/Montserrat'), ('America/Nassau', 'America/Nassau'), ('America/New_York', 'America/New_York'), ('America/Nome', 'America/Nome'), ('America/Noronha', 'America/Noronha'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Ojinaga', 'America/Ojinaga'), ('America/Panama', 'America/Panama'), ('America/Paramaribo', 'America/Paramaribo'), ('America/Phoenix', 'America/Phoenix'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Porto_Velho', 'America/Porto_Velho'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('America/Recife', 'America/Recife'), ('America/Regina', 'America/Regina'), ('America/Resolute', 'America/Resolute'), ('America/Rio_Branco', 'America/Rio_Branco'), ('America/Santarem', 'America/Santarem'), ('America/Santiago', 'America/Santiago'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Scoresbysund', 'America/Scoresbysund'), ('America/Sitka', 'America/Sitka'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('America/St_Johns', 'America/St_Johns'), ('America/St_Kitts', 'America/St_Kitts'), ('America/St_Lucia', 'America/St_Lucia'), ('America/St_Thomas', 'America/St_Thomas'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Swift_Current', 'America/Swift_Current'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('America/Thule', 'America/Thule'), ('America/Tijuana', 'America/Tijuana'), ('America/Toronto', 'America/Toronto'), ('America/Tortola', 'America/Tortola'), ('America/Vancouver', 'America/Vancouver'), ('America/Whitehorse', 'America/Whitehorse'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Yakutat', 'America/Yakutat'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Asia/Aden', 'Asia/Aden'), ('Asia/Almaty', 'Asia/Almaty'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Asia/Bahrain', 'Asia/Bahrain'), ('Asia/Baku', 'Asia/Baku'), ('Asia/Bangkok', 'Asia/Bangkok'), ('Asia/Barnaul', 'Asia/Barnaul'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Asia/Brunei', 'Asia/Brunei'), ('Asia/Calcutta', 'Asia/Calcutta'), ('Asia/Chita', 'Asia/Chita'), ('Asia/Colombo', 'Asia/Colombo'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Dhaka', 'Asia/Dhaka'), ('Asia/Dili', 'Asia/Dili'), ('Asia/Dubai', 'Asia/Dubai'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Asia/Gaza', 'Asia/Gaza'), ('Asia/Hebron', 'Asia/Hebron'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('Asia/Hovd', 'Asia/Hovd'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Asia/Jakarta', 'Asia/Jakarta'), ('Asia/Jayapura', 'Asia/Jayapura'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Kabul', 'Asia/Kabul'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Karachi', 'Asia/Karachi'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Asia/Kuching', 'Asia/Kuching'), ('Asia/Kuwait', 'Asia/Kuwait'), ('Asia/Macau', 'Asia/Macau'), ('Asia/Magadan', 'Asia/Magadan'), ('Asia/Makassar', 'Asia/Makassar'), ('Asia/Manila', 'Asia/Manila'), ('Asia/Muscat', 'Asia/Muscat'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Oral', 'Asia/Oral'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('Asia/Qatar', 'Asia/Qatar'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Asia/Saigon', 'Asia/Saigon'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Asia/Seoul', 'Asia/Seoul'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Singapore', 'Asia/Singapore'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Asia/Taipei', 'Asia/Taipei'), ('Asia/Tashkent', 'Asia/Tashkent'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Asia/Tehran', 'Asia/Tehran'), ('Asia/Thimphu', 'Asia/Thimphu'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Atlantic/Azores', 'Atlantic/Azores'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('Atlantic/Canary', 'Atlantic/Canary'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Australia/Darwin', 'Australia/Darwin'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Hobart', 'Australia/Hobart'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Australia/Perth', 'Australia/Perth'), ('Australia/Sydney', 'Australia/Sydney'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Europe/Andorra', 'Europe/Andorra'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Europe/Athens', 'Europe/Athens'), ('Europe/Belgrade', 'Europe/Belgrade'), ('Europe/Berlin', 'Europe/Berlin'), ('Europe/Bratislava', 'Europe/Bratislava'), ('Europe/Brussels', 'Europe/Brussels'), ('Europe/Bucharest', 'Europe/Bucharest'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Europe/Dublin', 'Europe/Dublin'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Europe/Helsinki', 'Europe/Helsinki'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Europe/Jersey', 'Europe/Jersey'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Kirov', 'Europe/Kirov'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Europe/London', 'Europe/London'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Europe/Madrid', 'Europe/Madrid'), ('Europe/Malta', 'Europe/Malta'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Europe/Minsk', 'Europe/Minsk'), ('Europe/Monaco', 'Europe/Monaco'), ('Europe/Moscow', 'Europe/Moscow'), ('Europe/Oslo', 'Europe/Oslo'), ('Europe/Paris', 'Europe/Paris'), ('Europe/Podgorica', 'Europe/Podgorica'), ('Europe/Prague', 'Europe/Prague'), ('Europe/Riga', 'Europe/Riga'), ('Europe/Rome', 'Europe/Rome'), ('Europe/Samara', 'Europe/Samara'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('Europe/Saratov', 'Europe/Saratov'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Europe/Skopje', 'Europe/Skopje'), ('Europe/Sofia', 'Europe/Sofia'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Europe/Tirane', 'Europe/Tirane'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Europe/Vatican', 'Europe/Vatican'), ('Europe/Vienna', 'Europe/Vienna'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Zurich', 'Europe/Zurich'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Indian/Chagos', 'Indian/Chagos'), ('Indian/Christmas', 'Indian/Christmas'), ('Indian/Cocos', 'Indian/Cocos'), ('Indian/Comoro', 'Indian/Comoro'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('Indian/Mahe', 'Indian/Mahe'), ('Indian/Maldives', 'Indian/Maldives'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Indian/Mayotte', 'Indian/Mayotte'), ('Indian/Reunion', 'Indian/Reunion'), ('Pacific/Apia', 'Pacific/Apia'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Pacific/Easter', 'Pacific/Easter'), ('Pacific/Efate', 'Pacific/Efate'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('Pacific/Guam', 'Pacific/Guam'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway'), ('Pacific/Nauru', 'Pacific/Nauru'), ('Pacific/Niue', 'Pacific/Niue'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Pacific/Palau', 'Pacific/Palau'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Pacific/Truk', 'Pacific/Truk'), ('Pacific/Wake', 'Pacific/Wake'), ('Pacific/Wallis', 'Pacific/Wallis')], max_length=50, null=True), + ), + migrations.AddField( + model_name='transportation', + name='start_timezone', + field=models.CharField(blank=True, choices=[('Africa/Abidjan', 'Africa/Abidjan'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('Africa/Algiers', 'Africa/Algiers'), ('Africa/Asmera', 'Africa/Asmera'), ('Africa/Bamako', 'Africa/Bamako'), ('Africa/Bangui', 'Africa/Bangui'), ('Africa/Banjul', 'Africa/Banjul'), ('Africa/Bissau', 'Africa/Bissau'), ('Africa/Blantyre', 'Africa/Blantyre'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Africa/Cairo', 'Africa/Cairo'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Dakar', 'Africa/Dakar'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Africa/Douala', 'Africa/Douala'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('Africa/Freetown', 'Africa/Freetown'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Africa/Harare', 'Africa/Harare'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Africa/Juba', 'Africa/Juba'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Africa/Kigali', 'Africa/Kigali'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Africa/Lagos', 'Africa/Lagos'), ('Africa/Libreville', 'Africa/Libreville'), ('Africa/Lome', 'Africa/Lome'), ('Africa/Luanda', 'Africa/Luanda'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Africa/Malabo', 'Africa/Malabo'), ('Africa/Maputo', 'Africa/Maputo'), ('Africa/Maseru', 'Africa/Maseru'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Africa/Nairobi', 'Africa/Nairobi'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Africa/Niamey', 'Africa/Niamey'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/Windhoek', 'Africa/Windhoek'), ('America/Adak', 'America/Adak'), ('America/Anchorage', 'America/Anchorage'), ('America/Anguilla', 'America/Anguilla'), ('America/Antigua', 'America/Antigua'), ('America/Araguaina', 'America/Araguaina'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('America/Aruba', 'America/Aruba'), ('America/Asuncion', 'America/Asuncion'), ('America/Bahia', 'America/Bahia'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Barbados', 'America/Barbados'), ('America/Belem', 'America/Belem'), ('America/Belize', 'America/Belize'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Boa_Vista', 'America/Boa_Vista'), ('America/Bogota', 'America/Bogota'), ('America/Boise', 'America/Boise'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('America/Campo_Grande', 'America/Campo_Grande'), ('America/Cancun', 'America/Cancun'), ('America/Caracas', 'America/Caracas'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayenne', 'America/Cayenne'), ('America/Cayman', 'America/Cayman'), ('America/Chicago', 'America/Chicago'), ('America/Chihuahua', 'America/Chihuahua'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('America/Cordoba', 'America/Cordoba'), ('America/Costa_Rica', 'America/Costa_Rica'), ('America/Creston', 'America/Creston'), ('America/Cuiaba', 'America/Cuiaba'), ('America/Curacao', 'America/Curacao'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('America/Dawson', 'America/Dawson'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Denver', 'America/Denver'), ('America/Detroit', 'America/Detroit'), ('America/Dominica', 'America/Dominica'), ('America/Edmonton', 'America/Edmonton'), ('America/Eirunepe', 'America/Eirunepe'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('America/Fortaleza', 'America/Fortaleza'), ('America/Glace_Bay', 'America/Glace_Bay'), ('America/Godthab', 'America/Godthab'), ('America/Goose_Bay', 'America/Goose_Bay'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Grenada', 'America/Grenada'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Guatemala', 'America/Guatemala'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Guyana', 'America/Guyana'), ('America/Halifax', 'America/Halifax'), ('America/Havana', 'America/Havana'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Inuvik', 'America/Inuvik'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Jamaica', 'America/Jamaica'), ('America/Jujuy', 'America/Jujuy'), ('America/Juneau', 'America/Juneau'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Kralendijk', 'America/Kralendijk'), ('America/La_Paz', 'America/La_Paz'), ('America/Lima', 'America/Lima'), ('America/Los_Angeles', 'America/Los_Angeles'), ('America/Louisville', 'America/Louisville'), ('America/Lower_Princes', 'America/Lower_Princes'), ('America/Maceio', 'America/Maceio'), ('America/Managua', 'America/Managua'), ('America/Manaus', 'America/Manaus'), ('America/Marigot', 'America/Marigot'), ('America/Martinique', 'America/Martinique'), ('America/Matamoros', 'America/Matamoros'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Mendoza', 'America/Mendoza'), ('America/Menominee', 'America/Menominee'), ('America/Merida', 'America/Merida'), ('America/Metlakatla', 'America/Metlakatla'), ('America/Mexico_City', 'America/Mexico_City'), ('America/Miquelon', 'America/Miquelon'), ('America/Moncton', 'America/Moncton'), ('America/Monterrey', 'America/Monterrey'), ('America/Montevideo', 'America/Montevideo'), ('America/Montserrat', 'America/Montserrat'), ('America/Nassau', 'America/Nassau'), ('America/New_York', 'America/New_York'), ('America/Nome', 'America/Nome'), ('America/Noronha', 'America/Noronha'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Ojinaga', 'America/Ojinaga'), ('America/Panama', 'America/Panama'), ('America/Paramaribo', 'America/Paramaribo'), ('America/Phoenix', 'America/Phoenix'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Porto_Velho', 'America/Porto_Velho'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('America/Recife', 'America/Recife'), ('America/Regina', 'America/Regina'), ('America/Resolute', 'America/Resolute'), ('America/Rio_Branco', 'America/Rio_Branco'), ('America/Santarem', 'America/Santarem'), ('America/Santiago', 'America/Santiago'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Scoresbysund', 'America/Scoresbysund'), ('America/Sitka', 'America/Sitka'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('America/St_Johns', 'America/St_Johns'), ('America/St_Kitts', 'America/St_Kitts'), ('America/St_Lucia', 'America/St_Lucia'), ('America/St_Thomas', 'America/St_Thomas'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Swift_Current', 'America/Swift_Current'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('America/Thule', 'America/Thule'), ('America/Tijuana', 'America/Tijuana'), ('America/Toronto', 'America/Toronto'), ('America/Tortola', 'America/Tortola'), ('America/Vancouver', 'America/Vancouver'), ('America/Whitehorse', 'America/Whitehorse'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Yakutat', 'America/Yakutat'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Asia/Aden', 'Asia/Aden'), ('Asia/Almaty', 'Asia/Almaty'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Asia/Bahrain', 'Asia/Bahrain'), ('Asia/Baku', 'Asia/Baku'), ('Asia/Bangkok', 'Asia/Bangkok'), ('Asia/Barnaul', 'Asia/Barnaul'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Asia/Brunei', 'Asia/Brunei'), ('Asia/Calcutta', 'Asia/Calcutta'), ('Asia/Chita', 'Asia/Chita'), ('Asia/Colombo', 'Asia/Colombo'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Dhaka', 'Asia/Dhaka'), ('Asia/Dili', 'Asia/Dili'), ('Asia/Dubai', 'Asia/Dubai'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Asia/Gaza', 'Asia/Gaza'), ('Asia/Hebron', 'Asia/Hebron'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('Asia/Hovd', 'Asia/Hovd'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Asia/Jakarta', 'Asia/Jakarta'), ('Asia/Jayapura', 'Asia/Jayapura'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Kabul', 'Asia/Kabul'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Karachi', 'Asia/Karachi'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Asia/Kuching', 'Asia/Kuching'), ('Asia/Kuwait', 'Asia/Kuwait'), ('Asia/Macau', 'Asia/Macau'), ('Asia/Magadan', 'Asia/Magadan'), ('Asia/Makassar', 'Asia/Makassar'), ('Asia/Manila', 'Asia/Manila'), ('Asia/Muscat', 'Asia/Muscat'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Oral', 'Asia/Oral'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('Asia/Qatar', 'Asia/Qatar'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Asia/Saigon', 'Asia/Saigon'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Asia/Seoul', 'Asia/Seoul'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Singapore', 'Asia/Singapore'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Asia/Taipei', 'Asia/Taipei'), ('Asia/Tashkent', 'Asia/Tashkent'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Asia/Tehran', 'Asia/Tehran'), ('Asia/Thimphu', 'Asia/Thimphu'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Atlantic/Azores', 'Atlantic/Azores'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('Atlantic/Canary', 'Atlantic/Canary'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Australia/Darwin', 'Australia/Darwin'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Hobart', 'Australia/Hobart'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Australia/Perth', 'Australia/Perth'), ('Australia/Sydney', 'Australia/Sydney'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Europe/Andorra', 'Europe/Andorra'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Europe/Athens', 'Europe/Athens'), ('Europe/Belgrade', 'Europe/Belgrade'), ('Europe/Berlin', 'Europe/Berlin'), ('Europe/Bratislava', 'Europe/Bratislava'), ('Europe/Brussels', 'Europe/Brussels'), ('Europe/Bucharest', 'Europe/Bucharest'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Europe/Dublin', 'Europe/Dublin'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Europe/Helsinki', 'Europe/Helsinki'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Europe/Jersey', 'Europe/Jersey'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Kirov', 'Europe/Kirov'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Europe/London', 'Europe/London'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Europe/Madrid', 'Europe/Madrid'), ('Europe/Malta', 'Europe/Malta'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Europe/Minsk', 'Europe/Minsk'), ('Europe/Monaco', 'Europe/Monaco'), ('Europe/Moscow', 'Europe/Moscow'), ('Europe/Oslo', 'Europe/Oslo'), ('Europe/Paris', 'Europe/Paris'), ('Europe/Podgorica', 'Europe/Podgorica'), ('Europe/Prague', 'Europe/Prague'), ('Europe/Riga', 'Europe/Riga'), ('Europe/Rome', 'Europe/Rome'), ('Europe/Samara', 'Europe/Samara'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('Europe/Saratov', 'Europe/Saratov'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Europe/Skopje', 'Europe/Skopje'), ('Europe/Sofia', 'Europe/Sofia'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Europe/Tirane', 'Europe/Tirane'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Europe/Vatican', 'Europe/Vatican'), ('Europe/Vienna', 'Europe/Vienna'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Zurich', 'Europe/Zurich'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Indian/Chagos', 'Indian/Chagos'), ('Indian/Christmas', 'Indian/Christmas'), ('Indian/Cocos', 'Indian/Cocos'), ('Indian/Comoro', 'Indian/Comoro'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('Indian/Mahe', 'Indian/Mahe'), ('Indian/Maldives', 'Indian/Maldives'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Indian/Mayotte', 'Indian/Mayotte'), ('Indian/Reunion', 'Indian/Reunion'), ('Pacific/Apia', 'Pacific/Apia'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Pacific/Easter', 'Pacific/Easter'), ('Pacific/Efate', 'Pacific/Efate'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('Pacific/Guam', 'Pacific/Guam'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway'), ('Pacific/Nauru', 'Pacific/Nauru'), ('Pacific/Niue', 'Pacific/Niue'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Pacific/Palau', 'Pacific/Palau'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Pacific/Truk', 'Pacific/Truk'), ('Pacific/Wake', 'Pacific/Wake'), ('Pacific/Wallis', 'Pacific/Wallis')], max_length=50, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0028_lodging_timezone.py b/backend/server/adventures/migrations/0028_lodging_timezone.py new file mode 100644 index 0000000..d9513f7 --- /dev/null +++ b/backend/server/adventures/migrations/0028_lodging_timezone.py @@ -0,0 +1,18 @@ +# Generated by Django 5.0.11 on 2025-05-10 15:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0027_transportation_end_timezone_and_more'), + ] + + operations = [ + migrations.AddField( + model_name='lodging', + name='timezone', + field=models.CharField(blank=True, choices=[('Africa/Abidjan', 'Africa/Abidjan'), ('Africa/Accra', 'Africa/Accra'), ('Africa/Addis_Ababa', 'Africa/Addis_Ababa'), ('Africa/Algiers', 'Africa/Algiers'), ('Africa/Asmera', 'Africa/Asmera'), ('Africa/Bamako', 'Africa/Bamako'), ('Africa/Bangui', 'Africa/Bangui'), ('Africa/Banjul', 'Africa/Banjul'), ('Africa/Bissau', 'Africa/Bissau'), ('Africa/Blantyre', 'Africa/Blantyre'), ('Africa/Brazzaville', 'Africa/Brazzaville'), ('Africa/Bujumbura', 'Africa/Bujumbura'), ('Africa/Cairo', 'Africa/Cairo'), ('Africa/Casablanca', 'Africa/Casablanca'), ('Africa/Ceuta', 'Africa/Ceuta'), ('Africa/Conakry', 'Africa/Conakry'), ('Africa/Dakar', 'Africa/Dakar'), ('Africa/Dar_es_Salaam', 'Africa/Dar_es_Salaam'), ('Africa/Djibouti', 'Africa/Djibouti'), ('Africa/Douala', 'Africa/Douala'), ('Africa/El_Aaiun', 'Africa/El_Aaiun'), ('Africa/Freetown', 'Africa/Freetown'), ('Africa/Gaborone', 'Africa/Gaborone'), ('Africa/Harare', 'Africa/Harare'), ('Africa/Johannesburg', 'Africa/Johannesburg'), ('Africa/Juba', 'Africa/Juba'), ('Africa/Kampala', 'Africa/Kampala'), ('Africa/Khartoum', 'Africa/Khartoum'), ('Africa/Kigali', 'Africa/Kigali'), ('Africa/Kinshasa', 'Africa/Kinshasa'), ('Africa/Lagos', 'Africa/Lagos'), ('Africa/Libreville', 'Africa/Libreville'), ('Africa/Lome', 'Africa/Lome'), ('Africa/Luanda', 'Africa/Luanda'), ('Africa/Lubumbashi', 'Africa/Lubumbashi'), ('Africa/Lusaka', 'Africa/Lusaka'), ('Africa/Malabo', 'Africa/Malabo'), ('Africa/Maputo', 'Africa/Maputo'), ('Africa/Maseru', 'Africa/Maseru'), ('Africa/Mbabane', 'Africa/Mbabane'), ('Africa/Mogadishu', 'Africa/Mogadishu'), ('Africa/Monrovia', 'Africa/Monrovia'), ('Africa/Nairobi', 'Africa/Nairobi'), ('Africa/Ndjamena', 'Africa/Ndjamena'), ('Africa/Niamey', 'Africa/Niamey'), ('Africa/Nouakchott', 'Africa/Nouakchott'), ('Africa/Ouagadougou', 'Africa/Ouagadougou'), ('Africa/Porto-Novo', 'Africa/Porto-Novo'), ('Africa/Sao_Tome', 'Africa/Sao_Tome'), ('Africa/Tripoli', 'Africa/Tripoli'), ('Africa/Tunis', 'Africa/Tunis'), ('Africa/Windhoek', 'Africa/Windhoek'), ('America/Adak', 'America/Adak'), ('America/Anchorage', 'America/Anchorage'), ('America/Anguilla', 'America/Anguilla'), ('America/Antigua', 'America/Antigua'), ('America/Araguaina', 'America/Araguaina'), ('America/Argentina/La_Rioja', 'America/Argentina/La_Rioja'), ('America/Argentina/Rio_Gallegos', 'America/Argentina/Rio_Gallegos'), ('America/Argentina/Salta', 'America/Argentina/Salta'), ('America/Argentina/San_Juan', 'America/Argentina/San_Juan'), ('America/Argentina/San_Luis', 'America/Argentina/San_Luis'), ('America/Argentina/Tucuman', 'America/Argentina/Tucuman'), ('America/Argentina/Ushuaia', 'America/Argentina/Ushuaia'), ('America/Aruba', 'America/Aruba'), ('America/Asuncion', 'America/Asuncion'), ('America/Bahia', 'America/Bahia'), ('America/Bahia_Banderas', 'America/Bahia_Banderas'), ('America/Barbados', 'America/Barbados'), ('America/Belem', 'America/Belem'), ('America/Belize', 'America/Belize'), ('America/Blanc-Sablon', 'America/Blanc-Sablon'), ('America/Boa_Vista', 'America/Boa_Vista'), ('America/Bogota', 'America/Bogota'), ('America/Boise', 'America/Boise'), ('America/Buenos_Aires', 'America/Buenos_Aires'), ('America/Cambridge_Bay', 'America/Cambridge_Bay'), ('America/Campo_Grande', 'America/Campo_Grande'), ('America/Cancun', 'America/Cancun'), ('America/Caracas', 'America/Caracas'), ('America/Catamarca', 'America/Catamarca'), ('America/Cayenne', 'America/Cayenne'), ('America/Cayman', 'America/Cayman'), ('America/Chicago', 'America/Chicago'), ('America/Chihuahua', 'America/Chihuahua'), ('America/Ciudad_Juarez', 'America/Ciudad_Juarez'), ('America/Coral_Harbour', 'America/Coral_Harbour'), ('America/Cordoba', 'America/Cordoba'), ('America/Costa_Rica', 'America/Costa_Rica'), ('America/Creston', 'America/Creston'), ('America/Cuiaba', 'America/Cuiaba'), ('America/Curacao', 'America/Curacao'), ('America/Danmarkshavn', 'America/Danmarkshavn'), ('America/Dawson', 'America/Dawson'), ('America/Dawson_Creek', 'America/Dawson_Creek'), ('America/Denver', 'America/Denver'), ('America/Detroit', 'America/Detroit'), ('America/Dominica', 'America/Dominica'), ('America/Edmonton', 'America/Edmonton'), ('America/Eirunepe', 'America/Eirunepe'), ('America/El_Salvador', 'America/El_Salvador'), ('America/Fort_Nelson', 'America/Fort_Nelson'), ('America/Fortaleza', 'America/Fortaleza'), ('America/Glace_Bay', 'America/Glace_Bay'), ('America/Godthab', 'America/Godthab'), ('America/Goose_Bay', 'America/Goose_Bay'), ('America/Grand_Turk', 'America/Grand_Turk'), ('America/Grenada', 'America/Grenada'), ('America/Guadeloupe', 'America/Guadeloupe'), ('America/Guatemala', 'America/Guatemala'), ('America/Guayaquil', 'America/Guayaquil'), ('America/Guyana', 'America/Guyana'), ('America/Halifax', 'America/Halifax'), ('America/Havana', 'America/Havana'), ('America/Hermosillo', 'America/Hermosillo'), ('America/Indiana/Knox', 'America/Indiana/Knox'), ('America/Indiana/Marengo', 'America/Indiana/Marengo'), ('America/Indiana/Petersburg', 'America/Indiana/Petersburg'), ('America/Indiana/Tell_City', 'America/Indiana/Tell_City'), ('America/Indiana/Vevay', 'America/Indiana/Vevay'), ('America/Indiana/Vincennes', 'America/Indiana/Vincennes'), ('America/Indiana/Winamac', 'America/Indiana/Winamac'), ('America/Indianapolis', 'America/Indianapolis'), ('America/Inuvik', 'America/Inuvik'), ('America/Iqaluit', 'America/Iqaluit'), ('America/Jamaica', 'America/Jamaica'), ('America/Jujuy', 'America/Jujuy'), ('America/Juneau', 'America/Juneau'), ('America/Kentucky/Monticello', 'America/Kentucky/Monticello'), ('America/Kralendijk', 'America/Kralendijk'), ('America/La_Paz', 'America/La_Paz'), ('America/Lima', 'America/Lima'), ('America/Los_Angeles', 'America/Los_Angeles'), ('America/Louisville', 'America/Louisville'), ('America/Lower_Princes', 'America/Lower_Princes'), ('America/Maceio', 'America/Maceio'), ('America/Managua', 'America/Managua'), ('America/Manaus', 'America/Manaus'), ('America/Marigot', 'America/Marigot'), ('America/Martinique', 'America/Martinique'), ('America/Matamoros', 'America/Matamoros'), ('America/Mazatlan', 'America/Mazatlan'), ('America/Mendoza', 'America/Mendoza'), ('America/Menominee', 'America/Menominee'), ('America/Merida', 'America/Merida'), ('America/Metlakatla', 'America/Metlakatla'), ('America/Mexico_City', 'America/Mexico_City'), ('America/Miquelon', 'America/Miquelon'), ('America/Moncton', 'America/Moncton'), ('America/Monterrey', 'America/Monterrey'), ('America/Montevideo', 'America/Montevideo'), ('America/Montserrat', 'America/Montserrat'), ('America/Nassau', 'America/Nassau'), ('America/New_York', 'America/New_York'), ('America/Nome', 'America/Nome'), ('America/Noronha', 'America/Noronha'), ('America/North_Dakota/Beulah', 'America/North_Dakota/Beulah'), ('America/North_Dakota/Center', 'America/North_Dakota/Center'), ('America/North_Dakota/New_Salem', 'America/North_Dakota/New_Salem'), ('America/Ojinaga', 'America/Ojinaga'), ('America/Panama', 'America/Panama'), ('America/Paramaribo', 'America/Paramaribo'), ('America/Phoenix', 'America/Phoenix'), ('America/Port-au-Prince', 'America/Port-au-Prince'), ('America/Port_of_Spain', 'America/Port_of_Spain'), ('America/Porto_Velho', 'America/Porto_Velho'), ('America/Puerto_Rico', 'America/Puerto_Rico'), ('America/Punta_Arenas', 'America/Punta_Arenas'), ('America/Rankin_Inlet', 'America/Rankin_Inlet'), ('America/Recife', 'America/Recife'), ('America/Regina', 'America/Regina'), ('America/Resolute', 'America/Resolute'), ('America/Rio_Branco', 'America/Rio_Branco'), ('America/Santarem', 'America/Santarem'), ('America/Santiago', 'America/Santiago'), ('America/Santo_Domingo', 'America/Santo_Domingo'), ('America/Sao_Paulo', 'America/Sao_Paulo'), ('America/Scoresbysund', 'America/Scoresbysund'), ('America/Sitka', 'America/Sitka'), ('America/St_Barthelemy', 'America/St_Barthelemy'), ('America/St_Johns', 'America/St_Johns'), ('America/St_Kitts', 'America/St_Kitts'), ('America/St_Lucia', 'America/St_Lucia'), ('America/St_Thomas', 'America/St_Thomas'), ('America/St_Vincent', 'America/St_Vincent'), ('America/Swift_Current', 'America/Swift_Current'), ('America/Tegucigalpa', 'America/Tegucigalpa'), ('America/Thule', 'America/Thule'), ('America/Tijuana', 'America/Tijuana'), ('America/Toronto', 'America/Toronto'), ('America/Tortola', 'America/Tortola'), ('America/Vancouver', 'America/Vancouver'), ('America/Whitehorse', 'America/Whitehorse'), ('America/Winnipeg', 'America/Winnipeg'), ('America/Yakutat', 'America/Yakutat'), ('Antarctica/Casey', 'Antarctica/Casey'), ('Antarctica/Davis', 'Antarctica/Davis'), ('Antarctica/DumontDUrville', 'Antarctica/DumontDUrville'), ('Antarctica/Macquarie', 'Antarctica/Macquarie'), ('Antarctica/Mawson', 'Antarctica/Mawson'), ('Antarctica/McMurdo', 'Antarctica/McMurdo'), ('Antarctica/Palmer', 'Antarctica/Palmer'), ('Antarctica/Rothera', 'Antarctica/Rothera'), ('Antarctica/Syowa', 'Antarctica/Syowa'), ('Antarctica/Troll', 'Antarctica/Troll'), ('Antarctica/Vostok', 'Antarctica/Vostok'), ('Arctic/Longyearbyen', 'Arctic/Longyearbyen'), ('Asia/Aden', 'Asia/Aden'), ('Asia/Almaty', 'Asia/Almaty'), ('Asia/Amman', 'Asia/Amman'), ('Asia/Anadyr', 'Asia/Anadyr'), ('Asia/Aqtau', 'Asia/Aqtau'), ('Asia/Aqtobe', 'Asia/Aqtobe'), ('Asia/Ashgabat', 'Asia/Ashgabat'), ('Asia/Atyrau', 'Asia/Atyrau'), ('Asia/Baghdad', 'Asia/Baghdad'), ('Asia/Bahrain', 'Asia/Bahrain'), ('Asia/Baku', 'Asia/Baku'), ('Asia/Bangkok', 'Asia/Bangkok'), ('Asia/Barnaul', 'Asia/Barnaul'), ('Asia/Beirut', 'Asia/Beirut'), ('Asia/Bishkek', 'Asia/Bishkek'), ('Asia/Brunei', 'Asia/Brunei'), ('Asia/Calcutta', 'Asia/Calcutta'), ('Asia/Chita', 'Asia/Chita'), ('Asia/Colombo', 'Asia/Colombo'), ('Asia/Damascus', 'Asia/Damascus'), ('Asia/Dhaka', 'Asia/Dhaka'), ('Asia/Dili', 'Asia/Dili'), ('Asia/Dubai', 'Asia/Dubai'), ('Asia/Dushanbe', 'Asia/Dushanbe'), ('Asia/Famagusta', 'Asia/Famagusta'), ('Asia/Gaza', 'Asia/Gaza'), ('Asia/Hebron', 'Asia/Hebron'), ('Asia/Hong_Kong', 'Asia/Hong_Kong'), ('Asia/Hovd', 'Asia/Hovd'), ('Asia/Irkutsk', 'Asia/Irkutsk'), ('Asia/Jakarta', 'Asia/Jakarta'), ('Asia/Jayapura', 'Asia/Jayapura'), ('Asia/Jerusalem', 'Asia/Jerusalem'), ('Asia/Kabul', 'Asia/Kabul'), ('Asia/Kamchatka', 'Asia/Kamchatka'), ('Asia/Karachi', 'Asia/Karachi'), ('Asia/Katmandu', 'Asia/Katmandu'), ('Asia/Khandyga', 'Asia/Khandyga'), ('Asia/Krasnoyarsk', 'Asia/Krasnoyarsk'), ('Asia/Kuala_Lumpur', 'Asia/Kuala_Lumpur'), ('Asia/Kuching', 'Asia/Kuching'), ('Asia/Kuwait', 'Asia/Kuwait'), ('Asia/Macau', 'Asia/Macau'), ('Asia/Magadan', 'Asia/Magadan'), ('Asia/Makassar', 'Asia/Makassar'), ('Asia/Manila', 'Asia/Manila'), ('Asia/Muscat', 'Asia/Muscat'), ('Asia/Nicosia', 'Asia/Nicosia'), ('Asia/Novokuznetsk', 'Asia/Novokuznetsk'), ('Asia/Novosibirsk', 'Asia/Novosibirsk'), ('Asia/Omsk', 'Asia/Omsk'), ('Asia/Oral', 'Asia/Oral'), ('Asia/Phnom_Penh', 'Asia/Phnom_Penh'), ('Asia/Pontianak', 'Asia/Pontianak'), ('Asia/Pyongyang', 'Asia/Pyongyang'), ('Asia/Qatar', 'Asia/Qatar'), ('Asia/Qostanay', 'Asia/Qostanay'), ('Asia/Qyzylorda', 'Asia/Qyzylorda'), ('Asia/Rangoon', 'Asia/Rangoon'), ('Asia/Riyadh', 'Asia/Riyadh'), ('Asia/Saigon', 'Asia/Saigon'), ('Asia/Sakhalin', 'Asia/Sakhalin'), ('Asia/Samarkand', 'Asia/Samarkand'), ('Asia/Seoul', 'Asia/Seoul'), ('Asia/Shanghai', 'Asia/Shanghai'), ('Asia/Singapore', 'Asia/Singapore'), ('Asia/Srednekolymsk', 'Asia/Srednekolymsk'), ('Asia/Taipei', 'Asia/Taipei'), ('Asia/Tashkent', 'Asia/Tashkent'), ('Asia/Tbilisi', 'Asia/Tbilisi'), ('Asia/Tehran', 'Asia/Tehran'), ('Asia/Thimphu', 'Asia/Thimphu'), ('Asia/Tokyo', 'Asia/Tokyo'), ('Asia/Tomsk', 'Asia/Tomsk'), ('Asia/Ulaanbaatar', 'Asia/Ulaanbaatar'), ('Asia/Urumqi', 'Asia/Urumqi'), ('Asia/Ust-Nera', 'Asia/Ust-Nera'), ('Asia/Vientiane', 'Asia/Vientiane'), ('Asia/Vladivostok', 'Asia/Vladivostok'), ('Asia/Yakutsk', 'Asia/Yakutsk'), ('Asia/Yekaterinburg', 'Asia/Yekaterinburg'), ('Asia/Yerevan', 'Asia/Yerevan'), ('Atlantic/Azores', 'Atlantic/Azores'), ('Atlantic/Bermuda', 'Atlantic/Bermuda'), ('Atlantic/Canary', 'Atlantic/Canary'), ('Atlantic/Cape_Verde', 'Atlantic/Cape_Verde'), ('Atlantic/Faeroe', 'Atlantic/Faeroe'), ('Atlantic/Madeira', 'Atlantic/Madeira'), ('Atlantic/Reykjavik', 'Atlantic/Reykjavik'), ('Atlantic/South_Georgia', 'Atlantic/South_Georgia'), ('Atlantic/St_Helena', 'Atlantic/St_Helena'), ('Atlantic/Stanley', 'Atlantic/Stanley'), ('Australia/Adelaide', 'Australia/Adelaide'), ('Australia/Brisbane', 'Australia/Brisbane'), ('Australia/Broken_Hill', 'Australia/Broken_Hill'), ('Australia/Darwin', 'Australia/Darwin'), ('Australia/Eucla', 'Australia/Eucla'), ('Australia/Hobart', 'Australia/Hobart'), ('Australia/Lindeman', 'Australia/Lindeman'), ('Australia/Lord_Howe', 'Australia/Lord_Howe'), ('Australia/Melbourne', 'Australia/Melbourne'), ('Australia/Perth', 'Australia/Perth'), ('Australia/Sydney', 'Australia/Sydney'), ('Europe/Amsterdam', 'Europe/Amsterdam'), ('Europe/Andorra', 'Europe/Andorra'), ('Europe/Astrakhan', 'Europe/Astrakhan'), ('Europe/Athens', 'Europe/Athens'), ('Europe/Belgrade', 'Europe/Belgrade'), ('Europe/Berlin', 'Europe/Berlin'), ('Europe/Bratislava', 'Europe/Bratislava'), ('Europe/Brussels', 'Europe/Brussels'), ('Europe/Bucharest', 'Europe/Bucharest'), ('Europe/Budapest', 'Europe/Budapest'), ('Europe/Busingen', 'Europe/Busingen'), ('Europe/Chisinau', 'Europe/Chisinau'), ('Europe/Copenhagen', 'Europe/Copenhagen'), ('Europe/Dublin', 'Europe/Dublin'), ('Europe/Gibraltar', 'Europe/Gibraltar'), ('Europe/Guernsey', 'Europe/Guernsey'), ('Europe/Helsinki', 'Europe/Helsinki'), ('Europe/Isle_of_Man', 'Europe/Isle_of_Man'), ('Europe/Istanbul', 'Europe/Istanbul'), ('Europe/Jersey', 'Europe/Jersey'), ('Europe/Kaliningrad', 'Europe/Kaliningrad'), ('Europe/Kiev', 'Europe/Kiev'), ('Europe/Kirov', 'Europe/Kirov'), ('Europe/Lisbon', 'Europe/Lisbon'), ('Europe/Ljubljana', 'Europe/Ljubljana'), ('Europe/London', 'Europe/London'), ('Europe/Luxembourg', 'Europe/Luxembourg'), ('Europe/Madrid', 'Europe/Madrid'), ('Europe/Malta', 'Europe/Malta'), ('Europe/Mariehamn', 'Europe/Mariehamn'), ('Europe/Minsk', 'Europe/Minsk'), ('Europe/Monaco', 'Europe/Monaco'), ('Europe/Moscow', 'Europe/Moscow'), ('Europe/Oslo', 'Europe/Oslo'), ('Europe/Paris', 'Europe/Paris'), ('Europe/Podgorica', 'Europe/Podgorica'), ('Europe/Prague', 'Europe/Prague'), ('Europe/Riga', 'Europe/Riga'), ('Europe/Rome', 'Europe/Rome'), ('Europe/Samara', 'Europe/Samara'), ('Europe/San_Marino', 'Europe/San_Marino'), ('Europe/Sarajevo', 'Europe/Sarajevo'), ('Europe/Saratov', 'Europe/Saratov'), ('Europe/Simferopol', 'Europe/Simferopol'), ('Europe/Skopje', 'Europe/Skopje'), ('Europe/Sofia', 'Europe/Sofia'), ('Europe/Stockholm', 'Europe/Stockholm'), ('Europe/Tallinn', 'Europe/Tallinn'), ('Europe/Tirane', 'Europe/Tirane'), ('Europe/Ulyanovsk', 'Europe/Ulyanovsk'), ('Europe/Vaduz', 'Europe/Vaduz'), ('Europe/Vatican', 'Europe/Vatican'), ('Europe/Vienna', 'Europe/Vienna'), ('Europe/Vilnius', 'Europe/Vilnius'), ('Europe/Volgograd', 'Europe/Volgograd'), ('Europe/Warsaw', 'Europe/Warsaw'), ('Europe/Zagreb', 'Europe/Zagreb'), ('Europe/Zurich', 'Europe/Zurich'), ('Indian/Antananarivo', 'Indian/Antananarivo'), ('Indian/Chagos', 'Indian/Chagos'), ('Indian/Christmas', 'Indian/Christmas'), ('Indian/Cocos', 'Indian/Cocos'), ('Indian/Comoro', 'Indian/Comoro'), ('Indian/Kerguelen', 'Indian/Kerguelen'), ('Indian/Mahe', 'Indian/Mahe'), ('Indian/Maldives', 'Indian/Maldives'), ('Indian/Mauritius', 'Indian/Mauritius'), ('Indian/Mayotte', 'Indian/Mayotte'), ('Indian/Reunion', 'Indian/Reunion'), ('Pacific/Apia', 'Pacific/Apia'), ('Pacific/Auckland', 'Pacific/Auckland'), ('Pacific/Bougainville', 'Pacific/Bougainville'), ('Pacific/Chatham', 'Pacific/Chatham'), ('Pacific/Easter', 'Pacific/Easter'), ('Pacific/Efate', 'Pacific/Efate'), ('Pacific/Enderbury', 'Pacific/Enderbury'), ('Pacific/Fakaofo', 'Pacific/Fakaofo'), ('Pacific/Fiji', 'Pacific/Fiji'), ('Pacific/Funafuti', 'Pacific/Funafuti'), ('Pacific/Galapagos', 'Pacific/Galapagos'), ('Pacific/Gambier', 'Pacific/Gambier'), ('Pacific/Guadalcanal', 'Pacific/Guadalcanal'), ('Pacific/Guam', 'Pacific/Guam'), ('Pacific/Honolulu', 'Pacific/Honolulu'), ('Pacific/Kiritimati', 'Pacific/Kiritimati'), ('Pacific/Kosrae', 'Pacific/Kosrae'), ('Pacific/Kwajalein', 'Pacific/Kwajalein'), ('Pacific/Majuro', 'Pacific/Majuro'), ('Pacific/Marquesas', 'Pacific/Marquesas'), ('Pacific/Midway', 'Pacific/Midway'), ('Pacific/Nauru', 'Pacific/Nauru'), ('Pacific/Niue', 'Pacific/Niue'), ('Pacific/Norfolk', 'Pacific/Norfolk'), ('Pacific/Noumea', 'Pacific/Noumea'), ('Pacific/Pago_Pago', 'Pacific/Pago_Pago'), ('Pacific/Palau', 'Pacific/Palau'), ('Pacific/Pitcairn', 'Pacific/Pitcairn'), ('Pacific/Ponape', 'Pacific/Ponape'), ('Pacific/Port_Moresby', 'Pacific/Port_Moresby'), ('Pacific/Rarotonga', 'Pacific/Rarotonga'), ('Pacific/Saipan', 'Pacific/Saipan'), ('Pacific/Tahiti', 'Pacific/Tahiti'), ('Pacific/Tarawa', 'Pacific/Tarawa'), ('Pacific/Tongatapu', 'Pacific/Tongatapu'), ('Pacific/Truk', 'Pacific/Truk'), ('Pacific/Wake', 'Pacific/Wake'), ('Pacific/Wallis', 'Pacific/Wallis')], max_length=50, null=True), + ), + ] diff --git a/backend/server/adventures/migrations/0029_adventure_city_adventure_country_adventure_region.py b/backend/server/adventures/migrations/0029_adventure_city_adventure_country_adventure_region.py new file mode 100644 index 0000000..3df78e0 --- /dev/null +++ b/backend/server/adventures/migrations/0029_adventure_city_adventure_country_adventure_region.py @@ -0,0 +1,30 @@ +# Generated by Django 5.0.11 on 2025-05-22 22:48 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0028_lodging_timezone'), + ('worldtravel', '0015_city_insert_id_country_insert_id_region_insert_id'), + ] + + operations = [ + migrations.AddField( + model_name='adventure', + name='city', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.city'), + ), + migrations.AddField( + model_name='adventure', + name='country', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.country'), + ), + migrations.AddField( + model_name='adventure', + name='region', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='worldtravel.region'), + ), + ] diff --git a/backend/server/adventures/migrations/0030_set_end_date_equal_start.py b/backend/server/adventures/migrations/0030_set_end_date_equal_start.py new file mode 100644 index 0000000..55d5f93 --- /dev/null +++ b/backend/server/adventures/migrations/0030_set_end_date_equal_start.py @@ -0,0 +1,18 @@ +from django.db import migrations + +def set_end_date_equal_to_start(apps, schema_editor): + Visit = apps.get_model('adventures', 'Visit') + for visit in Visit.objects.filter(end_date__isnull=True): + if visit.start_date: + visit.end_date = visit.start_date + visit.save() + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0029_adventure_city_adventure_country_adventure_region'), + ] + + operations = [ + migrations.RunPython(set_end_date_equal_to_start), + ] diff --git a/backend/server/adventures/migrations/0031_adventureimage_immich_id_alter_adventureimage_image_and_more.py b/backend/server/adventures/migrations/0031_adventureimage_immich_id_alter_adventureimage_image_and_more.py new file mode 100644 index 0000000..75ebb60 --- /dev/null +++ b/backend/server/adventures/migrations/0031_adventureimage_immich_id_alter_adventureimage_image_and_more.py @@ -0,0 +1,31 @@ +# Generated by Django 5.2.1 on 2025-06-01 16:57 + +import adventures.models +import django_resized.forms +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0030_set_end_date_equal_start'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='adventureimage', + name='immich_id', + field=models.CharField(blank=True, max_length=200, null=True), + ), + migrations.AlterField( + model_name='adventureimage', + name='image', + field=django_resized.forms.ResizedImageField(blank=True, crop=None, force_format='WEBP', keep_meta=True, null=True, quality=75, scale=None, size=[1920, 1080], upload_to=adventures.models.PathAndRename('images/')), + ), + migrations.AddConstraint( + model_name='adventureimage', + constraint=models.CheckConstraint(condition=models.Q(models.Q(('image__isnull', False), ('immich_id__isnull', True)), models.Q(('image__isnull', True), ('immich_id__isnull', False)), _connector='OR'), name='image_xor_immich_id'), + ), + ] diff --git a/backend/server/adventures/migrations/0032_remove_adventureimage_image_xor_immich_id.py b/backend/server/adventures/migrations/0032_remove_adventureimage_image_xor_immich_id.py new file mode 100644 index 0000000..2ae8076 --- /dev/null +++ b/backend/server/adventures/migrations/0032_remove_adventureimage_image_xor_immich_id.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.1 on 2025-06-01 17:18 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0031_adventureimage_immich_id_alter_adventureimage_image_and_more'), + ] + + operations = [ + migrations.RemoveConstraint( + model_name='adventureimage', + name='image_xor_immich_id', + ), + ] diff --git a/backend/server/adventures/migrations/0033_adventureimage_unique_immich_id_per_user.py b/backend/server/adventures/migrations/0033_adventureimage_unique_immich_id_per_user.py new file mode 100644 index 0000000..d3b1bb5 --- /dev/null +++ b/backend/server/adventures/migrations/0033_adventureimage_unique_immich_id_per_user.py @@ -0,0 +1,19 @@ +# Generated by Django 5.2.1 on 2025-06-02 02:31 + +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0032_remove_adventureimage_image_xor_immich_id'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddConstraint( + model_name='adventureimage', + constraint=models.UniqueConstraint(fields=('immich_id', 'user_id'), name='unique_immich_id_per_user'), + ), + ] diff --git a/backend/server/adventures/migrations/0034_remove_adventureimage_unique_immich_id_per_user.py b/backend/server/adventures/migrations/0034_remove_adventureimage_unique_immich_id_per_user.py new file mode 100644 index 0000000..52b3e52 --- /dev/null +++ b/backend/server/adventures/migrations/0034_remove_adventureimage_unique_immich_id_per_user.py @@ -0,0 +1,17 @@ +# Generated by Django 5.2.1 on 2025-06-02 02:44 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0033_adventureimage_unique_immich_id_per_user'), + ] + + operations = [ + migrations.RemoveConstraint( + model_name='adventureimage', + name='unique_immich_id_per_user', + ), + ] diff --git a/backend/server/adventures/migrations/0035_remove_adventure_collection_adventure_collections.py b/backend/server/adventures/migrations/0035_remove_adventure_collection_adventure_collections.py new file mode 100644 index 0000000..59d3580 --- /dev/null +++ b/backend/server/adventures/migrations/0035_remove_adventure_collection_adventure_collections.py @@ -0,0 +1,59 @@ +# Generated by Django 5.2.1 on 2025-06-10 03:04 + +from django.db import migrations, models + + +def migrate_collection_relationships(apps, schema_editor): + """ + Migrate existing ForeignKey relationships to ManyToMany relationships + """ + Adventure = apps.get_model('adventures', 'Adventure') + + # Get all adventures that have a collection assigned + adventures_with_collections = Adventure.objects.filter(collection__isnull=False) + + for adventure in adventures_with_collections: + # Add the existing collection to the new many-to-many field + adventure.collections.add(adventure.collection_id) + + +def reverse_migrate_collection_relationships(apps, schema_editor): + """ + Reverse migration - convert first collection back to ForeignKey + Note: This will only preserve the first collection if an adventure has multiple + """ + Adventure = apps.get_model('adventures', 'Adventure') + + for adventure in Adventure.objects.all(): + first_collection = adventure.collections.first() + if first_collection: + adventure.collection = first_collection + adventure.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0034_remove_adventureimage_unique_immich_id_per_user'), + ] + + operations = [ + # First, add the new ManyToMany field + migrations.AddField( + model_name='adventure', + name='collections', + field=models.ManyToManyField(blank=True, related_name='adventures', to='adventures.collection'), + ), + + # Migrate existing data from old field to new field + migrations.RunPython( + migrate_collection_relationships, + reverse_migrate_collection_relationships + ), + + # Finally, remove the old ForeignKey field + migrations.RemoveField( + model_name='adventure', + name='collection', + ), + ] \ No newline at end of file diff --git a/backend/server/adventures/migrations/migrate_images.py b/backend/server/adventures/migrations/migrate_images.py new file mode 100644 index 0000000..9ef361f --- /dev/null +++ b/backend/server/adventures/migrations/migrate_images.py @@ -0,0 +1,29 @@ +from django.db import migrations + +def move_images_to_new_model(apps, schema_editor): + Adventure = apps.get_model('adventures', 'Adventure') + AdventureImage = apps.get_model('adventures', 'AdventureImage') + + for adventure in Adventure.objects.all(): + if adventure.image: + AdventureImage.objects.create( + adventure=adventure, + image=adventure.image, + user_id=adventure.user_id, + ) + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0001_initial'), + ('adventures', '0002_adventureimage'), + ] + + operations = [ + migrations.RunPython(move_images_to_new_model), + migrations.RemoveField( + model_name='Adventure', + name='image', + ), + ] \ No newline at end of file diff --git a/backend/server/adventures/migrations/migrate_visits_categories.py b/backend/server/adventures/migrations/migrate_visits_categories.py new file mode 100644 index 0000000..c9afb4a --- /dev/null +++ b/backend/server/adventures/migrations/migrate_visits_categories.py @@ -0,0 +1,31 @@ +from django.db import migrations +from django.db import migrations, models + +def move_images_to_new_model(apps, schema_editor): + Adventure = apps.get_model('adventures', 'Adventure') + Visit = apps.get_model('adventures', 'Visit') + + for adventure in Adventure.objects.all(): + # if the type is visited and there is no date, set note to 'No date provided.' + note = 'No date provided.' if adventure.type == 'visited' and not adventure.date else '' + if adventure.date or adventure.type == 'visited': + Visit.objects.create( + adventure=adventure, + start_date=adventure.date, + end_date=adventure.end_date, + notes=note, + ) + if adventure.type == 'visited' or adventure.type == 'planned': + adventure.type = 'general' + adventure.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('adventures', '0007_visit_model'), + ] + + operations = [ + migrations.RunPython(move_images_to_new_model), + ] \ No newline at end of file diff --git a/backend/server/adventures/models.py b/backend/server/adventures/models.py index 3ff173a..40bb680 100644 --- a/backend/server/adventures/models.py +++ b/backend/server/adventures/models.py @@ -1,39 +1,741 @@ +from django.core.exceptions import ValidationError +import os +from typing import Iterable +import uuid from django.db import models - +from django.utils.deconstruct import deconstructible +from adventures.managers import AdventureManager +import threading from django.contrib.auth import get_user_model from django.contrib.postgres.fields import ArrayField from django.forms import ValidationError from django_resized import ResizedImageField +from worldtravel.models import City, Country, Region, VisitedCity, VisitedRegion +from django.core.exceptions import ValidationError +from django.utils import timezone + +def background_geocode_and_assign(adventure_id: str): + print(f"[Adventure Geocode Thread] Starting geocode for adventure {adventure_id}") + try: + adventure = Adventure.objects.get(id=adventure_id) + if not (adventure.latitude and adventure.longitude): + return + + from adventures.geocoding import reverse_geocode # or wherever you defined it + is_visited = adventure.is_visited_status() + result = reverse_geocode(adventure.latitude, adventure.longitude, adventure.user_id) + + if 'region_id' in result: + region = Region.objects.filter(id=result['region_id']).first() + if region: + adventure.region = region + if is_visited: + VisitedRegion.objects.get_or_create(user_id=adventure.user_id, region=region) + + if 'city_id' in result: + city = City.objects.filter(id=result['city_id']).first() + if city: + adventure.city = city + if is_visited: + VisitedCity.objects.get_or_create(user_id=adventure.user_id, city=city) + + if 'country_id' in result: + country = Country.objects.filter(country_code=result['country_id']).first() + if country: + adventure.country = country + + # Save updated location info + # Save updated location info, skip geocode threading + adventure.save(update_fields=["region", "city", "country"], _skip_geocode=True) + + # print(f"[Adventure Geocode Thread] Successfully processed {adventure_id}: {adventure.name} - {adventure.latitude}, {adventure.longitude}") + + except Exception as e: + # Optional: log or print the error + print(f"[Adventure Geocode Thread] Error processing {adventure_id}: {e}") + +def validate_file_extension(value): + import os + from django.core.exceptions import ValidationError + ext = os.path.splitext(value.name)[1] # [0] returns path+filename + valid_extensions = ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.mp4', '.mov', '.avi', '.mkv', '.mp3', '.wav', '.flac', '.ogg', '.m4a', '.wma', '.aac', '.opus', '.zip', '.rar', '.7z', '.tar', '.gz', '.bz2', '.xz', '.zst', '.lz4', '.lzma', '.lzo', '.z', '.tar.gz', '.tar.bz2', '.tar.xz', '.tar.zst', '.tar.lz4', '.tar.lzma', '.tar.lzo', '.tar.z', '.gpx', '.md'] + if not ext.lower() in valid_extensions: + raise ValidationError('Unsupported file extension.') ADVENTURE_TYPES = [ - ('visited', 'Visited'), - ('planned', 'Planned'), + ('general', 'General 🌍'), + ('outdoor', 'Outdoor 🏞️'), + ('lodging', 'Lodging 🛌'), + ('dining', 'Dining 🍽️'), + ('activity', 'Activity 🏄'), + ('attraction', 'Attraction 🎢'), + ('shopping', 'Shopping 🛍️'), + ('nightlife', 'Nightlife 🌃'), + ('event', 'Event 🎉'), + ('transportation', 'Transportation 🚗'), + ('culture', 'Culture 🎭'), + ('water_sports', 'Water Sports 🚤'), + ('hiking', 'Hiking 🥾'), + ('wildlife', 'Wildlife 🦒'), + ('historical_sites', 'Historical Sites 🏛️'), + ('music_concerts', 'Music & Concerts 🎶'), + ('fitness', 'Fitness 🏋️'), + ('art_museums', 'Art & Museums 🎨'), + ('festivals', 'Festivals 🎪'), + ('spiritual_journeys', 'Spiritual Journeys 🧘‍♀️'), + ('volunteer_work', 'Volunteer Work 🤝'), + ('other', 'Other') ] +TIMEZONES = [ + "Africa/Abidjan", + "Africa/Accra", + "Africa/Addis_Ababa", + "Africa/Algiers", + "Africa/Asmera", + "Africa/Bamako", + "Africa/Bangui", + "Africa/Banjul", + "Africa/Bissau", + "Africa/Blantyre", + "Africa/Brazzaville", + "Africa/Bujumbura", + "Africa/Cairo", + "Africa/Casablanca", + "Africa/Ceuta", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Douala", + "Africa/El_Aaiun", + "Africa/Freetown", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Johannesburg", + "Africa/Juba", + "Africa/Kampala", + "Africa/Khartoum", + "Africa/Kigali", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Libreville", + "Africa/Lome", + "Africa/Luanda", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Malabo", + "Africa/Maputo", + "Africa/Maseru", + "Africa/Mbabane", + "Africa/Mogadishu", + "Africa/Monrovia", + "Africa/Nairobi", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Africa/Porto-Novo", + "Africa/Sao_Tome", + "Africa/Tripoli", + "Africa/Tunis", + "Africa/Windhoek", + "America/Adak", + "America/Anchorage", + "America/Anguilla", + "America/Antigua", + "America/Araguaina", + "America/Argentina/La_Rioja", + "America/Argentina/Rio_Gallegos", + "America/Argentina/Salta", + "America/Argentina/San_Juan", + "America/Argentina/San_Luis", + "America/Argentina/Tucuman", + "America/Argentina/Ushuaia", + "America/Aruba", + "America/Asuncion", + "America/Bahia", + "America/Bahia_Banderas", + "America/Barbados", + "America/Belem", + "America/Belize", + "America/Blanc-Sablon", + "America/Boa_Vista", + "America/Bogota", + "America/Boise", + "America/Buenos_Aires", + "America/Cambridge_Bay", + "America/Campo_Grande", + "America/Cancun", + "America/Caracas", + "America/Catamarca", + "America/Cayenne", + "America/Cayman", + "America/Chicago", + "America/Chihuahua", + "America/Ciudad_Juarez", + "America/Coral_Harbour", + "America/Cordoba", + "America/Costa_Rica", + "America/Creston", + "America/Cuiaba", + "America/Curacao", + "America/Danmarkshavn", + "America/Dawson", + "America/Dawson_Creek", + "America/Denver", + "America/Detroit", + "America/Dominica", + "America/Edmonton", + "America/Eirunepe", + "America/El_Salvador", + "America/Fort_Nelson", + "America/Fortaleza", + "America/Glace_Bay", + "America/Godthab", + "America/Goose_Bay", + "America/Grand_Turk", + "America/Grenada", + "America/Guadeloupe", + "America/Guatemala", + "America/Guayaquil", + "America/Guyana", + "America/Halifax", + "America/Havana", + "America/Hermosillo", + "America/Indiana/Knox", + "America/Indiana/Marengo", + "America/Indiana/Petersburg", + "America/Indiana/Tell_City", + "America/Indiana/Vevay", + "America/Indiana/Vincennes", + "America/Indiana/Winamac", + "America/Indianapolis", + "America/Inuvik", + "America/Iqaluit", + "America/Jamaica", + "America/Jujuy", + "America/Juneau", + "America/Kentucky/Monticello", + "America/Kralendijk", + "America/La_Paz", + "America/Lima", + "America/Los_Angeles", + "America/Louisville", + "America/Lower_Princes", + "America/Maceio", + "America/Managua", + "America/Manaus", + "America/Marigot", + "America/Martinique", + "America/Matamoros", + "America/Mazatlan", + "America/Mendoza", + "America/Menominee", + "America/Merida", + "America/Metlakatla", + "America/Mexico_City", + "America/Miquelon", + "America/Moncton", + "America/Monterrey", + "America/Montevideo", + "America/Montserrat", + "America/Nassau", + "America/New_York", + "America/Nome", + "America/Noronha", + "America/North_Dakota/Beulah", + "America/North_Dakota/Center", + "America/North_Dakota/New_Salem", + "America/Ojinaga", + "America/Panama", + "America/Paramaribo", + "America/Phoenix", + "America/Port-au-Prince", + "America/Port_of_Spain", + "America/Porto_Velho", + "America/Puerto_Rico", + "America/Punta_Arenas", + "America/Rankin_Inlet", + "America/Recife", + "America/Regina", + "America/Resolute", + "America/Rio_Branco", + "America/Santarem", + "America/Santiago", + "America/Santo_Domingo", + "America/Sao_Paulo", + "America/Scoresbysund", + "America/Sitka", + "America/St_Barthelemy", + "America/St_Johns", + "America/St_Kitts", + "America/St_Lucia", + "America/St_Thomas", + "America/St_Vincent", + "America/Swift_Current", + "America/Tegucigalpa", + "America/Thule", + "America/Tijuana", + "America/Toronto", + "America/Tortola", + "America/Vancouver", + "America/Whitehorse", + "America/Winnipeg", + "America/Yakutat", + "Antarctica/Casey", + "Antarctica/Davis", + "Antarctica/DumontDUrville", + "Antarctica/Macquarie", + "Antarctica/Mawson", + "Antarctica/McMurdo", + "Antarctica/Palmer", + "Antarctica/Rothera", + "Antarctica/Syowa", + "Antarctica/Troll", + "Antarctica/Vostok", + "Arctic/Longyearbyen", + "Asia/Aden", + "Asia/Almaty", + "Asia/Amman", + "Asia/Anadyr", + "Asia/Aqtau", + "Asia/Aqtobe", + "Asia/Ashgabat", + "Asia/Atyrau", + "Asia/Baghdad", + "Asia/Bahrain", + "Asia/Baku", + "Asia/Bangkok", + "Asia/Barnaul", + "Asia/Beirut", + "Asia/Bishkek", + "Asia/Brunei", + "Asia/Calcutta", + "Asia/Chita", + "Asia/Colombo", + "Asia/Damascus", + "Asia/Dhaka", + "Asia/Dili", + "Asia/Dubai", + "Asia/Dushanbe", + "Asia/Famagusta", + "Asia/Gaza", + "Asia/Hebron", + "Asia/Hong_Kong", + "Asia/Hovd", + "Asia/Irkutsk", + "Asia/Jakarta", + "Asia/Jayapura", + "Asia/Jerusalem", + "Asia/Kabul", + "Asia/Kamchatka", + "Asia/Karachi", + "Asia/Katmandu", + "Asia/Khandyga", + "Asia/Krasnoyarsk", + "Asia/Kuala_Lumpur", + "Asia/Kuching", + "Asia/Kuwait", + "Asia/Macau", + "Asia/Magadan", + "Asia/Makassar", + "Asia/Manila", + "Asia/Muscat", + "Asia/Nicosia", + "Asia/Novokuznetsk", + "Asia/Novosibirsk", + "Asia/Omsk", + "Asia/Oral", + "Asia/Phnom_Penh", + "Asia/Pontianak", + "Asia/Pyongyang", + "Asia/Qatar", + "Asia/Qostanay", + "Asia/Qyzylorda", + "Asia/Rangoon", + "Asia/Riyadh", + "Asia/Saigon", + "Asia/Sakhalin", + "Asia/Samarkand", + "Asia/Seoul", + "Asia/Shanghai", + "Asia/Singapore", + "Asia/Srednekolymsk", + "Asia/Taipei", + "Asia/Tashkent", + "Asia/Tbilisi", + "Asia/Tehran", + "Asia/Thimphu", + "Asia/Tokyo", + "Asia/Tomsk", + "Asia/Ulaanbaatar", + "Asia/Urumqi", + "Asia/Ust-Nera", + "Asia/Vientiane", + "Asia/Vladivostok", + "Asia/Yakutsk", + "Asia/Yekaterinburg", + "Asia/Yerevan", + "Atlantic/Azores", + "Atlantic/Bermuda", + "Atlantic/Canary", + "Atlantic/Cape_Verde", + "Atlantic/Faeroe", + "Atlantic/Madeira", + "Atlantic/Reykjavik", + "Atlantic/South_Georgia", + "Atlantic/St_Helena", + "Atlantic/Stanley", + "Australia/Adelaide", + "Australia/Brisbane", + "Australia/Broken_Hill", + "Australia/Darwin", + "Australia/Eucla", + "Australia/Hobart", + "Australia/Lindeman", + "Australia/Lord_Howe", + "Australia/Melbourne", + "Australia/Perth", + "Australia/Sydney", + "Europe/Amsterdam", + "Europe/Andorra", + "Europe/Astrakhan", + "Europe/Athens", + "Europe/Belgrade", + "Europe/Berlin", + "Europe/Bratislava", + "Europe/Brussels", + "Europe/Bucharest", + "Europe/Budapest", + "Europe/Busingen", + "Europe/Chisinau", + "Europe/Copenhagen", + "Europe/Dublin", + "Europe/Gibraltar", + "Europe/Guernsey", + "Europe/Helsinki", + "Europe/Isle_of_Man", + "Europe/Istanbul", + "Europe/Jersey", + "Europe/Kaliningrad", + "Europe/Kiev", + "Europe/Kirov", + "Europe/Lisbon", + "Europe/Ljubljana", + "Europe/London", + "Europe/Luxembourg", + "Europe/Madrid", + "Europe/Malta", + "Europe/Mariehamn", + "Europe/Minsk", + "Europe/Monaco", + "Europe/Moscow", + "Europe/Oslo", + "Europe/Paris", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Riga", + "Europe/Rome", + "Europe/Samara", + "Europe/San_Marino", + "Europe/Sarajevo", + "Europe/Saratov", + "Europe/Simferopol", + "Europe/Skopje", + "Europe/Sofia", + "Europe/Stockholm", + "Europe/Tallinn", + "Europe/Tirane", + "Europe/Ulyanovsk", + "Europe/Vaduz", + "Europe/Vatican", + "Europe/Vienna", + "Europe/Vilnius", + "Europe/Volgograd", + "Europe/Warsaw", + "Europe/Zagreb", + "Europe/Zurich", + "Indian/Antananarivo", + "Indian/Chagos", + "Indian/Christmas", + "Indian/Cocos", + "Indian/Comoro", + "Indian/Kerguelen", + "Indian/Mahe", + "Indian/Maldives", + "Indian/Mauritius", + "Indian/Mayotte", + "Indian/Reunion", + "Pacific/Apia", + "Pacific/Auckland", + "Pacific/Bougainville", + "Pacific/Chatham", + "Pacific/Easter", + "Pacific/Efate", + "Pacific/Enderbury", + "Pacific/Fakaofo", + "Pacific/Fiji", + "Pacific/Funafuti", + "Pacific/Galapagos", + "Pacific/Gambier", + "Pacific/Guadalcanal", + "Pacific/Guam", + "Pacific/Honolulu", + "Pacific/Kiritimati", + "Pacific/Kosrae", + "Pacific/Kwajalein", + "Pacific/Majuro", + "Pacific/Marquesas", + "Pacific/Midway", + "Pacific/Nauru", + "Pacific/Niue", + "Pacific/Norfolk", + "Pacific/Noumea", + "Pacific/Pago_Pago", + "Pacific/Palau", + "Pacific/Pitcairn", + "Pacific/Ponape", + "Pacific/Port_Moresby", + "Pacific/Rarotonga", + "Pacific/Saipan", + "Pacific/Tahiti", + "Pacific/Tarawa", + "Pacific/Tongatapu", + "Pacific/Truk", + "Pacific/Wake", + "Pacific/Wallis" +] + +LODGING_TYPES = [ + ('hotel', 'Hotel'), + ('hostel', 'Hostel'), + ('resort', 'Resort'), + ('bnb', 'Bed & Breakfast'), + ('campground', 'Campground'), + ('cabin', 'Cabin'), + ('apartment', 'Apartment'), + ('house', 'House'), + ('villa', 'Villa'), + ('motel', 'Motel'), + ('other', 'Other') +] + +TRANSPORTATION_TYPES = [ + ('car', 'Car'), + ('plane', 'Plane'), + ('train', 'Train'), + ('bus', 'Bus'), + ('boat', 'Boat'), + ('bike', 'Bike'), + ('walking', 'Walking'), + ('other', 'Other') +] # Assuming you have a default user ID you want to use default_user_id = 1 # Replace with an actual user ID User = get_user_model() +class Visit(models.Model): + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + adventure = models.ForeignKey('Adventure', on_delete=models.CASCADE, related_name='visits') + start_date = models.DateTimeField(null=True, blank=True) + end_date = models.DateTimeField(null=True, blank=True) + timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True) + notes = models.TextField(blank=True, null=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def clean(self): + if self.start_date > self.end_date: + raise ValidationError('The start date must be before or equal to the end date.') + + def __str__(self): + return f"{self.adventure.name} - {self.start_date} to {self.end_date}" class Adventure(models.Model): - id = models.AutoField(primary_key=True) + #id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE, default=default_user_id) - type = models.CharField(max_length=100, choices=ADVENTURE_TYPES) + + category = models.ForeignKey('Category', on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=200) location = models.CharField(max_length=200, blank=True, null=True) activity_types = ArrayField(models.CharField( max_length=100), blank=True, null=True) description = models.TextField(blank=True, null=True) rating = models.FloatField(blank=True, null=True) - link = models.URLField(blank=True, null=True) - image = ResizedImageField(force_format="WEBP", quality=75, null=True, blank=True, upload_to='images/') - date = models.DateField(blank=True, null=True) + link = models.URLField(blank=True, null=True, max_length=2083) is_public = models.BooleanField(default=False) + longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + + city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True) + region = models.ForeignKey(Region, on_delete=models.SET_NULL, blank=True, null=True) + country = models.ForeignKey(Country, on_delete=models.SET_NULL, blank=True, null=True) + + # Changed from ForeignKey to ManyToManyField + collections = models.ManyToManyField('Collection', blank=True, related_name='adventures') + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + objects = AdventureManager() + + def is_visited_status(self): + current_date = timezone.now().date() + for visit in self.visits.all(): + start_date = visit.start_date.date() if isinstance(visit.start_date, timezone.datetime) else visit.start_date + end_date = visit.end_date.date() if isinstance(visit.end_date, timezone.datetime) else visit.end_date + if start_date and end_date and (start_date <= current_date): + return True + elif start_date and not end_date and (start_date <= current_date): + return True + return False + + def clean(self, skip_shared_validation=False): + """ + Validate model constraints. + skip_shared_validation: Skip validation when called by shared users + """ + # Skip validation if this is a shared user update + if skip_shared_validation: + return + + # Check collections after the instance is saved (in save method or separate validation) + if self.pk: # Only check if the instance has been saved + for collection in self.collections.all(): + if collection.is_public and not self.is_public: + raise ValidationError(f'Adventures associated with a public collection must be public. Collection: {collection.name} Adventure: {self.name}') + + # Only enforce same-user constraint for non-shared collections + if self.user_id != collection.user_id: + # Check if this is a shared collection scenario + # Allow if the adventure owner has access to the collection through sharing + if not collection.shared_with.filter(uuid=self.user_id.uuid).exists(): + raise ValidationError(f'Adventures must be associated with collections owned by the same user or shared collections. Collection owner: {collection.user_id.username} Adventure owner: {self.user_id.username}') + + if self.category: + if self.user_id != self.category.user_id: + raise ValidationError(f'Adventures must be associated with categories owned by the same user. Category owner: {self.category.user_id.username} Adventure owner: {self.user_id.username}') + + def save(self, force_insert=False, force_update=False, using=None, update_fields=None, _skip_geocode=False, _skip_shared_validation=False): + if force_insert and force_update: + raise ValueError("Cannot force both insert and updating in model saving.") + + if not self.category: + category, _ = Category.objects.get_or_create( + user_id=self.user_id, + name='general', + defaults={'display_name': 'General', 'icon': '🌍'} + ) + self.category = category + + result = super().save(force_insert, force_update, using, update_fields) + + # Validate collections after saving (since M2M relationships require saved instance) + if self.pk: + try: + self.clean(skip_shared_validation=_skip_shared_validation) + except ValidationError as e: + # If validation fails, you might want to handle this differently + # For now, we'll re-raise the error + raise e + + # ⛔ Skip threading if called from geocode background thread + if _skip_geocode: + return result + + if self.latitude and self.longitude: + thread = threading.Thread(target=background_geocode_and_assign, args=(str(self.id),)) + thread.daemon = True # Allows the thread to exit when the main program ends + thread.start() + + return result + + def __str__(self): + return self.name + +class Collection(models.Model): + #id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + name = models.CharField(max_length=200) + description = models.TextField(blank=True, null=True) + is_public = models.BooleanField(default=False) + created_at = models.DateTimeField(auto_now_add=True) + start_date = models.DateField(blank=True, null=True) + end_date = models.DateField(blank=True, null=True) + updated_at = models.DateTimeField(auto_now=True) + is_archived = models.BooleanField(default=False) + shared_with = models.ManyToManyField(User, related_name='shared_with', blank=True) + link = models.URLField(blank=True, null=True, max_length=2083) + + # if connected adventures are private and collection is public, raise an error + def clean(self): + if self.is_public and self.pk: # Only check if the instance has a primary key + # Updated to use the new related_name 'adventures' + for adventure in self.adventures.all(): + if not adventure.is_public: + raise ValidationError(f'Public collections cannot be associated with private adventures. Collection: {self.name} Adventure: {adventure.name}') + + def __str__(self): + return self.name + +class Transportation(models.Model): + #id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + type = models.CharField(max_length=100, choices=TRANSPORTATION_TYPES) + name = models.CharField(max_length=200) + description = models.TextField(blank=True, null=True) + rating = models.FloatField(blank=True, null=True) + link = models.URLField(blank=True, null=True) + date = models.DateTimeField(blank=True, null=True) + end_date = models.DateTimeField(blank=True, null=True) + start_timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True) + end_timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True) + flight_number = models.CharField(max_length=100, blank=True, null=True) + from_location = models.CharField(max_length=200, blank=True, null=True) + origin_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + origin_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + destination_latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + destination_longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + to_location = models.CharField(max_length=200, blank=True, null=True) + is_public = models.BooleanField(default=False) + collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def clean(self): + print(self.date) + if self.date and self.end_date and self.date > self.end_date: + raise ValidationError('The start date must be before the end date. Start date: ' + str(self.date) + ' End date: ' + str(self.end_date)) + + if self.collection: + if self.collection.is_public and not self.is_public: + raise ValidationError('Transportations associated with a public collection must be public. Collection: ' + self.collection.name + ' Transportation: ' + self.name) + if self.user_id != self.collection.user_id: + raise ValidationError('Transportations must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Transportation owner: ' + self.user_id.username) + + def __str__(self): + return self.name + +class Note(models.Model): + #id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + name = models.CharField(max_length=200) + content = models.TextField(blank=True, null=True) + links = ArrayField(models.URLField(), blank=True, null=True) + date = models.DateField(blank=True, null=True) + is_public = models.BooleanField(default=False) collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @@ -41,28 +743,167 @@ class Adventure(models.Model): def clean(self): if self.collection: if self.collection.is_public and not self.is_public: - raise ValidationError('Adventures associated with a public collection must be public. Collection: ' + self.trip.name + ' Adventure: ' + self.name) + raise ValidationError('Notes associated with a public collection must be public. Collection: ' + self.collection.name + ' Transportation: ' + self.name) if self.user_id != self.collection.user_id: - raise ValidationError('Adventures must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Adventure owner: ' + self.user_id.username) + raise ValidationError('Notes must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Transportation owner: ' + self.user_id.username) + + def __str__(self): + return self.name + +class Checklist(models.Model): + # id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + name = models.CharField(max_length=200) + date = models.DateField(blank=True, null=True) + is_public = models.BooleanField(default=False) + collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def clean(self): + if self.collection: + if self.collection.is_public and not self.is_public: + raise ValidationError('Checklists associated with a public collection must be public. Collection: ' + self.collection.name + ' Checklist: ' + self.name) + if self.user_id != self.collection.user_id: + raise ValidationError('Checklists must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Checklist owner: ' + self.user_id.username) def __str__(self): return self.name -class Collection(models.Model): - id = models.AutoField(primary_key=True) +class ChecklistItem(models.Model): + #id = models.AutoField(primary_key=True) + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) user_id = models.ForeignKey( User, on_delete=models.CASCADE, default=default_user_id) name = models.CharField(max_length=200) - description = models.TextField(blank=True, null=True) - is_public = models.BooleanField(default=False) + is_checked = models.BooleanField(default=False) + checklist = models.ForeignKey('Checklist', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) - # if connected adventures are private and collection is public, raise an error def clean(self): - if self.is_public and self.pk: # Only check if the instance has a primary key - for adventure in self.adventure_set.all(): - if not adventure.is_public: - raise ValidationError('Public collections cannot be associated with private adventures. Collection: ' + self.name + ' Adventure: ' + adventure.name) + if self.checklist.is_public and not self.checklist.is_public: + raise ValidationError('Checklist items associated with a public checklist must be public. Checklist: ' + self.checklist.name + ' Checklist item: ' + self.name) + if self.user_id != self.checklist.user_id: + raise ValidationError('Checklist items must be associated with checklists owned by the same user. Checklist owner: ' + self.checklist.user_id.username + ' Checklist item owner: ' + self.user_id.username) + + def __str__(self): + return self.name + +@deconstructible +class PathAndRename: + def __init__(self, path): + self.path = path + + def __call__(self, instance, filename): + ext = filename.split('.')[-1] + # Generate a new UUID for the filename + filename = f"{uuid.uuid4()}.{ext}" + return os.path.join(self.path, filename) + +class AdventureImage(models.Model): + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey(User, on_delete=models.CASCADE, default=default_user_id) + image = ResizedImageField( + force_format="WEBP", + quality=75, + upload_to=PathAndRename('images/'), + blank=True, + null=True, + ) + immich_id = models.CharField(max_length=200, null=True, blank=True) + adventure = models.ForeignKey(Adventure, related_name='images', on_delete=models.CASCADE) + is_primary = models.BooleanField(default=False) + + def clean(self): + + # One of image or immich_id must be set, but not both + has_image = bool(self.image and str(self.image).strip()) + has_immich_id = bool(self.immich_id and str(self.immich_id).strip()) + + if has_image and has_immich_id: + raise ValidationError("Cannot have both image file and Immich ID. Please provide only one.") + if not has_image and not has_immich_id: + raise ValidationError("Must provide either an image file or an Immich ID.") + + def save(self, *args, **kwargs): + # Clean empty strings to None for proper database storage + if not self.image: + self.image = None + if not self.immich_id or not str(self.immich_id).strip(): + self.immich_id = None + + self.full_clean() # This calls clean() method + super().save(*args, **kwargs) + + def __str__(self): + return self.image.url if self.image else f"Immich ID: {self.immich_id or 'No image'}" + +class Attachment(models.Model): + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + file = models.FileField(upload_to=PathAndRename('attachments/'),validators=[validate_file_extension]) + adventure = models.ForeignKey(Adventure, related_name='attachments', on_delete=models.CASCADE) + name = models.CharField(max_length=200, null=True, blank=True) + + def __str__(self): + return self.file.url + +class Category(models.Model): + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + name = models.CharField(max_length=200) + display_name = models.CharField(max_length=200) + icon = models.CharField(max_length=200, default='🌍') + + class Meta: + verbose_name_plural = 'Categories' + unique_together = ['name', 'user_id'] + + def clean(self) -> None: + self.name = self.name.lower().strip() + + return super().clean() + + + def __str__(self): + return self.name + ' - ' + self.display_name + ' - ' + self.icon + +class Lodging(models.Model): + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + user_id = models.ForeignKey( + User, on_delete=models.CASCADE, default=default_user_id) + name = models.CharField(max_length=200) + type = models.CharField(max_length=100, choices=LODGING_TYPES, default='other') + description = models.TextField(blank=True, null=True) + rating = models.FloatField(blank=True, null=True) + link = models.URLField(blank=True, null=True, max_length=2083) + check_in = models.DateTimeField(blank=True, null=True) + check_out = models.DateTimeField(blank=True, null=True) + timezone = models.CharField(max_length=50, choices=[(tz, tz) for tz in TIMEZONES], null=True, blank=True) + reservation_number = models.CharField(max_length=100, blank=True, null=True) + price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) + latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True) + location = models.CharField(max_length=200, blank=True, null=True) + is_public = models.BooleanField(default=False) + collection = models.ForeignKey('Collection', on_delete=models.CASCADE, blank=True, null=True) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + def clean(self): + if self.check_in and self.check_out and self.check_in > self.check_out: + raise ValidationError('The start date must be before the end date. Start date: ' + str(self.check_in) + ' End date: ' + str(self.check_out)) + + if self.collection: + if self.collection.is_public and not self.is_public: + raise ValidationError('Lodging associated with a public collection must be public. Collection: ' + self.collection.name + ' Loging: ' + self.name) + if self.user_id != self.collection.user_id: + raise ValidationError('Lodging must be associated with collections owned by the same user. Collection owner: ' + self.collection.user_id.username + ' Lodging owner: ' + self.user_id.username) def __str__(self): return self.name \ No newline at end of file diff --git a/backend/server/adventures/permissions.py b/backend/server/adventures/permissions.py index b4241c2..ce38f74 100644 --- a/backend/server/adventures/permissions.py +++ b/backend/server/adventures/permissions.py @@ -2,29 +2,99 @@ from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ - Custom permission to only allow owners of an object to edit it. + Owners can edit, others have read-only access. """ - def has_object_permission(self, request, view, obj): - # Read permissions are allowed to any request, - # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True - - # Write permissions are only allowed to the owner of the object. + # obj.user_id is FK to User, compare with request.user return obj.user_id == request.user class IsPublicReadOnly(permissions.BasePermission): """ - Custom permission to only allow read-only access to public objects, - and write access to the owner of the object. + Read-only if public or owner, write only for owner. """ - def has_object_permission(self, request, view, obj): - # Read permissions are allowed if the object is public if request.method in permissions.SAFE_METHODS: return obj.is_public or obj.user_id == request.user + return obj.user_id == request.user - # Write permissions are only allowed to the owner of the object - return obj.user_id == request.user \ No newline at end of file + +class CollectionShared(permissions.BasePermission): + """ + Allow full access if user is in shared_with of collection(s) or owner, + read-only if public or shared_with, + write only if owner or shared_with. + """ + def has_object_permission(self, request, view, obj): + user = request.user + if not user or not user.is_authenticated: + # Anonymous: only read public + return request.method in permissions.SAFE_METHODS and obj.is_public + + # Check if user is in shared_with of any collections related to the obj + # If obj is a Collection itself: + if hasattr(obj, 'shared_with'): + if obj.shared_with.filter(id=user.id).exists(): + return True + + # If obj is an Adventure (has collections M2M) + if hasattr(obj, 'collections'): + # Check if user is in shared_with of any related collection + shared_collections = obj.collections.filter(shared_with=user) + if shared_collections.exists(): + return True + + # Read permission if public or owner + if request.method in permissions.SAFE_METHODS: + return obj.is_public or obj.user_id == user + + # Write permission only if owner or shared user via collections + if obj.user_id == user: + return True + + if hasattr(obj, 'collections'): + if obj.collections.filter(shared_with=user).exists(): + return True + + # Default deny + return False + + +class IsOwnerOrSharedWithFullAccess(permissions.BasePermission): + """ + Full access for owners and users shared via collections, + read-only for others if public. + """ + def has_object_permission(self, request, view, obj): + user = request.user + if not user or not user.is_authenticated: + return request.method in permissions.SAFE_METHODS and obj.is_public + + # If safe method (read), allow if: + if request.method in permissions.SAFE_METHODS: + if obj.is_public: + return True + if obj.user_id == user: + return True + # If user in shared_with of any collection related to obj + if hasattr(obj, 'collections') and obj.collections.filter(shared_with=user).exists(): + return True + if hasattr(obj, 'collection') and obj.collection and obj.collection.shared_with.filter(id=user.id).exists(): + return True + if hasattr(obj, 'shared_with') and obj.shared_with.filter(id=user.id).exists(): + return True + return False + + # For write methods, allow if owner or shared user + if obj.user_id == user: + return True + if hasattr(obj, 'collections') and obj.collections.filter(shared_with=user).exists(): + return True + if hasattr(obj, 'collection') and obj.collection and obj.collection.shared_with.filter(id=user.id).exists(): + return True + if hasattr(obj, 'shared_with') and obj.shared_with.filter(id=user.id).exists(): + return True + + return False diff --git a/backend/server/adventures/serializers.py b/backend/server/adventures/serializers.py index 40f24bd..622e2eb 100644 --- a/backend/server/adventures/serializers.py +++ b/backend/server/adventures/serializers.py @@ -1,35 +1,412 @@ +from django.utils import timezone import os -from .models import Adventure, Collection +from .models import Adventure, AdventureImage, ChecklistItem, Collection, Note, Transportation, Checklist, Visit, Category, Attachment, Lodging from rest_framework import serializers +from main.utils import CustomModelSerializer +from users.serializers import CustomUserDetailsSerializer +from worldtravel.serializers import CountrySerializer, RegionSerializer, CitySerializer +from geopy.distance import geodesic +from integrations.models import ImmichIntegration -class AdventureSerializer(serializers.ModelSerializer): +class AdventureImageSerializer(CustomModelSerializer): class Meta: - model = Adventure - fields = '__all__' + model = AdventureImage + fields = ['id', 'image', 'adventure', 'is_primary', 'user_id', 'immich_id'] + read_only_fields = ['id', 'user_id'] + + def to_representation(self, instance): + # If immich_id is set, check for user integration once + integration = None + if instance.immich_id: + integration = ImmichIntegration.objects.filter(user=instance.user_id).first() + if not integration: + return None # Skip if Immich image but no integration + + # Base representation + representation = super().to_representation(instance) + + # Prepare public URL once + public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/').replace("'", "") + + if instance.immich_id: + # Use Immich integration URL + representation['image'] = f"{public_url}/api/integrations/immich/{integration.id}/get/{instance.immich_id}" + elif instance.image: + # Use local image URL + representation['image'] = f"{public_url}/media/{instance.image.name}" + + return representation + +class AttachmentSerializer(CustomModelSerializer): + extension = serializers.SerializerMethodField() + class Meta: + model = Attachment + fields = ['id', 'file', 'adventure', 'extension', 'name', 'user_id'] + read_only_fields = ['id', 'user_id'] + + def get_extension(self, obj): + return obj.file.name.split('.')[-1] def to_representation(self, instance): representation = super().to_representation(instance) - if instance.image: + if instance.file: public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/') - print(public_url) + #print(public_url) # remove any ' from the url public_url = public_url.replace("'", "") - representation['image'] = f"{public_url}/media/{instance.image.name}" + representation['file'] = f"{public_url}/media/{instance.file.name}" return representation - def validate_activity_types(self, value): - if value: - return [activity.lower() for activity in value] - return value +class CategorySerializer(serializers.ModelSerializer): + num_adventures = serializers.SerializerMethodField() + class Meta: + model = Category + fields = ['id', 'name', 'display_name', 'icon', 'num_adventures'] + read_only_fields = ['id', 'num_adventures'] + + def validate_name(self, value): + return value.lower() + + def create(self, validated_data): + user = self.context['request'].user + validated_data['name'] = validated_data['name'].lower() + return Category.objects.create(user_id=user, **validated_data) + + def update(self, instance, validated_data): + for attr, value in validated_data.items(): + setattr(instance, attr, value) + if 'name' in validated_data: + instance.name = validated_data['name'].lower() + instance.save() + return instance -class CollectionSerializer(serializers.ModelSerializer): - adventures = AdventureSerializer(many=True, read_only=True, source='adventure_set') + def get_num_adventures(self, obj): + return Adventure.objects.filter(category=obj, user_id=obj.user_id).count() + +class VisitSerializer(serializers.ModelSerializer): + + class Meta: + model = Visit + fields = ['id', 'start_date', 'end_date', 'timezone', 'notes'] + read_only_fields = ['id'] + +class AdventureSerializer(CustomModelSerializer): + images = serializers.SerializerMethodField() + visits = VisitSerializer(many=True, read_only=False, required=False) + attachments = AttachmentSerializer(many=True, read_only=True) + category = CategorySerializer(read_only=False, required=False) + is_visited = serializers.SerializerMethodField() + user = serializers.SerializerMethodField() + country = CountrySerializer(read_only=True) + region = RegionSerializer(read_only=True) + city = CitySerializer(read_only=True) + collections = serializers.PrimaryKeyRelatedField( + many=True, + queryset=Collection.objects.all(), + required=False + ) + + class Meta: + model = Adventure + fields = [ + 'id', 'user_id', 'name', 'description', 'rating', 'activity_types', 'location', + 'is_public', 'collections', 'created_at', 'updated_at', 'images', 'link', 'longitude', + 'latitude', 'visits', 'is_visited', 'category', 'attachments', 'user', 'city', 'country', 'region' + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'is_visited', 'user'] + + def get_images(self, obj): + serializer = AdventureImageSerializer(obj.images.all(), many=True, context=self.context) + # Filter out None values from the serialized data + return [image for image in serializer.data if image is not None] + + def validate_collections(self, collections): + """Validate that collections belong to the same user""" + if not collections: + return collections + + user = self.context['request'].user + for collection in collections: + if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists(): + raise serializers.ValidationError( + f"Collection '{collection.name}' does not belong to the current user." + ) + return collections + + def validate_category(self, category_data): + if isinstance(category_data, Category): + return category_data + if category_data: + user = self.context['request'].user + name = category_data.get('name', '').lower() + existing_category = Category.objects.filter(user_id=user, name=name).first() + if existing_category: + return existing_category + category_data['name'] = name + return category_data + + def get_or_create_category(self, category_data): + user = self.context['request'].user + + if isinstance(category_data, Category): + return category_data + + if isinstance(category_data, dict): + name = category_data.get('name', '').lower() + display_name = category_data.get('display_name', name) + icon = category_data.get('icon', '🌍') + else: + name = category_data.name.lower() + display_name = category_data.display_name + icon = category_data.icon + + category, created = Category.objects.get_or_create( + user_id=user, + name=name, + defaults={ + 'display_name': display_name, + 'icon': icon + } + ) + return category + + def get_user(self, obj): + user = obj.user_id + return CustomUserDetailsSerializer(user).data + + def get_is_visited(self, obj): + return obj.is_visited_status() + + def create(self, validated_data): + visits_data = validated_data.pop('visits', None) + category_data = validated_data.pop('category', None) + collections_data = validated_data.pop('collections', []) + + print(category_data) + adventure = Adventure.objects.create(**validated_data) + + # Handle visits + for visit_data in visits_data: + Visit.objects.create(adventure=adventure, **visit_data) + + # Handle category + if category_data: + category = self.get_or_create_category(category_data) + adventure.category = category + + # Handle collections - set after adventure is saved + if collections_data: + adventure.collections.set(collections_data) + + adventure.save() + + return adventure + + def update(self, instance, validated_data): + has_visits = 'visits' in validated_data + visits_data = validated_data.pop('visits', []) + category_data = validated_data.pop('category', None) + + collections_data = validated_data.pop('collections', None) + + # Update regular fields + for attr, value in validated_data.items(): + setattr(instance, attr, value) + + # Handle category - ONLY allow the adventure owner to change categories + user = self.context['request'].user + if category_data and instance.user_id == user: + # Only the owner can set categories + category = self.get_or_create_category(category_data) + instance.category = category + # If not the owner, ignore category changes + + # Handle collections - only update if collections were provided + if collections_data is not None: + instance.collections.set(collections_data) + + # Handle visits + if has_visits: + current_visits = instance.visits.all() + current_visit_ids = set(current_visits.values_list('id', flat=True)) + + updated_visit_ids = set() + for visit_data in visits_data: + visit_id = visit_data.get('id') + if visit_id and visit_id in current_visit_ids: + visit = current_visits.get(id=visit_id) + for attr, value in visit_data.items(): + setattr(visit, attr, value) + visit.save() + updated_visit_ids.add(visit_id) + else: + new_visit = Visit.objects.create(adventure=instance, **visit_data) + updated_visit_ids.add(new_visit.id) + + visits_to_delete = current_visit_ids - updated_visit_ids + instance.visits.filter(id__in=visits_to_delete).delete() + + # call save on the adventure to update the updated_at field and trigger any geocoding + instance.save() + + return instance + +class TransportationSerializer(CustomModelSerializer): + distance = serializers.SerializerMethodField() + + class Meta: + model = Transportation + fields = [ + 'id', 'user_id', 'type', 'name', 'description', 'rating', + 'link', 'date', 'flight_number', 'from_location', 'to_location', + 'is_public', 'collection', 'created_at', 'updated_at', 'end_date', + 'origin_latitude', 'origin_longitude', 'destination_latitude', 'destination_longitude', + 'start_timezone', 'end_timezone', 'distance' # ✅ Add distance here + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'distance'] + + def get_distance(self, obj): + if ( + obj.origin_latitude and obj.origin_longitude and + obj.destination_latitude and obj.destination_longitude + ): + try: + origin = (float(obj.origin_latitude), float(obj.origin_longitude)) + destination = (float(obj.destination_latitude), float(obj.destination_longitude)) + return round(geodesic(origin, destination).km, 2) + except ValueError: + return None + return None + +class LodgingSerializer(CustomModelSerializer): + + class Meta: + model = Lodging + fields = [ + 'id', 'user_id', 'name', 'description', 'rating', 'link', 'check_in', 'check_out', + 'reservation_number', 'price', 'latitude', 'longitude', 'location', 'is_public', + 'collection', 'created_at', 'updated_at', 'type', 'timezone' + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id'] + +class NoteSerializer(CustomModelSerializer): + + class Meta: + model = Note + fields = [ + 'id', 'user_id', 'name', 'content', 'date', 'links', + 'is_public', 'collection', 'created_at', 'updated_at' + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id'] + +class ChecklistItemSerializer(CustomModelSerializer): + class Meta: + model = ChecklistItem + fields = [ + 'id', 'user_id', 'name', 'is_checked', 'checklist', 'created_at', 'updated_at' + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id', 'checklist'] + +class ChecklistSerializer(CustomModelSerializer): + items = ChecklistItemSerializer(many=True, source='checklistitem_set') + + class Meta: + model = Checklist + fields = [ + 'id', 'user_id', 'name', 'date', 'is_public', 'collection', 'created_at', 'updated_at', 'items' + ] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id'] + + def create(self, validated_data): + items_data = validated_data.pop('checklistitem_set') + checklist = Checklist.objects.create(**validated_data) + + for item_data in items_data: + # Remove user_id from item_data to avoid constraint issues + item_data.pop('user_id', None) + # Set user_id from the parent checklist + ChecklistItem.objects.create( + checklist=checklist, + user_id=checklist.user_id, + **item_data + ) + return checklist + + def update(self, instance, validated_data): + items_data = validated_data.pop('checklistitem_set', []) + + # Update Checklist fields + for attr, value in validated_data.items(): + setattr(instance, attr, value) + instance.save() + + # Get current items + current_items = instance.checklistitem_set.all() + current_item_ids = set(current_items.values_list('id', flat=True)) + + # Update or create items + updated_item_ids = set() + for item_data in items_data: + # Remove user_id from item_data to avoid constraint issues + item_data.pop('user_id', None) + + item_id = item_data.get('id') + if item_id: + if item_id in current_item_ids: + item = current_items.get(id=item_id) + for attr, value in item_data.items(): + setattr(item, attr, value) + item.save() + updated_item_ids.add(item_id) + else: + # If ID is provided but doesn't exist, create new item + ChecklistItem.objects.create( + checklist=instance, + user_id=instance.user_id, + **item_data + ) + else: + # If no ID is provided, create new item + ChecklistItem.objects.create( + checklist=instance, + user_id=instance.user_id, + **item_data + ) + + # Delete items that are not in the updated data + items_to_delete = current_item_ids - updated_item_ids + instance.checklistitem_set.filter(id__in=items_to_delete).delete() + + return instance + + def validate(self, data): + # Check if the collection is public and the checklist is not + collection = data.get('collection') + is_public = data.get('is_public', False) + if collection and collection.is_public and not is_public: + raise serializers.ValidationError( + 'Checklists associated with a public collection must be public.' + ) + return data + +class CollectionSerializer(CustomModelSerializer): + adventures = AdventureSerializer(many=True, read_only=True) + transportations = TransportationSerializer(many=True, read_only=True, source='transportation_set') + notes = NoteSerializer(many=True, read_only=True, source='note_set') + checklists = ChecklistSerializer(many=True, read_only=True, source='checklist_set') + lodging = LodgingSerializer(many=True, read_only=True, source='lodging_set') class Meta: model = Collection - # fields are all plus the adventures field - fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures'] + fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures', 'created_at', 'start_date', 'end_date', 'transportations', 'notes', 'updated_at', 'checklists', 'is_archived', 'shared_with', 'link', 'lodging'] + read_only_fields = ['id', 'created_at', 'updated_at', 'user_id'] - - \ No newline at end of file + def to_representation(self, instance): + representation = super().to_representation(instance) + # Make it display the user uuid for the shared users instead of the PK + shared_uuids = [] + for user in instance.shared_with.all(): + shared_uuids.append(str(user.uuid)) + representation['shared_with'] = shared_uuids + return representation \ No newline at end of file diff --git a/backend/server/adventures/signals.py b/backend/server/adventures/signals.py new file mode 100644 index 0000000..b8501c8 --- /dev/null +++ b/backend/server/adventures/signals.py @@ -0,0 +1,23 @@ +from django.db.models.signals import m2m_changed +from django.dispatch import receiver +from adventures.models import Adventure + +@receiver(m2m_changed, sender=Adventure.collections.through) +def update_adventure_publicity(sender, instance, action, **kwargs): + """ + Signal handler to update adventure publicity when collections are added/removed + """ + # Only process when collections are added or removed + if action in ('post_add', 'post_remove', 'post_clear'): + collections = instance.collections.all() + + if collections.exists(): + # If any collection is public, make the adventure public + has_public_collection = collections.filter(is_public=True).exists() + + if has_public_collection and not instance.is_public: + instance.is_public = True + instance.save(update_fields=['is_public']) + elif not has_public_collection and instance.is_public: + instance.is_public = False + instance.save(update_fields=['is_public']) diff --git a/backend/server/adventures/urls.py b/backend/server/adventures/urls.py index 10cdb1a..d1bf6cb 100644 --- a/backend/server/adventures/urls.py +++ b/backend/server/adventures/urls.py @@ -1,6 +1,6 @@ from django.urls import include, path from rest_framework.routers import DefaultRouter -from .views import AdventureViewSet, CollectionViewSet, StatsViewSet, GenerateDescription, ActivityTypesView +from adventures.views import * router = DefaultRouter() router.register(r'adventures', AdventureViewSet, basename='adventures') @@ -8,7 +8,17 @@ router.register(r'collections', CollectionViewSet, basename='collections') router.register(r'stats', StatsViewSet, basename='stats') router.register(r'generate', GenerateDescription, basename='generate') router.register(r'activity-types', ActivityTypesView, basename='activity-types') - +router.register(r'transportations', TransportationViewSet, basename='transportations') +router.register(r'notes', NoteViewSet, basename='notes') +router.register(r'checklists', ChecklistViewSet, basename='checklists') +router.register(r'images', AdventureImageViewSet, basename='images') +router.register(r'reverse-geocode', ReverseGeocodeViewSet, basename='reverse-geocode') +router.register(r'categories', CategoryViewSet, basename='categories') +router.register(r'ics-calendar', IcsCalendarGeneratorViewSet, basename='ics-calendar') +router.register(r'search', GlobalSearchView, basename='search') +router.register(r'attachments', AttachmentViewSet, basename='attachments') +router.register(r'lodging', LodgingViewSet, basename='lodging') +router.register(r'recommendations', RecommendationsViewSet, basename='recommendations') urlpatterns = [ # Include the router under the 'api/' prefix diff --git a/backend/server/adventures/utils/file_permissions.py b/backend/server/adventures/utils/file_permissions.py new file mode 100644 index 0000000..b9a63f0 --- /dev/null +++ b/backend/server/adventures/utils/file_permissions.py @@ -0,0 +1,48 @@ +from adventures.models import AdventureImage, Attachment + +protected_paths = ['images/', 'attachments/'] + +def checkFilePermission(fileId, user, mediaType): + if mediaType not in protected_paths: + return True + if mediaType == 'images/': + try: + # Construct the full relative path to match the database field + image_path = f"images/{fileId}" + # Fetch the AdventureImage object + adventure = AdventureImage.objects.get(image=image_path).adventure + if adventure.is_public: + return True + elif adventure.user_id == user: + return True + elif adventure.collections.exists(): + # Check if the user is in any collection's shared_with list + for collection in adventure.collections.all(): + if collection.shared_with.filter(id=user.id).exists(): + return True + return False + else: + return False + except AdventureImage.DoesNotExist: + return False + elif mediaType == 'attachments/': + try: + # Construct the full relative path to match the database field + attachment_path = f"attachments/{fileId}" + # Fetch the Attachment object + attachment = Attachment.objects.get(file=attachment_path) + adventure = attachment.adventure + if adventure.is_public: + return True + elif adventure.user_id == user: + return True + elif adventure.collections.exists(): + # Check if the user is in any collection's shared_with list + for collection in adventure.collections.all(): + if collection.shared_with.filter(id=user.id).exists(): + return True + return False + else: + return False + except Attachment.DoesNotExist: + return False \ No newline at end of file diff --git a/backend/server/adventures/utils/pagination.py b/backend/server/adventures/utils/pagination.py new file mode 100644 index 0000000..4337190 --- /dev/null +++ b/backend/server/adventures/utils/pagination.py @@ -0,0 +1,6 @@ +from rest_framework.pagination import PageNumberPagination + +class StandardResultsSetPagination(PageNumberPagination): + page_size = 25 + page_size_query_param = 'page_size' + max_page_size = 1000 \ No newline at end of file diff --git a/backend/server/adventures/views.py b/backend/server/adventures/views.py deleted file mode 100644 index b9fcb30..0000000 --- a/backend/server/adventures/views.py +++ /dev/null @@ -1,380 +0,0 @@ -import requests -from django.db import transaction -from rest_framework.decorators import action -from rest_framework import viewsets -from django.db.models.functions import Lower -from rest_framework.response import Response -from .models import Adventure, Collection -from worldtravel.models import VisitedRegion, Region, Country -from .serializers import AdventureSerializer, CollectionSerializer -from rest_framework.permissions import IsAuthenticated -from django.db.models import Q, Prefetch -from .permissions import IsOwnerOrReadOnly, IsPublicReadOnly -from rest_framework.pagination import PageNumberPagination -from django.shortcuts import get_object_or_404 -from rest_framework import status - -class StandardResultsSetPagination(PageNumberPagination): - page_size = 10 - page_size_query_param = 'page_size' - max_page_size = 1000 - -from rest_framework.pagination import PageNumberPagination - -from rest_framework.decorators import action -from rest_framework.response import Response -from django.db.models import Q - -class AdventureViewSet(viewsets.ModelViewSet): - serializer_class = AdventureSerializer - permission_classes = [IsOwnerOrReadOnly, IsPublicReadOnly] - pagination_class = StandardResultsSetPagination - - def apply_sorting(self, queryset): - order_by = self.request.query_params.get('order_by', 'updated_at') - order_direction = self.request.query_params.get('order_direction', 'asc') - include_collections = self.request.query_params.get('include_collections', 'true') - - valid_order_by = ['name', 'type', 'date', 'rating', 'updated_at'] - if order_by not in valid_order_by: - order_by = 'name' - - if order_direction not in ['asc', 'desc']: - order_direction = 'asc' - - # Apply case-insensitive sorting for the 'name' field - if order_by == 'name': - queryset = queryset.annotate(lower_name=Lower('name')) - ordering = 'lower_name' - else: - ordering = order_by - - if order_direction == 'desc': - ordering = f'-{ordering}' - - # reverse ordering for updated_at field - if order_by == 'updated_at': - if order_direction == 'asc': - ordering = '-updated_at' - else: - ordering = 'updated_at' - - print(f"Ordering by: {ordering}") # For debugging - - if include_collections == 'false': - queryset = queryset.filter(collection = None) - - return queryset.order_by(ordering) - - def get_queryset(self): - if self.action == 'retrieve': - # For individual adventure retrieval, include public adventures - return Adventure.objects.filter( - Q(is_public=True) | Q(user_id=self.request.user.id) - ) - else: - # For other actions, only include user's own adventures - return Adventure.objects.filter(user_id=self.request.user.id) - - def list(self, request, *args, **kwargs): - # Prevent listing all adventures - return Response({"detail": "Listing all adventures is not allowed."}, - status=status.HTTP_403_FORBIDDEN) - - def retrieve(self, request, *args, **kwargs): - queryset = self.get_queryset() - adventure = get_object_or_404(queryset, pk=kwargs['pk']) - serializer = self.get_serializer(adventure) - return Response(serializer.data) - - def perform_create(self, serializer): - adventure = serializer.save(user_id=self.request.user) - if adventure.collection: - adventure.is_public = adventure.collection.is_public - adventure.save() - - def perform_update(self, serializer): - adventure = serializer.save() - if adventure.collection: - adventure.is_public = adventure.collection.is_public - adventure.save() - - def perform_create(self, serializer): - serializer.save(user_id=self.request.user) - - @action(detail=False, methods=['get']) - def filtered(self, request): - types = request.query_params.get('types', '').split(',') - valid_types = ['visited', 'planned'] - types = [t for t in types if t in valid_types] - - if not types: - return Response({"error": "No valid types provided"}, status=400) - - queryset = Adventure.objects.none() - - for adventure_type in types: - if adventure_type in ['visited', 'planned']: - queryset |= Adventure.objects.filter( - type=adventure_type, user_id=request.user.id) - - queryset = self.apply_sorting(queryset) - adventures = self.paginate_and_respond(queryset, request) - return adventures - - @action(detail=False, methods=['get']) - def all(self, request): - if not request.user.is_authenticated: - return Response({"error": "User is not authenticated"}, status=400) - # include_collections = request.query_params.get('include_collections', 'false') - # if include_collections not in ['true', 'false']: - # include_collections = 'false' - - # if include_collections == 'true': - # queryset = Adventure.objects.filter( - # Q(is_public=True) | Q(user_id=request.user.id) - # ) - # else: - # queryset = Adventure.objects.filter( - # Q(is_public=True) | Q(user_id=request.user.id), collection=None - # ) - queryset = Adventure.objects.filter( - Q(user_id=request.user.id) - ) - - queryset = self.apply_sorting(queryset) - serializer = self.get_serializer(queryset, many=True) - - return Response(serializer.data) - - @action(detail=False, methods=['get']) - def search(self, request): - query = self.request.query_params.get('query', '') - if len(query) < 2: - return Response({"error": "Query must be at least 2 characters long"}, status=400) - queryset = Adventure.objects.filter( - (Q(name__icontains=query) | Q(description__icontains=query) | Q(location__icontains=query) | Q(activity_types__icontains=query)) & - (Q(user_id=request.user.id) | Q(is_public=True)) -) - queryset = self.apply_sorting(queryset) - adventures = self.paginate_and_respond(queryset, request) - return adventures - - def paginate_and_respond(self, queryset, request): - paginator = self.pagination_class() - page = paginator.paginate_queryset(queryset, request) - if page is not None: - serializer = self.get_serializer(page, many=True) - return paginator.get_paginated_response(serializer.data) - serializer = self.get_serializer(queryset, many=True) - return Response(serializer.data) - -class CollectionViewSet(viewsets.ModelViewSet): - serializer_class = CollectionSerializer - permission_classes = [IsOwnerOrReadOnly, IsPublicReadOnly] - pagination_class = StandardResultsSetPagination - - def apply_sorting(self, queryset): - order_by = self.request.query_params.get('order_by', 'name') - order_direction = self.request.query_params.get('order_direction', 'asc') - - valid_order_by = ['name'] - if order_by not in valid_order_by: - order_by = 'name' - - if order_direction not in ['asc', 'desc']: - order_direction = 'asc' - - # Apply case-insensitive sorting for the 'name' field - if order_by == 'name': - queryset = queryset.annotate(lower_name=Lower('name')) - ordering = 'lower_name' - else: - ordering = order_by - - if order_direction == 'desc': - ordering = f'-{ordering}' - - print(f"Ordering by: {ordering}") # For debugging - - return queryset.order_by(ordering) - - def list(self, request, *args, **kwargs): - # make sure the user is authenticated - if not request.user.is_authenticated: - return Response({"error": "User is not authenticated"}, status=400) - queryset = self.get_queryset() - queryset = self.apply_sorting(queryset) - collections = self.paginate_and_respond(queryset, request) - return collections - - @action(detail=False, methods=['get']) - def all(self, request): - if not request.user.is_authenticated: - return Response({"error": "User is not authenticated"}, status=400) - - queryset = Collection.objects.filter( - Q(user_id=request.user.id) - ) - - queryset = self.apply_sorting(queryset) - serializer = self.get_serializer(queryset, many=True) - - return Response(serializer.data) - - # this make the is_public field of the collection cascade to the adventures - @transaction.atomic - def update(self, request, *args, **kwargs): - partial = kwargs.pop('partial', False) - instance = self.get_object() - serializer = self.get_serializer(instance, data=request.data, partial=partial) - serializer.is_valid(raise_exception=True) - - # Check if the 'is_public' field is present in the update data - if 'is_public' in serializer.validated_data: - new_public_status = serializer.validated_data['is_public'] - - # Update associated adventures to match the collection's is_public status - Adventure.objects.filter(collection=instance).update(is_public=new_public_status) - - # Log the action (optional) - action = "public" if new_public_status else "private" - print(f"Collection {instance.id} and its adventures were set to {action}") - - self.perform_update(serializer) - - if getattr(instance, '_prefetched_objects_cache', None): - # If 'prefetch_related' has been applied to a queryset, we need to - # forcibly invalidate the prefetch cache on the instance. - instance._prefetched_objects_cache = {} - - return Response(serializer.data) - - def get_queryset(self): - collections = Collection.objects.filter( - Q(is_public=True) | Q(user_id=self.request.user.id) - ).prefetch_related( - Prefetch('adventure_set', queryset=Adventure.objects.filter( - Q(is_public=True) | Q(user_id=self.request.user.id) - )) - ) - return self.apply_sorting(collections) - - def perform_create(self, serializer): - serializer.save(user_id=self.request.user) - - # @action(detail=False, methods=['get']) - # def filtered(self, request): - # types = request.query_params.get('types', '').split(',') - # valid_types = ['visited', 'planned'] - # types = [t for t in types if t in valid_types] - - # if not types: - # return Response({"error": "No valid types provided"}, status=400) - - # queryset = Collection.objects.none() - - # for adventure_type in types: - # if adventure_type in ['visited', 'planned']: - # queryset |= Collection.objects.filter( - # type=adventure_type, user_id=request.user.id) - - # queryset = self.apply_sorting(queryset) - # collections = self.paginate_and_respond(queryset, request) - # return collections - - def paginate_and_respond(self, queryset, request): - paginator = self.pagination_class() - page = paginator.paginate_queryset(queryset, request) - if page is not None: - serializer = self.get_serializer(page, many=True) - return paginator.get_paginated_response(serializer.data) - serializer = self.get_serializer(queryset, many=True) - return Response(serializer.data) - -class StatsViewSet(viewsets.ViewSet): - permission_classes = [IsAuthenticated] - - @action(detail=False, methods=['get']) - def counts(self, request): - visited_count = Adventure.objects.filter( - type='visited', user_id=request.user.id).count() - planned_count = Adventure.objects.filter( - type='planned', user_id=request.user.id).count() - trips_count = Collection.objects.filter( - user_id=request.user.id).count() - visited_region_count = VisitedRegion.objects.filter( - user_id=request.user.id).count() - total_regions = Region.objects.count() - country_count = VisitedRegion.objects.filter( - user_id=request.user.id).values('region__country').distinct().count() - total_countries = Country.objects.count() - return Response({ - 'visited_count': visited_count, - 'planned_count': planned_count, - 'trips_count': trips_count, - 'visited_region_count': visited_region_count, - 'total_regions': total_regions, - 'country_count': country_count, - 'total_countries': total_countries - }) - -class GenerateDescription(viewsets.ViewSet): - permission_classes = [IsAuthenticated] - - @action(detail=False, methods=['get'],) - def desc(self, request): - name = self.request.query_params.get('name', '') - # un url encode the name - name = name.replace('%20', ' ') - print(name) - url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=extracts&exintro&explaintext&format=json&titles=%s' % name - response = requests.get(url) - data = response.json() - data = response.json() - page_id = next(iter(data["query"]["pages"])) - extract = data["query"]["pages"][page_id] - if extract.get('extract') is None: - return Response({"error": "No description found"}, status=400) - return Response(extract) - @action(detail=False, methods=['get'],) - def img(self, request): - name = self.request.query_params.get('name', '') - # un url encode the name - name = name.replace('%20', ' ') - url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=pageimages&format=json&piprop=original&titles=%s' % name - response = requests.get(url) - data = response.json() - page_id = next(iter(data["query"]["pages"])) - extract = data["query"]["pages"][page_id] - if extract.get('original') is None: - return Response({"error": "No image found"}, status=400) - return Response(extract["original"]) - - -class ActivityTypesView(viewsets.ViewSet): - permission_classes = [IsAuthenticated] - - @action(detail=False, methods=['get']) - def types(self, request): - """ - Retrieve a list of distinct activity types for adventures associated with the current user. - - Args: - request (HttpRequest): The HTTP request object. - - Returns: - Response: A response containing a list of distinct activity types. - """ - types = Adventure.objects.filter(user_id=request.user.id).values_list('activity_types', flat=True).distinct() - - allTypes = [] - - for i in types: - if not i: - continue - for x in i: - if x and x not in allTypes: - allTypes.append(x) - - return Response(allTypes) diff --git a/backend/server/adventures/views/__init__.py b/backend/server/adventures/views/__init__.py new file mode 100644 index 0000000..c9aedb0 --- /dev/null +++ b/backend/server/adventures/views/__init__.py @@ -0,0 +1,16 @@ +from .activity_types_view import * +from .adventure_image_view import * +from .adventure_view import * +from .category_view import * +from .checklist_view import * +from .collection_view import * +from .generate_description_view import * +from .ics_calendar_view import * +from .note_view import * +from .reverse_geocode_view import * +from .stats_view import * +from .transportation_view import * +from .global_search_view import * +from .attachment_view import * +from .lodging_view import * +from .recommendations_view import * \ No newline at end of file diff --git a/backend/server/adventures/views/activity_types_view.py b/backend/server/adventures/views/activity_types_view.py new file mode 100644 index 0000000..438c0d0 --- /dev/null +++ b/backend/server/adventures/views/activity_types_view.py @@ -0,0 +1,32 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from adventures.models import Adventure + +class ActivityTypesView(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + + @action(detail=False, methods=['get']) + def types(self, request): + """ + Retrieve a list of distinct activity types for adventures associated with the current user. + + Args: + request (HttpRequest): The HTTP request object. + + Returns: + Response: A response containing a list of distinct activity types. + """ + types = Adventure.objects.filter(user_id=request.user.id).values_list('activity_types', flat=True).distinct() + + allTypes = [] + + for i in types: + if not i: + continue + for x in i: + if x and x not in allTypes: + allTypes.append(x) + + return Response(allTypes) \ No newline at end of file diff --git a/backend/server/adventures/views/adventure_image_view.py b/backend/server/adventures/views/adventure_image_view.py new file mode 100644 index 0000000..ab7f8e1 --- /dev/null +++ b/backend/server/adventures/views/adventure_image_view.py @@ -0,0 +1,215 @@ +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from django.db.models import Q +from django.core.files.base import ContentFile +from adventures.models import Adventure, AdventureImage +from adventures.serializers import AdventureImageSerializer +from integrations.models import ImmichIntegration +import uuid +import requests + +class AdventureImageViewSet(viewsets.ModelViewSet): + serializer_class = AdventureImageSerializer + permission_classes = [IsAuthenticated] + + @action(detail=True, methods=['post']) + def image_delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) + + @action(detail=True, methods=['post']) + def toggle_primary(self, request, *args, **kwargs): + # Makes the image the primary image for the adventure, if there is already a primary image linked to the adventure, it is set to false and the new image is set to true. make sure that the permission is set to the owner of the adventure + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + + instance = self.get_object() + adventure = instance.adventure + if adventure.user_id != request.user: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + # Check if the image is already the primary image + if instance.is_primary: + return Response({"error": "Image is already the primary image"}, status=status.HTTP_400_BAD_REQUEST) + + # Set the current primary image to false + AdventureImage.objects.filter(adventure=adventure, is_primary=True).update(is_primary=False) + + # Set the new image to true + instance.is_primary = True + instance.save() + return Response({"success": "Image set as primary image"}) + + def create(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + adventure_id = request.data.get('adventure') + try: + adventure = Adventure.objects.get(id=adventure_id) + except Adventure.DoesNotExist: + return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND) + + if adventure.user_id != request.user: + # Check if the adventure has any collections + if adventure.collections.exists(): + # Check if the user is in the shared_with list of any of the adventure's collections + user_has_access = False + for collection in adventure.collections.all(): + if collection.shared_with.filter(id=request.user.id).exists(): + user_has_access = True + break + + if not user_has_access: + return Response({"error": "User does not have permission to access this adventure"}, status=status.HTTP_403_FORBIDDEN) + else: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + # Handle Immich ID for shared users by downloading the image + if (request.user != adventure.user_id and + 'immich_id' in request.data and + request.data.get('immich_id')): + + immich_id = request.data.get('immich_id') + + # Get the shared user's Immich integration + try: + user_integration = ImmichIntegration.objects.get(user_id=request.user) + except ImmichIntegration.DoesNotExist: + return Response({ + "error": "No Immich integration found for your account. Please set up Immich integration first.", + "code": "immich_integration_not_found" + }, status=status.HTTP_400_BAD_REQUEST) + + # Download the image from the shared user's Immich server + try: + immich_response = requests.get( + f'{user_integration.server_url}/assets/{immich_id}/thumbnail?size=preview', + headers={'x-api-key': user_integration.api_key}, + timeout=10 + ) + immich_response.raise_for_status() + + # Create a temporary file with the downloaded content + content_type = immich_response.headers.get('Content-Type', 'image/jpeg') + if not content_type.startswith('image/'): + return Response({ + "error": "Invalid content type returned from Immich server.", + "code": "invalid_content_type" + }, status=status.HTTP_400_BAD_REQUEST) + + # Determine file extension from content type + ext_map = { + 'image/jpeg': '.jpg', + 'image/png': '.png', + 'image/webp': '.webp', + 'image/gif': '.gif' + } + file_ext = ext_map.get(content_type, '.jpg') + filename = f"immich_{immich_id}{file_ext}" + + # Create a Django ContentFile from the downloaded image + image_file = ContentFile(immich_response.content, name=filename) + + # Modify request data to use the downloaded image instead of immich_id + request_data = request.data.copy() + request_data.pop('immich_id', None) # Remove immich_id + request_data['image'] = image_file # Add the image file + + # Create the serializer with the modified data + serializer = self.get_serializer(data=request_data) + serializer.is_valid(raise_exception=True) + + # Save with the downloaded image + adventure = serializer.validated_data['adventure'] + serializer.save(user_id=adventure.user_id, image=image_file) + + return Response(serializer.data, status=status.HTTP_201_CREATED) + + except requests.exceptions.RequestException: + return Response({ + "error": f"Failed to fetch image from Immich server", + "code": "immich_fetch_failed" + }, status=status.HTTP_502_BAD_GATEWAY) + except Exception: + return Response({ + "error": f"Unexpected error processing Immich image", + "code": "immich_processing_error" + }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + return super().create(request, *args, **kwargs) + + def update(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + + adventure_id = request.data.get('adventure') + try: + adventure = Adventure.objects.get(id=adventure_id) + except Adventure.DoesNotExist: + return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND) + + if adventure.user_id != request.user: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + return super().update(request, *args, **kwargs) + + def perform_destroy(self, instance): + print("perform_destroy") + return super().perform_destroy(instance) + + def destroy(self, request, *args, **kwargs): + print("destroy") + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + + instance = self.get_object() + adventure = instance.adventure + if adventure.user_id != request.user: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + return super().destroy(request, *args, **kwargs) + + def partial_update(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + + instance = self.get_object() + adventure = instance.adventure + if adventure.user_id != request.user: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + return super().partial_update(request, *args, **kwargs) + + @action(detail=False, methods=['GET'], url_path='(?P[0-9a-f-]+)') + def adventure_images(self, request, adventure_id=None, *args, **kwargs): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + + try: + adventure_uuid = uuid.UUID(adventure_id) + except ValueError: + return Response({"error": "Invalid adventure ID"}, status=status.HTTP_400_BAD_REQUEST) + + # Updated queryset to include images from adventures the user owns OR has shared access to + queryset = AdventureImage.objects.filter( + Q(adventure__id=adventure_uuid) & ( + Q(adventure__user_id=request.user) | # User owns the adventure + Q(adventure__collections__shared_with=request.user) # User has shared access via collection + ) + ).distinct() + + serializer = self.get_serializer(queryset, many=True, context={'request': request}) + return Response(serializer.data) + + def get_queryset(self): + # Updated to include images from adventures the user owns OR has shared access to + return AdventureImage.objects.filter( + Q(adventure__user_id=self.request.user) | # User owns the adventure + Q(adventure__collections__shared_with=self.request.user) # User has shared access via collection + ).distinct() + + def perform_create(self, serializer): + # Always set the image owner to the adventure owner, not the current user + adventure = serializer.validated_data['adventure'] + serializer.save(user_id=adventure.user_id) \ No newline at end of file diff --git a/backend/server/adventures/views/adventure_view.py b/backend/server/adventures/views/adventure_view.py new file mode 100644 index 0000000..b4bbfb9 --- /dev/null +++ b/backend/server/adventures/views/adventure_view.py @@ -0,0 +1,341 @@ +from django.utils import timezone +from django.db import transaction +from django.core.exceptions import PermissionDenied +from django.db.models import Q, Max +from django.db.models.functions import Lower +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response +import requests + +from adventures.models import Adventure, Category, Transportation, Lodging +from adventures.permissions import IsOwnerOrSharedWithFullAccess +from adventures.serializers import AdventureSerializer, TransportationSerializer, LodgingSerializer +from adventures.utils import pagination + + +class AdventureViewSet(viewsets.ModelViewSet): + """ + ViewSet for managing Adventure objects with support for filtering, sorting, + and sharing functionality. + """ + serializer_class = AdventureSerializer + permission_classes = [IsOwnerOrSharedWithFullAccess] + pagination_class = pagination.StandardResultsSetPagination + + # ==================== QUERYSET & PERMISSIONS ==================== + + def get_queryset(self): + """ + Returns queryset based on user authentication and action type. + Public actions allow unauthenticated access to public adventures. + """ + user = self.request.user + public_allowed_actions = {'retrieve', 'additional_info'} + + if not user.is_authenticated: + if self.action in public_allowed_actions: + return Adventure.objects.retrieve_adventures( + user, include_public=True + ).order_by('-updated_at') + return Adventure.objects.none() + + include_public = self.action in public_allowed_actions + return Adventure.objects.retrieve_adventures( + user, + include_public=include_public, + include_owned=True, + include_shared=True + ).order_by('-updated_at') + + # ==================== SORTING & FILTERING ==================== + + def apply_sorting(self, queryset): + """Apply sorting and collection filtering to queryset.""" + order_by = self.request.query_params.get('order_by', 'updated_at') + order_direction = self.request.query_params.get('order_direction', 'asc') + include_collections = self.request.query_params.get('include_collections', 'true') + + # Validate parameters + valid_order_by = ['name', 'type', 'date', 'rating', 'updated_at'] + if order_by not in valid_order_by: + order_by = 'name' + + if order_direction not in ['asc', 'desc']: + order_direction = 'asc' + + # Apply sorting logic + queryset = self._apply_ordering(queryset, order_by, order_direction) + + # Filter adventures without collections if requested + if include_collections == 'false': + queryset = queryset.filter(collections__isnull=True) + + return queryset + + def _apply_ordering(self, queryset, order_by, order_direction): + """Apply ordering to queryset based on field type.""" + if order_by == 'date': + queryset = queryset.annotate( + latest_visit=Max('visits__start_date') + ).filter(latest_visit__isnull=False) + ordering = 'latest_visit' + elif order_by == 'name': + queryset = queryset.annotate(lower_name=Lower('name')) + ordering = 'lower_name' + elif order_by == 'rating': + queryset = queryset.filter(rating__isnull=False) + ordering = 'rating' + elif order_by == 'updated_at': + # Special handling for updated_at (reverse default order) + ordering = '-updated_at' if order_direction == 'asc' else 'updated_at' + return queryset.order_by(ordering) + else: + ordering = order_by + + # Apply direction + if order_direction == 'desc': + ordering = f'-{ordering}' + + return queryset.order_by(ordering) + + # ==================== CRUD OPERATIONS ==================== + + @transaction.atomic + def perform_create(self, serializer): + """Create adventure with collection validation and ownership logic.""" + collections = serializer.validated_data.get('collections', []) + + # Validate permissions for all collections + self._validate_collection_permissions(collections) + + # Determine what user to assign as owner + user_to_assign = self.request.user + + if collections: + # Use the current user as owner since ManyToMany allows multiple collection owners + user_to_assign = self.request.user + + serializer.save(user_id=user_to_assign) + + def perform_update(self, serializer): + """Update adventure.""" + # Just save the adventure - the signal will handle publicity updates + serializer.save() + + def update(self, request, *args, **kwargs): + """Handle adventure updates with collection permission validation.""" + instance = self.get_object() + partial = kwargs.pop('partial', False) + + serializer = self.get_serializer(instance, data=request.data, partial=partial) + serializer.is_valid(raise_exception=True) + + # Validate collection permissions if collections are being updated + if 'collections' in serializer.validated_data: + self._validate_collection_update_permissions( + instance, serializer.validated_data['collections'] + ) + else: + # Remove collections from validated_data if not provided + serializer.validated_data.pop('collections', None) + + self.perform_update(serializer) + return Response(serializer.data) + + # ==================== CUSTOM ACTIONS ==================== + + @action(detail=False, methods=['get']) + def filtered(self, request): + """Filter adventures by category types and visit status.""" + types = request.query_params.get('types', '').split(',') + + # Handle 'all' types + if 'all' in types: + types = Category.objects.filter( + user_id=request.user + ).values_list('name', flat=True) + else: + # Validate provided types + if not types or not all( + Category.objects.filter(user_id=request.user, name=type_name).exists() + for type_name in types + ): + return Response( + {"error": "Invalid category or no types provided"}, + status=400 + ) + + # Build base queryset + queryset = Adventure.objects.filter( + category__in=Category.objects.filter(name__in=types, user_id=request.user), + user_id=request.user.id + ) + + # Apply visit status filtering + queryset = self._apply_visit_filtering(queryset, request) + queryset = self.apply_sorting(queryset) + + return self.paginate_and_respond(queryset, request) + + @action(detail=False, methods=['get']) + def all(self, request): + """Get all adventures (public and owned) with optional collection filtering.""" + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + + include_collections = request.query_params.get('include_collections', 'false') == 'true' + + # Build queryset with collection filtering + base_filter = Q(user_id=request.user.id) + + if include_collections: + queryset = Adventure.objects.filter(base_filter) + else: + queryset = Adventure.objects.filter(base_filter, collections__isnull=True) + + queryset = self.apply_sorting(queryset) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + @action(detail=True, methods=['get'], url_path='additional-info') + def additional_info(self, request, pk=None): + """Get adventure with additional sunrise/sunset information.""" + adventure = self.get_object() + user = request.user + + # Validate access permissions + if not self._has_adventure_access(adventure, user): + return Response( + {"error": "User does not have permission to access this adventure"}, + status=status.HTTP_403_FORBIDDEN + ) + + # Get base adventure data + serializer = self.get_serializer(adventure) + response_data = serializer.data + + # Add sunrise/sunset data + response_data['sun_times'] = self._get_sun_times(adventure, response_data.get('visits', [])) + + return Response(response_data) + + # ==================== HELPER METHODS ==================== + + def _validate_collection_permissions(self, collections): + """Validate user has permission to use all provided collections. Only the owner or shared users can use collections.""" + for collection in collections: + if not (collection.user_id == self.request.user or + collection.shared_with.filter(uuid=self.request.user.uuid).exists()): + raise PermissionDenied( + f"You do not have permission to use collection '{collection.name}'." + ) + + def _validate_collection_update_permissions(self, instance, new_collections): + """Validate permissions for collection updates (add/remove).""" + # Check permissions for new collections being added + for collection in new_collections: + if (collection.user_id != self.request.user and + not collection.shared_with.filter(uuid=self.request.user.uuid).exists()): + raise PermissionDenied( + f"You do not have permission to use collection '{collection.name}'." + ) + + # Check permissions for collections being removed + current_collections = set(instance.collections.all()) + new_collections_set = set(new_collections) + collections_to_remove = current_collections - new_collections_set + + for collection in collections_to_remove: + if (collection.user_id != self.request.user and + not collection.shared_with.filter(uuid=self.request.user.uuid).exists()): + raise PermissionDenied( + f"You cannot remove the adventure from collection '{collection.name}' " + f"as you don't have permission." + ) + + def _apply_visit_filtering(self, queryset, request): + """Apply visit status filtering to queryset.""" + is_visited_param = request.query_params.get('is_visited') + if is_visited_param is None: + return queryset + + # Convert parameter to boolean + if is_visited_param.lower() == 'true': + is_visited_bool = True + elif is_visited_param.lower() == 'false': + is_visited_bool = False + else: + return queryset + + # Apply visit filtering + now = timezone.now().date() + if is_visited_bool: + queryset = queryset.filter(visits__start_date__lte=now).distinct() + else: + queryset = queryset.exclude(visits__start_date__lte=now).distinct() + + return queryset + + def _has_adventure_access(self, adventure, user): + """Check if user has access to adventure.""" + # Allow if public + if adventure.is_public: + return True + + # Check ownership + if user.is_authenticated and adventure.user_id == user: + return True + + # Check shared collection access + if user.is_authenticated: + for collection in adventure.collections.all(): + if collection.shared_with.filter(uuid=user.uuid).exists(): + return True + + return False + + def _get_sun_times(self, adventure, visits): + """Get sunrise/sunset times for adventure visits.""" + sun_times = [] + + for visit in visits: + date = visit.get('start_date') + if not (date and adventure.longitude and adventure.latitude): + continue + + api_url = ( + f'https://api.sunrisesunset.io/json?' + f'lat={adventure.latitude}&lng={adventure.longitude}&date={date}' + ) + + try: + response = requests.get(api_url) + if response.status_code == 200: + data = response.json() + results = data.get('results', {}) + + if results.get('sunrise') and results.get('sunset'): + sun_times.append({ + "date": date, + "visit_id": visit.get('id'), + "sunrise": results.get('sunrise'), + "sunset": results.get('sunset') + }) + except requests.RequestException: + # Skip this visit if API call fails + continue + + return sun_times + + def paginate_and_respond(self, queryset, request): + """Paginate queryset and return response.""" + paginator = self.pagination_class() + page = paginator.paginate_queryset(queryset, request) + + if page is not None: + serializer = self.get_serializer(page, many=True) + return paginator.get_paginated_response(serializer.data) + + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) \ No newline at end of file diff --git a/backend/server/adventures/views/attachment_view.py b/backend/server/adventures/views/attachment_view.py new file mode 100644 index 0000000..2ca4770 --- /dev/null +++ b/backend/server/adventures/views/attachment_view.py @@ -0,0 +1,56 @@ +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from adventures.models import Adventure, Attachment +from adventures.serializers import AttachmentSerializer + +class AttachmentViewSet(viewsets.ModelViewSet): + serializer_class = AttachmentSerializer + permission_classes = [IsAuthenticated] + + def get_queryset(self): + return Attachment.objects.filter(user_id=self.request.user) + + @action(detail=True, methods=['post']) + def attachment_delete(self, request, *args, **kwargs): + return self.destroy(request, *args, **kwargs) + + def create(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=status.HTTP_401_UNAUTHORIZED) + adventure_id = request.data.get('adventure') + try: + adventure = Adventure.objects.get(id=adventure_id) + except Adventure.DoesNotExist: + return Response({"error": "Adventure not found"}, status=status.HTTP_404_NOT_FOUND) + + if adventure.user_id != request.user: + # Check if the adventure has any collections + if adventure.collections.exists(): + # Check if the user is in the shared_with list of any of the adventure's collections + user_has_access = False + for collection in adventure.collections.all(): + if collection.shared_with.filter(id=request.user.id).exists(): + user_has_access = True + break + + if not user_has_access: + return Response({"error": "User does not have permission to access this adventure"}, status=status.HTTP_403_FORBIDDEN) + else: + return Response({"error": "User does not own this adventure"}, status=status.HTTP_403_FORBIDDEN) + + return super().create(request, *args, **kwargs) + + def perform_create(self, serializer): + adventure_id = self.request.data.get('adventure') + adventure = Adventure.objects.get(id=adventure_id) + + # If the adventure belongs to collections, set the owner to the collection owner + if adventure.collections.exists(): + # Get the first collection's owner (assuming all collections have the same owner) + collection = adventure.collections.first() + serializer.save(user_id=collection.user_id) + else: + # Otherwise, set the owner to the request user + serializer.save(user_id=self.request.user) \ No newline at end of file diff --git a/backend/server/adventures/views/category_view.py b/backend/server/adventures/views/category_view.py new file mode 100644 index 0000000..4bde278 --- /dev/null +++ b/backend/server/adventures/views/category_view.py @@ -0,0 +1,42 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from adventures.models import Category, Adventure +from adventures.serializers import CategorySerializer + +class CategoryViewSet(viewsets.ModelViewSet): + queryset = Category.objects.all() + serializer_class = CategorySerializer + permission_classes = [IsAuthenticated] + + def get_queryset(self): + return Category.objects.filter(user_id=self.request.user) + + @action(detail=False, methods=['get']) + def categories(self, request): + """ + Retrieve a list of distinct categories for adventures associated with the current user. + """ + categories = self.get_queryset().distinct() + serializer = self.get_serializer(categories, many=True) + return Response(serializer.data) + + def destroy(self, request, *args, **kwargs): + instance = self.get_object() + if instance.user_id != request.user: + return Response({"error": "User does not own this category"}, status + =400) + + if instance.name == 'general': + return Response({"error": "Cannot delete the general category"}, status=400) + + # set any adventures with this category to a default category called general before deleting the category, if general does not exist create it for the user + general_category = Category.objects.filter(user_id=request.user, name='general').first() + + if not general_category: + general_category = Category.objects.create(user_id=request.user, name='general', icon='🌍', display_name='General') + + Adventure.objects.filter(category=instance).update(category=general_category) + + return super().destroy(request, *args, **kwargs) \ No newline at end of file diff --git a/backend/server/adventures/views/checklist_view.py b/backend/server/adventures/views/checklist_view.py new file mode 100644 index 0000000..6824f03 --- /dev/null +++ b/backend/server/adventures/views/checklist_view.py @@ -0,0 +1,130 @@ +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response +from django.db.models import Q +from adventures.models import Checklist +from adventures.serializers import ChecklistSerializer +from rest_framework.exceptions import PermissionDenied +from adventures.permissions import IsOwnerOrSharedWithFullAccess + +class ChecklistViewSet(viewsets.ModelViewSet): + queryset = Checklist.objects.all() + serializer_class = ChecklistSerializer + permission_classes = [IsOwnerOrSharedWithFullAccess] + filterset_fields = ['is_public', 'collection'] + + # return error message if user is not authenticated on the root endpoint + def list(self, request, *args, **kwargs): + # Prevent listing all adventures + return Response({"detail": "Listing all checklists is not allowed."}, + status=status.HTTP_403_FORBIDDEN) + + @action(detail=False, methods=['get']) + def all(self, request): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + queryset = Checklist.objects.filter( + Q(user_id=request.user.id) + ) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + + def get_queryset(self): + # if the user is not authenticated return only public transportations for retrieve action + if not self.request.user.is_authenticated: + if self.action == 'retrieve': + return Checklist.objects.filter(is_public=True).distinct().order_by('-updated_at') + return Checklist.objects.none() + + + if self.action == 'retrieve': + # For individual adventure retrieval, include public adventures + return Checklist.objects.filter( + Q(is_public=True) | Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user) + ).distinct().order_by('-updated_at') + else: + # For other actions, include user's own adventures and shared adventures + return Checklist.objects.filter( + Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user) + ).distinct().order_by('-updated_at') + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + user = request.user + print(new_collection) + + if new_collection is not None and new_collection!=instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + user = request.user + print(new_collection) + + if new_collection is not None and new_collection!=instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def perform_update(self, serializer): + serializer.save() + + # when creating an adventure, make sure the user is the owner of the collection or shared with the collection + def perform_create(self, serializer): + # Retrieve the collection from the validated data + collection = serializer.validated_data.get('collection') + + # Check if a collection is provided + if collection: + user = self.request.user + # Check if the user is the owner or is in the shared_with list + if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists(): + # Return an error response if the user does not have permission + raise PermissionDenied("You do not have permission to use this collection.") + # if collection the owner of the adventure is the owner of the collection + serializer.save(user_id=collection.user_id) + return + + # Save the adventure with the current user as the owner + serializer.save(user_id=self.request.user) \ No newline at end of file diff --git a/backend/server/adventures/views/collection_view.py b/backend/server/adventures/views/collection_view.py new file mode 100644 index 0000000..40ebbd6 --- /dev/null +++ b/backend/server/adventures/views/collection_view.py @@ -0,0 +1,240 @@ +from django.db.models import Q +from django.db.models.functions import Lower +from django.db import transaction +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.response import Response +from adventures.models import Collection, Adventure, Transportation, Note, Checklist +from adventures.permissions import CollectionShared +from adventures.serializers import CollectionSerializer +from users.models import CustomUser as User +from adventures.utils import pagination + +class CollectionViewSet(viewsets.ModelViewSet): + serializer_class = CollectionSerializer + permission_classes = [CollectionShared] + pagination_class = pagination.StandardResultsSetPagination + + # def get_queryset(self): + # return Collection.objects.filter(Q(user_id=self.request.user.id) & Q(is_archived=False)) + + def apply_sorting(self, queryset): + order_by = self.request.query_params.get('order_by', 'name') + order_direction = self.request.query_params.get('order_direction', 'asc') + + valid_order_by = ['name', 'updated_at', 'start_date'] + if order_by not in valid_order_by: + order_by = 'updated_at' + + if order_direction not in ['asc', 'desc']: + order_direction = 'asc' + + # Apply case-insensitive sorting for the 'name' field + if order_by == 'name': + queryset = queryset.annotate(lower_name=Lower('name')) + ordering = 'lower_name' + if order_direction == 'desc': + ordering = f'-{ordering}' + elif order_by == 'start_date': + ordering = 'start_date' + if order_direction == 'asc': + ordering = 'start_date' + else: + ordering = '-start_date' + else: + order_by == 'updated_at' + ordering = 'updated_at' + if order_direction == 'asc': + ordering = '-updated_at' + + #print(f"Ordering by: {ordering}") # For debugging + + return queryset.order_by(ordering) + + def list(self, request, *args, **kwargs): + # make sure the user is authenticated + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + queryset = Collection.objects.filter(user_id=request.user.id, is_archived=False) + queryset = self.apply_sorting(queryset) + collections = self.paginate_and_respond(queryset, request) + return collections + + @action(detail=False, methods=['get']) + def all(self, request): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + + queryset = Collection.objects.filter( + Q(user_id=request.user.id) + ) + + queryset = self.apply_sorting(queryset) + serializer = self.get_serializer(queryset, many=True) + + return Response(serializer.data) + + @action(detail=False, methods=['get']) + def archived(self, request): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + + queryset = Collection.objects.filter( + Q(user_id=request.user.id) & Q(is_archived=True) + ) + + queryset = self.apply_sorting(queryset) + serializer = self.get_serializer(queryset, many=True) + + return Response(serializer.data) + + # this make the is_public field of the collection cascade to the adventures + @transaction.atomic + def update(self, request, *args, **kwargs): + partial = kwargs.pop('partial', False) + instance = self.get_object() + serializer = self.get_serializer(instance, data=request.data, partial=partial) + serializer.is_valid(raise_exception=True) + + if 'collection' in serializer.validated_data: + new_collection = serializer.validated_data['collection'] + # if the new collection is different from the old one and the user making the request is not the owner of the new collection return an error + if new_collection != instance.collection and new_collection.user_id != request.user: + return Response({"error": "User does not own the new collection"}, status=400) + + # Check if the 'is_public' field is present in the update data + if 'is_public' in serializer.validated_data: + new_public_status = serializer.validated_data['is_public'] + + # if is_public has changed and the user is not the owner of the collection return an error + if new_public_status != instance.is_public and instance.user_id != request.user: + print(f"User {request.user.id} does not own the collection {instance.id} that is owned by {instance.user_id}") + return Response({"error": "User does not own the collection"}, status=400) + + # Get all adventures in this collection + adventures_in_collection = Adventure.objects.filter(collections=instance) + + if new_public_status: + # If collection becomes public, make all adventures public + adventures_in_collection.update(is_public=True) + else: + # If collection becomes private, check each adventure + # Only set an adventure to private if ALL of its collections are private + # Collect adventures that do NOT belong to any other public collection (excluding the current one) + adventure_ids_to_set_private = [] + + for adventure in adventures_in_collection: + has_public_collection = adventure.collections.filter(is_public=True).exclude(id=instance.id).exists() + if not has_public_collection: + adventure_ids_to_set_private.append(adventure.id) + + # Bulk update those adventures + Adventure.objects.filter(id__in=adventure_ids_to_set_private).update(is_public=False) + + # Update transportations, notes, and checklists related to this collection + # These still use direct ForeignKey relationships + Transportation.objects.filter(collection=instance).update(is_public=new_public_status) + Note.objects.filter(collection=instance).update(is_public=new_public_status) + Checklist.objects.filter(collection=instance).update(is_public=new_public_status) + + # Log the action (optional) + action = "public" if new_public_status else "private" + print(f"Collection {instance.id} and its related objects were set to {action}") + + self.perform_update(serializer) + + if getattr(instance, '_prefetched_objects_cache', None): + # If 'prefetch_related' has been applied to a queryset, we need to + # forcibly invalidate the prefetch cache on the instance. + instance._prefetched_objects_cache = {} + + return Response(serializer.data) + + # make an action to retreive all adventures that are shared with the user + @action(detail=False, methods=['get']) + def shared(self, request): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + queryset = Collection.objects.filter( + shared_with=request.user + ) + queryset = self.apply_sorting(queryset) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + # Adds a new user to the shared_with field of an adventure + @action(detail=True, methods=['post'], url_path='share/(?P[^/.]+)') + def share(self, request, pk=None, uuid=None): + collection = self.get_object() + if not uuid: + return Response({"error": "User UUID is required"}, status=400) + try: + user = User.objects.get(uuid=uuid, public_profile=True) + except User.DoesNotExist: + return Response({"error": "User not found"}, status=404) + + if user == request.user: + return Response({"error": "Cannot share with yourself"}, status=400) + + if collection.shared_with.filter(id=user.id).exists(): + return Response({"error": "Adventure is already shared with this user"}, status=400) + + collection.shared_with.add(user) + collection.save() + return Response({"success": f"Shared with {user.username}"}) + + @action(detail=True, methods=['post'], url_path='unshare/(?P[^/.]+)') + def unshare(self, request, pk=None, uuid=None): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + collection = self.get_object() + if not uuid: + return Response({"error": "User UUID is required"}, status=400) + try: + user = User.objects.get(uuid=uuid, public_profile=True) + except User.DoesNotExist: + return Response({"error": "User not found"}, status=404) + + if user == request.user: + return Response({"error": "Cannot unshare with yourself"}, status=400) + + if not collection.shared_with.filter(id=user.id).exists(): + return Response({"error": "Collection is not shared with this user"}, status=400) + + collection.shared_with.remove(user) + collection.save() + return Response({"success": f"Unshared with {user.username}"}) + + def get_queryset(self): + if self.action == 'destroy': + return Collection.objects.filter(user_id=self.request.user.id) + + if self.action in ['update', 'partial_update']: + return Collection.objects.filter( + Q(user_id=self.request.user.id) | Q(shared_with=self.request.user) + ).distinct() + + if self.action == 'retrieve': + if not self.request.user.is_authenticated: + return Collection.objects.filter(is_public=True) + return Collection.objects.filter( + Q(is_public=True) | Q(user_id=self.request.user.id) | Q(shared_with=self.request.user) + ).distinct() + + # For list action, include collections owned by the user or shared with the user, that are not archived + return Collection.objects.filter( + (Q(user_id=self.request.user.id) | Q(shared_with=self.request.user)) & Q(is_archived=False) + ).distinct() + + def perform_create(self, serializer): + # This is ok because you cannot share a collection when creating it + serializer.save(user_id=self.request.user) + + def paginate_and_respond(self, queryset, request): + paginator = self.pagination_class() + page = paginator.paginate_queryset(queryset, request) + if page is not None: + serializer = self.get_serializer(page, many=True) + return paginator.get_paginated_response(serializer.data) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) diff --git a/backend/server/adventures/views/generate_description_view.py b/backend/server/adventures/views/generate_description_view.py new file mode 100644 index 0000000..988773a --- /dev/null +++ b/backend/server/adventures/views/generate_description_view.py @@ -0,0 +1,44 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +import requests + +class GenerateDescription(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + + @action(detail=False, methods=['get'],) + def desc(self, request): + name = self.request.query_params.get('name', '') + # un url encode the name + name = name.replace('%20', ' ') + name = self.get_search_term(name) + url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=extracts&exintro&explaintext&format=json&titles=%s' % name + response = requests.get(url) + data = response.json() + data = response.json() + page_id = next(iter(data["query"]["pages"])) + extract = data["query"]["pages"][page_id] + if extract.get('extract') is None: + return Response({"error": "No description found"}, status=400) + return Response(extract) + @action(detail=False, methods=['get'],) + def img(self, request): + name = self.request.query_params.get('name', '') + # un url encode the name + name = name.replace('%20', ' ') + name = self.get_search_term(name) + url = 'https://en.wikipedia.org/w/api.php?origin=*&action=query&prop=pageimages&format=json&piprop=original&titles=%s' % name + response = requests.get(url) + data = response.json() + page_id = next(iter(data["query"]["pages"])) + extract = data["query"]["pages"][page_id] + if extract.get('original') is None: + return Response({"error": "No image found"}, status=400) + return Response(extract["original"]) + + def get_search_term(self, term): + response = requests.get(f'https://en.wikipedia.org/w/api.php?action=opensearch&search={term}&limit=10&namespace=0&format=json') + data = response.json() + if data[1] and len(data[1]) > 0: + return data[1][0] \ No newline at end of file diff --git a/backend/server/adventures/views/global_search_view.py b/backend/server/adventures/views/global_search_view.py new file mode 100644 index 0000000..d2fa5d3 --- /dev/null +++ b/backend/server/adventures/views/global_search_view.py @@ -0,0 +1,73 @@ +from rest_framework import viewsets +from rest_framework.response import Response +from rest_framework.permissions import IsAuthenticated +from django.db.models import Q +from django.contrib.postgres.search import SearchVector, SearchQuery +from adventures.models import Adventure, Collection +from adventures.serializers import AdventureSerializer, CollectionSerializer +from worldtravel.models import Country, Region, City, VisitedCity, VisitedRegion +from worldtravel.serializers import CountrySerializer, RegionSerializer, CitySerializer, VisitedCitySerializer, VisitedRegionSerializer +from users.models import CustomUser as User +from users.serializers import CustomUserDetailsSerializer as UserSerializer + +class GlobalSearchView(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + + def list(self, request): + search_term = request.query_params.get('query', '').strip() + if not search_term: + return Response({"error": "Search query is required"}, status=400) + + # Initialize empty results + results = { + "adventures": [], + "collections": [], + "users": [], + "countries": [], + "regions": [], + "cities": [], + "visited_regions": [], + "visited_cities": [] + } + + # Adventures: Full-Text Search + adventures = Adventure.objects.annotate( + search=SearchVector('name', 'description', 'location') + ).filter(search=SearchQuery(search_term), user_id=request.user) + results["adventures"] = AdventureSerializer(adventures, many=True).data + + # Collections: Partial Match Search + collections = Collection.objects.filter( + Q(name__icontains=search_term) & Q(user_id=request.user) + ) + results["collections"] = CollectionSerializer(collections, many=True).data + + # Users: Public Profiles Only + users = User.objects.filter( + (Q(username__icontains=search_term) | + Q(first_name__icontains=search_term) | + Q(last_name__icontains=search_term)) & Q(public_profile=True) + ) + results["users"] = UserSerializer(users, many=True).data + + # Countries: Full-Text Search + countries = Country.objects.annotate( + search=SearchVector('name', 'country_code') + ).filter(search=SearchQuery(search_term)) + results["countries"] = CountrySerializer(countries, many=True).data + + # Regions and Cities: Partial Match Search + regions = Region.objects.filter(Q(name__icontains=search_term)) + results["regions"] = RegionSerializer(regions, many=True).data + + cities = City.objects.filter(Q(name__icontains=search_term)) + results["cities"] = CitySerializer(cities, many=True).data + + # Visited Regions and Cities + visited_regions = VisitedRegion.objects.filter(user_id=request.user) + results["visited_regions"] = VisitedRegionSerializer(visited_regions, many=True).data + + visited_cities = VisitedCity.objects.filter(user_id=request.user) + results["visited_cities"] = VisitedCitySerializer(visited_cities, many=True).data + + return Response(results) diff --git a/backend/server/adventures/views/ics_calendar_view.py b/backend/server/adventures/views/ics_calendar_view.py new file mode 100644 index 0000000..9d120e4 --- /dev/null +++ b/backend/server/adventures/views/ics_calendar_view.py @@ -0,0 +1,67 @@ +from django.http import HttpResponse +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from icalendar import Calendar, Event, vText, vCalAddress +from datetime import datetime, timedelta +from adventures.models import Adventure +from adventures.serializers import AdventureSerializer + +class IcsCalendarGeneratorViewSet(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + + @action(detail=False, methods=['get']) + def generate(self, request): + adventures = Adventure.objects.filter(user_id=request.user) + serializer = AdventureSerializer(adventures, many=True) + user = request.user + name = f"{user.first_name} {user.last_name}" + print(serializer.data) + + cal = Calendar() + cal.add('prodid', '-//My Adventure Calendar//example.com//') + cal.add('version', '2.0') + + for adventure in serializer.data: + if adventure['visits']: + for visit in adventure['visits']: + # Skip if start_date is missing + if not visit.get('start_date'): + continue + + # Parse start_date and handle end_date + try: + start_date = datetime.strptime(visit['start_date'], '%Y-%m-%d').date() + except ValueError: + continue # Skip if the start_date is invalid + + end_date = ( + datetime.strptime(visit['end_date'], '%Y-%m-%d').date() + timedelta(days=1) + if visit.get('end_date') else start_date + timedelta(days=1) + ) + + # Create event + event = Event() + event.add('summary', adventure['name']) + event.add('dtstart', start_date) + event.add('dtend', end_date) + event.add('dtstamp', datetime.now()) + event.add('transp', 'TRANSPARENT') + event.add('class', 'PUBLIC') + event.add('created', datetime.now()) + event.add('last-modified', datetime.now()) + event.add('description', adventure['description']) + if adventure.get('location'): + event.add('location', adventure['location']) + if adventure.get('link'): + event.add('url', adventure['link']) + + organizer = vCalAddress(f'MAILTO:{user.email}') + organizer.params['cn'] = vText(name) + event.add('organizer', organizer) + + cal.add_component(event) + + response = HttpResponse(cal.to_ical(), content_type='text/calendar') + response['Content-Disposition'] = 'attachment; filename=adventures.ics' + return response \ No newline at end of file diff --git a/backend/server/adventures/views/lodging_view.py b/backend/server/adventures/views/lodging_view.py new file mode 100644 index 0000000..16114ba --- /dev/null +++ b/backend/server/adventures/views/lodging_view.py @@ -0,0 +1,84 @@ +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response +from django.db.models import Q +from adventures.models import Lodging +from adventures.serializers import LodgingSerializer +from rest_framework.exceptions import PermissionDenied +from adventures.permissions import IsOwnerOrSharedWithFullAccess +from rest_framework.permissions import IsAuthenticated + +class LodgingViewSet(viewsets.ModelViewSet): + queryset = Lodging.objects.all() + serializer_class = LodgingSerializer + permission_classes = [IsOwnerOrSharedWithFullAccess] + + def list(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response(status=status.HTTP_403_FORBIDDEN) + queryset = Lodging.objects.filter( + Q(user_id=request.user.id) + ) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + def get_queryset(self): + user = self.request.user + if self.action == 'retrieve': + # For individual adventure retrieval, include public adventures, user's own adventures and shared adventures + return Lodging.objects.filter( + Q(is_public=True) | Q(user_id=user.id) | Q(collection__shared_with=user.id) + ).distinct().order_by('-updated_at') + # For other actions, include user's own adventures and shared adventures + return Lodging.objects.filter( + Q(user_id=user.id) | Q(collection__shared_with=user.id) + ).distinct().order_by('-updated_at') + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + user = request.user + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + if new_collection is not None and new_collection != instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def perform_update(self, serializer): + serializer.save() + + # when creating an adventure, make sure the user is the owner of the collection or shared with the collection + def perform_create(self, serializer): + # Retrieve the collection from the validated data + collection = serializer.validated_data.get('collection') + + # Check if a collection is provided + if collection: + user = self.request.user + # Check if the user is the owner or is in the shared_with list + if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists(): + # Return an error response if the user does not have permission + raise PermissionDenied("You do not have permission to use this collection.") + # if collection the owner of the adventure is the owner of the collection + serializer.save(user_id=collection.user_id) + return + + # Save the adventure with the current user as the owner + serializer.save(user_id=self.request.user) \ No newline at end of file diff --git a/backend/server/adventures/views/note_view.py b/backend/server/adventures/views/note_view.py new file mode 100644 index 0000000..5f5f314 --- /dev/null +++ b/backend/server/adventures/views/note_view.py @@ -0,0 +1,130 @@ +from rest_framework import viewsets, status +from rest_framework.response import Response +from django.db.models import Q +from adventures.models import Note +from adventures.serializers import NoteSerializer +from rest_framework.exceptions import PermissionDenied +from adventures.permissions import IsOwnerOrSharedWithFullAccess +from rest_framework.decorators import action + +class NoteViewSet(viewsets.ModelViewSet): + queryset = Note.objects.all() + serializer_class = NoteSerializer + permission_classes = [IsOwnerOrSharedWithFullAccess] + filterset_fields = ['is_public', 'collection'] + + # return error message if user is not authenticated on the root endpoint + def list(self, request, *args, **kwargs): + # Prevent listing all adventures + return Response({"detail": "Listing all notes is not allowed."}, + status=status.HTTP_403_FORBIDDEN) + + @action(detail=False, methods=['get']) + def all(self, request): + if not request.user.is_authenticated: + return Response({"error": "User is not authenticated"}, status=400) + queryset = Note.objects.filter( + Q(user_id=request.user.id) + ) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + + def get_queryset(self): + # if the user is not authenticated return only public transportations for retrieve action + if not self.request.user.is_authenticated: + if self.action == 'retrieve': + return Note.objects.filter(is_public=True).distinct().order_by('-updated_at') + return Note.objects.none() + + + if self.action == 'retrieve': + # For individual adventure retrieval, include public adventures + return Note.objects.filter( + Q(is_public=True) | Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user) + ).distinct().order_by('-updated_at') + else: + # For other actions, include user's own adventures and shared adventures + return Note.objects.filter( + Q(user_id=self.request.user.id) | Q(collection__shared_with=self.request.user) + ).distinct().order_by('-updated_at') + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + user = request.user + print(new_collection) + + if new_collection is not None and new_collection!=instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + user = request.user + print(new_collection) + + if new_collection is not None and new_collection!=instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def perform_update(self, serializer): + serializer.save() + + # when creating an adventure, make sure the user is the owner of the collection or shared with the collection + def perform_create(self, serializer): + # Retrieve the collection from the validated data + collection = serializer.validated_data.get('collection') + + # Check if a collection is provided + if collection: + user = self.request.user + # Check if the user is the owner or is in the shared_with list + if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists(): + # Return an error response if the user does not have permission + raise PermissionDenied("You do not have permission to use this collection.") + # if collection the owner of the adventure is the owner of the collection + serializer.save(user_id=collection.user_id) + return + + # Save the adventure with the current user as the owner + serializer.save(user_id=self.request.user) diff --git a/backend/server/adventures/views/recommendations_view.py b/backend/server/adventures/views/recommendations_view.py new file mode 100644 index 0000000..e759f9c --- /dev/null +++ b/backend/server/adventures/views/recommendations_view.py @@ -0,0 +1,258 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from django.conf import settings +import requests +from geopy.distance import geodesic +import time + + +class RecommendationsViewSet(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + BASE_URL = "https://overpass-api.de/api/interpreter" + HEADERS = {'User-Agent': 'AdventureLog Server'} + + def parse_google_places(self, places, origin): + adventures = [] + + for place in places: + location = place.get('location', {}) + types = place.get('types', []) + + # Updated for new API response structure + formatted_address = place.get("formattedAddress") or place.get("shortFormattedAddress") + display_name = place.get("displayName", {}) + name = display_name.get("text") if isinstance(display_name, dict) else display_name + + lat = location.get('latitude') + lon = location.get('longitude') + + if not name or not lat or not lon: + continue + + distance_km = geodesic(origin, (lat, lon)).km + + adventure = { + "id": place.get('id'), + "type": 'place', + "name": name, + "description": place.get('businessStatus', None), + "latitude": lat, + "longitude": lon, + "address": formatted_address, + "tag": types[0] if types else None, + "distance_km": round(distance_km, 2), + } + + adventures.append(adventure) + + # Sort by distance ascending + adventures.sort(key=lambda x: x["distance_km"]) + + return adventures + + def parse_overpass_response(self, data, request): + nodes = data.get('elements', []) + adventures = [] + all = request.query_params.get('all', False) + + origin = None + try: + origin = ( + float(request.query_params.get('lat')), + float(request.query_params.get('lon')) + ) + except(ValueError, TypeError): + origin = None + + for node in nodes: + if node.get('type') not in ['node', 'way', 'relation']: + continue + + tags = node.get('tags', {}) + lat = node.get('lat') + lon = node.get('lon') + name = tags.get('name', tags.get('official_name', '')) + + if not name or lat is None or lon is None: + if not all: + continue + + # Flatten address + address_parts = [tags.get(f'addr:{k}') for k in ['housenumber', 'street', 'suburb', 'city', 'state', 'postcode', 'country']] + formatted_address = ", ".join(filter(None, address_parts)) or name + + # Calculate distance if possible + distance_km = None + if origin: + distance_km = round(geodesic(origin, (lat, lon)).km, 2) + + # Unified format + adventure = { + "id": f"osm:{node.get('id')}", + "type": "place", + "name": name, + "description": tags.get('description'), + "latitude": lat, + "longitude": lon, + "address": formatted_address, + "tag": next((tags.get(key) for key in ['leisure', 'tourism', 'natural', 'historic', 'amenity'] if key in tags), None), + "distance_km": distance_km, + "powered_by": "osm" + } + + adventures.append(adventure) + + # Sort by distance if available + if origin: + adventures.sort(key=lambda x: x.get("distance_km") or float("inf")) + + return adventures + + + def query_overpass(self, lat, lon, radius, category, request): + if category == 'tourism': + query = f""" + [out:json]; + ( + node(around:{radius},{lat},{lon})["tourism"]; + node(around:{radius},{lat},{lon})["leisure"]; + node(around:{radius},{lat},{lon})["historic"]; + node(around:{radius},{lat},{lon})["sport"]; + node(around:{radius},{lat},{lon})["natural"]; + node(around:{radius},{lat},{lon})["attraction"]; + node(around:{radius},{lat},{lon})["museum"]; + node(around:{radius},{lat},{lon})["zoo"]; + node(around:{radius},{lat},{lon})["aquarium"]; + ); + out; + """ + elif category == 'lodging': + query = f""" + [out:json]; + ( + node(around:{radius},{lat},{lon})["tourism"="hotel"]; + node(around:{radius},{lat},{lon})["tourism"="motel"]; + node(around:{radius},{lat},{lon})["tourism"="guest_house"]; + node(around:{radius},{lat},{lon})["tourism"="hostel"]; + node(around:{radius},{lat},{lon})["tourism"="camp_site"]; + node(around:{radius},{lat},{lon})["tourism"="caravan_site"]; + node(around:{radius},{lat},{lon})["tourism"="chalet"]; + node(around:{radius},{lat},{lon})["tourism"="alpine_hut"]; + node(around:{radius},{lat},{lon})["tourism"="apartment"]; + ); + out; + """ + elif category == 'food': + query = f""" + [out:json]; + ( + node(around:{radius},{lat},{lon})["amenity"="restaurant"]; + node(around:{radius},{lat},{lon})["amenity"="cafe"]; + node(around:{radius},{lat},{lon})["amenity"="fast_food"]; + node(around:{radius},{lat},{lon})["amenity"="pub"]; + node(around:{radius},{lat},{lon})["amenity"="bar"]; + node(around:{radius},{lat},{lon})["amenity"="food_court"]; + node(around:{radius},{lat},{lon})["amenity"="ice_cream"]; + node(around:{radius},{lat},{lon})["amenity"="bakery"]; + node(around:{radius},{lat},{lon})["amenity"="confectionery"]; + ); + out; + """ + else: + return Response({"error": "Invalid category."}, status=400) + + overpass_url = f"{self.BASE_URL}?data={query}" + try: + response = requests.get(overpass_url, headers=self.HEADERS) + response.raise_for_status() + data = response.json() + except Exception as e: + print("Overpass API error:", e) + return Response({"error": "Failed to retrieve data from Overpass API."}, status=500) + + adventures = self.parse_overpass_response(data, request) + return Response(adventures) + + def query_google_nearby(self, lat, lon, radius, category, request): + """Query Google Places API (New) for nearby places""" + api_key = settings.GOOGLE_MAPS_API_KEY + + # Updated to use new Places API endpoint + url = "https://places.googleapis.com/v1/places:searchNearby" + + headers = { + 'Content-Type': 'application/json', + 'X-Goog-Api-Key': api_key, + 'X-Goog-FieldMask': 'places.displayName.text,places.formattedAddress,places.location,places.types,places.rating,places.userRatingCount,places.businessStatus,places.id' + } + + # Map categories to place types for the new API + type_mapping = { + 'lodging': 'lodging', + 'food': 'restaurant', + 'tourism': 'tourist_attraction', + } + + payload = { + "includedTypes": [type_mapping[category]], + "maxResultCount": 20, + "locationRestriction": { + "circle": { + "center": { + "latitude": float(lat), + "longitude": float(lon) + }, + "radius": float(radius) + } + } + } + + try: + response = requests.post(url, json=payload, headers=headers, timeout=10) + response.raise_for_status() + data = response.json() + + places = data.get('places', []) + origin = (float(lat), float(lon)) + adventures = self.parse_google_places(places, origin) + + return Response(adventures) + + except requests.exceptions.RequestException as e: + print(f"Google Places API error: {e}") + # Fallback to Overpass API + return self.query_overpass(lat, lon, radius, category, request) + except Exception as e: + print(f"Unexpected error with Google Places API: {e}") + # Fallback to Overpass API + return self.query_overpass(lat, lon, radius, category, request) + + @action(detail=False, methods=['get']) + def query(self, request): + lat = request.query_params.get('lat') + lon = request.query_params.get('lon') + radius = request.query_params.get('radius', '1000') + category = request.query_params.get('category', 'all') + + if not lat or not lon: + return Response({"error": "Latitude and longitude parameters are required."}, status=400) + + valid_categories = { + 'lodging': 'lodging', + 'food': 'restaurant', + 'tourism': 'tourist_attraction', + } + + if category not in valid_categories: + return Response({"error": f"Invalid category. Valid categories: {', '.join(valid_categories)}"}, status=400) + + api_key = getattr(settings, 'GOOGLE_MAPS_API_KEY', None) + + # Fallback to Overpass if no API key configured + if not api_key: + return self.query_overpass(lat, lon, radius, category, request) + + # Use the new Google Places API + return self.query_google_nearby(lat, lon, radius, category, request) \ No newline at end of file diff --git a/backend/server/adventures/views/reverse_geocode_view.py b/backend/server/adventures/views/reverse_geocode_view.py new file mode 100644 index 0000000..df45f13 --- /dev/null +++ b/backend/server/adventures/views/reverse_geocode_view.py @@ -0,0 +1,87 @@ +from rest_framework import viewsets +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from worldtravel.models import Region, City, VisitedRegion, VisitedCity +from adventures.models import Adventure +from adventures.serializers import AdventureSerializer +import requests +from adventures.geocoding import reverse_geocode +from adventures.geocoding import extractIsoCode +from django.conf import settings +from adventures.geocoding import search_google, search_osm + +class ReverseGeocodeViewSet(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + + @action(detail=False, methods=['get']) + def reverse_geocode(self, request): + lat = request.query_params.get('lat', '') + lon = request.query_params.get('lon', '') + if not lat or not lon: + return Response({"error": "Latitude and longitude are required"}, status=400) + try: + lat = float(lat) + lon = float(lon) + except ValueError: + return Response({"error": "Invalid latitude or longitude"}, status=400) + data = reverse_geocode(lat, lon, self.request.user) + if 'error' in data: + return Response({"error": "An internal error occurred while processing the request"}, status=400) + return Response(data) + + @action(detail=False, methods=['get']) + def search(self, request): + query = request.query_params.get('query', '') + if not query: + return Response({"error": "Query parameter is required"}, status=400) + + try: + if getattr(settings, 'GOOGLE_MAPS_API_KEY', None): + results = search_google(query) + else: + results = search_osm(query) + return Response(results) + except Exception: + return Response({"error": "An internal error occurred while processing the request"}, status=500) + + @action(detail=False, methods=['post']) + def mark_visited_region(self, request): + # searches through all of the users adventures, if the serialized data is_visited, is true, runs reverse geocode on the adventures and if a region is found, marks it as visited. Use the extractIsoCode function to get the region + new_region_count = 0 + new_regions = {} + new_city_count = 0 + new_cities = {} + adventures = Adventure.objects.filter(user_id=self.request.user) + serializer = AdventureSerializer(adventures, many=True) + for adventure, serialized_adventure in zip(adventures, serializer.data): + if serialized_adventure['is_visited'] == True: + lat = adventure.latitude + lon = adventure.longitude + if not lat or not lon: + continue + + # Use the existing reverse_geocode function which handles both Google and OSM + data = reverse_geocode(lat, lon, self.request.user) + if 'error' in data: + continue + + # data already contains region_id and city_id + if 'region_id' in data and data['region_id'] is not None: + region = Region.objects.filter(id=data['region_id']).first() + visited_region = VisitedRegion.objects.filter(region=region, user_id=self.request.user).first() + if not visited_region: + visited_region = VisitedRegion(region=region, user_id=self.request.user) + visited_region.save() + new_region_count += 1 + new_regions[region.id] = region.name + + if 'city_id' in data and data['city_id'] is not None: + city = City.objects.filter(id=data['city_id']).first() + visited_city = VisitedCity.objects.filter(city=city, user_id=self.request.user).first() + if not visited_city: + visited_city = VisitedCity(city=city, user_id=self.request.user) + visited_city.save() + new_city_count += 1 + new_cities[city.id] = city.name + return Response({"new_regions": new_region_count, "regions": new_regions, "new_cities": new_city_count, "cities": new_cities}) \ No newline at end of file diff --git a/backend/server/adventures/views/stats_view.py b/backend/server/adventures/views/stats_view.py new file mode 100644 index 0000000..8b56f26 --- /dev/null +++ b/backend/server/adventures/views/stats_view.py @@ -0,0 +1,51 @@ +from rest_framework import viewsets +from rest_framework.permissions import IsAuthenticated +from rest_framework.response import Response +from rest_framework.decorators import action +from django.shortcuts import get_object_or_404 +from worldtravel.models import City, Region, Country, VisitedCity, VisitedRegion +from adventures.models import Adventure, Collection +from users.serializers import CustomUserDetailsSerializer as PublicUserSerializer +from django.contrib.auth import get_user_model + +User = get_user_model() + +class StatsViewSet(viewsets.ViewSet): + """ + A simple ViewSet for listing the stats of a user. + """ + @action(detail=False, methods=['get'], url_path=r'counts/(?P[\w.@+-]+)') + def counts(self, request, username): + if request.user.username == username: + user = get_object_or_404(User, username=username) + else: + user = get_object_or_404(User, username=username, public_profile=True) + # serializer = PublicUserSerializer(user) + + # remove the email address from the response + user.email = None + + # get the counts for the user + adventure_count = Adventure.objects.filter( + user_id=user.id).count() + trips_count = Collection.objects.filter( + user_id=user.id).count() + visited_city_count = VisitedCity.objects.filter( + user_id=user.id).count() + total_cities = City.objects.count() + visited_region_count = VisitedRegion.objects.filter( + user_id=user.id).count() + total_regions = Region.objects.count() + visited_country_count = VisitedRegion.objects.filter( + user_id=user.id).values('region__country').distinct().count() + total_countries = Country.objects.count() + return Response({ + 'adventure_count': adventure_count, + 'trips_count': trips_count, + 'visited_city_count': visited_city_count, + 'total_cities': total_cities, + 'visited_region_count': visited_region_count, + 'total_regions': total_regions, + 'visited_country_count': visited_country_count, + 'total_countries': total_countries + }) \ No newline at end of file diff --git a/backend/server/adventures/views/transportation_view.py b/backend/server/adventures/views/transportation_view.py new file mode 100644 index 0000000..2bd1e8c --- /dev/null +++ b/backend/server/adventures/views/transportation_view.py @@ -0,0 +1,84 @@ +from rest_framework import viewsets, status +from rest_framework.decorators import action +from rest_framework.response import Response +from django.db.models import Q +from adventures.models import Transportation +from adventures.serializers import TransportationSerializer +from rest_framework.exceptions import PermissionDenied +from adventures.permissions import IsOwnerOrSharedWithFullAccess +from rest_framework.permissions import IsAuthenticated + +class TransportationViewSet(viewsets.ModelViewSet): + queryset = Transportation.objects.all() + serializer_class = TransportationSerializer + permission_classes = [IsOwnerOrSharedWithFullAccess] + + def list(self, request, *args, **kwargs): + if not request.user.is_authenticated: + return Response(status=status.HTTP_403_FORBIDDEN) + queryset = Transportation.objects.filter( + Q(user_id=request.user.id) + ) + serializer = self.get_serializer(queryset, many=True) + return Response(serializer.data) + + def get_queryset(self): + user = self.request.user + if self.action == 'retrieve': + # For individual adventure retrieval, include public adventures, user's own adventures and shared adventures + return Transportation.objects.filter( + Q(is_public=True) | Q(user_id=user.id) | Q(collection__shared_with=user.id) + ).distinct().order_by('-updated_at') + # For other actions, include user's own adventures and shared adventures + return Transportation.objects.filter( + Q(user_id=user.id) | Q(collection__shared_with=user.id) + ).distinct().order_by('-updated_at') + + def partial_update(self, request, *args, **kwargs): + # Retrieve the current object + instance = self.get_object() + user = request.user + + # Partially update the instance with the request data + serializer = self.get_serializer(instance, data=request.data, partial=True) + serializer.is_valid(raise_exception=True) + + # Retrieve the collection from the validated data + new_collection = serializer.validated_data.get('collection') + + if new_collection is not None and new_collection != instance.collection: + # Check if the user is the owner of the new collection + if new_collection.user_id != user or instance.user_id != user: + raise PermissionDenied("You do not have permission to use this collection.") + elif new_collection is None: + # Handle the case where the user is trying to set the collection to None + if instance.collection is not None and instance.collection.user_id != user: + raise PermissionDenied("You cannot remove the collection as you are not the owner.") + + # Perform the update + self.perform_update(serializer) + + # Return the updated instance + return Response(serializer.data) + + def perform_update(self, serializer): + serializer.save() + + # when creating an adventure, make sure the user is the owner of the collection or shared with the collection + def perform_create(self, serializer): + # Retrieve the collection from the validated data + collection = serializer.validated_data.get('collection') + + # Check if a collection is provided + if collection: + user = self.request.user + # Check if the user is the owner or is in the shared_with list + if collection.user_id != user and not collection.shared_with.filter(id=user.id).exists(): + # Return an error response if the user does not have permission + raise PermissionDenied("You do not have permission to use this collection.") + # if collection the owner of the adventure is the owner of the collection + serializer.save(user_id=collection.user_id) + return + + # Save the adventure with the current user as the owner + serializer.save(user_id=self.request.user) \ No newline at end of file diff --git a/backend/server/demo/settings.py b/backend/server/demo/settings.py deleted file mode 100644 index 9170fe2..0000000 --- a/backend/server/demo/settings.py +++ /dev/null @@ -1,213 +0,0 @@ -""" -Django settings for demo project. - -For more information on this file, see -https://docs.djangoproject.com/en/1.7/topics/settings/ - -For the full list of settings and their values, see -https://docs.djangoproject.com/en/1.7/ref/settings/ -""" - -# Build paths inside the project like this: os.path.join(BASE_DIR, ...) -import os -from dotenv import load_dotenv -from datetime import timedelta -from os import getenv -from pathlib import Path -# Load environment variables from .env file -load_dotenv() - -BASE_DIR = os.path.dirname(os.path.dirname(__file__)) - -# Quick-start development settings - unsuitable for production -# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ - -# SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = getenv('SECRET_KEY') - -# SECURITY WARNING: don't run with debug turned on in production! -DEBUG = getenv('DEBUG', 'True') == 'True' - -# ALLOWED_HOSTS = [ -# 'localhost', -# '127.0.0.1', -# 'server' -# ] -ALLOWED_HOSTS = ['*'] - -# Application definition - -INSTALLED_APPS = ( - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'django.contrib.sites', - 'rest_framework', - 'rest_framework.authtoken', - 'dj_rest_auth', - 'allauth', - 'allauth.account', - 'dj_rest_auth.registration', - 'allauth.socialaccount', - 'allauth.socialaccount.providers.facebook', - 'drf_yasg', - 'corsheaders', - 'adventures', - 'worldtravel', - 'users', - -) - -MIDDLEWARE = ( - 'whitenoise.middleware.WhiteNoiseMiddleware', - 'corsheaders.middleware.CorsMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', - 'allauth.account.middleware.AccountMiddleware', - -) - -# For backwards compatibility for Django 1.8 -MIDDLEWARE_CLASSES = MIDDLEWARE - -ROOT_URLCONF = 'demo.urls' - -# WSGI_APPLICATION = 'demo.wsgi.application' - -SIMPLE_JWT = { - "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), - "REFRESH_TOKEN_LIFETIME": timedelta(days=365), -} - -# Database -# https://docs.djangoproject.com/en/1.7/ref/settings/#databases - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.postgresql', - 'NAME': getenv('PGDATABASE'), - 'USER': getenv('PGUSER'), - 'PASSWORD': getenv('PGPASSWORD'), - 'HOST': getenv('PGHOST'), - 'PORT': getenv('PGPORT', 5432), - 'OPTIONS': { - 'sslmode': 'prefer', # Prefer SSL, but allow non-SSL connections - }, - } -} - - -# Internationalization -# https://docs.djangoproject.com/en/1.7/topics/i18n/ - -LANGUAGE_CODE = 'en-us' - -TIME_ZONE = 'America/New_York' - -USE_I18N = True - -USE_L10N = True - -USE_TZ = True - -# Static files (CSS, JavaScript, Images) -# https://docs.djangoproject.com/en/1.7/howto/static-files/ - - -BASE_DIR = Path(__file__).resolve().parent.parent -STATIC_ROOT = BASE_DIR / "staticfiles" -STATIC_URL = '/static/' - -MEDIA_URL = '/media/' -MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] - - -# TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')] - -TEMPLATES = [ - { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', - ], - }, - }, -] - -REST_AUTH = { - 'SESSION_LOGIN': True, - 'USE_JWT': True, - 'JWT_AUTH_COOKIE': 'auth', - 'JWT_AUTH_HTTPONLY': False, - 'REGISTER_SERIALIZER': 'users.serializers.RegisterSerializer', - 'USER_DETAILS_SERIALIZER': 'users.serializers.CustomUserDetailsSerializer', - -} - -STORAGES = { - "staticfiles": { - "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", - }, - "default": { - "BACKEND": "django.core.files.storage.FileSystemStorage", - } -} - -AUTH_USER_MODEL = 'users.CustomUser' - -EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' -SITE_ID = 1 -ACCOUNT_EMAIL_REQUIRED = True -ACCOUNT_AUTHENTICATION_METHOD = 'username' -ACCOUNT_EMAIL_VERIFICATION = 'optional' - -# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -# EMAIL_HOST = 'smtp.resend.com' -# EMAIL_USE_TLS = False -# EMAIL_PORT = 2465 -# EMAIL_USE_SSL = True -# EMAIL_HOST_USER = 'resend' -# EMAIL_HOST_PASSWORD = '' -# DEFAULT_FROM_EMAIL = 'mail@mail.user.com' - - -REST_FRAMEWORK = { - 'DEFAULT_AUTHENTICATION_CLASSES': ( - 'rest_framework.authentication.SessionAuthentication', - 'rest_framework.authentication.TokenAuthentication', - 'dj_rest_auth.jwt_auth.JWTCookieAuthentication' - ), - 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', - # 'DEFAULT_PERMISSION_CLASSES': [ - # 'rest_framework.permissions.IsAuthenticated', - # ], -} - -SWAGGER_SETTINGS = { - 'LOGIN_URL': 'login', - 'LOGOUT_URL': 'logout', -} - - -# For demo purposes only. Use a white list in the real world. -CORS_ORIGIN_ALLOW_ALL = True - - -from os import getenv - -CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost').split(',') if origin.strip()] -DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' diff --git a/backend/server/demo/urls.py b/backend/server/demo/urls.py deleted file mode 100644 index b5d705b..0000000 --- a/backend/server/demo/urls.py +++ /dev/null @@ -1,71 +0,0 @@ -from django.urls import include, re_path, path -from django.contrib import admin -from django.views.generic import RedirectView, TemplateView -from django.conf import settings -from django.conf.urls.static import static -from adventures import urls as adventures -from users.views import ChangeEmailView -from .views import get_csrf_token -from drf_yasg.views import get_schema_view - -from drf_yasg import openapi - -schema_view = get_schema_view( - openapi.Info( - title='API Docs', - default_version='v1', - ) -) -urlpatterns = [ - path('api/', include('adventures.urls')), - path('api/', include('worldtravel.urls')), - - path('auth/change-email/', ChangeEmailView.as_view(), name='change_email'), - - path('csrf/', get_csrf_token, name='get_csrf_token'), - re_path(r'^$', TemplateView.as_view( - template_name="home.html"), name='home'), - re_path(r'^signup/$', TemplateView.as_view(template_name="signup.html"), - name='signup'), - re_path(r'^email-verification/$', - TemplateView.as_view(template_name="email_verification.html"), - name='email-verification'), - re_path(r'^login/$', TemplateView.as_view(template_name="login.html"), - name='login'), - re_path(r'^logout/$', TemplateView.as_view(template_name="logout.html"), - name='logout'), - re_path(r'^password-reset/$', - TemplateView.as_view(template_name="password_reset.html"), - name='password-reset'), - re_path(r'^password-reset/confirm/$', - TemplateView.as_view(template_name="password_reset_confirm.html"), - name='password-reset-confirm'), - - re_path(r'^user-details/$', - TemplateView.as_view(template_name="user_details.html"), - name='user-details'), - re_path(r'^password-change/$', - TemplateView.as_view(template_name="password_change.html"), - name='password-change'), - re_path(r'^resend-email-verification/$', - TemplateView.as_view( - template_name="resend_email_verification.html"), - name='resend-email-verification'), - - - # this url is used to generate email content - re_path(r'^password-reset/confirm/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,32})/$', - TemplateView.as_view(template_name="password_reset_confirm.html"), - name='password_reset_confirm'), - - re_path(r'^auth/', include('dj_rest_auth.urls')), - re_path(r'^auth/registration/', - include('dj_rest_auth.registration.urls')), - re_path(r'^account/', include('allauth.urls')), - re_path(r'^admin/', admin.site.urls), - re_path(r'^accounts/profile/$', RedirectView.as_view(url='/', - permanent=True), name='profile-redirect'), - re_path(r'^docs/$', schema_view.with_ui('swagger', - cache_timeout=0), name='api_docs'), - # path('auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), -] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/backend/server/demo/views.py b/backend/server/demo/views.py deleted file mode 100644 index 7a7507d..0000000 --- a/backend/server/demo/views.py +++ /dev/null @@ -1,6 +0,0 @@ -from django.http import JsonResponse -from django.middleware.csrf import get_token - -def get_csrf_token(request): - csrf_token = get_token(request) - return JsonResponse({'csrfToken': csrf_token}) diff --git a/documentation/static/.nojekyll b/backend/server/integrations/__init__.py similarity index 100% rename from documentation/static/.nojekyll rename to backend/server/integrations/__init__.py diff --git a/backend/server/integrations/admin.py b/backend/server/integrations/admin.py new file mode 100644 index 0000000..d561cf4 --- /dev/null +++ b/backend/server/integrations/admin.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from allauth.account.decorators import secure_admin_login + +from .models import ImmichIntegration + +admin.autodiscover() +admin.site.login = secure_admin_login(admin.site.login) + +admin.site.register(ImmichIntegration) \ No newline at end of file diff --git a/backend/server/integrations/apps.py b/backend/server/integrations/apps.py new file mode 100644 index 0000000..73adb7a --- /dev/null +++ b/backend/server/integrations/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class IntegrationsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'integrations' diff --git a/backend/server/integrations/migrations/0001_initial.py b/backend/server/integrations/migrations/0001_initial.py new file mode 100644 index 0000000..1bf029b --- /dev/null +++ b/backend/server/integrations/migrations/0001_initial.py @@ -0,0 +1,27 @@ +# Generated by Django 5.0.8 on 2025-01-02 23:16 + +import django.db.models.deletion +import uuid +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='ImmichIntegration', + fields=[ + ('server_url', models.CharField(max_length=255)), + ('api_key', models.CharField(max_length=255)), + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/backend/server/integrations/migrations/0002_immichintegration_copy_locally.py b/backend/server/integrations/migrations/0002_immichintegration_copy_locally.py new file mode 100644 index 0000000..cdd59cc --- /dev/null +++ b/backend/server/integrations/migrations/0002_immichintegration_copy_locally.py @@ -0,0 +1,18 @@ +# Generated by Django 5.2.1 on 2025-06-01 21:38 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('integrations', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='immichintegration', + name='copy_locally', + field=models.BooleanField(default=True, help_text='Copy image to local storage, instead of just linking to the remote URL.'), + ), + ] diff --git a/backend/server/integrations/migrations/__init__.py b/backend/server/integrations/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/server/integrations/models.py b/backend/server/integrations/models.py new file mode 100644 index 0000000..7b0400a --- /dev/null +++ b/backend/server/integrations/models.py @@ -0,0 +1,16 @@ +from django.db import models +from django.contrib.auth import get_user_model +import uuid + +User = get_user_model() + +class ImmichIntegration(models.Model): + server_url = models.CharField(max_length=255) + api_key = models.CharField(max_length=255) + user = models.ForeignKey( + User, on_delete=models.CASCADE) + copy_locally = models.BooleanField(default=True, help_text="Copy image to local storage, instead of just linking to the remote URL.") + id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) + + def __str__(self): + return self.user.username + ' - ' + self.server_url \ No newline at end of file diff --git a/backend/server/integrations/serializers.py b/backend/server/integrations/serializers.py new file mode 100644 index 0000000..cc92d21 --- /dev/null +++ b/backend/server/integrations/serializers.py @@ -0,0 +1,13 @@ +from .models import ImmichIntegration +from rest_framework import serializers + +class ImmichIntegrationSerializer(serializers.ModelSerializer): + class Meta: + model = ImmichIntegration + fields = '__all__' + read_only_fields = ['id', 'user'] + + def to_representation(self, instance): + representation = super().to_representation(instance) + representation.pop('user', None) + return representation diff --git a/backend/server/integrations/tests.py b/backend/server/integrations/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/backend/server/integrations/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/backend/server/integrations/urls.py b/backend/server/integrations/urls.py new file mode 100644 index 0000000..a15bbd0 --- /dev/null +++ b/backend/server/integrations/urls.py @@ -0,0 +1,14 @@ +from django.urls import path, include +from rest_framework.routers import DefaultRouter +from integrations.views import ImmichIntegrationView, IntegrationView, ImmichIntegrationViewSet + +# Create the router and register the ViewSet +router = DefaultRouter() +router.register(r'immich', ImmichIntegrationView, basename='immich') +router.register(r'', IntegrationView, basename='integrations') +router.register(r'immich', ImmichIntegrationViewSet, basename='immich_viewset') + +# Include the router URLs +urlpatterns = [ + path("", include(router.urls)), # Includes /immich/ routes +] diff --git a/backend/server/integrations/views.py b/backend/server/integrations/views.py new file mode 100644 index 0000000..e5540b9 --- /dev/null +++ b/backend/server/integrations/views.py @@ -0,0 +1,566 @@ +import os +from rest_framework.response import Response +from rest_framework import viewsets, status +from .serializers import ImmichIntegrationSerializer +from .models import ImmichIntegration +from rest_framework.decorators import action +from rest_framework.permissions import IsAuthenticated +import requests +from rest_framework.pagination import PageNumberPagination +from django.conf import settings +from adventures.models import AdventureImage +from django.http import HttpResponse +from django.shortcuts import get_object_or_404 +import logging + +logger = logging.getLogger(__name__) + +class IntegrationView(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + def list(self, request): + """ + RESTful GET method for listing all integrations. + """ + immich_integrations = ImmichIntegration.objects.filter(user=request.user) + google_map_integration = settings.GOOGLE_MAPS_API_KEY != '' + + return Response( + { + 'immich': immich_integrations.exists(), + 'google_maps': google_map_integration + }, + status=status.HTTP_200_OK + ) + +class StandardResultsSetPagination(PageNumberPagination): + page_size = 25 + page_size_query_param = 'page_size' + max_page_size = 1000 + +class ImmichIntegrationView(viewsets.ViewSet): + permission_classes = [IsAuthenticated] + pagination_class = StandardResultsSetPagination + + def check_integration(self, request): + """ + Checks if the user has an active Immich integration. + Returns: + - The integration object if it exists. + - A Response with an error message if the integration is missing. + """ + if not request.user.is_authenticated: + return Response( + { + 'message': 'You need to be authenticated to use this feature.', + 'error': True, + 'code': 'immich.authentication_required' + }, + status=status.HTTP_403_FORBIDDEN + ) + + user_integrations = ImmichIntegration.objects.filter(user=request.user) + if not user_integrations.exists(): + return Response( + { + 'message': 'You need to have an active Immich integration to use this feature.', + 'error': True, + 'code': 'immich.integration_missing' + }, + status=status.HTTP_403_FORBIDDEN + ) + + return user_integrations.first() + + @action(detail=False, methods=['get'], url_path='search') + def search(self, request): + """ + Handles the logic for searching Immich images. + """ + # Check for integration before proceeding + integration = self.check_integration(request) + if isinstance(integration, Response): + return integration + + query = request.query_params.get('query', '') + date = request.query_params.get('date', '') + + if not query and not date: + return Response( + { + 'message': 'Query or date is required.', + 'error': True, + 'code': 'immich.query_required' + }, + status=status.HTTP_400_BAD_REQUEST + ) + + arguments = {} + if query: + arguments['query'] = query + if date: + # Create date range for the entire selected day + from datetime import datetime, timedelta + try: + # Parse the date and create start/end of day + selected_date = datetime.strptime(date, '%Y-%m-%d') + start_of_day = selected_date.strftime('%Y-%m-%d') + end_of_day = (selected_date + timedelta(days=1)).strftime('%Y-%m-%d') + + arguments['takenAfter'] = start_of_day + arguments['takenBefore'] = end_of_day + except ValueError: + return Response( + { + 'message': 'Invalid date format. Use YYYY-MM-DD.', + 'error': True, + 'code': 'immich.invalid_date_format' + }, + status=status.HTTP_400_BAD_REQUEST + ) + + # check so if the server is down, it does not tweak out like a madman and crash the server with a 500 error code + try: + url = f'{integration.server_url}/search/{"smart" if query else "metadata"}' + immich_fetch = requests.post(url, headers={ + 'x-api-key': integration.api_key + }, + json = arguments + ) + res = immich_fetch.json() + except requests.exceptions.ConnectionError: + return Response( + { + 'message': 'The Immich server is currently down or unreachable.', + 'error': True, + 'code': 'immich.server_down' + }, + status=status.HTTP_503_SERVICE_UNAVAILABLE + ) + + if 'assets' in res and 'items' in res['assets']: + paginator = self.pagination_class() + # for each item in the items, we need to add the image url to the item so we can display it in the frontend + public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/') + public_url = public_url.replace("'", "") + for item in res['assets']['items']: + item['image_url'] = f'{public_url}/api/integrations/immich/{integration.id}/get/{item["id"]}' + result_page = paginator.paginate_queryset(res['assets']['items'], request) + return paginator.get_paginated_response(result_page) + else: + return Response( + { + 'message': 'No items found.', + 'error': True, + 'code': 'immich.no_items_found' + }, + status=status.HTTP_404_NOT_FOUND + ) + + @action(detail=False, methods=['get']) + def albums(self, request): + """ + RESTful GET method for retrieving all Immich albums. + """ + # Check for integration before proceeding + integration = self.check_integration(request) + if isinstance(integration, Response): + return integration + + # check so if the server is down, it does not tweak out like a madman and crash the server with a 500 error code + try: + immich_fetch = requests.get(f'{integration.server_url}/albums', headers={ + 'x-api-key': integration.api_key + }) + res = immich_fetch.json() + except requests.exceptions.ConnectionError: + return Response( + { + 'message': 'The Immich server is currently down or unreachable.', + 'error': True, + 'code': 'immich.server_down' + }, + status=status.HTTP_503_SERVICE_UNAVAILABLE + ) + + return Response( + res, + status=status.HTTP_200_OK + ) + + @action(detail=False, methods=['get'], url_path='albums/(?P[^/.]+)') + def album(self, request, albumid=None): + """ + RESTful GET method for retrieving a specific Immich album by ID. + """ + # Check for integration before proceeding + integration = self.check_integration(request) + print(integration.user) + if isinstance(integration, Response): + return integration + + if not albumid: + return Response( + { + 'message': 'Album ID is required.', + 'error': True, + 'code': 'immich.albumid_required' + }, + status=status.HTTP_400_BAD_REQUEST + ) + + # check so if the server is down, it does not tweak out like a madman and crash the server with a 500 error code + try: + immich_fetch = requests.get(f'{integration.server_url}/albums/{albumid}', headers={ + 'x-api-key': integration.api_key + }) + res = immich_fetch.json() + except requests.exceptions.ConnectionError: + return Response( + { + 'message': 'The Immich server is currently down or unreachable.', + 'error': True, + 'code': 'immich.server_down' + }, + status=status.HTTP_503_SERVICE_UNAVAILABLE + ) + + if 'assets' in res: + paginator = self.pagination_class() + # for each item in the items, we need to add the image url to the item so we can display it in the frontend + public_url = os.environ.get('PUBLIC_URL', 'http://127.0.0.1:8000').rstrip('/') + public_url = public_url.replace("'", "") + for item in res['assets']: + item['image_url'] = f'{public_url}/api/integrations/immich/{integration.id}/get/{item["id"]}' + result_page = paginator.paginate_queryset(res['assets'], request) + return paginator.get_paginated_response(result_page) + else: + return Response( + { + 'message': 'No assets found in this album.', + 'error': True, + 'code': 'immich.no_assets_found' + }, + status=status.HTTP_404_NOT_FOUND + ) + + @action( + detail=False, + methods=['get'], + url_path='(?P[^/.]+)/get/(?P[^/.]+)', + permission_classes=[] + ) + def get_by_integration(self, request, integration_id=None, imageid=None): + """ + GET an Immich image using the integration and asset ID. + Access levels (in order of priority): + 1. Public adventures: accessible by anyone + 2. Private adventures in public collections: accessible by anyone + 3. Private adventures in private collections shared with user: accessible by shared users + 4. Private adventures: accessible only to the owner + 5. No AdventureImage: owner can still view via integration + """ + if not imageid or not integration_id: + return Response({ + 'message': 'Image ID and Integration ID are required.', + 'error': True, + 'code': 'immich.missing_params' + }, status=status.HTTP_400_BAD_REQUEST) + + # Lookup integration and user + integration = get_object_or_404(ImmichIntegration, id=integration_id) + owner_id = integration.user_id + + # Try to find the image entry with collections and sharing information + image_entry = ( + AdventureImage.objects + .filter(immich_id=imageid, user_id=owner_id) + .select_related('adventure') + .prefetch_related('adventure__collections', 'adventure__collections__shared_with') + .order_by('-adventure__is_public') # Public adventures first + .first() + ) + + # Access control + if image_entry: + adventure = image_entry.adventure + collections = adventure.collections.all() + + # Determine access level + is_authorized = False + + # Level 1: Public adventure (highest priority) + if adventure.is_public: + is_authorized = True + + # Level 2: Private adventure in any public collection + elif any(collection.is_public for collection in collections): + is_authorized = True + + # Level 3: Owner access + elif request.user.is_authenticated and request.user.id == owner_id: + is_authorized = True + + # Level 4: Shared collection access - check if user has access to any collection + elif (request.user.is_authenticated and + any(collection.shared_with.filter(id=request.user.id).exists() + for collection in collections)): + is_authorized = True + + if not is_authorized: + return Response({ + 'message': 'This image belongs to a private adventure and you are not authorized.', + 'error': True, + 'code': 'immich.permission_denied' + }, status=status.HTTP_403_FORBIDDEN) + else: + # No AdventureImage exists; allow only the integration owner + if not request.user.is_authenticated or request.user.id != owner_id: + return Response({ + 'message': 'Image is not linked to any adventure and you are not the owner.', + 'error': True, + 'code': 'immich.not_found' + }, status=status.HTTP_404_NOT_FOUND) + + # Fetch from Immich + try: + immich_response = requests.get( + f'{integration.server_url}/assets/{imageid}/thumbnail?size=preview', + headers={'x-api-key': integration.api_key}, + timeout=5 + ) + content_type = immich_response.headers.get('Content-Type', 'image/jpeg') + if not content_type.startswith('image/'): + return Response({ + 'message': 'Invalid content type returned from Immich.', + 'error': True, + 'code': 'immich.invalid_content' + }, status=status.HTTP_502_BAD_GATEWAY) + + response = HttpResponse(immich_response.content, content_type=content_type, status=200) + response['Cache-Control'] = 'public, max-age=86400, stale-while-revalidate=3600' + return response + + except requests.exceptions.ConnectionError: + return Response({ + 'message': 'The Immich server is unreachable.', + 'error': True, + 'code': 'immich.server_down' + }, status=status.HTTP_503_SERVICE_UNAVAILABLE) + + except requests.exceptions.Timeout: + return Response({ + 'message': 'The Immich server request timed out.', + 'error': True, + 'code': 'immich.timeout' + }, status=status.HTTP_504_GATEWAY_TIMEOUT) + +class ImmichIntegrationViewSet(viewsets.ModelViewSet): + permission_classes = [IsAuthenticated] + serializer_class = ImmichIntegrationSerializer + queryset = ImmichIntegration.objects.all() + + def get_queryset(self): + return ImmichIntegration.objects.filter(user=self.request.user) + + def _validate_immich_connection(self, server_url, api_key): + """ + Validate connection to Immich server before saving integration. + Returns tuple: (is_valid, corrected_server_url, error_message) + """ + if not server_url or not api_key: + return False, server_url, "Server URL and API key are required" + + # Ensure server_url has proper format + if not server_url.startswith(('http://', 'https://')): + server_url = f"https://{server_url}" + + # Remove trailing slash if present + original_server_url = server_url.rstrip('/') + + # Try both with and without /api prefix + test_configs = [ + (original_server_url, f"{original_server_url}/users/me"), + (f"{original_server_url}/api", f"{original_server_url}/api/users/me") + ] + + headers = { + 'X-API-Key': api_key, + 'Content-Type': 'application/json' + } + + for corrected_url, test_endpoint in test_configs: + try: + response = requests.get( + test_endpoint, + headers=headers, + timeout=10, # 10 second timeout + verify=True # SSL verification + ) + + if response.status_code == 200: + try: + json_response = response.json() + # Validate expected Immich user response structure + required_fields = ['id', 'email', 'name', 'isAdmin', 'createdAt'] + if all(field in json_response for field in required_fields): + return True, corrected_url, None + else: + continue # Try next endpoint + except (ValueError, KeyError): + continue # Try next endpoint + elif response.status_code == 401: + return False, original_server_url, "Invalid API key or unauthorized access" + elif response.status_code == 403: + return False, original_server_url, "Access forbidden - check API key permissions" + # Continue to next endpoint for 404 errors + + except requests.exceptions.ConnectTimeout: + return False, original_server_url, "Connection timeout - server may be unreachable" + except requests.exceptions.ConnectionError: + return False, original_server_url, "Cannot connect to server - check URL and network connectivity" + except requests.exceptions.SSLError: + return False, original_server_url, "SSL certificate error - check server certificate" + except requests.exceptions.RequestException as e: + logger.error(f"RequestException during Immich connection validation: {str(e)}") + return False, original_server_url, "Connection failed due to a network error." + except Exception as e: + logger.error(f"Unexpected error during Immich connection validation: {str(e)}") + return False, original_server_url, "An unexpected error occurred while validating the connection." + + # If we get here, none of the endpoints worked + return False, original_server_url, "Immich server endpoint not found - check server URL" + + def create(self, request): + """ + RESTful POST method for creating a new Immich integration. + """ + # Check if the user already has an integration + user_integrations = ImmichIntegration.objects.filter(user=request.user) + if user_integrations.exists(): + return Response( + { + 'message': 'You already have an active Immich integration.', + 'error': True, + 'code': 'immich.integration_exists' + }, + status=status.HTTP_400_BAD_REQUEST + ) + + serializer = self.serializer_class(data=request.data) + if serializer.is_valid(): + # Validate Immich server connection before saving + server_url = serializer.validated_data.get('server_url') + api_key = serializer.validated_data.get('api_key') + + is_valid, corrected_server_url, error_message = self._validate_immich_connection(server_url, api_key) + + if not is_valid: + return Response( + { + 'message': f'Cannot connect to Immich server: {error_message}', + 'error': True, + 'code': 'immich.connection_failed', + 'details': error_message + }, + status=status.HTTP_400_BAD_REQUEST + ) + + # If validation passes, save the integration with the corrected URL + serializer.save(user=request.user, server_url=corrected_server_url) + return Response( + serializer.data, + status=status.HTTP_201_CREATED + ) + + return Response( + serializer.errors, + status=status.HTTP_400_BAD_REQUEST + ) + + def update(self, request, pk=None): + """ + RESTful PUT method for updating an existing Immich integration. + """ + integration = ImmichIntegration.objects.filter(user=request.user, id=pk).first() + if not integration: + return Response( + { + 'message': 'Integration not found.', + 'error': True, + 'code': 'immich.integration_not_found' + }, + status=status.HTTP_404_NOT_FOUND + ) + + serializer = self.serializer_class(integration, data=request.data, partial=True) + if serializer.is_valid(): + # Validate Immich server connection before updating + server_url = serializer.validated_data.get('server_url', integration.server_url) + api_key = serializer.validated_data.get('api_key', integration.api_key) + + is_valid, corrected_server_url, error_message = self._validate_immich_connection(server_url, api_key) + + if not is_valid: + return Response( + { + 'message': f'Cannot connect to Immich server: {error_message}', + 'error': True, + 'code': 'immich.connection_failed', + 'details': error_message + }, + status=status.HTTP_400_BAD_REQUEST + ) + + # If validation passes, save the integration with the corrected URL + serializer.save(server_url=corrected_server_url) + return Response( + serializer.data, + status=status.HTTP_200_OK + ) + + return Response( + serializer.errors, + status=status.HTTP_400_BAD_REQUEST + ) + + def destroy(self, request, pk=None): + """ + RESTful DELETE method for deleting an existing Immich integration. + """ + integration = ImmichIntegration.objects.filter(user=request.user, id=pk).first() + if not integration: + return Response( + { + 'message': 'Integration not found.', + 'error': True, + 'code': 'immich.integration_not_found' + }, + status=status.HTTP_404_NOT_FOUND + ) + integration.delete() + return Response( + { + 'message': 'Integration deleted successfully.' + }, + status=status.HTTP_200_OK + ) + + def list(self, request, *args, **kwargs): + # If the user has an integration, we only want to return that integration + user_integrations = ImmichIntegration.objects.filter(user=request.user) + if user_integrations.exists(): + integration = user_integrations.first() + serializer = self.serializer_class(integration) + return Response( + serializer.data, + status=status.HTTP_200_OK + ) + else: + return Response( + { + 'message': 'No integration found.', + 'error': True, + 'code': 'immich.integration_not_found' + }, + status=status.HTTP_404_NOT_FOUND + ) \ No newline at end of file diff --git a/backend/server/main/__init__.py b/backend/server/main/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/server/main/settings.py b/backend/server/main/settings.py new file mode 100644 index 0000000..073fd77 --- /dev/null +++ b/backend/server/main/settings.py @@ -0,0 +1,330 @@ +""" +Django settings for demo project. + +For more information on this file, see +https://docs.djangoproject.com/en/1.7/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.7/ref/settings/ +""" + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +import os +from dotenv import load_dotenv +from os import getenv +from pathlib import Path +from urllib.parse import urlparse +from publicsuffix2 import get_sld +# Load environment variables from .env file +load_dotenv() + +BASE_DIR = os.path.dirname(os.path.dirname(__file__)) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = getenv('SECRET_KEY') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = getenv('DEBUG', 'true').lower() == 'true' + +# ALLOWED_HOSTS = [ +# 'localhost', +# '127.0.0.1', +# 'server' +# ] +ALLOWED_HOSTS = ['*'] + +INSTALLED_APPS = ( + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'django.contrib.sites', + # "allauth_ui", + 'rest_framework', + 'rest_framework.authtoken', + 'allauth', + 'allauth.account', + 'allauth.mfa', + 'allauth.headless', + 'allauth.socialaccount', + 'allauth.socialaccount.providers.github', + 'allauth.socialaccount.providers.openid_connect', + 'drf_yasg', + 'corsheaders', + 'adventures', + 'worldtravel', + 'users', + 'integrations', + 'django.contrib.gis', + # 'achievements', # Not done yet, will be added later in a future update + # 'widget_tweaks', + # 'slippers', + +) + +MIDDLEWARE = ( + 'whitenoise.middleware.WhiteNoiseMiddleware', + 'adventures.middleware.XSessionTokenMiddleware', + 'adventures.middleware.DisableCSRFForSessionTokenMiddleware', + 'adventures.middleware.DisableCSRFForMobileLoginSignup', + 'corsheaders.middleware.CorsMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'adventures.middleware.OverrideHostMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'allauth.account.middleware.AccountMiddleware', +) + +# disable verifications for new users +ACCOUNT_EMAIL_VERIFICATION = 'none' + +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + } +} + +# For backwards compatibility for Django 1.8 +MIDDLEWARE_CLASSES = MIDDLEWARE + +ROOT_URLCONF = 'main.urls' + +# WSGI_APPLICATION = 'demo.wsgi.application' + +# Database +# https://docs.djangoproject.com/en/1.7/ref/settings/#databases + +# Using legacy PG environment variables for compatibility with existing setups + +def env(*keys, default=None): + """Return the first non-empty environment variable from a list of keys.""" + for key in keys: + value = os.getenv(key) + if value: + return value + return default + +DATABASES = { + 'default': { + 'ENGINE': 'django.contrib.gis.db.backends.postgis', + 'NAME': env('PGDATABASE', 'POSTGRES_DB'), + 'USER': env('PGUSER', 'POSTGRES_USER'), + 'PASSWORD': env('PGPASSWORD', 'POSTGRES_PASSWORD'), + 'HOST': env('PGHOST', default='localhost'), + 'PORT': int(env('PGPORT', default='5432')), + 'OPTIONS': { + 'sslmode': 'prefer', # Prefer SSL, but allow non-SSL connections + }, + } +} + +# Internationalization +# https://docs.djangoproject.com/en/1.7/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + +unParsedFrontenedUrl = getenv('FRONTEND_URL', 'http://localhost:3000') +FRONTEND_URL = unParsedFrontenedUrl.translate(str.maketrans('', '', '\'"')) + +SESSION_COOKIE_SAMESITE = 'Lax' + +SESSION_COOKIE_NAME = 'sessionid' + +SESSION_COOKIE_SECURE = FRONTEND_URL.startswith('https') +CSRF_COOKIE_SECURE = FRONTEND_URL.startswith('https') + + +hostname = urlparse(FRONTEND_URL).hostname +is_ip_address = hostname.replace('.', '').isdigit() + +# Check if the hostname is single-label (no dots) +is_single_label = '.' not in hostname + +if is_ip_address or is_single_label: + # Do not set a domain for IP addresses or single-label hostnames + SESSION_COOKIE_DOMAIN = None +else: + # Use publicsuffix2 to calculate the correct cookie domain + cookie_domain = get_sld(hostname) + if cookie_domain: + SESSION_COOKIE_DOMAIN = f".{cookie_domain}" + else: + # Fallback to the hostname if parsing fails + SESSION_COOKIE_DOMAIN = hostname + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.7/howto/static-files/ + +SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') + + +BASE_DIR = Path(__file__).resolve().parent.parent +STATIC_ROOT = BASE_DIR / "staticfiles" +STATIC_URL = '/static/' + +MEDIA_URL = '/media/' +MEDIA_ROOT = BASE_DIR / 'media' # This path must match the NGINX root +STATICFILES_DIRS = [BASE_DIR / 'static'] + +STORAGES = { + "staticfiles": { + "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage", + }, + "default": { + "BACKEND": "django.core.files.storage.FileSystemStorage", + } +} + +SILENCED_SYSTEM_CHECKS = ["slippers.E001"] + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +# Authentication settings + +DISABLE_REGISTRATION = getenv('DISABLE_REGISTRATION', 'false').lower() == 'true' +DISABLE_REGISTRATION_MESSAGE = getenv('DISABLE_REGISTRATION_MESSAGE', 'Registration is disabled. Please contact the administrator if you need an account.') + +AUTH_USER_MODEL = 'users.CustomUser' + +ACCOUNT_ADAPTER = 'users.adapters.NoNewUsersAccountAdapter' + +ACCOUNT_SIGNUP_FORM_CLASS = 'users.form_overrides.CustomSignupForm' + +SESSION_SAVE_EVERY_REQUEST = True + +# Set login redirect URL to the frontend +LOGIN_REDIRECT_URL = FRONTEND_URL + +SOCIALACCOUNT_LOGIN_ON_GET = True + +HEADLESS_FRONTEND_URLS = { + "account_confirm_email": f"{FRONTEND_URL}/user/verify-email/{{key}}", + "account_reset_password": f"{FRONTEND_URL}/user/reset-password", + "account_reset_password_from_key": f"{FRONTEND_URL}/user/reset-password/{{key}}", + "account_signup": f"{FRONTEND_URL}/signup", + # Fallback in case the state containing the `next` URL is lost and the handshake + # with the third-party provider fails. + "socialaccount_login_error": f"{FRONTEND_URL}/account/provider/callback", +} + +AUTHENTICATION_BACKENDS = [ + 'users.backends.NoPasswordAuthBackend', + # 'allauth.account.auth_backends.AuthenticationBackend', + # 'django.contrib.auth.backends.ModelBackend', +] + +EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' +SITE_ID = 1 +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_AUTHENTICATION_METHOD = 'username' +ACCOUNT_EMAIL_VERIFICATION = 'optional' + +if getenv('EMAIL_BACKEND', 'console') == 'console': + EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' +else: + EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' + EMAIL_HOST = getenv('EMAIL_HOST') + EMAIL_USE_TLS = getenv('EMAIL_USE_TLS', 'true').lower() == 'true' + EMAIL_PORT = getenv('EMAIL_PORT', 587) + EMAIL_USE_SSL = getenv('EMAIL_USE_SSL', 'false').lower() == 'true' + EMAIL_HOST_USER = getenv('EMAIL_HOST_USER') + EMAIL_HOST_PASSWORD = getenv('EMAIL_HOST_PASSWORD') + DEFAULT_FROM_EMAIL = getenv('DEFAULT_FROM_EMAIL') + +# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +# EMAIL_HOST = 'smtp.resend.com' +# EMAIL_USE_TLS = False +# EMAIL_PORT = 2465 +# EMAIL_USE_SSL = True +# EMAIL_HOST_USER = 'resend' +# EMAIL_HOST_PASSWORD = '' +# DEFAULT_FROM_EMAIL = 'mail@mail.user.com' + + +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework.authentication.SessionAuthentication', + ), + 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', +} + +if DEBUG: + REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = ( + 'rest_framework.renderers.JSONRenderer', + 'rest_framework.renderers.BrowsableAPIRenderer', + ) +else: + REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = ( + 'rest_framework.renderers.JSONRenderer', + ) + + +CORS_ALLOWED_ORIGINS = [origin.strip() for origin in getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost').split(',') if origin.strip()] + + +CSRF_TRUSTED_ORIGINS = [origin.strip() for origin in getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost').split(',') if origin.strip()] + +DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + }, + 'file': { + 'class': 'logging.FileHandler', + 'filename': 'scheduler.log', + }, + }, + 'root': { + 'handlers': ['console', 'file'], + 'level': 'INFO', + }, + 'loggers': { + 'django': { + 'handlers': ['console', 'file'], + 'level': 'INFO', + 'propagate': False, + }, + }, +} + +# ADVENTURELOG_CDN_URL = getenv('ADVENTURELOG_CDN_URL', 'https://cdn.adventurelog.app') + +# https://github.com/dr5hn/countries-states-cities-database/tags +COUNTRY_REGION_JSON_VERSION = 'v2.6' + +GOOGLE_MAPS_API_KEY = getenv('GOOGLE_MAPS_API_KEY', '') \ No newline at end of file diff --git a/backend/server/main/urls.py b/backend/server/main/urls.py new file mode 100644 index 0000000..3b8415e --- /dev/null +++ b/backend/server/main/urls.py @@ -0,0 +1,50 @@ +from django.urls import include, re_path, path +from django.contrib import admin +from django.views.generic import RedirectView, TemplateView +from users.views import IsRegistrationDisabled, PublicUserListView, PublicUserDetailView, UserMetadataView, UpdateUserMetadataView, EnabledSocialProvidersView, DisablePasswordAuthenticationView +from .views import get_csrf_token, get_public_url, serve_protected_media +from drf_yasg.views import get_schema_view +from drf_yasg import openapi + +schema_view = get_schema_view( + openapi.Info( + title='API Docs', + default_version='v1', + ) +) +urlpatterns = [ + path('api/', include('adventures.urls')), + path('api/', include('worldtravel.urls')), + path("auth/", include("allauth.headless.urls")), + + # Serve protected media files + re_path(r'^media/(?P.*)$', serve_protected_media, name='serve-protected-media'), + + path('auth/is-registration-disabled/', IsRegistrationDisabled.as_view(), name='is_registration_disabled'), + path('auth/users/', PublicUserListView.as_view(), name='public-user-list'), + path('auth/user//', PublicUserDetailView.as_view(), name='public-user-detail'), + path('auth/update-user/', UpdateUserMetadataView.as_view(), name='update-user-metadata'), + + path('auth/user-metadata/', UserMetadataView.as_view(), name='user-metadata'), + + path('auth/social-providers/', EnabledSocialProvidersView.as_view(), name='enabled-social-providers'), + + path('auth/disable-password/', DisablePasswordAuthenticationView.as_view(), name='disable-password-authentication'), + + path('csrf/', get_csrf_token, name='get_csrf_token'), + path('public-url/', get_public_url, name='get_public_url'), + + path('', TemplateView.as_view(template_name='home.html')), + + re_path(r'^admin/', admin.site.urls), + re_path(r'^accounts/profile/$', RedirectView.as_view(url='/', + permanent=True), name='profile-redirect'), + re_path(r'^docs/$', schema_view.with_ui('swagger', + cache_timeout=0), name='api_docs'), + # path('auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent'), + path("accounts/", include("allauth.urls")), + + path("api/integrations/", include("integrations.urls")), + + # Include the API endpoints: +] \ No newline at end of file diff --git a/backend/server/main/utils.py b/backend/server/main/utils.py new file mode 100644 index 0000000..0963ba6 --- /dev/null +++ b/backend/server/main/utils.py @@ -0,0 +1,10 @@ +from rest_framework import serializers + +def get_user_uuid(user): + return str(user.uuid) + +class CustomModelSerializer(serializers.ModelSerializer): + def to_representation(self, instance): + representation = super().to_representation(instance) + representation['user_id'] = get_user_uuid(instance.user_id) + return representation \ No newline at end of file diff --git a/backend/server/main/views.py b/backend/server/main/views.py new file mode 100644 index 0000000..3393e13 --- /dev/null +++ b/backend/server/main/views.py @@ -0,0 +1,42 @@ +from django.http import JsonResponse +from django.middleware.csrf import get_token +from os import getenv +from django.conf import settings +from django.http import HttpResponse, HttpResponseForbidden +from django.views.static import serve +from adventures.utils.file_permissions import checkFilePermission + +def get_csrf_token(request): + csrf_token = get_token(request) + return JsonResponse({'csrfToken': csrf_token}) + +def get_public_url(request): + return JsonResponse({'PUBLIC_URL': getenv('PUBLIC_URL')}) + +protected_paths = ['images/', 'attachments/'] + +def serve_protected_media(request, path): + if any([path.startswith(protected_path) for protected_path in protected_paths]): + image_id = path.split('/')[1] + user = request.user + media_type = path.split('/')[0] + '/' + if checkFilePermission(image_id, user, media_type): + if settings.DEBUG: + # In debug mode, serve the file directly + return serve(request, path, document_root=settings.MEDIA_ROOT) + else: + # In production, use X-Accel-Redirect to serve the file using Nginx + response = HttpResponse() + response['Content-Type'] = '' + response['X-Accel-Redirect'] = '/protectedMedia/' + path + return response + else: + return HttpResponseForbidden() + else: + if settings.DEBUG: + return serve(request, path, document_root=settings.MEDIA_ROOT) + else: + response = HttpResponse() + response['Content-Type'] = '' + response['X-Accel-Redirect'] = '/protectedMedia/' + path + return response \ No newline at end of file diff --git a/backend/server/demo/wsgi.py b/backend/server/main/wsgi.py similarity index 85% rename from backend/server/demo/wsgi.py rename to backend/server/main/wsgi.py index 71ca83e..0a4407a 100644 --- a/backend/server/demo/wsgi.py +++ b/backend/server/main/wsgi.py @@ -11,7 +11,7 @@ import os from django.core.wsgi import get_wsgi_application -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") application = get_wsgi_application() # add this vercel variable diff --git a/backend/server/manage.py b/backend/server/manage.py index 86cc0b0..a09fede 100644 --- a/backend/server/manage.py +++ b/backend/server/manage.py @@ -3,7 +3,7 @@ import os import sys if __name__ == "__main__": - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") from django.core.management import execute_from_command_line diff --git a/backend/server/requirements.txt b/backend/server/requirements.txt index 164078a..c679ecc 100644 --- a/backend/server/requirements.txt +++ b/backend/server/requirements.txt @@ -1,13 +1,26 @@ -Django==5.0.7 -dj-rest-auth @ git+https://github.com/iMerica/dj-rest-auth.git@master +Django==5.2.1 djangorestframework>=3.15.2 -djangorestframework-simplejwt==5.3.1 django-allauth==0.63.3 drf-yasg==1.21.4 django-cors-headers==4.4.0 coreapi==2.3.3 -python-dotenv -psycopg2-binary -Pillow -whitenoise -django-resized \ No newline at end of file +python-dotenv==1.1.0 +psycopg2-binary==2.9.10 +pillow==11.2.1 +whitenoise==6.9.0 +django-resized==1.0.3 +django-geojson==4.2.0 +setuptools==79.0.1 +gunicorn==23.0.0 +qrcode==8.0 +slippers==0.6.2 +django-allauth-ui==1.5.1 +django-widget-tweaks==1.5.0 +django-ical==1.9.2 +icalendar==6.1.0 +ijson==3.3.0 +tqdm==4.67.1 +overpy==0.7 +publicsuffix2==2.20191221 +geopy==2.4.1 +psutil==6.1.1 \ No newline at end of file diff --git a/backend/server/templates/base.html b/backend/server/templates/base.html index f8a7bd5..9e1d48c 100644 --- a/backend/server/templates/base.html +++ b/backend/server/templates/base.html @@ -4,8 +4,8 @@ - - + + AdventureLog API Server @@ -31,39 +31,6 @@