Compare commits
16 Commits
f961440f13
...
0.0.12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77498b6261 | ||
|
|
960c080f1c | ||
|
|
c420e03ca1 | ||
|
|
e496c29101 | ||
|
|
47f12834c1 | ||
|
|
b4a65a1af4 | ||
|
|
65aeeda263 | ||
|
|
f61e014d2a | ||
| ce6a5c7477 | |||
|
|
f66f58f67f | ||
|
|
5f036dbc89 | ||
|
|
6394c8496d | ||
|
|
579ba8f5ef | ||
|
|
e0796a071b | ||
|
|
ce78c6e07f | ||
|
|
057ba02865 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,4 +1,7 @@
|
|||||||
.direnv
|
.direnv
|
||||||
server.log
|
server.log
|
||||||
|
shell.nix
|
||||||
mem.go
|
mem.go
|
||||||
nxcaldav
|
nxcaldav
|
||||||
|
in/
|
||||||
|
out/
|
||||||
|
|||||||
4
.ignore
4
.ignore
@@ -1,4 +1,6 @@
|
|||||||
.direnv
|
.direnv
|
||||||
server.log
|
# server.log
|
||||||
mem.go
|
mem.go
|
||||||
nxcaldav
|
nxcaldav
|
||||||
|
in/
|
||||||
|
out/
|
||||||
|
|||||||
55
README.md
55
README.md
@@ -21,7 +21,7 @@ DELETE FROM users WHERE name = 'bob';
|
|||||||
```sql
|
```sql
|
||||||
DELETE FROM calendars WHERE name = 'bob_calendar' AND owner_id = (SELECT id FROM users WHERE name = 'bob');
|
DELETE FROM calendars WHERE name = 'bob_calendar' AND owner_id = (SELECT id FROM users WHERE name = 'bob');
|
||||||
/* or */
|
/* or */
|
||||||
DELETE FROM calendars WHERE ;
|
DELETE FROM calendars WHERE path = '/bob/calendars/old/';
|
||||||
```
|
```
|
||||||
## rename calendar
|
## rename calendar
|
||||||
```sql
|
```sql
|
||||||
@@ -33,3 +33,56 @@ UPDATE calendar_objects SET path = regexp_replace(path, '/old/', '/new/')' WHERE
|
|||||||
```sql
|
```sql
|
||||||
select id, path, linecut from calendar_objects, LATERAL regexp_split_to_table(data, E'\r\n') AS linecut where linecut ~ 'CLASS';
|
select id, path, linecut from calendar_objects, LATERAL regexp_split_to_table(data, E'\r\n') AS linecut where linecut ~ 'CLASS';
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Helpers
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
The scripts require psycopg2 (or psycopg2-binary) and PyYAML.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
pip install psycopg2-binary pyyaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Exporting Events
|
||||||
|
The `export_events.py` script extracts events from the database and saves them as `.ics` files in a structured directory format: `username/calendarID/filename.ics`.
|
||||||
|
|
||||||
|
### Examples:
|
||||||
|
- Export everything:
|
||||||
|
```shell
|
||||||
|
python export_events.py --output ./my_backup
|
||||||
|
```
|
||||||
|
|
||||||
|
- Export only one user:
|
||||||
|
```shell
|
||||||
|
python export_events.py --user alice --output ./alice_backup
|
||||||
|
```
|
||||||
|
|
||||||
|
- Export a specific calendar:
|
||||||
|
```shell
|
||||||
|
python export_events.py --user alice --calendar preservation --output ./preservation_backup
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Importing Events
|
||||||
|
The `import_events.py` script uploads events back into the database. It can either walk a structured directory (like the one created by the export script) or upload a flat directory of files to a specific target calendar.
|
||||||
|
|
||||||
|
### Examples:
|
||||||
|
- Restore everything from a backup:
|
||||||
|
```shell
|
||||||
|
python import_events.py --input ./my_backup
|
||||||
|
```
|
||||||
|
|
||||||
|
- Upload a directory of .ics files to a specific calendar:
|
||||||
|
```shell
|
||||||
|
python import_events.py --input ./some_events/ --user alice --calendar work
|
||||||
|
```
|
||||||
|
|
||||||
|
- Upload a single file to a specific calendar:
|
||||||
|
```shell
|
||||||
|
python import_events.py --input ./event.ics --user bob --calendar bob
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
51
config.yaml
51
config.yaml
@@ -1,42 +1,23 @@
|
|||||||
server:
|
|
||||||
bind_address: "0.0.0.0:14243"
|
|
||||||
public_url: "http://localhost:8080"
|
|
||||||
redaction_text: "[-]"
|
|
||||||
default_class: "CONFIDENTIAL"
|
|
||||||
|
|
||||||
database:
|
database:
|
||||||
url: "postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable"
|
url: postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable
|
||||||
|
server:
|
||||||
|
bind_address: 0.0.0.0:14243
|
||||||
|
default_class: CONFIDENTIAL
|
||||||
|
public_url: http://example.com/
|
||||||
|
email_domain: example.com
|
||||||
|
redaction_text: '[-]'
|
||||||
|
|
||||||
|
smtp:
|
||||||
|
host: localhost
|
||||||
|
port: 587
|
||||||
|
user: nxcaldav@nx2.site
|
||||||
|
password_cmd: echo "Vastly-Wrinkle9-Corsage"
|
||||||
|
|
||||||
users:
|
users:
|
||||||
- name: "daniel"
|
|
||||||
password: "Cyclist-Hypnotize7-Blurb"
|
|
||||||
groups:
|
|
||||||
- family
|
|
||||||
- name: "diane"
|
|
||||||
password: "Carve-Unluckily-Reprint1"
|
|
||||||
groups:
|
|
||||||
- family
|
|
||||||
- name: "lennart"
|
|
||||||
password: "Baton6-Extortion-Monologue"
|
|
||||||
groups:
|
|
||||||
- family
|
|
||||||
- name: "shared"
|
|
||||||
password: "Oxidant-Ageless3-Dispersed"
|
|
||||||
|
|
||||||
calendars:
|
calendars:
|
||||||
- id: "default"
|
|
||||||
owner: "lennart"
|
address_books:
|
||||||
- id: "family"
|
|
||||||
owner: "shared"
|
|
||||||
access:
|
|
||||||
- groups: "family"
|
|
||||||
mode: "read-write"
|
|
||||||
|
|
||||||
aggregates:
|
aggregates:
|
||||||
- id: "lennart_aggregate"
|
|
||||||
owner: "shared"
|
|
||||||
sources: [ "default", "family" ]
|
|
||||||
access:
|
|
||||||
- group: "diane"
|
|
||||||
mode: "read-only"
|
|
||||||
- ics: "future-only"
|
|
||||||
|
|||||||
77
export_events.py
Normal file
77
export_events.py
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
import psycopg2
|
||||||
|
import yaml
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
def get_db_url(config_path):
|
||||||
|
with open(config_path, 'r') as f:
|
||||||
|
cfg = yaml.safe_load(f)
|
||||||
|
return cfg.get('database', {}).get('url')
|
||||||
|
|
||||||
|
def export_events():
|
||||||
|
parser = argparse.ArgumentParser(description='Export CalDAV events from database to files.')
|
||||||
|
parser.add_argument('--config', default='config.yaml', help='Path to config.yaml')
|
||||||
|
parser.add_argument('--output', default='export', help='Output directory')
|
||||||
|
parser.add_argument('--user', help='Filter by user name')
|
||||||
|
parser.add_argument('--calendar', help='Filter by calendar ID (name in DB)')
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
db_url = get_db_url(args.config)
|
||||||
|
if not db_url:
|
||||||
|
print("Error: Could not find database URL in config.")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = psycopg2.connect(db_url)
|
||||||
|
cur = conn.cursor()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error connecting to database: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
query = """
|
||||||
|
SELECT u.name as user_name, c.name as cal_name, co.path, co.data
|
||||||
|
FROM calendar_objects co
|
||||||
|
JOIN calendars c ON co.calendar_id = c.id
|
||||||
|
JOIN users u ON c.owner_id = u.id
|
||||||
|
WHERE 1=1
|
||||||
|
"""
|
||||||
|
params = []
|
||||||
|
if args.user:
|
||||||
|
query += " AND u.name = %s"
|
||||||
|
params.append(args.user)
|
||||||
|
if args.calendar:
|
||||||
|
query += " AND c.name = %s"
|
||||||
|
params.append(args.calendar)
|
||||||
|
|
||||||
|
cur.execute(query, params)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
if not rows:
|
||||||
|
print("No events found matching the filters.")
|
||||||
|
return
|
||||||
|
|
||||||
|
for user_name, cal_name, obj_path, data in rows:
|
||||||
|
# Create directory structure: output/user/calendar/
|
||||||
|
target_dir = os.path.join(args.output, user_name, cal_name)
|
||||||
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Filename from the path (the last part after /)
|
||||||
|
filename = os.path.basename(obj_path)
|
||||||
|
if not filename: # Should not happen with valid paths
|
||||||
|
continue
|
||||||
|
|
||||||
|
file_path = os.path.join(target_dir, filename)
|
||||||
|
with open(file_path, 'w') as f:
|
||||||
|
f.write(data)
|
||||||
|
|
||||||
|
print(f"Exported: {user_name}/{cal_name}/{filename}")
|
||||||
|
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
print(f"Done. Exported {len(rows)} events to '{args.output}'.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
export_events()
|
||||||
1
go.mod
1
go.mod
@@ -10,6 +10,7 @@ require (
|
|||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
|||||||
2
go.sum
2
go.sum
@@ -6,6 +6,8 @@ github.com/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6/go.mod h1:BEksegN
|
|||||||
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608 h1:5XWaET4YAcppq3l1/Yh2ay5VmQjUdq6qhJuucdGbmOY=
|
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608 h1:5XWaET4YAcppq3l1/Yh2ay5VmQjUdq6qhJuucdGbmOY=
|
||||||
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw=
|
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw=
|
||||||
github.com/emersion/go-vcard v0.0.0-20230815062825-8fda7d206ec9/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM=
|
github.com/emersion/go-vcard v0.0.0-20230815062825-8fda7d206ec9/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM=
|
||||||
|
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff h1:4N8wnS3f1hNHSmFD5zgFkWCyA4L1kCDkImPAtK7D6tg=
|
||||||
|
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM=
|
||||||
github.com/emersion/go-webdav v0.7.0 h1:cp6aBWXBf8Sjzguka9VJarr4XTkGc2IHxXI1Gq3TKpA=
|
github.com/emersion/go-webdav v0.7.0 h1:cp6aBWXBf8Sjzguka9VJarr4XTkGc2IHxXI1Gq3TKpA=
|
||||||
github.com/emersion/go-webdav v0.7.0/go.mod h1:mI8iBx3RAODwX7PJJ7qzsKAKs/vY429YfS2/9wKnDbQ=
|
github.com/emersion/go-webdav v0.7.0/go.mod h1:mI8iBx3RAODwX7PJJ7qzsKAKs/vY429YfS2/9wKnDbQ=
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
|||||||
124
import_events.py
Normal file
124
import_events.py
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
#!/usr/bin/env python
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
import psycopg2
|
||||||
|
import yaml
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
def get_config(config_path):
|
||||||
|
with open(config_path, 'r') as f:
|
||||||
|
return yaml.safe_load(f)
|
||||||
|
|
||||||
|
def count_events(data):
|
||||||
|
return data.count('BEGIN:VEVENT')
|
||||||
|
|
||||||
|
def import_events():
|
||||||
|
parser = argparse.ArgumentParser(description='Import CalDAV events from files to database.')
|
||||||
|
parser.add_argument('--config', default='config.yaml', help='Path to config.yaml')
|
||||||
|
parser.add_argument('--input', default='export', help='Input directory or file')
|
||||||
|
parser.add_argument('--user', help='Target user (filter or override)')
|
||||||
|
parser.add_argument('--calendar', help='Target calendar (filter or override)')
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
cfg = get_config(args.config)
|
||||||
|
db_url = cfg.get('database', {}).get('url')
|
||||||
|
if not db_url:
|
||||||
|
print("Error: Could not find database URL in config.")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
conn = psycopg2.connect(db_url)
|
||||||
|
cur = conn.cursor()
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error connecting to database: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
def upload_file(file_path, user_name, cal_name):
|
||||||
|
cur.execute("""
|
||||||
|
SELECT c.id, c.path
|
||||||
|
FROM calendars c
|
||||||
|
JOIN users u ON c.owner_id = u.id
|
||||||
|
WHERE u.name = %s AND c.name = %s
|
||||||
|
""", (user_name, cal_name))
|
||||||
|
res = cur.fetchone()
|
||||||
|
if not res:
|
||||||
|
print(f"Warning: Calendar '{cal_name}' for user '{user_name}' not found in DB. Skipping {file_path}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
cal_id, cal_base_path = res
|
||||||
|
with open(file_path, 'r') as f:
|
||||||
|
data = f.read()
|
||||||
|
|
||||||
|
filename = os.path.basename(file_path)
|
||||||
|
obj_path = os.path.join(cal_base_path, filename)
|
||||||
|
etag = f'"{count_events(data)}"'
|
||||||
|
|
||||||
|
cur.execute("""
|
||||||
|
INSERT INTO calendar_objects (calendar_id, path, data, etag)
|
||||||
|
VALUES (%s, %s, %s, %s)
|
||||||
|
ON CONFLICT (calendar_id, path) DO UPDATE
|
||||||
|
SET data = EXCLUDED.data, etag = EXCLUDED.etag
|
||||||
|
""", (cal_id, obj_path, data, etag))
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Gather all files
|
||||||
|
files_to_process = []
|
||||||
|
if os.path.isfile(args.input):
|
||||||
|
files_to_process.append(args.input)
|
||||||
|
elif os.path.isdir(args.input):
|
||||||
|
for root, _, filenames in os.walk(args.input):
|
||||||
|
for f in filenames:
|
||||||
|
if f.endswith('.ics'):
|
||||||
|
files_to_process.append(os.path.join(root, f))
|
||||||
|
else:
|
||||||
|
print(f"Error: Input '{args.input}' not found.")
|
||||||
|
return
|
||||||
|
|
||||||
|
success_count = 0
|
||||||
|
for f_path in files_to_process:
|
||||||
|
# Determine source structure
|
||||||
|
# If input is a dir, rel_path is relative to it. If file, it's just the filename.
|
||||||
|
if os.path.isdir(args.input):
|
||||||
|
rel_path = os.path.relpath(f_path, args.input)
|
||||||
|
else:
|
||||||
|
rel_path = os.path.basename(f_path)
|
||||||
|
|
||||||
|
parts = rel_path.split(os.sep)
|
||||||
|
|
||||||
|
source_user = None
|
||||||
|
source_cal = None
|
||||||
|
|
||||||
|
# Structure: user/calendar/file.ics (len 3)
|
||||||
|
if len(parts) >= 3:
|
||||||
|
source_user = parts[-3]
|
||||||
|
source_cal = parts[-2]
|
||||||
|
# Structure: calendar/file.ics (len 2)
|
||||||
|
elif len(parts) == 2:
|
||||||
|
source_cal = parts[-2]
|
||||||
|
|
||||||
|
# 1. Apply Filtering: If flag is set and we have a source value, they must match.
|
||||||
|
if args.user and source_user and args.user != source_user:
|
||||||
|
continue
|
||||||
|
if args.calendar and source_cal and args.calendar != source_cal:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 2. Determine Target: Flag overrides source.
|
||||||
|
target_user = args.user or source_user
|
||||||
|
target_cal = args.calendar or source_cal
|
||||||
|
|
||||||
|
if not target_user or not target_cal:
|
||||||
|
print(f"Skipping {f_path}: Cannot determine user/calendar. Use --user and --calendar flags.")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if upload_file(f_path, target_user, target_cal):
|
||||||
|
print(f"Imported: {target_user}/{target_cal}/{os.path.basename(f_path)}")
|
||||||
|
success_count += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
print(f"Done. Successfully imported {success_count} events.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import_events()
|
||||||
File diff suppressed because it is too large
Load Diff
126
internal/backend/email.go
Normal file
126
internal/backend/email.go
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
package backend
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/smtp"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/emersion/go-ical"
|
||||||
|
"nxcaldav/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sendInvitation sends an iMIP (RFC 6047) invitation email.
|
||||||
|
// It includes a plain-text fallback and a METHOD:REQUEST iCalendar attachment
|
||||||
|
// that calendar clients (Thunderbird, Apple, etc.) will recognize.
|
||||||
|
func (b *DBBackend) sendInvitation(senderName, recipientEmail, summary, description, start, end, objectPath, originalICS string) error {
|
||||||
|
fromAddr := fmt.Sprintf("%s@%s", senderName, b.emailDomain)
|
||||||
|
if b.smtp.User != "" {
|
||||||
|
fromAddr = b.smtp.User
|
||||||
|
}
|
||||||
|
fromHeader := fmt.Sprintf("%s <%s>", senderName, fromAddr)
|
||||||
|
|
||||||
|
baseURL := strings.TrimSuffix(b.publicURL, "/")
|
||||||
|
acceptURL := fmt.Sprintf("%s/respond?path=%s&attendee=%s&status=ACCEPTED", baseURL, url.QueryEscape(objectPath), url.QueryEscape(recipientEmail))
|
||||||
|
declineURL := fmt.Sprintf("%s/respond?path=%s&attendee=%s&status=DECLINED", baseURL, url.QueryEscape(objectPath), url.QueryEscape(recipientEmail))
|
||||||
|
|
||||||
|
// 1. Prepare plain-text fallback - with prominent links
|
||||||
|
textPart := "PLEASE RESPOND TO THIS INVITATION:\r\n"
|
||||||
|
textPart += fmt.Sprintf("✅ ACCEPT: %s\r\n", acceptURL)
|
||||||
|
textPart += fmt.Sprintf("❌ DECLINE: %s\r\n", declineURL)
|
||||||
|
textPart += "\r\n------------------------------------------\r\n\r\n"
|
||||||
|
textPart += fmt.Sprintf("You have been invited to an event by %s.\r\n\r\n", senderName)
|
||||||
|
textPart += fmt.Sprintf("Event: %s\r\n", summary)
|
||||||
|
|
||||||
|
// 2. Prepare iCalendar part with METHOD:REQUEST
|
||||||
|
var icsContent string
|
||||||
|
calendar, err := ical.NewDecoder(strings.NewReader(originalICS)).Decode()
|
||||||
|
if err == nil {
|
||||||
|
calendar.Props.SetText("METHOD", "REQUEST")
|
||||||
|
// Discourage clients from sending their own response emails
|
||||||
|
for _, event := range calendar.Events() {
|
||||||
|
for _, attendee := range event.Props["ATTENDEE"] {
|
||||||
|
attendee.Params.Set("RSVP", "FALSE")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := ical.NewEncoder(&buf).Encode(calendar); err == nil {
|
||||||
|
icsContent = buf.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if icsContent == "" {
|
||||||
|
icsContent = originalICS // Fallback to raw if decoding failed
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Construct Multipart MIME Email
|
||||||
|
boundary := "nxcaldav_invite_boundary"
|
||||||
|
subject := fmt.Sprintf("Invitation: %s", summary)
|
||||||
|
|
||||||
|
header := fmt.Sprintf("Subject: %s\r\n", subject)
|
||||||
|
header += fmt.Sprintf("From: %s\r\n", fromHeader)
|
||||||
|
header += fmt.Sprintf("To: %s\r\n", recipientEmail)
|
||||||
|
header += "MIME-Version: 1.0\r\n"
|
||||||
|
header += fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\r\n", boundary)
|
||||||
|
header += "\r\n"
|
||||||
|
|
||||||
|
body := fmt.Sprintf("--%s\r\n", boundary)
|
||||||
|
body += "Content-Type: text/plain; charset=UTF-8\r\n"
|
||||||
|
body += "Content-Transfer-Encoding: 7bit\r\n"
|
||||||
|
body += "\r\n"
|
||||||
|
body += textPart + "\r\n"
|
||||||
|
|
||||||
|
body += fmt.Sprintf("--%s\r\n", boundary)
|
||||||
|
body += "Content-Type: text/calendar; method=REQUEST; charset=UTF-8\r\n"
|
||||||
|
body += "Content-Transfer-Encoding: 7bit\r\n"
|
||||||
|
body += "\r\n"
|
||||||
|
body += icsContent + "\r\n"
|
||||||
|
body += fmt.Sprintf("--%s--\r\n", boundary)
|
||||||
|
|
||||||
|
// 4. Send the mail
|
||||||
|
addr := fmt.Sprintf("%s:%d", b.smtp.Host, b.smtp.Port)
|
||||||
|
tlsConfig := &tls.Config{InsecureSkipVerify: true, ServerName: b.smtp.Host}
|
||||||
|
|
||||||
|
var c *smtp.Client
|
||||||
|
if b.smtp.Port == 465 {
|
||||||
|
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||||
|
if err != nil { return err }
|
||||||
|
c, err = smtp.NewClient(conn, b.smtp.Host)
|
||||||
|
} else {
|
||||||
|
c, err = smtp.Dial(addr)
|
||||||
|
}
|
||||||
|
if err != nil { return err }
|
||||||
|
defer c.Close()
|
||||||
|
|
||||||
|
if err = c.Hello("localhost"); err != nil { return err }
|
||||||
|
if b.smtp.Port != 465 {
|
||||||
|
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||||
|
if err = c.StartTLS(tlsConfig); err != nil { return err }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
smtpPassword, err := config.ResolvePassword(b.smtp.Password, b.smtp.PasswordCmd)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to resolve SMTP password: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.smtp.User != "" && smtpPassword != "" {
|
||||||
|
auth := smtp.PlainAuth("", b.smtp.User, smtpPassword, b.smtp.Host)
|
||||||
|
if err = c.Auth(auth); err != nil { return err }
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = c.Mail(fromAddr); err != nil { return err }
|
||||||
|
if err = c.Rcpt(recipientEmail); err != nil { return err }
|
||||||
|
|
||||||
|
w, err := c.Data()
|
||||||
|
if err != nil { return err }
|
||||||
|
_, err = w.Write([]byte(header + body))
|
||||||
|
if err != nil { return err }
|
||||||
|
err = w.Close()
|
||||||
|
if err != nil { return err }
|
||||||
|
|
||||||
|
log.Printf("[email] Successfully sent iMIP invitation to %s", recipientEmail)
|
||||||
|
return c.Quit()
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -10,14 +12,22 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Access struct {
|
type Access struct {
|
||||||
User string `yaml:"user,omitempty"`
|
User string `yaml:"user,omitempty"`
|
||||||
Group string `yaml:"group,omitempty"`
|
Users []string `yaml:"users,omitempty"`
|
||||||
Groups string `yaml:"groups,omitempty"`
|
Group string `yaml:"group,omitempty"`
|
||||||
Mode string `yaml:"mode"` // "read-only" or "read-write"
|
Groups string `yaml:"groups,omitempty"`
|
||||||
ICS string `yaml:"ics,omitempty"`
|
Mode string `yaml:"mode"` // "read-only" or "read-write"
|
||||||
|
ICS string `yaml:"ics,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Calendar struct {
|
type Calendar struct {
|
||||||
|
ID string `yaml:"id"`
|
||||||
|
Owner string `yaml:"owner"`
|
||||||
|
Color string `yaml:"color,omitempty"`
|
||||||
|
Access []Access `yaml:"access,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddressBook struct {
|
||||||
ID string `yaml:"id"`
|
ID string `yaml:"id"`
|
||||||
Owner string `yaml:"owner"`
|
Owner string `yaml:"owner"`
|
||||||
Access []Access `yaml:"access,omitempty"`
|
Access []Access `yaml:"access,omitempty"`
|
||||||
@@ -26,6 +36,7 @@ type Calendar struct {
|
|||||||
type Aggregate struct {
|
type Aggregate struct {
|
||||||
ID string `yaml:"id"`
|
ID string `yaml:"id"`
|
||||||
Owner string `yaml:"owner"`
|
Owner string `yaml:"owner"`
|
||||||
|
Color string `yaml:"color,omitempty"`
|
||||||
Sources []string `yaml:"sources"` // Calendar IDs
|
Sources []string `yaml:"sources"` // Calendar IDs
|
||||||
Access []Access `yaml:"access,omitempty"`
|
Access []Access `yaml:"access,omitempty"`
|
||||||
}
|
}
|
||||||
@@ -44,24 +55,59 @@ type DatabaseConfig struct {
|
|||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
BindAddress string `yaml:"bind_address"`
|
BindAddress string `yaml:"bind_address"`
|
||||||
PublicURL string `yaml:"public_url"`
|
PublicURL string `yaml:"public_url"`
|
||||||
Redaction string `yaml:"redaction_text"`
|
EmailDomain string `yaml:"email_domain"`
|
||||||
DefaultClass string `yaml:"default_class"`
|
Redaction string `yaml:"redaction_text"` // "[-]"
|
||||||
|
DefaultClass string `yaml:"default_class"` // CONFIDENTIAL/PRIVATE/PUBLIC
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s ServerConfig) BasePath() string {
|
func (s ServerConfig) BasePath() string {
|
||||||
u, err := url.Parse(s.PublicURL)
|
u, err := url.Parse(s.PublicURL)
|
||||||
if err != nil {
|
if err != nil { return "" }
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return strings.TrimSuffix(u.Path, "/")
|
return strings.TrimSuffix(u.Path, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
type SMTPConfig struct {
|
||||||
|
Host string `yaml:"host"`
|
||||||
|
Port int `yaml:"port"`
|
||||||
|
User string `yaml:"user"`
|
||||||
|
Password string `yaml:"password"`
|
||||||
|
PasswordCmd string `yaml:"password_cmd"`
|
||||||
|
}
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Server ServerConfig `yaml:"server"`
|
Server ServerConfig `yaml:"server"`
|
||||||
Database DatabaseConfig `yaml:"database"`
|
Database DatabaseConfig `yaml:"database"`
|
||||||
Users []User `yaml:"users"`
|
SMTP SMTPConfig `yaml:"smtp"`
|
||||||
Calendars []Calendar `yaml:"calendars"`
|
Users []User `yaml:"users"`
|
||||||
Aggregates []Aggregate `yaml:"aggregates"`
|
Calendars []Calendar `yaml:"calendars"`
|
||||||
|
AddressBooks []AddressBook `yaml:"address_books"`
|
||||||
|
Aggregates []Aggregate `yaml:"aggregates"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolvePassword(password, passwordCmd string) (string, error) {
|
||||||
|
if passwordCmd != "" {
|
||||||
|
cmd := exec.Command("sh", "-c", passwordCmd)
|
||||||
|
out, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to run password command: %v", err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out)), nil
|
||||||
|
}
|
||||||
|
return password, nil
|
||||||
|
}
|
||||||
|
func (c *Config) setDefaults() {
|
||||||
|
if c.Server.BindAddress == "" { c.Server.BindAddress = ":8080" }
|
||||||
|
if c.Server.Redaction == "" { c.Server.Redaction = "Busy" }
|
||||||
|
if c.Server.DefaultClass == "" { c.Server.DefaultClass = "CONFIDENTIAL" }
|
||||||
|
if c.Server.EmailDomain == "" { c.Server.EmailDomain = "nx2.site" }
|
||||||
|
if c.Database.URL == "" { c.Database.URL = "postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable" }
|
||||||
|
if c.SMTP.Host == "" { c.SMTP.Host = "localhost" }
|
||||||
|
if c.SMTP.Port == 0 { c.SMTP.Port = 25 }
|
||||||
|
}
|
||||||
|
func (c *Config) checkConfig() {
|
||||||
|
if !(slices.Contains([]string{"PUBLIC", "PRIVATE", "CONFIDENTIAL"}, c.Server.DefaultClass)) {
|
||||||
|
panic("Invaldi Config, default_class")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load(path string) (*Config, error) {
|
func Load(path string) (*Config, error) {
|
||||||
@@ -82,23 +128,3 @@ func Load(path string) (*Config, error) {
|
|||||||
return &cfg, nil
|
return &cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) checkConfig() {
|
|
||||||
if !(slices.Contains([]string{"PUBLIC", "PRIVATE", "CONFIDENTIAL"}, c.Server.DefaultClass)) {
|
|
||||||
panic("Invaldi Config, default_class")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) setDefaults() {
|
|
||||||
if c.Server.BindAddress == "" {
|
|
||||||
c.Server.BindAddress = ":8080"
|
|
||||||
}
|
|
||||||
if c.Server.Redaction == "" {
|
|
||||||
c.Server.Redaction = "Busy"
|
|
||||||
}
|
|
||||||
if c.Server.DefaultClass == "" {
|
|
||||||
c.Server.DefaultClass = "CONFIDENTIAL"
|
|
||||||
}
|
|
||||||
if c.Database.URL == "" {
|
|
||||||
c.Database.URL = "postgres://nxcaldav@localhost:5432/nxcaldav?sslmode=disable"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
226
internal/extra/injector.go
Normal file
226
internal/extra/injector.go
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
package extra
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strings"
|
||||||
|
"fmt"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"nxcaldav/internal/backend"
|
||||||
|
"regexp"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type responseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
buffer *bytes.Buffer
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
||||||
|
return rw.buffer.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *responseWriter) WriteHeader(status int) {
|
||||||
|
rw.status = status
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add Color To Calendar Propfind
|
||||||
|
func InjectColor(r *http.Request, ctx context.Context, handler http.Handler, w http.ResponseWriter, be *backend.DBBackend) {
|
||||||
|
reqBody, _ := io.ReadAll(r.Body)
|
||||||
|
r.Body = io.NopCloser(bytes.NewBuffer(reqBody))
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
rw := &responseWriter{w, buf, http.StatusOK}
|
||||||
|
handler.ServeHTTP(rw, r.WithContext(ctx))
|
||||||
|
|
||||||
|
body := buf.Bytes()
|
||||||
|
|
||||||
|
// this models after the Radicale Response, largely AI code
|
||||||
|
// 1. Add namespaces to the root multistatus tag only if they are missing
|
||||||
|
if !bytes.Contains(body, []byte("xmlns:ICAL=")) {
|
||||||
|
reMultistatus := regexp.MustCompile(`(<[a-zA-Z0-9]*:?multistatus)`)
|
||||||
|
body = reMultistatus.ReplaceAll(body, []byte(`$1 xmlns:ICAL="http://apple.com/ns/ical/"`))
|
||||||
|
}
|
||||||
|
if !bytes.Contains(body, []byte("xmlns:C=")) && !bytes.Contains(body, []byte("xmlns:c=")) {
|
||||||
|
reMultistatus := regexp.MustCompile(`(<[a-zA-Z0-9]*:?multistatus)`)
|
||||||
|
body = reMultistatus.ReplaceAll(body, []byte(`$1 xmlns:C="urn:ietf:params:xml:ns:caldav"`))
|
||||||
|
}
|
||||||
|
if !bytes.Contains(body, []byte("xmlns:CS=")) {
|
||||||
|
reMultistatus := regexp.MustCompile(`(<[a-zA-Z0-9]*:?multistatus)`)
|
||||||
|
body = reMultistatus.ReplaceAll(body, []byte(`$1 xmlns:CS="http://calendarserver.org/ns/"`))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Response processing
|
||||||
|
reResponse := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?response.*?>.*?</[a-zA-Z0-9]*:?response>`)
|
||||||
|
reHref := regexp.MustCompile(`<[a-zA-Z0-9]*:?href.*?>(.*?)</[a-zA-Z0-9]*:?href>`)
|
||||||
|
rePropstat := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?propstat.*?>.*?</[a-zA-Z0-9]*:?propstat>`)
|
||||||
|
reStatusOk := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?status.*?>HTTP/1.1 200 OK</[a-zA-Z0-9]*:?status>`)
|
||||||
|
reProp := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?prop.*?>.*?</[a-zA-Z0-9]*:?prop>`)
|
||||||
|
rePropClose := regexp.MustCompile(`</[a-zA-Z0-9]*:?prop>`)
|
||||||
|
|
||||||
|
body = reResponse.ReplaceAllFunc(body, func(resp []byte) []byte {
|
||||||
|
hrefMatch := reHref.FindSubmatch(resp)
|
||||||
|
if len(hrefMatch) < 2 {
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
href := string(hrefMatch[1])
|
||||||
|
color := be.GetColor(r.Context(), href)
|
||||||
|
if color == "" {
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. Strip any existing conflicting tags that might be in 404 blocks (non-greedy)
|
||||||
|
reStrip := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?(calendar-color|getctag|calendar-order).*?/>|<[a-zA-Z0-9]*:?(calendar-color|getctag|calendar-order).*?>.*?</[a-zA-Z0-9]*:?(calendar-color|getctag|calendar-order)>`)
|
||||||
|
resp = reStrip.ReplaceAll(resp, []byte(""))
|
||||||
|
|
||||||
|
fullColor := strings.ToLower(color)
|
||||||
|
if len(fullColor) == 7 && strings.HasPrefix(fullColor, "#") {
|
||||||
|
fullColor += "ff"
|
||||||
|
}
|
||||||
|
// Prepare the properties to inject
|
||||||
|
props := fmt.Sprintf("<ICAL:calendar-color>%s</ICAL:calendar-color>", fullColor)
|
||||||
|
props += fmt.Sprintf("<C:calendar-color>%s</C:calendar-color>", fullColor)
|
||||||
|
props += "<ICAL:calendar-order>0</ICAL:calendar-order>"
|
||||||
|
props += fmt.Sprintf("<CS:getctag>\"%d\"</CS:getctag>", time.Now().Unix())
|
||||||
|
|
||||||
|
// 2. Try to inject into an existing 200 OK propstat
|
||||||
|
has200 := false
|
||||||
|
resp = rePropstat.ReplaceAllFunc(resp, func(ps []byte) []byte {
|
||||||
|
if reStatusOk.Match(ps) {
|
||||||
|
has200 = true
|
||||||
|
return reProp.ReplaceAllFunc(ps, func(prop []byte) []byte {
|
||||||
|
return rePropClose.ReplaceAllFunc(prop, func(closeTag []byte) []byte {
|
||||||
|
return append([]byte(props), closeTag...)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return ps
|
||||||
|
})
|
||||||
|
|
||||||
|
// 3. If no 200 OK propstat was found, create one
|
||||||
|
if !has200 {
|
||||||
|
newPropstat := fmt.Sprintf("<propstat xmlns=\"DAV:\"><prop>%s</prop><status>HTTP/1.1 200 OK</status></propstat>", props)
|
||||||
|
reResponseClose := regexp.MustCompile(`</[a-zA-Z0-9]*:?response>`)
|
||||||
|
resp = reResponseClose.ReplaceAllFunc(resp, func(closeTag []byte) []byte {
|
||||||
|
return append([]byte(newPropstat), closeTag...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp
|
||||||
|
})
|
||||||
|
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
|
||||||
|
w.WriteHeader(rw.status)
|
||||||
|
w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleDiscoveryOptions(r *http.Request, ctx context.Context, handler http.Handler, w http.ResponseWriter, be *backend.DBBackend) {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
rw := &responseWriter{w, buf, http.StatusOK}
|
||||||
|
handler.ServeHTTP(rw, r.WithContext(ctx))
|
||||||
|
|
||||||
|
if has, _ := be.HasAddressBooks(ctx); has {
|
||||||
|
dav := w.Header().Get("DAV")
|
||||||
|
if dav == "" {
|
||||||
|
w.Header().Set("DAV", "1, 3, addressbook, calendar-access")
|
||||||
|
} else if !strings.Contains(dav, "addressbook") {
|
||||||
|
w.Header().Set("DAV", dav+", addressbook")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(rw.status)
|
||||||
|
w.Write(buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleDiscoveryPropfind(r *http.Request, ctx context.Context, handler http.Handler, w http.ResponseWriter, be *backend.DBBackend) {
|
||||||
|
reqBody, _ := io.ReadAll(r.Body)
|
||||||
|
r.Body = io.NopCloser(bytes.NewBuffer(reqBody))
|
||||||
|
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
rw := &responseWriter{w, buf, http.StatusOK}
|
||||||
|
handler.ServeHTTP(rw, r.WithContext(ctx))
|
||||||
|
|
||||||
|
body := buf.Bytes()
|
||||||
|
|
||||||
|
calHome, _ := be.CalendarHomeSetPath(ctx)
|
||||||
|
cardHome, _ := be.AddressBookHomeSetPath(ctx)
|
||||||
|
hasAddressBooks, _ := be.HasAddressBooks(ctx)
|
||||||
|
|
||||||
|
// Ensure DAV: addressbook header is present if user has address books
|
||||||
|
if hasAddressBooks {
|
||||||
|
dav := w.Header().Get("DAV")
|
||||||
|
if dav == "" {
|
||||||
|
w.Header().Set("DAV", "1, 3, addressbook, calendar-access")
|
||||||
|
} else if !strings.Contains(dav, "addressbook") {
|
||||||
|
w.Header().Set("DAV", dav+", addressbook")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Response processing
|
||||||
|
reResponse := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?response.*?>.*?</[a-zA-Z0-9]*:?response>`)
|
||||||
|
reHref := regexp.MustCompile(`<[a-zA-Z0-9]*:?href.*?>(.*?)</[a-zA-Z0-9]*:?href>`)
|
||||||
|
rePropstat := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?propstat.*?>.*?</[a-zA-Z0-9]*:?propstat>`)
|
||||||
|
reStatusOk := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?status.*?>HTTP/1.1 200 OK</[a-zA-Z0-9]*:?status>`)
|
||||||
|
reProp := regexp.MustCompile(`(?s)<[a-zA-Z0-9]*:?prop.*?>.*?</[a-zA-Z0-9]*:?prop>`)
|
||||||
|
rePropClose := regexp.MustCompile(`</[a-zA-Z0-9]*:?prop>`)
|
||||||
|
|
||||||
|
body = reResponse.ReplaceAllFunc(body, func(resp []byte) []byte {
|
||||||
|
hrefMatch := reHref.FindSubmatch(resp)
|
||||||
|
if len(hrefMatch) < 2 {
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip these tags ONLY from non-200 propstats to avoid duplicates or 404 overrides
|
||||||
|
resp = rePropstat.ReplaceAllFunc(resp, func(ps []byte) []byte {
|
||||||
|
if !reStatusOk.Match(ps) {
|
||||||
|
reTags := regexp.MustCompile(`(?s)<[a-zA-Z0-9:]*(calendar-home-set|addressbook-home-set).*?/>|<[a-zA-Z0-9:]*(calendar-home-set|addressbook-home-set).*?>.*?</[a-zA-Z0-9:]*(calendar-home-set|addressbook-home-set)>`)
|
||||||
|
return reTags.ReplaceAll(ps, []byte(""))
|
||||||
|
}
|
||||||
|
return ps
|
||||||
|
})
|
||||||
|
|
||||||
|
props := ""
|
||||||
|
// Inject calendar-home-set if missing (with local namespace definition for safety)
|
||||||
|
if calHome != "" && !strings.Contains(string(resp), "calendar-home-set") {
|
||||||
|
props += fmt.Sprintf("<C:calendar-home-set xmlns:C=\"urn:ietf:params:xml:ns:caldav\"><href xmlns=\"DAV:\">%s</href></C:calendar-home-set>", calHome)
|
||||||
|
}
|
||||||
|
// Inject addressbook-home-set if missing and user has address books
|
||||||
|
if hasAddressBooks && cardHome != "" && !strings.Contains(string(resp), "addressbook-home-set") {
|
||||||
|
props += fmt.Sprintf("<CARD:addressbook-home-set xmlns:CARD=\"urn:ietf:params:xml:ns:carddav\"><href xmlns=\"DAV:\">%s</href></CARD:addressbook-home-set>", cardHome)
|
||||||
|
}
|
||||||
|
|
||||||
|
if props == "" {
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Try to inject into an existing 200 OK propstat
|
||||||
|
has200 := false
|
||||||
|
resp = rePropstat.ReplaceAllFunc(resp, func(ps []byte) []byte {
|
||||||
|
if reStatusOk.Match(ps) {
|
||||||
|
has200 = true
|
||||||
|
return reProp.ReplaceAllFunc(ps, func(prop []byte) []byte {
|
||||||
|
return rePropClose.ReplaceAllFunc(prop, func(closeTag []byte) []byte {
|
||||||
|
return append([]byte(props), closeTag...)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return ps
|
||||||
|
})
|
||||||
|
|
||||||
|
// 3. If no 200 OK propstat was found, create one
|
||||||
|
if !has200 {
|
||||||
|
newPropstat := fmt.Sprintf("<propstat xmlns=\"DAV:\"><prop>%s</prop><status>HTTP/1.1 200 OK</status></propstat>", props)
|
||||||
|
reResponseClose := regexp.MustCompile(`</[a-zA-Z0-9]*:?response>`)
|
||||||
|
resp = reResponseClose.ReplaceAllFunc(resp, func(closeTag []byte) []byte {
|
||||||
|
return append([]byte(newPropstat), closeTag...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return resp
|
||||||
|
})
|
||||||
|
|
||||||
|
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
|
||||||
|
w.WriteHeader(rw.status)
|
||||||
|
w.Write(body)
|
||||||
|
}
|
||||||
103
main.go
103
main.go
@@ -4,19 +4,24 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/emersion/go-webdav/caldav"
|
"github.com/emersion/go-webdav/caldav"
|
||||||
|
"github.com/emersion/go-webdav/carddav"
|
||||||
|
|
||||||
"nxcaldav/internal/backend"
|
"nxcaldav/internal/backend"
|
||||||
"nxcaldav/internal/config"
|
"nxcaldav/internal/config"
|
||||||
|
"nxcaldav/internal/extra"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
path := "config.yaml";
|
// -- GET CONFIG
|
||||||
|
path := "config.yaml"
|
||||||
if len(os.Args) == 3 {
|
if len(os.Args) == 3 {
|
||||||
if os.Args[1] == "-c" {
|
if os.Args[1] == "-c" {
|
||||||
path = os.Args[2]
|
path = os.Args[2]
|
||||||
@@ -27,30 +32,39 @@ func main() {
|
|||||||
log.Fatalf("failed to load config: %v", err)
|
log.Fatalf("failed to load config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -- GET CONTEXT AND DB
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
be, err := backend.NewDBBackend(ctx, cfg)
|
be, err := backend.NewDBBackend(ctx, cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("failed to initialize database backend: %v", err)
|
log.Fatalf("failed to initialize database backend: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := &caldav.Handler{Backend: be}
|
// -- GET CONTEXT AND DB
|
||||||
|
caldavHandler := &caldav.Handler{Backend: be}
|
||||||
|
carddavHandler := &carddav.Handler{Backend: be}
|
||||||
publicURL, _ := url.Parse(cfg.Server.PublicURL)
|
publicURL, _ := url.Parse(cfg.Server.PublicURL)
|
||||||
|
|
||||||
|
// -- DISCOVERIES
|
||||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||||
// Proxy-aware normalization:
|
|
||||||
|
scheme := r.URL.Scheme
|
||||||
|
if scheme == "" {
|
||||||
|
scheme = "http"
|
||||||
|
}
|
||||||
|
|
||||||
|
// set host (because reverse proxies exist)
|
||||||
if publicURL != nil && publicURL.Host != "" {
|
if publicURL != nil && publicURL.Host != "" {
|
||||||
r.Host = publicURL.Host
|
r.Host = publicURL.Host
|
||||||
r.URL.Host = publicURL.Host
|
r.URL.Host = publicURL.Host
|
||||||
|
|
||||||
// Detect scheme: prioritize X-Forwarded-Proto, then PublicURL
|
// prioritize X-Forwarded-Proto, then PublicURL (e.g. Cloudfalre proxy)
|
||||||
scheme := publicURL.Scheme
|
scheme = publicURL.Scheme
|
||||||
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
|
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
|
||||||
scheme = proto
|
scheme = proto
|
||||||
}
|
}
|
||||||
r.URL.Scheme = scheme
|
r.URL.Scheme = scheme
|
||||||
|
|
||||||
// Also rewrite WebDAV Destination header (used for MOVE/COPY)
|
// Also rewrite WebDAV Destination header (for MOVE/COPY)
|
||||||
if dest := r.Header.Get("Destination"); dest != "" {
|
if dest := r.Header.Get("Destination"); dest != "" {
|
||||||
destURL, err := url.Parse(dest)
|
destURL, err := url.Parse(dest)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -61,58 +75,95 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// public ics access
|
||||||
prefix := cfg.Server.BasePath()
|
prefix := cfg.Server.BasePath()
|
||||||
if strings.HasPrefix(r.URL.Path, prefix+"/public/") {
|
if strings.HasPrefix(r.URL.Path, prefix+"/public/") {
|
||||||
be.ServePublicICS(w, r)
|
be.ServePublicICS(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DAV needs auth
|
||||||
user, password, ok := r.BasicAuth()
|
user, password, ok := r.BasicAuth()
|
||||||
if !ok {
|
if !ok {
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`)
|
w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`)
|
||||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify via Database (bcrypt)
|
|
||||||
valid, err := be.VerifyUser(r.Context(), user, password)
|
valid, err := be.VerifyUser(r.Context(), user, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("auth error for %s: %v", user, err)
|
log.Printf("auth error for %s: %v", user, err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !valid {
|
if !valid {
|
||||||
log.Printf("auth failed for %s", user)
|
log.Printf("auth failed for %s", user)
|
||||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Printf("%s %s (user: %s)", r.Method, r.URL.Path, user)
|
log.Printf("[user: %s] %s %s", user, r.Method, r.URL.Path)
|
||||||
prefix = cfg.Server.BasePath()
|
|
||||||
principalPath := prefix + fmt.Sprintf("/%s/", user)
|
principalPath := prefix + fmt.Sprintf("/%s/", user)
|
||||||
ctx := context.WithValue(r.Context(), "principal", principalPath)
|
ctx := context.WithValue(r.Context(), "principal", principalPath)
|
||||||
|
|
||||||
if r.URL.Path == "/.well-known/caldav" || r.URL.Path == prefix+"/.well-known/caldav" {
|
// set header for carddav if user has address books
|
||||||
// If we normalized the request, use the normalized host/scheme for the redirect
|
if slices.Contains([]string{
|
||||||
if publicURL != nil && publicURL.Host != "" {
|
"/", prefix + "/",
|
||||||
scheme := r.URL.Scheme
|
"/.well-known/carddav",
|
||||||
if scheme == "" {
|
prefix + "/.well-known/carddav",
|
||||||
scheme = "http"
|
principalPath,
|
||||||
}
|
strings.TrimSuffix(principalPath, "/"),
|
||||||
target := fmt.Sprintf("%s://%s%s", scheme, r.Host, principalPath)
|
}, r.URL.Path) || strings.Contains(r.URL.Path, "/addressbooks/") {
|
||||||
http.Redirect(w, r, target, http.StatusMovedPermanently)
|
if has, _ := be.HasAddressBooks(ctx); has {
|
||||||
} else {
|
w.Header().Add("DAV", "addressbook")
|
||||||
http.Redirect(w, r, principalPath, http.StatusMovedPermanently)
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// for caldav and carddav discovery
|
||||||
|
if slices.Contains([]string{
|
||||||
|
"/.well-known/caldav",
|
||||||
|
prefix + "/.well-known/caldav",
|
||||||
|
"/.well-known/carddav",
|
||||||
|
prefix + "/.well-known/carddav",
|
||||||
|
}, r.URL.Path) {
|
||||||
|
http.Redirect(w, r, fmt.Sprintf("%s://%s%s", scheme, r.Host, principalPath), http.StatusMovedPermanently)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// serve caldav
|
||||||
|
if strings.Contains(r.URL.Path, "/calendars/") {
|
||||||
|
if r.Method == "PROPFIND" {
|
||||||
|
// Calendar colors
|
||||||
|
// needed because color info is not RFC, so I hacked it in with regex, to look like Radicales response
|
||||||
|
extra.InjectColor(r, ctx, caldavHandler, w, be)
|
||||||
|
} else {
|
||||||
|
caldavHandler.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
|
||||||
handler.ServeHTTP(w, r.WithContext(ctx))
|
// serve carddav
|
||||||
|
} else if strings.Contains(r.URL.Path, "/addressbooks/") {
|
||||||
|
carddavHandler.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
|
||||||
|
// catch weird requests
|
||||||
|
} else {
|
||||||
|
|
||||||
|
if strings.HasSuffix(r.URL.Path, user+"/") || strings.HasSuffix(r.URL.Path, user) || r.URL.Path == "/" || r.URL.Path == prefix+"/" {
|
||||||
|
// For principal path or root, use merged discovery handler
|
||||||
|
if r.Method == "PROPFIND" {
|
||||||
|
extra.HandleDiscoveryPropfind(r, ctx, caldavHandler, w, be)
|
||||||
|
} else if r.Method == "OPTIONS" {
|
||||||
|
extra.HandleDiscoveryOptions(r, ctx, caldavHandler, w, be)
|
||||||
|
} else {
|
||||||
|
caldavHandler.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Printf("Not found: %s", r)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
fmt.Printf("Starting CalDAV server on %s...\n", cfg.Server.BindAddress)
|
fmt.Printf("Starting CalDAV/CardDAV server on %s...\n", cfg.Server.BindAddress)
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
Addr: cfg.Server.BindAddress,
|
Addr: cfg.Server.BindAddress,
|
||||||
ReadTimeout: 30 * time.Second,
|
ReadTimeout: 30 * time.Second,
|
||||||
|
|||||||
Reference in New Issue
Block a user