added gitea activity for fun
This commit is contained in:
@@ -44,3 +44,59 @@ systemctl list-timers tasknest-demo-seed.timer
|
||||
|
||||
The supplied timer runs daily at 03:15 Europe/Amsterdam and catches up after a
|
||||
missed scheduled run when the host comes back online.
|
||||
|
||||
## Fasting phase notifications
|
||||
|
||||
The `notify_fasting_phases` command checks each active fasting schedule and sends
|
||||
an ntfy notification when the current phase changes to fasting or eating. It
|
||||
requires a tested, enabled ntfy topic in Settings. The command records each
|
||||
phase boundary so repeated runs do not send duplicate notifications. A failed
|
||||
delivery is retried on the next run. If the host was offline across several
|
||||
boundaries, only the current phase is announced.
|
||||
|
||||
The host runs Python 3.12 while the development environment uses Python 3.13.
|
||||
Create a separate host virtualenv so systemd does not follow a symlink to a
|
||||
Python executable absent from the host:
|
||||
|
||||
```sh
|
||||
cd /home/jorenmartijn/django
|
||||
python3 -m venv tasksnest-host
|
||||
tasksnest-host/bin/python -m pip install -r main/requirements.txt
|
||||
tasksnest-host/bin/python main/manage.py check
|
||||
```
|
||||
|
||||
Install the provided systemd service and timer to run this check every minute:
|
||||
|
||||
```sh
|
||||
sudo cp main/deploy/systemd/tasknest-fasting-notifications.{service,timer} /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now tasknest-fasting-notifications.timer
|
||||
```
|
||||
|
||||
Run database migrations before enabling the timer. Adjust the service's user
|
||||
and paths for your deployment.
|
||||
|
||||
## Gitea activity widget
|
||||
|
||||
The main task page shows a contribution grid below Daily Workout when
|
||||
`GITEA_USERNAME` is set in the Django server process environment. It uses
|
||||
Gitea's `/api/v1/users/{username}/heatmap` endpoint, refreshes the server-side
|
||||
cache every 15 minutes, and keeps any token out of browser requests.
|
||||
|
||||
Put these values in `/home/jorenmartijn/django/.env`, then restart the service
|
||||
that runs Django. Values set directly in the service environment take priority:
|
||||
|
||||
```ini
|
||||
GITEA_USERNAME=your-gitea-username
|
||||
GITEA_BASE_URL=https://git.jorendegraaf.eu
|
||||
# Only if the public heatmap endpoint does not show the activity you want:
|
||||
GITEA_TOKEN=your-read-only-token
|
||||
```
|
||||
|
||||
The base URL already defaults to `https://git.jorendegraaf.eu`. For public
|
||||
activity, try without a token first. If Gitea requires authentication or you
|
||||
want activity visible only to your account, create a token in Gitea's **User
|
||||
Settings → Applications → Generate New Token** with `read:user` permission.
|
||||
Store it in the Django service environment, never in this repository or in
|
||||
browser JavaScript. The dashboard shows a short unavailable message if the
|
||||
endpoint cannot be reached.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Send Tasknest fasting phase notifications
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=jorenmartijn
|
||||
WorkingDirectory=/home/jorenmartijn/django/main
|
||||
ExecStart=/home/jorenmartijn/django/tasksnest-host/bin/python manage.py notify_fasting_phases
|
||||
@@ -0,0 +1,10 @@
|
||||
[Unit]
|
||||
Description=Check Tasknest fasting phase changes every minute
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:*:00
|
||||
Persistent=true
|
||||
Unit=tasknest-fasting-notifications.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -151,6 +151,19 @@ function initialiseGeolocation() {
|
||||
document.addEventListener('DOMContentLoaded', initialiseGeolocation);
|
||||
htmx.on('htmx:afterSwap', initialiseGeolocation);
|
||||
|
||||
function initialiseNtfyForm() {
|
||||
document.querySelectorAll('[data-ntfy-form]').forEach((form) => {
|
||||
if (form.dataset.ready) return;
|
||||
form.dataset.ready = 'true';
|
||||
form.querySelector('[name="ntfy_url"]')?.addEventListener('input', () => {
|
||||
form.querySelector('#ntfy-test-result')?.replaceChildren();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialiseNtfyForm);
|
||||
htmx.on('htmx:afterSwap', initialiseNtfyForm);
|
||||
|
||||
|
||||
function initialiseCategoryPickers() {
|
||||
document.querySelectorAll("[data-category-picker]").forEach((picker) => {
|
||||
|
||||
@@ -385,8 +385,12 @@ body[data-theme="dark"] .brushing-control__mark { color: #9adab0; }
|
||||
body[data-theme="dark"] .checkin-form--bowel .field textarea { border-color: #536159; color: #edf5ef; background: #161d19; }
|
||||
.checkin-calendar__exports { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 14px; }
|
||||
.checkin-calendar__exports .button:focus-visible { outline: 2px solid $forest; outline-offset: 2px; }
|
||||
.health-layout { max-width: 920px; margin: 0 auto; }
|
||||
.health-layout { display:grid; grid-template-columns:minmax(0,1fr) 285px; gap:24px; max-width:1180px; margin:0 auto; align-items:start; }
|
||||
.health-layout__main { min-width:0; }
|
||||
.health-layout__sidebar { position:sticky; top:96px; display:grid; gap:16px; }
|
||||
.health-layout__sidebar .hydration-widget { margin-bottom:0; }
|
||||
.health-layout .checkin-panel { margin-top: 24px; }
|
||||
@media (max-width:820px) { .health-layout { grid-template-columns:1fr; }.health-layout__sidebar { position:static; } }
|
||||
.mobile-weather-slot { display: none; }
|
||||
@media (max-width: 820px) {
|
||||
.mobile-weather-slot { display: block; }
|
||||
@@ -420,3 +424,102 @@ body[data-theme="dark"] .checkin-form--bowel .field textarea { border-color: #53
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.js-nav-ready .primary-nav { transition: none; }
|
||||
}
|
||||
|
||||
.hydration-widget { margin-bottom:16px; padding:18px; border:1px solid #557261; border-radius:18px; background:#242d27; color:#edf5ef; box-shadow:0 0 20px rgba(71,119,82,.12); }
|
||||
.hydration-widget .eyebrow { margin:0; color:#acc5af; }
|
||||
.hydration-widget h2 { margin:0 0 8px; font-size:1.35rem; color:#f6f4e9; }
|
||||
.hydration-widget__main { display:flex; align-items:center; justify-content:space-between; gap:8px; min-width:0; }
|
||||
.hydration-widget__stats { flex:1; min-width:0; }
|
||||
.hydration-widget__stats p { margin:0 0 8px; font-size:.78rem; color:#b8cbbd; }
|
||||
.hydration-widget__total { font-size:1.38rem !important; font-weight:700; color:#fff !important; white-space:nowrap; }
|
||||
.hydration-widget__total span { font-size:.8rem; color:#b8cbbd; }
|
||||
.hydration-widget__track { height:8px; overflow:hidden; border-radius:10px; background:#45554a; }
|
||||
.hydration-widget__track span { display:block; height:100%; border-radius:10px; background:#dcae61; transition:width .35s ease; }
|
||||
.hydration-bottle { flex:none; max-width:42%; --bottle-stroke:#8da99a; --bottle-fill:#dcae61; --bottle-shell:#253c34; --bottle-cap:#597468; }
|
||||
.hydration-bottle__water { transition:transform .35s ease; }
|
||||
.hydration-widget__actions { display:flex; align-items:flex-start; flex-wrap:wrap; gap:6px; margin-top:7px; }
|
||||
.hydration-widget__actions form { display:flex; flex-wrap:wrap; gap:6px; margin:0; }
|
||||
.hydration-widget__actions button, .hydration-widget__other summary { display:inline-block; padding:7px 9px; border:1px solid #6f795d; border-radius:8px; background:#39463b; color:#f9edce; font-size:.76rem; font-weight:700; cursor:pointer; }
|
||||
.hydration-widget__other summary { list-style:none; }
|
||||
.hydration-widget__other summary::-webkit-details-marker { display:none; }
|
||||
.hydration-widget__other[open] { width:100%; }
|
||||
.hydration-widget__other form { align-items:center; margin-top:8px; }
|
||||
.hydration-widget__other label { font-size:.75rem; }
|
||||
.hydration-widget__other input { width:88px; padding:6px; border:1px solid #738678; border-radius:7px; background:#17231c; color:#fff; }
|
||||
.hydration-widget__info { display:flex; align-items:center; justify-content:space-between; gap:6px; margin:12px 0; font-size:.73rem; color:#b8cbbd; }
|
||||
.hydration-widget__info button { padding:0; border:0; background:none; color:#efc27d; text-decoration:underline; font-size:.73rem; }
|
||||
.hydration-widget__error { color:#ffd1bd; font-size:.78rem; }
|
||||
.hydration-widget__week { border-top:1px solid #40574a; padding-top:10px; }
|
||||
.hydration-widget__week p { margin:0 0 7px; color:#b8cbbd; font-size:.72rem; }
|
||||
.hydration-widget__days { display:grid; grid-template-columns:repeat(7,minmax(0,1fr)); gap:5px; }
|
||||
.hydration-widget__day { display:grid; place-items:center; min-height:27px; border-radius:6px; font-size:.7rem; font-weight:700; }
|
||||
.hydration-widget__day--none { color:#ffc7bc; background:#633d3a; }
|
||||
.hydration-widget__day--partial { color:#fff0cf; background:#805e31; }
|
||||
.hydration-widget__day--goal { color:#e1ffe6; background:#326c48; }
|
||||
.hydration-widget__day--today { outline:1px solid #e8d9a7; outline-offset:2px; }
|
||||
.hydration-widget button:focus-visible, .hydration-widget summary:focus-visible, .hydration-widget input:focus-visible { outline:2px solid #efc27d; outline-offset:2px; }
|
||||
@media (prefers-reduced-motion:reduce) { .hydration-widget__track span, .hydration-bottle__water { transition:none; } }
|
||||
|
||||
body[data-theme="light"] .hydration-widget { border-color:#cbded0; background:#f7faf5; color:#253a2d; box-shadow:0 12px 30px rgba(36,89,55,.08); }
|
||||
body[data-theme="light"] .hydration-widget .eyebrow { color:#437053; }
|
||||
body[data-theme="light"] .hydration-widget h2 { color:#213a2b; }
|
||||
body[data-theme="light"] .hydration-widget__stats p, body[data-theme="light"] .hydration-widget__total span, body[data-theme="light"] .hydration-widget__info, body[data-theme="light"] .hydration-widget__week p { color:#526758; }
|
||||
body[data-theme="light"] .hydration-widget__total { color:#213a2b !important; }
|
||||
body[data-theme="light"] .hydration-widget__track { background:#dce8dc; }
|
||||
body[data-theme="light"] .hydration-widget__track span { background:#b9802c; }
|
||||
body[data-theme="light"] .hydration-bottle { --bottle-stroke:#557964; --bottle-fill:#d5a24f; --bottle-shell:#e8f1e9; --bottle-cap:#a7c3ad; }
|
||||
body[data-theme="light"] .hydration-widget__actions button, body[data-theme="light"] .hydration-widget__other summary { border-color:#abc5af; background:#e3f0e4; color:#24543a; }
|
||||
body[data-theme="light"] .hydration-widget__other input { border-color:#abc5af; background:#fff; color:#213a2b; }
|
||||
body[data-theme="light"] .hydration-widget__info button { color:#875819; }
|
||||
body[data-theme="light"] .hydration-widget__error { color:#a33d2e; }
|
||||
body[data-theme="light"] .hydration-widget__week { border-color:#d2e2d4; }
|
||||
body[data-theme="light"] .hydration-widget__day--none { color:#783b34; background:#f2d9d5; }
|
||||
body[data-theme="light"] .hydration-widget__day--partial { color:#704915; background:#f4e1b9; }
|
||||
body[data-theme="light"] .hydration-widget__day--goal { color:#245537; background:#d2ead7; }
|
||||
body[data-theme="light"] .hydration-widget__day--today { outline-color:#537c60; }
|
||||
body[data-theme="light"] .hydration-widget button:focus-visible, body[data-theme="light"] .hydration-widget summary:focus-visible, body[data-theme="light"] .hydration-widget input:focus-visible { outline-color:#376e49; }
|
||||
.ntfy-check { display: flex; align-items: center; gap: .6rem; }
|
||||
.ntfy-check label { margin: 0; }
|
||||
#ntfy-url { width: 100%; box-sizing: border-box; min-height: 2.8rem; }
|
||||
.ntfy-result { margin: 0; padding: .75rem; border-radius: .55rem; }
|
||||
.ntfy-result--success { color: #14532d; background: #d1fae5; }
|
||||
.ntfy-result--error { color: #7f1d1d; background: #fee2e2; }
|
||||
|
||||
.gitea-activity {
|
||||
margin-top: 30px;
|
||||
padding: 25px 29px;
|
||||
border: 1px solid $line;
|
||||
border-radius: 20px;
|
||||
background: $surface;
|
||||
box-shadow: $shadow;
|
||||
}
|
||||
.gitea-activity__header { display: flex; justify-content: space-between; align-items: end; gap: 18px; }
|
||||
.gitea-activity__header h2 { margin: 0; font-size: 1.7rem; }
|
||||
.gitea-activity__header .eyebrow { margin-bottom: 4px; }
|
||||
.gitea-activity__summary, .gitea-activity__message { margin: 8px 0 20px; color: $muted; font-size: .9rem; }
|
||||
.gitea-activity__summary strong { color: $forest; font-size: 1.1rem; }
|
||||
.gitea-activity__scroller { max-width: 100%; overflow-x: auto; padding-bottom: 8px; }
|
||||
.gitea-activity__chart { display: flex; gap: 3px; width: max-content; }
|
||||
.gitea-activity__week, .gitea-activity__day-labels { display: grid; grid-template-rows: 17px repeat(7, 10px); gap: 3px; }
|
||||
.gitea-activity__week { width: 10px; }
|
||||
.gitea-activity__day-labels { width: 27px; margin-right: 2px; color: $muted; font-size: .65rem; line-height: 10px; }
|
||||
.gitea-activity__month { height: 17px; white-space: nowrap; color: $muted; font-size: .69rem; line-height: 14px; }
|
||||
.gitea-activity__cell { display: block; width: 10px; height: 10px; border-radius: 2px; background: #e9eee9; }
|
||||
.gitea-activity__cell--1 { background: #b7dfc2; }
|
||||
.gitea-activity__cell--2 { background: #77bd8d; }
|
||||
.gitea-activity__cell--3 { background: #3f9564; }
|
||||
.gitea-activity__cell--4 { background: #1f6544; }
|
||||
.gitea-activity__cell--future { background: transparent; }
|
||||
.gitea-activity__legend { display: flex; align-items: center; justify-content: end; gap: 4px; margin-top: 12px; color: $muted; font-size: .7rem; }
|
||||
.gitea-activity__legend span:first-child { margin-right: 3px; }
|
||||
.gitea-activity__legend span:last-child { margin-left: 3px; }
|
||||
body[data-theme="dark"] .gitea-activity { border-color: #38443d; background: #202923; box-shadow: 0 18px 45px rgba(0, 0, 0, .22); }
|
||||
body[data-theme="dark"] .gitea-activity__summary,
|
||||
body[data-theme="dark"] .gitea-activity__message,
|
||||
body[data-theme="dark"] .gitea-activity__month,
|
||||
body[data-theme="dark"] .gitea-activity__day-labels,
|
||||
body[data-theme="dark"] .gitea-activity__legend { color: #b8c3bb; }
|
||||
body[data-theme="dark"] .gitea-activity__summary strong { color: #9bd5ae; }
|
||||
body[data-theme="dark"] .gitea-activity__cell--0 { background: #303a33; }
|
||||
body[data-theme="dark"] .gitea-activity__cell--future { background: transparent; }
|
||||
@media (max-width: 560px) { .gitea-activity { padding: 22px; }.gitea-activity__header { align-items: start; }.gitea-activity__header h2 { font-size: 1.45rem; } }
|
||||
|
||||
@@ -145,6 +145,34 @@ class UserSettingsForm(forms.ModelForm):
|
||||
}
|
||||
|
||||
|
||||
class NtfySettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('ntfy_url', 'ntfy_enabled')
|
||||
widgets = {'ntfy_url': forms.URLInput(attrs={'id': 'ntfy-url', 'placeholder': 'https://ntfy.example.com/my-topic'})}
|
||||
|
||||
def clean_ntfy_url(self):
|
||||
return self.cleaned_data['ntfy_url'].strip()
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
if data.get('ntfy_enabled') and not data.get('ntfy_url'):
|
||||
self.add_error('ntfy_url', 'Enter a topic URL before enabling notifications.')
|
||||
return data
|
||||
|
||||
|
||||
class HydrationGoalForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('daily_water_goal_ml',)
|
||||
labels = {'daily_water_goal_ml': 'Daily water goal (ml)'}
|
||||
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})}
|
||||
|
||||
|
||||
class WaterIntakeForm(forms.Form):
|
||||
amount_ml = forms.IntegerField(min_value=1, max_value=3000)
|
||||
|
||||
|
||||
class SickDaySettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = SickDaySettings
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from planner.services.fasting_notifications import notify_fasting_phase_changes
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Send ntfy notifications for fasting and eating phase changes.'
|
||||
|
||||
def handle(self, *args, **options):
|
||||
delivered = notify_fasting_phase_changes()
|
||||
self.stdout.write(f'Delivered {delivered} fasting phase notification(s).')
|
||||
@@ -0,0 +1,36 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-02 19:50
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import django.utils.timezone
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0015_bowelhealthcheckin_toothbrushing'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='usersettings',
|
||||
name='daily_water_goal_ml',
|
||||
field=models.PositiveIntegerField(default=2000, validators=[django.core.validators.MinValueValidator(250), django.core.validators.MaxValueValidator(10000)]),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='WaterIntakeEntry',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('amount_ml', models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(3000)])),
|
||||
('recorded_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='water_entries', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-recorded_at', '-pk'),
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,11 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('planner', '0016_usersettings_daily_water_goal_ml_waterintakeentry')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='usersettings', name='ntfy_url', field=models.URLField(blank=True)),
|
||||
migrations.AddField(model_name='usersettings', name='ntfy_enabled', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='usersettings', name='ntfy_last_tested_at', field=models.DateTimeField(blank=True, null=True)),
|
||||
]
|
||||
@@ -0,0 +1,12 @@
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('planner', '0017_usersettings_ntfy')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='fastingsettings', name='last_phase_notification_at',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
||||
@@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class Task(models.Model):
|
||||
@@ -116,6 +117,12 @@ class UserSettings(models.Model):
|
||||
)
|
||||
onboarding_enabled = models.BooleanField(default=True)
|
||||
onboarding_step = models.PositiveSmallIntegerField(default=0)
|
||||
daily_water_goal_ml = models.PositiveIntegerField(
|
||||
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)],
|
||||
)
|
||||
ntfy_url = models.URLField(blank=True)
|
||||
ntfy_enabled = models.BooleanField(default=False)
|
||||
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
@@ -341,6 +348,7 @@ class FastingSettings(models.Model):
|
||||
validators=[MinValueValidator(1), MaxValueValidator((24 * 60) - 1)],
|
||||
)
|
||||
tracking_started_at = models.DateTimeField(blank=True, null=True)
|
||||
last_phase_notification_at = models.DateTimeField(blank=True, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
@@ -366,6 +374,16 @@ class FastingPause(models.Model):
|
||||
return f'Fasting pause for {self.user} at {self.paused_at}'
|
||||
|
||||
|
||||
class WaterIntakeEntry(models.Model):
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='water_entries')
|
||||
amount_ml = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(3000)])
|
||||
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-recorded_at', '-pk')
|
||||
|
||||
|
||||
class FastingPeriod(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
COMPLETED = 'completed', 'Completed'
|
||||
|
||||
@@ -113,6 +113,7 @@ def configure_fasting(
|
||||
'fasting_start_time': fasting_start_time,
|
||||
'fasting_duration_minutes': fasting_duration_minutes,
|
||||
'tracking_started_at': now if enabled else None,
|
||||
'last_phase_notification_at': now,
|
||||
},
|
||||
)
|
||||
if created:
|
||||
@@ -121,9 +122,16 @@ def configure_fasting(
|
||||
return settings
|
||||
|
||||
was_enabled = settings.enabled
|
||||
schedule_changed = (
|
||||
settings.fasting_start_time != fasting_start_time
|
||||
or settings.fasting_duration_minutes != fasting_duration_minutes
|
||||
or was_enabled != enabled
|
||||
)
|
||||
settings.fasting_start_time = fasting_start_time
|
||||
settings.fasting_duration_minutes = fasting_duration_minutes
|
||||
settings.enabled = enabled
|
||||
if schedule_changed:
|
||||
settings.last_phase_notification_at = now
|
||||
if enabled and settings.tracking_started_at is None:
|
||||
settings.tracking_started_at = now
|
||||
settings.save()
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Deliver the latest fasting phase transition once per tracked schedule."""
|
||||
|
||||
import logging
|
||||
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import FastingSettings
|
||||
from planner.services.fasting import current_fasting_phase
|
||||
from planner.services.notifications import NotificationError, send_notification
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def notify_fasting_phase_changes(now=None):
|
||||
now = now or timezone.now()
|
||||
delivered = 0
|
||||
for settings_id in FastingSettings.objects.filter(enabled=True).values_list('pk', flat=True):
|
||||
with transaction.atomic():
|
||||
settings = FastingSettings.objects.select_for_update().select_related('user').get(pk=settings_id)
|
||||
if not settings.enabled:
|
||||
continue
|
||||
phase = current_fasting_phase(settings, now)
|
||||
boundary = phase.cycle_start
|
||||
cursor = settings.last_phase_notification_at
|
||||
if cursor is None:
|
||||
# Existing configurations start at the current phase without a catch-up alert.
|
||||
settings.last_phase_notification_at = now
|
||||
settings.save(update_fields=['last_phase_notification_at'])
|
||||
continue
|
||||
if boundary <= cursor or boundary > now:
|
||||
continue
|
||||
title = 'Fasting started' if phase.is_fasting else 'Eating window started'
|
||||
message = 'Your fasting window has started.' if phase.is_fasting else 'Your eating window is open.'
|
||||
try:
|
||||
sent = send_notification(settings.user, title, message)
|
||||
except NotificationError:
|
||||
logger.warning('Could not deliver fasting phase notification for user %s.', settings.user_id)
|
||||
continue
|
||||
settings.last_phase_notification_at = boundary
|
||||
settings.save(update_fields=['last_phase_notification_at'])
|
||||
delivered += int(sent)
|
||||
return delivered
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Fetch and shape a Gitea user's contribution heatmap for the dashboard."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone as utc_timezone
|
||||
import json
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from django.utils import timezone
|
||||
|
||||
HEATMAP_CACHE_SECONDS = 15 * 60
|
||||
|
||||
|
||||
def fetch_heatmap():
|
||||
username = settings.GITEA_USERNAME
|
||||
if not username:
|
||||
return None
|
||||
key = f'gitea-heatmap:{settings.GITEA_BASE_URL}:{username}'
|
||||
cached = cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
url = f'{settings.GITEA_BASE_URL}/api/v1/users/{quote(username, safe="")}/heatmap'
|
||||
headers = {'Accept': 'application/json'}
|
||||
if settings.GITEA_TOKEN:
|
||||
headers['Authorization'] = f'token {settings.GITEA_TOKEN}'
|
||||
try:
|
||||
with urlopen(Request(url, headers=headers), timeout=4) as response:
|
||||
data = json.load(response)
|
||||
except (HTTPError, URLError, TimeoutError, OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, list):
|
||||
return None
|
||||
cache.set(key, data, HEATMAP_CACHE_SECONDS)
|
||||
return data
|
||||
|
||||
|
||||
def activity_level(count):
|
||||
if count <= 0:
|
||||
return 0
|
||||
if count == 1:
|
||||
return 1
|
||||
if count <= 3:
|
||||
return 2
|
||||
if count <= 6:
|
||||
return 3
|
||||
return 4
|
||||
|
||||
|
||||
def activity_context(today=None):
|
||||
"""Return 53 Sunday-first weeks ending in the current week."""
|
||||
today = today or timezone.localdate()
|
||||
data = fetch_heatmap()
|
||||
if data is None:
|
||||
return {'activity_unavailable': True}
|
||||
counts = {}
|
||||
for item in data:
|
||||
try:
|
||||
day = datetime.fromtimestamp(item['timestamp'], utc_timezone.utc).date()
|
||||
count = max(0, int(item['contributions']))
|
||||
except (KeyError, TypeError, ValueError, OverflowError, OSError):
|
||||
continue
|
||||
counts[day] = count
|
||||
first = today - timedelta(days=364)
|
||||
first -= timedelta(days=(first.weekday() + 1) % 7)
|
||||
weeks = []
|
||||
total = 0
|
||||
for week_number in range(53):
|
||||
week_start = first + timedelta(days=week_number * 7)
|
||||
week = []
|
||||
for weekday in range(7):
|
||||
day = week_start + timedelta(days=weekday)
|
||||
count = counts.get(day, 0) if day <= today else 0
|
||||
if day <= today and day >= today - timedelta(days=364):
|
||||
total += count
|
||||
week.append({
|
||||
'date': day, 'count': count, 'level': activity_level(count),
|
||||
'future': day > today,
|
||||
})
|
||||
month = week_start.strftime('%b') if week_number == 0 or week_start.month != (week_start - timedelta(days=7)).month else ''
|
||||
weeks.append({'days': week, 'month': month})
|
||||
return {
|
||||
'activity_weeks': weeks,
|
||||
'activity_total': total, 'activity_username': settings.GITEA_USERNAME,
|
||||
'activity_profile_url': f'{settings.GITEA_BASE_URL}/{quote(settings.GITEA_USERNAME, safe="")}',
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
from datetime import datetime, time, timedelta
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import UserSettings, WaterIntakeEntry
|
||||
from planner.timezones import timezone_for_user
|
||||
|
||||
|
||||
def hydration_context(user, now=None):
|
||||
zone = timezone_for_user(user)
|
||||
today = timezone.localtime(now or timezone.now(), zone).date()
|
||||
start = today - timedelta(days=today.weekday())
|
||||
week_start = timezone.make_aware(datetime.combine(start, time.min), zone)
|
||||
week_end = timezone.make_aware(datetime.combine(start + timedelta(days=7), time.min), zone)
|
||||
goal = UserSettings.objects.get_or_create(user=user)[0].daily_water_goal_ml
|
||||
entries = WaterIntakeEntry.objects.filter(user=user, recorded_at__gte=week_start, recorded_at__lt=week_end)
|
||||
totals = {start + timedelta(days=i): 0 for i in range(7)}
|
||||
for entry in entries:
|
||||
totals[timezone.localtime(entry.recorded_at, zone).date()] += entry.amount_ml
|
||||
total = totals[today]
|
||||
last = entries.filter(
|
||||
recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone),
|
||||
recorded_at__lt=timezone.make_aware(datetime.combine(today + timedelta(days=1), time.min), zone),
|
||||
).order_by('-recorded_at', '-pk').first()
|
||||
percent = round(total * 100 / goal)
|
||||
visual = min(100, percent)
|
||||
days = []
|
||||
for day, amount in totals.items():
|
||||
state = 'none' if amount == 0 else ('goal' if amount >= goal else 'partial')
|
||||
days.append({'date': day, 'label': day.strftime('%a')[0], 'total': amount,
|
||||
'state': state, 'state_label': {'none': 'no water logged', 'partial': 'partial goal', 'goal': 'goal met'}[state],
|
||||
'today': day == today})
|
||||
return {'hydration_total': total, 'hydration_goal': goal, 'hydration_percent': percent,
|
||||
'hydration_visual': visual, 'hydration_fill_y': 168 - round(visual * 1.22),
|
||||
'hydration_fill_height': round(visual * 1.22), 'hydration_last': last,
|
||||
'hydration_last_time': timezone.localtime(last.recorded_at, zone).strftime('%H:%M') if last else None,
|
||||
'hydration_zone': zone, 'hydration_days': days,
|
||||
'hydration_markers': [
|
||||
{'y': 46, 'value': goal}, {'y': 77, 'value': round(goal * .75)},
|
||||
{'y': 107, 'value': round(goal * .5)}, {'y': 138, 'value': round(goal * .25)},
|
||||
]}
|
||||
@@ -0,0 +1,37 @@
|
||||
import socket
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from planner.models import UserSettings
|
||||
|
||||
|
||||
class NotificationError(Exception):
|
||||
"""A delivery error safe to display without exposing the topic URL."""
|
||||
|
||||
|
||||
def send_ntfy_notification(url, title, message, timeout=10):
|
||||
request = Request(
|
||||
url,
|
||||
data=message.encode('utf-8'),
|
||||
headers={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
|
||||
method='POST',
|
||||
)
|
||||
try:
|
||||
with urlopen(request, timeout=timeout) as response:
|
||||
status = response.getcode()
|
||||
except HTTPError as error:
|
||||
raise NotificationError(f'ntfy server responded with HTTP {error.code}.') from error
|
||||
except (TimeoutError, socket.timeout):
|
||||
raise NotificationError('Connection to the ntfy server timed out.') from None
|
||||
except (URLError, OSError):
|
||||
raise NotificationError('Could not connect to the ntfy server.') from None
|
||||
if not 200 <= status < 300:
|
||||
raise NotificationError(f'ntfy server responded with HTTP {status}.')
|
||||
|
||||
|
||||
def send_notification(user, title, message):
|
||||
preferences = UserSettings.objects.filter(user=user).first()
|
||||
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
|
||||
return False
|
||||
send_ntfy_notification(preferences.ntfy_url, title, message)
|
||||
return True
|
||||
@@ -11,7 +11,13 @@
|
||||
</div>
|
||||
</section>
|
||||
<div class="health-layout">
|
||||
{% include 'planner/partials/neck_headache_checkin.html' %}
|
||||
{% include 'planner/partials/bowel_health_checkin.html' %}
|
||||
<div class="health-layout__main">
|
||||
{% include 'planner/partials/neck_headache_checkin.html' %}
|
||||
{% include 'planner/partials/bowel_health_checkin.html' %}
|
||||
</div>
|
||||
<aside class="health-layout__sidebar" aria-label="Health routines">
|
||||
{% include 'planner/partials/fasting_widget.html' %}
|
||||
{% include 'planner/partials/hydration_widget.html' %}
|
||||
</aside>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<section class="gitea-activity" id="gitea-activity" aria-labelledby="gitea-activity-heading">
|
||||
<div class="gitea-activity__header">
|
||||
<div><p class="eyebrow">Code garden</p><h2 id="gitea-activity-heading">Gitea activity</h2></div>
|
||||
{% if activity_profile_url %}<a class="text-link" href="{{ activity_profile_url }}" target="_blank" rel="noopener noreferrer">View profile<span class="visually-hidden"> on Gitea</span></a>{% endif %}
|
||||
</div>
|
||||
{% if activity_unavailable %}
|
||||
<p class="gitea-activity__message">Activity is unavailable right now.</p>
|
||||
{% else %}
|
||||
<p class="gitea-activity__summary"><strong>{{ activity_total }}</strong> contributions in the last year</p>
|
||||
<div class="gitea-activity__scroller">
|
||||
<div class="gitea-activity__chart" role="img" aria-label="Gitea contribution calendar: {{ activity_total }} contributions in the last year">
|
||||
<div class="gitea-activity__day-labels" aria-hidden="true"><span></span><span>Mon</span><span></span><span>Wed</span><span></span><span>Fri</span><span></span></div>
|
||||
{% for week in activity_weeks %}
|
||||
<div class="gitea-activity__week" aria-hidden="true">
|
||||
<span class="gitea-activity__month">{{ week.month }}</span>
|
||||
{% for day in week.days %}<time class="gitea-activity__cell gitea-activity__cell--{{ day.level }}{% if day.future %} gitea-activity__cell--future{% endif %}" datetime="{{ day.date|date:'Y-m-d' }}" title="{{ day.date|date:'j M Y' }}: {{ day.count }} contribution{{ day.count|pluralize }}"></time>{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="gitea-activity__legend" aria-hidden="true"><span>Less</span>{% for level in '01234' %}<i class="gitea-activity__cell gitea-activity__cell--{{ level }}"></i>{% endfor %}<span>More</span></div>
|
||||
{% endif %}
|
||||
</section>
|
||||
@@ -0,0 +1,9 @@
|
||||
<svg class="hydration-bottle" viewBox="0 0 112 184" width="112" height="184" aria-hidden="true" focusable="false">
|
||||
<defs><clipPath id="hydration-bottle-clip"><path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z"/></clipPath></defs>
|
||||
<path d="M46 16 Q46 9 53 9 H71 Q78 9 78 16 V32 H46 Z" fill="none" stroke="var(--bottle-stroke)" stroke-width="2"/>
|
||||
<rect x="44" y="27" width="36" height="12" rx="3" fill="var(--bottle-cap)" stroke="var(--bottle-stroke)" stroke-width="2"/>
|
||||
<path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z" fill="var(--bottle-shell)" stroke="var(--bottle-stroke)" stroke-width="2"/>
|
||||
<g clip-path="url(#hydration-bottle-clip)" class="hydration-bottle__water"><rect x="30" y="{{ hydration_fill_y }}" width="64" height="{{ hydration_fill_height }}" fill="var(--bottle-fill)" opacity=".85"/><ellipse cx="62" cy="{{ hydration_fill_y }}" rx="33" ry="3" fill="var(--bottle-fill)" opacity=".85"/></g>
|
||||
<path d="M35 42 Q30 47 30 58 V151 Q30 168 47 168 H77 Q94 168 94 151 V58 Q94 47 89 42 Z" fill="none" stroke="var(--bottle-stroke)" stroke-width="2"/>
|
||||
{% for marker in hydration_markers %}<path d="M22 {{ marker.y }} h6" stroke="var(--bottle-stroke)" stroke-width="1.5"/><text x="20" y="{{ marker.y|add:3 }}" text-anchor="end" fill="var(--bottle-stroke)" font-size="8">{{ marker.value }}</text>{% endfor %}
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,19 @@
|
||||
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite">
|
||||
<p class="eyebrow">Daily hydration</p>
|
||||
<h2 id="hydration-heading">Water</h2>
|
||||
<div class="hydration-widget__main">
|
||||
<div class="hydration-widget__stats">
|
||||
<p class="hydration-widget__total">{{ hydration_total|floatformat:0 }} <span>/ {{ hydration_goal }} ml</span></p>
|
||||
<p>{{ hydration_percent }}% of daily goal</p>
|
||||
<div class="hydration-widget__track" role="progressbar" aria-label="Daily water goal" aria-valuenow="{{ hydration_visual }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ hydration_visual }}%"></span></div>
|
||||
</div>
|
||||
{% include 'planner/partials/hydration_bottle.html' %}
|
||||
</div>
|
||||
<div class="hydration-widget__actions">
|
||||
<form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit" name="amount_ml" value="250">+250 ml</button><button type="submit" name="amount_ml" value="500">+500 ml</button></form>
|
||||
<details class="hydration-widget__other"><summary>Other</summary><form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<label for="hydration-amount">Amount (ml)</label><input id="hydration-amount" name="amount_ml" type="number" min="1" max="3000" step="1" required inputmode="numeric"><button type="submit">Add</button></form></details>
|
||||
</div>
|
||||
{% if hydration_error %}<p class="hydration-widget__error" role="alert">Enter a whole amount from 1 to 3000 ml.</p>{% endif %}
|
||||
<div class="hydration-widget__info">{% if hydration_last %}<span>Last: {{ hydration_last.amount_ml }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No water logged today</span>{% endif %}</div>
|
||||
<div class="hydration-widget__week"><p>This week</p><div class="hydration-widget__days">{% for day in hydration_days %}<span class="hydration-widget__day hydration-widget__day--{{ day.state }}{% if day.today %} hydration-widget__day--today{% endif %}" title="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}" aria-label="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}">{{ day.label }}</span>{% endfor %}</div></div>
|
||||
</article>
|
||||
@@ -0,0 +1 @@
|
||||
{% if success %}<p class="ntfy-result ntfy-result--success">Test notification sent successfully.</p>{% else %}<p class="ntfy-result ntfy-result--error">Could not send the test notification: {{ error }}</p>{% endif %}
|
||||
@@ -41,11 +41,17 @@
|
||||
</section>
|
||||
|
||||
{% include 'planner/partials/workout_section.html' %}
|
||||
{% if gitea_activity_enabled %}
|
||||
<div id="gitea-activity" hx-get="{% url 'planner:gitea-activity' %}" hx-trigger="load" hx-swap="outerHTML" aria-live="polite">
|
||||
<section class="gitea-activity" aria-label="Gitea activity"><p>Loading Gitea activity…</p></section>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if user.is_authenticated %}
|
||||
<aside class="homepage-sidebar" aria-label="Personal routines">
|
||||
<div class="desktop-weather-slot">{% include 'planner/partials/weather_widget.html' %}</div>
|
||||
{% include 'planner/partials/tooth_brushing_widget.html' %}
|
||||
{% include 'planner/partials/hydration_widget.html' %}
|
||||
{% include 'planner/partials/fasting_widget.html' %}
|
||||
</aside>
|
||||
{% endif %}
|
||||
|
||||
@@ -7,6 +7,18 @@
|
||||
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
|
||||
<section class="settings-card"><h2>Location & weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
|
||||
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
|
||||
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
|
||||
<section class="settings-card" aria-labelledby="ntfy-title">
|
||||
<h2 id="ntfy-title">Notifications / ntfy</h2>
|
||||
<p>Enter your private topic URL, test it, then enable notifications.</p>
|
||||
<form method="post" data-ntfy-form>{% csrf_token %}<input type="hidden" name="section" value="ntfy">
|
||||
<div class="form-field">{{ ntfy_form.ntfy_url.label_tag }}{{ ntfy_form.ntfy_url }}{{ ntfy_form.ntfy_url.errors }}</div>
|
||||
<div class="ntfy-check">{{ ntfy_form.ntfy_enabled }}<label for="{{ ntfy_form.ntfy_enabled.id_for_label }}">Enable ntfy notifications</label></div>
|
||||
<button class="button button--secondary" type="button" hx-post="{% url 'planner:ntfy-test' %}" hx-include="closest form" hx-target="#ntfy-test-result" hx-swap="innerHTML">Test notification</button>
|
||||
<div id="ntfy-test-result" role="status" aria-live="polite"></div>
|
||||
<button class="button" type="submit">Save notification settings</button>
|
||||
</form>
|
||||
</section>
|
||||
<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
from datetime import datetime, time
|
||||
from unittest.mock import patch
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
|
||||
from .models import FastingSettings
|
||||
from .services.fasting import configure_fasting
|
||||
from .services.fasting_notifications import notify_fasting_phase_changes
|
||||
from .services.notifications import NotificationError
|
||||
|
||||
|
||||
class FastingNotificationTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='phase-user')
|
||||
self.at = lambda hour, minute=0: datetime(2026, 10, 3, hour, minute, tzinfo=ZoneInfo('Europe/Amsterdam'))
|
||||
configure_fasting(
|
||||
self.user, enabled=True, fasting_start_time=time(20),
|
||||
fasting_duration_minutes=16 * 60, now=self.at(13),
|
||||
)
|
||||
|
||||
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
|
||||
def test_each_phase_is_sent_once(self, sender):
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(19, 59)), 0)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 1)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
|
||||
self.assertEqual(notify_fasting_phase_changes(datetime(2026, 10, 4, 12, tzinfo=ZoneInfo('Europe/Amsterdam'))), 1)
|
||||
self.assertEqual(sender.call_count, 2)
|
||||
self.assertEqual(sender.call_args.args[1], 'Eating window started')
|
||||
|
||||
@patch('planner.services.fasting_notifications.send_notification', side_effect=[NotificationError('failed'), True])
|
||||
def test_delivery_failure_is_retried(self, sender):
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 1)
|
||||
self.assertEqual(sender.call_count, 2)
|
||||
|
||||
@patch('planner.services.fasting_notifications.send_notification', return_value=True)
|
||||
def test_paused_tracking_and_schedule_changes_do_not_send_old_transition(self, sender):
|
||||
configure_fasting(
|
||||
self.user, enabled=False, fasting_start_time=time(20),
|
||||
fasting_duration_minutes=16 * 60, now=self.at(19),
|
||||
)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
||||
configure_fasting(
|
||||
self.user, enabled=True, fasting_start_time=time(20),
|
||||
fasting_duration_minutes=16 * 60, now=self.at(21),
|
||||
)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(21, 1)), 0)
|
||||
sender.assert_not_called()
|
||||
|
||||
@patch('planner.services.fasting_notifications.send_notification', return_value=False)
|
||||
def test_disabled_ntfy_does_not_queue_old_phase_for_later(self, sender):
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20)), 0)
|
||||
self.assertEqual(notify_fasting_phase_changes(self.at(20, 1)), 0)
|
||||
self.assertEqual(sender.call_count, 1)
|
||||
self.assertEqual(FastingSettings.objects.get(user=self.user).last_phase_notification_at, self.at(20))
|
||||
@@ -0,0 +1,60 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from io import BytesIO
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.cache import cache
|
||||
from django.test import TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
|
||||
from .services.gitea_activity import activity_context, fetch_heatmap
|
||||
|
||||
|
||||
@override_settings(GITEA_BASE_URL='https://git.example.com', GITEA_USERNAME='coder', GITEA_TOKEN='private-token')
|
||||
class GiteaActivityTests(TestCase):
|
||||
def setUp(self):
|
||||
cache.clear()
|
||||
|
||||
@patch('planner.services.gitea_activity.urlopen')
|
||||
def test_fetch_uses_server_side_token_and_cache(self, open_url):
|
||||
timestamp = int(datetime(2026, 10, 3, tzinfo=timezone.utc).timestamp())
|
||||
open_url.return_value.__enter__.return_value = BytesIO(json.dumps([
|
||||
{'timestamp': timestamp, 'contributions': 7},
|
||||
]).encode())
|
||||
context = activity_context(date(2026, 10, 3))
|
||||
self.assertEqual(context['activity_total'], 7)
|
||||
self.assertEqual(context['activity_weeks'][-1]['days'][-1]['level'], 4)
|
||||
request = open_url.call_args.args[0]
|
||||
self.assertEqual(request.get_header('Authorization'), 'token private-token')
|
||||
self.assertEqual(request.full_url, 'https://git.example.com/api/v1/users/coder/heatmap')
|
||||
fetch_heatmap()
|
||||
self.assertEqual(open_url.call_count, 1)
|
||||
|
||||
@patch('planner.services.gitea_activity.urlopen', side_effect=OSError('offline'))
|
||||
def test_api_failure_is_a_widget_message(self, open_url):
|
||||
self.assertTrue(activity_context(date(2026, 10, 3))['activity_unavailable'])
|
||||
|
||||
@patch('planner.services.gitea_activity.urlopen')
|
||||
def test_widget_renders_contribution_cells(self, open_url):
|
||||
timestamp = int(datetime(2026, 10, 3, tzinfo=timezone.utc).timestamp())
|
||||
open_url.return_value.__enter__.return_value = BytesIO(json.dumps([
|
||||
{'timestamp': timestamp, 'contributions': 7},
|
||||
]).encode())
|
||||
user = get_user_model().objects.create_user(username='chart-user')
|
||||
self.client.force_login(user)
|
||||
response = self.client.get(reverse('planner:gitea-activity'))
|
||||
self.assertContains(response, '7</strong> contributions')
|
||||
self.assertContains(response, '2026-10-03')
|
||||
self.assertContains(response, 'gitea-activity__cell--4')
|
||||
|
||||
@patch('planner.views.activity_context', return_value={'activity_unavailable': True})
|
||||
def test_widget_requires_login_and_is_below_workout(self, context):
|
||||
url = reverse('planner:gitea-activity')
|
||||
self.assertEqual(self.client.get(url).status_code, 302)
|
||||
user = get_user_model().objects.create_user(username='dashboard-user')
|
||||
self.client.force_login(user)
|
||||
response = self.client.get(reverse('planner:task-list'))
|
||||
html = response.content.decode()
|
||||
self.assertLess(html.index('id="workout-section"'), html.index('id="gitea-activity"'))
|
||||
self.assertContains(self.client.get(url), 'Activity is unavailable right now.')
|
||||
@@ -0,0 +1,49 @@
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import UserSettings
|
||||
from .services.notifications import NotificationError, send_notification
|
||||
|
||||
|
||||
class NtfySettingsTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='ntfy-user', password='test-password')
|
||||
self.client.force_login(self.user)
|
||||
self.settings_url = reverse('planner:user-settings')
|
||||
self.test_url = reverse('planner:ntfy-test')
|
||||
self.topic = 'https://ntfy.example.com/private-topic'
|
||||
|
||||
def save(self, url=None, enabled=True):
|
||||
return self.client.post(self.settings_url, {
|
||||
'section': 'ntfy', 'ntfy_url': self.topic if url is None else url,
|
||||
'ntfy_enabled': 'on' if enabled else '',
|
||||
})
|
||||
|
||||
def test_enable_requires_successful_test(self):
|
||||
response = self.save()
|
||||
self.assertContains(response, 'Test this URL successfully')
|
||||
self.assertFalse(UserSettings.objects.get(user=self.user).ntfy_enabled)
|
||||
|
||||
@patch('planner.views.send_ntfy_notification')
|
||||
def test_successful_test_allows_enable_and_changed_url_requires_retest(self, sender):
|
||||
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': 'invalid'}).status_code, 400)
|
||||
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 200)
|
||||
sender.assert_called_once()
|
||||
self.assertEqual(self.save().status_code, 302)
|
||||
preferences = UserSettings.objects.get(user=self.user)
|
||||
self.assertTrue(preferences.ntfy_enabled)
|
||||
self.assertIsNotNone(preferences.ntfy_last_tested_at)
|
||||
self.assertContains(self.save(url='https://ntfy.example.com/other'), 'Test this URL successfully')
|
||||
|
||||
@patch('planner.views.send_ntfy_notification', side_effect=NotificationError('Could not connect.'))
|
||||
def test_failed_test_does_not_allow_enable(self, sender):
|
||||
self.assertEqual(self.client.post(self.test_url, {'ntfy_url': self.topic}).status_code, 502)
|
||||
self.assertContains(self.save(), 'Test this URL successfully')
|
||||
|
||||
@patch('planner.services.notifications.send_ntfy_notification')
|
||||
def test_disabled_preference_suppresses_delivery(self, sender):
|
||||
self.assertFalse(send_notification(self.user, 'Title', 'Message'))
|
||||
sender.assert_not_called()
|
||||
@@ -9,6 +9,8 @@ from django.utils import timezone
|
||||
from django.urls import reverse
|
||||
|
||||
from .models import FastingPause, FastingPeriod, FastingSettings, SickDaySettings, Task
|
||||
from .models import UserSettings, WaterIntakeEntry
|
||||
from .services.hydration import hydration_context
|
||||
from .forms import DAILY_FASTING_DURATION_CHOICES, FastingSettingsForm
|
||||
from .services.deferrals import (
|
||||
apply_missed_task_deferrals,
|
||||
@@ -1511,3 +1513,48 @@ class TaskCompletionViewTests(TestCase):
|
||||
self.client.post(reverse('planner:task-toggle-completed', args=[foreign.pk])).status_code,
|
||||
404,
|
||||
)
|
||||
|
||||
class HydrationWidgetTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user(username='hydration-user', password='test-password')
|
||||
self.client.force_login(self.user)
|
||||
UserSettings.objects.update_or_create(user=self.user, defaults={'daily_water_goal_ml': 500})
|
||||
|
||||
def test_entries_total_and_over_goal_visual_cap(self):
|
||||
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 250})
|
||||
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 500})
|
||||
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 2)
|
||||
context = hydration_context(self.user)
|
||||
self.assertEqual(context['hydration_total'], 750)
|
||||
self.assertEqual(context['hydration_percent'], 150)
|
||||
self.assertEqual(context['hydration_visual'], 100)
|
||||
self.assertEqual(next(day for day in context['hydration_days'] if day['today'])['state'], 'goal')
|
||||
|
||||
def test_health_page_reuses_widgets_and_live_hydration(self):
|
||||
response = self.client.get(reverse('planner:health'))
|
||||
self.assertContains(response, 'Health routines')
|
||||
self.assertContains(response, 'id="fasting-widget"')
|
||||
self.assertContains(response, 'id="hydration-widget"')
|
||||
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 250})
|
||||
self.assertContains(self.client.get(reverse('planner:health')), '250 <span>/ 500 ml</span>', html=True)
|
||||
|
||||
def test_undo_only_current_user_current_day(self):
|
||||
other = get_user_model().objects.create_user(username='other-hydration-user')
|
||||
WaterIntakeEntry.objects.create(user=other, amount_ml=500)
|
||||
yesterday = timezone.now() - timedelta(days=1)
|
||||
WaterIntakeEntry.objects.create(user=self.user, amount_ml=250, recorded_at=yesterday)
|
||||
self.client.post(reverse('planner:hydration-add'), {'amount_ml': 500})
|
||||
self.client.post(reverse('planner:hydration-undo'))
|
||||
self.assertEqual(hydration_context(self.user)['hydration_total'], 0)
|
||||
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 1)
|
||||
self.assertEqual(WaterIntakeEntry.objects.filter(user=other).count(), 1)
|
||||
|
||||
def test_week_rolls_forward_and_invalid_amount_is_rejected(self):
|
||||
monday = timezone.now().astimezone(ZoneInfo('Europe/Amsterdam'))
|
||||
monday = monday - timedelta(days=monday.weekday())
|
||||
prior_week = monday - timedelta(days=7)
|
||||
WaterIntakeEntry.objects.create(user=self.user, amount_ml=500, recorded_at=prior_week)
|
||||
self.assertTrue(all(day['state'] == 'none' for day in hydration_context(self.user)['hydration_days']))
|
||||
response = self.client.post(reverse('planner:hydration-add'), {'amount_ml': 3001})
|
||||
self.assertContains(response, 'Enter a whole amount')
|
||||
self.assertEqual(WaterIntakeEntry.objects.filter(user=self.user).count(), 1)
|
||||
|
||||
@@ -8,7 +8,7 @@ from .views import (
|
||||
TaskUpdateView, WorkoutCreateView, WorkoutUpdateView, delete_workout, fasting_configure, neck_headache_checkin_panel,
|
||||
fasting_toggle_tracking, fasting_widget, logout_view, register, toggle_task_active, toggle_task_completed,
|
||||
save_neck_headache_checkin, save_sleep_checkin, advance_onboarding, toggle_workout_completed, user_settings, workout_today,
|
||||
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing,
|
||||
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing, hydration_add, hydration_undo, test_ntfy, gitea_activity,
|
||||
)
|
||||
|
||||
app_name = 'planner'
|
||||
@@ -20,6 +20,8 @@ urlpatterns = [
|
||||
path('register/', register, name='register'),
|
||||
path('logout/', logout_view, name='logout'),
|
||||
path('settings/', user_settings, name='user-settings'),
|
||||
path('settings/notifications/ntfy/test/', test_ntfy, name='ntfy-test'),
|
||||
path('gitea/activity/', gitea_activity, name='gitea-activity'),
|
||||
path('onboarding/advance/', advance_onboarding, name='onboarding-advance'),
|
||||
path('daily/', DailyPlannerView.as_view(), name='daily-planner'),
|
||||
path('fasting/widget/', fasting_widget, name='fasting-widget'),
|
||||
@@ -29,6 +31,8 @@ urlpatterns = [
|
||||
path('check-ins/save/', save_neck_headache_checkin, name='neck-headache-checkin-save'),
|
||||
path('sleep-check-ins/save/', save_sleep_checkin, name='sleep-checkin-save'),
|
||||
path('teeth/toggle/', toggle_tooth_brushing, name='tooth-brushing-toggle'),
|
||||
path('hydration/add/', hydration_add, name='hydration-add'),
|
||||
path('hydration/undo/', hydration_undo, name='hydration-undo'),
|
||||
path('bowel-health/panel/', bowel_health_panel, name='bowel-health-panel'),
|
||||
path('bowel-health/save/', save_bowel_health_checkin, name='bowel-health-save'),
|
||||
path('check-ins/export/<str:period>/', export_pain_csv, name='pain-export'),
|
||||
|
||||
+87
-2
@@ -1,9 +1,13 @@
|
||||
import calendar
|
||||
from hashlib import sha256
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import login, logout
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import URLValidator
|
||||
from django.http import Http404, HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse, reverse_lazy
|
||||
@@ -16,9 +20,12 @@ from django.views.generic import CreateView, DeleteView, DetailView, ListView, T
|
||||
|
||||
from .forms import (
|
||||
DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm,
|
||||
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm,
|
||||
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm, HydrationGoalForm, WaterIntakeForm, NtfySettingsForm,
|
||||
)
|
||||
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout
|
||||
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout, WaterIntakeEntry
|
||||
from .services.hydration import hydration_context
|
||||
from .services.gitea_activity import activity_context
|
||||
from .services.notifications import NotificationError, send_ntfy_notification
|
||||
from .services.checkins import (
|
||||
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE, LOW_PAIN_STREAK_THRESHOLD, calculate_check_in_streaks,
|
||||
)
|
||||
@@ -513,11 +520,19 @@ class TaskListView(LoginRequiredMixin, ListView):
|
||||
context.update(dashboard_weather_context(self.request.user))
|
||||
context.update(workout_context(self.request.user))
|
||||
context.update(brushing_context(self.request.user))
|
||||
context.update(hydration_context(self.request.user))
|
||||
context['gitea_activity_enabled'] = bool(settings.GITEA_USERNAME)
|
||||
profile, _ = UserSettings.objects.get_or_create(user=self.request.user)
|
||||
context['onboarding_tour'] = onboarding_context(profile)
|
||||
return context
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET'])
|
||||
def gitea_activity(request):
|
||||
return render(request, 'planner/partials/gitea_activity.html', activity_context())
|
||||
|
||||
|
||||
class HealthView(LoginRequiredMixin, TemplateView):
|
||||
template_name = 'planner/health.html'
|
||||
|
||||
@@ -530,6 +545,8 @@ class HealthView(LoginRequiredMixin, TemplateView):
|
||||
context.update(bowel_context(
|
||||
self.request.user, selected_check_in_date(self.request.GET.get('bowel_date'), self.request.user),
|
||||
))
|
||||
context.update(fasting_widget_context(self.request.user))
|
||||
context.update(hydration_context(self.request.user))
|
||||
return context
|
||||
|
||||
|
||||
@@ -735,9 +752,11 @@ def user_settings(request):
|
||||
sick_day, _ = SickDaySettings.objects.get_or_create(user=request.user)
|
||||
fasting = FastingSettings.objects.filter(user=request.user).first()
|
||||
profile_form = UserSettingsForm(instance=profile)
|
||||
hydration_goal_form = HydrationGoalForm(instance=profile)
|
||||
sick_form = SickDaySettingsForm(instance=sick_day)
|
||||
fasting_form = FastingSettingsForm(instance=fasting)
|
||||
time_zone_form = TimeZoneSettingsForm(instance=profile)
|
||||
ntfy_form = NtfySettingsForm(instance=profile)
|
||||
|
||||
if request.method == 'POST':
|
||||
section = request.POST.get('section')
|
||||
@@ -747,6 +766,34 @@ def user_settings(request):
|
||||
profile_form.save()
|
||||
messages.success(request, 'Your weather location was saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'hydration':
|
||||
hydration_goal_form = HydrationGoalForm(request.POST, instance=profile)
|
||||
if hydration_goal_form.is_valid():
|
||||
hydration_goal_form.save()
|
||||
messages.success(request, 'Your daily water goal was saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'ntfy':
|
||||
old_url = profile.ntfy_url
|
||||
ntfy_form = NtfySettingsForm(request.POST, instance=profile)
|
||||
if ntfy_form.is_valid():
|
||||
url = ntfy_form.cleaned_data['ntfy_url']
|
||||
tested = bool(url) and request.session.get(f'ntfy_tested:{request.user.pk}') == sha256(url.encode()).hexdigest()
|
||||
previously_tested = url == old_url and profile.ntfy_last_tested_at is not None
|
||||
if ntfy_form.cleaned_data['ntfy_enabled'] and not (tested or previously_tested):
|
||||
ntfy_form.add_error('ntfy_url', 'Test this URL successfully before enabling notifications.')
|
||||
else:
|
||||
profile = ntfy_form.save(commit=False)
|
||||
if not url:
|
||||
profile.ntfy_enabled = False
|
||||
profile.ntfy_last_tested_at = None
|
||||
elif tested:
|
||||
profile.ntfy_last_tested_at = timezone.now()
|
||||
elif url != old_url:
|
||||
profile.ntfy_last_tested_at = None
|
||||
profile.save()
|
||||
request.session.pop(f'ntfy_tested:{request.user.pk}', None)
|
||||
messages.success(request, 'Notification settings were saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'sick-day':
|
||||
sick_form = SickDaySettingsForm(request.POST, instance=sick_day)
|
||||
if sick_form.is_valid():
|
||||
@@ -794,13 +841,51 @@ def user_settings(request):
|
||||
|
||||
return render(request, 'planner/user_settings.html', {
|
||||
'profile_form': profile_form,
|
||||
'hydration_goal_form': hydration_goal_form,
|
||||
'sick_form': sick_form,
|
||||
'fasting_form': fasting_form,
|
||||
'time_zone_form': time_zone_form,
|
||||
'ntfy_form': ntfy_form,
|
||||
'onboarding_enabled': profile.onboarding_enabled,
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def test_ntfy(request):
|
||||
url = request.POST.get('ntfy_url', '').strip()
|
||||
try:
|
||||
URLValidator(schemes=['http', 'https'])(url)
|
||||
except ValidationError:
|
||||
return render(request, 'planner/partials/ntfy_test_result.html', {'error': 'Enter a valid HTTP or HTTPS topic URL.'}, status=400)
|
||||
try:
|
||||
send_ntfy_notification(url, 'Tasknest', 'Test notification sent successfully.')
|
||||
except NotificationError as error:
|
||||
return render(request, 'planner/partials/ntfy_test_result.html', {'error': str(error)}, status=502)
|
||||
request.session[f'ntfy_tested:{request.user.pk}'] = sha256(url.encode()).hexdigest()
|
||||
return render(request, 'planner/partials/ntfy_test_result.html', {'success': True})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_add(request):
|
||||
form = WaterIntakeForm(request.POST)
|
||||
if form.is_valid():
|
||||
WaterIntakeEntry.objects.create(user=request.user, amount_ml=form.cleaned_data['amount_ml'])
|
||||
context = hydration_context(request.user)
|
||||
context['hydration_error'] = form.errors.get('amount_ml') if not form.is_valid() else None
|
||||
return render(request, 'planner/partials/hydration_widget.html', context)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_undo(request):
|
||||
context = hydration_context(request.user)
|
||||
if context['hydration_last']:
|
||||
context['hydration_last'].delete()
|
||||
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
|
||||
|
||||
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def register(request):
|
||||
if request.user.is_authenticated:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
asarPy==1.0.1
|
||||
asgiref==3.12.1
|
||||
Django==6.1.1
|
||||
h3==4.5.0
|
||||
sqlparse==0.6.0
|
||||
@@ -129,6 +129,30 @@ VITE_DEV_SERVER = os.environ.get('VITE_DEV_SERVER', 'http://localhost:5173')
|
||||
VITE_USE_DEV_SERVER = os.environ.get('VITE_USE_DEV_SERVER', str(DEBUG)).lower() in {'1', 'true', 'yes'}
|
||||
VITE_MANIFEST_PATH = BASE_DIR / 'planner' / 'static' / 'planner' / 'dist' / '.vite' / 'manifest.json'
|
||||
|
||||
# Optional Gitea contribution grid on the task dashboard. Read only these
|
||||
# values from the repository's ignored .env file; the process environment wins.
|
||||
def _gitea_env(name, default=''):
|
||||
if name in os.environ:
|
||||
return os.environ[name]
|
||||
env_file = BASE_DIR.parent / '.env'
|
||||
try:
|
||||
lines = env_file.read_text(encoding='utf-8').splitlines()
|
||||
except FileNotFoundError:
|
||||
return default
|
||||
for line in lines:
|
||||
key, separator, value = line.strip().partition('=')
|
||||
if separator and key.strip() == name:
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
|
||||
value = value[1:-1]
|
||||
return value
|
||||
return default
|
||||
|
||||
|
||||
GITEA_BASE_URL = _gitea_env('GITEA_BASE_URL', 'https://git.jorendegraaf.eu').rstrip('/')
|
||||
GITEA_USERNAME = _gitea_env('GITEA_USERNAME').strip()
|
||||
GITEA_TOKEN = _gitea_env('GITEA_TOKEN').strip()
|
||||
|
||||
LOGIN_URL = 'planner:login'
|
||||
LOGIN_REDIRECT_URL = 'planner:task-list'
|
||||
LOGOUT_REDIRECT_URL = 'planner:login'
|
||||
|
||||
Reference in New Issue
Block a user