This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
{
|
||||
inputs,
|
||||
flake,
|
||||
self,
|
||||
}:
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}: let
|
||||
cfg = config.hectic.services.routine-server;
|
||||
system = pkgs.stdenv.hostPlatform.system;
|
||||
in {
|
||||
options.hectic.services.routine-server = {
|
||||
enable = lib.mkEnableOption "daily, weekly, and monthly routine server";
|
||||
|
||||
address = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "127.0.0.1";
|
||||
description = "Address on which the routine server listens.";
|
||||
};
|
||||
|
||||
port = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 8090;
|
||||
description = "Port on which the routine server listens.";
|
||||
};
|
||||
|
||||
generationDays = lib.mkOption {
|
||||
type = lib.types.ints.unsigned;
|
||||
default = 62;
|
||||
description = "Number of future routine days to materialize.";
|
||||
};
|
||||
|
||||
databaseName = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "routine-server";
|
||||
description = "PostgreSQL database used by the routine server.";
|
||||
};
|
||||
|
||||
databaseUser = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "routine-server";
|
||||
description = "PostgreSQL and dynamic system user used by the routine server.";
|
||||
};
|
||||
|
||||
databaseSocket = lib.mkOption {
|
||||
type = lib.types.path;
|
||||
default = "/run/postgresql";
|
||||
description = "PostgreSQL Unix socket directory.";
|
||||
};
|
||||
|
||||
timezone = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "UTC";
|
||||
description = "Timezone used for dates and reminder times.";
|
||||
};
|
||||
|
||||
environmentFile = lib.mkOption {
|
||||
type = with lib.types; nullOr path;
|
||||
default = null;
|
||||
description = ''
|
||||
Optional secret environment file. Supported variables:
|
||||
ROUTINE_API_TOKEN=
|
||||
ROUTINE_TELEGRAM_BOT_TOKEN=
|
||||
ROUTINE_TELEGRAM_CHAT_ID=
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
services.postgresql = {
|
||||
enable = true;
|
||||
ensureDatabases = [ cfg.databaseName ];
|
||||
ensureUsers = [
|
||||
{
|
||||
name = cfg.databaseUser;
|
||||
ensureDBOwnership = true;
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
systemd.services.routine-server = {
|
||||
description = "Personal routine task server";
|
||||
after = [ "network-online.target" "postgresql.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
requires = [ "postgresql.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
|
||||
environment = {
|
||||
ROUTINE_BIND = "${cfg.address}:${toString cfg.port}";
|
||||
ROUTINE_DATABASE_URL = "host=${cfg.databaseSocket} dbname=${cfg.databaseName} user=${cfg.databaseUser}";
|
||||
ROUTINE_GENERATION_DAYS = toString cfg.generationDays;
|
||||
TZ = cfg.timezone;
|
||||
};
|
||||
|
||||
serviceConfig = lib.mkMerge [
|
||||
{
|
||||
Type = "simple";
|
||||
ExecStart = "${self.packages.${system}.routine-server}/bin/routine-server";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
DynamicUser = true;
|
||||
User = cfg.databaseUser;
|
||||
Group = cfg.databaseUser;
|
||||
UMask = "0077";
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectHome = true;
|
||||
ProtectSystem = "strict";
|
||||
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
|
||||
}
|
||||
(lib.mkIf (cfg.environmentFile != null) {
|
||||
EnvironmentFile = cfg.environmentFile;
|
||||
})
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -204,6 +204,10 @@ in {
|
||||
debugSshPublicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSWIv80pyCMDQ6zH34P2qWizpOcO7X86BVhMGtbob9U gcr-controller@hectic-lab";
|
||||
hcloudSshKeyId = 118512401;
|
||||
};
|
||||
services.routine-server = {
|
||||
enable = true;
|
||||
timezone = "Europe/Rome";
|
||||
};
|
||||
};
|
||||
|
||||
zramSwap = {
|
||||
|
||||
@@ -151,6 +151,7 @@ in {
|
||||
element-web = pkgs.callPackage ./element-web { pnpm = giteaPkgs.pnpm_10; };
|
||||
shellplot = pkgs.callPackage ./shellplot {};
|
||||
gitea-kanban-tui = pkgs.callPackage ./gitea-kanban-tui rust.commonArgs;
|
||||
routine-server = pkgs.callPackage ./routine-server rust.commonArgs;
|
||||
which-country-rs = pkgs.callPackage ./which-country-rs {};
|
||||
onlinepubs2man = pkgs.callPackage ./onlinepubs2man {};
|
||||
migrator = pkgs.callPackage ./migrator { inherit self; };
|
||||
|
||||
Generated
+1097
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "routine-server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Small HTTP server for daily, weekly, and monthly routines"
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "=0.4.38", default-features = false, features = ["clock", "serde"] }
|
||||
minreq = { version = "=2.12.0", default-features = false, features = ["https-rustls"] }
|
||||
postgres = { version = "=0.19.8", features = ["with-chrono-0_4", "with-serde_json-1"] }
|
||||
serde = { version = "=1.0.210", features = ["derive"] }
|
||||
serde_json = "=1.0.128"
|
||||
tiny_http = "=0.12.0"
|
||||
@@ -0,0 +1,66 @@
|
||||
# routine-server
|
||||
|
||||
Small PostgreSQL-backed HTTP service for one-off tasks and daily, weekly, or
|
||||
monthly routine tasks. The server generates future task occurrences and can
|
||||
send due reminders through the Telegram Bot API.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ROUTINE_BIND` | `127.0.0.1:8090` | HTTP listen address |
|
||||
| `ROUTINE_DATABASE_URL` | local `routine-server` database | PostgreSQL/libpq connection string |
|
||||
| `ROUTINE_API_TOKEN` | unset | Optional bearer token for every route except `/health` |
|
||||
| `ROUTINE_GENERATION_DAYS` | `62` | Number of future days to materialize |
|
||||
| `ROUTINE_WORKER_INTERVAL_SECONDS` | `60` | Generation/reminder polling interval |
|
||||
| `ROUTINE_TELEGRAM_BOT_TOKEN` | unset | Telegram bot token |
|
||||
| `ROUTINE_TELEGRAM_CHAT_ID` | unset | Telegram target chat |
|
||||
|
||||
Telegram delivery is enabled only when both Telegram variables are present.
|
||||
Times use the service's local timezone and `HH:MM` format.
|
||||
|
||||
## API
|
||||
|
||||
Create a weekly routine:
|
||||
|
||||
```sh
|
||||
curl -X POST http://127.0.0.1:8090/v1/routines \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"title": "Exercise",
|
||||
"section": "evening",
|
||||
"priority": "should",
|
||||
"schedule": {"kind": "weekly", "weekdays": [1, 3, 5]},
|
||||
"reminder_time": "18:00"
|
||||
}'
|
||||
```
|
||||
|
||||
Create a monthly routine that moves day 31 to a shorter month's final day:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Review finances",
|
||||
"section": "work",
|
||||
"priority": "must",
|
||||
"schedule": {
|
||||
"kind": "monthly",
|
||||
"days": [31],
|
||||
"clamp_to_last_day": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Routes:
|
||||
|
||||
```text
|
||||
GET /health
|
||||
GET /v1/tasks?date=YYYY-MM-DD
|
||||
POST /v1/tasks
|
||||
POST /v1/tasks/{id}/complete
|
||||
POST /v1/tasks/{id}/reschedule
|
||||
DELETE /v1/tasks/{id}
|
||||
GET /v1/routines
|
||||
POST /v1/routines
|
||||
```
|
||||
|
||||
Weekly days use ISO numbers: Monday is `1`, Sunday is `7`.
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
cargoToml,
|
||||
lib,
|
||||
nativeBuildInputs,
|
||||
pkgs,
|
||||
...
|
||||
}: let
|
||||
cargo = cargoToml ./Cargo.toml;
|
||||
in
|
||||
pkgs.rustPlatform.buildRustPackage {
|
||||
pname = cargo.package.name;
|
||||
version = cargo.package.version;
|
||||
src = ./.;
|
||||
|
||||
inherit nativeBuildInputs;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
doCheck = true;
|
||||
|
||||
meta = {
|
||||
description = cargo.package.description;
|
||||
license = lib.licenses.mit;
|
||||
mainProgram = "routine-server";
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod model;
|
||||
pub mod server;
|
||||
pub mod store;
|
||||
pub mod telegram;
|
||||
@@ -0,0 +1,96 @@
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Local;
|
||||
use routine_server::server;
|
||||
use routine_server::store::Store;
|
||||
use routine_server::telegram::Telegram;
|
||||
|
||||
struct Config {
|
||||
bind: String,
|
||||
database_url: String,
|
||||
api_token: Option<String>,
|
||||
generation_days: u64,
|
||||
worker_interval: Duration,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("routine-server: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run() -> Result<(), String> {
|
||||
let config = Config::from_env()?;
|
||||
let store = Store::new(&config.database_url);
|
||||
store.migrate()?;
|
||||
store.generate(Local::now().date_naive(), config.generation_days)?;
|
||||
|
||||
let worker_store = store.clone();
|
||||
let worker_days = config.generation_days;
|
||||
let worker_interval = config.worker_interval;
|
||||
let telegram = Telegram::from_env();
|
||||
thread::spawn(move || loop {
|
||||
if let Err(error) = worker_tick(&worker_store, worker_days, telegram.as_ref()) {
|
||||
eprintln!("background worker failed: {error}");
|
||||
}
|
||||
thread::sleep(worker_interval);
|
||||
});
|
||||
|
||||
server::serve(&config.bind, store, config.api_token)
|
||||
}
|
||||
|
||||
fn worker_tick(
|
||||
store: &Store,
|
||||
generation_days: u64,
|
||||
telegram: Option<&Telegram>,
|
||||
) -> Result<(), String> {
|
||||
let now = Local::now();
|
||||
store.generate(now.date_naive(), generation_days)?;
|
||||
|
||||
let Some(telegram) = telegram else {
|
||||
return Ok(());
|
||||
};
|
||||
let date = now.date_naive().to_string();
|
||||
let time = now.format("%H:%M").to_string();
|
||||
while let Some(notification) = store.next_due_notification(&date, &time)? {
|
||||
let text = format!(
|
||||
"Routine reminder: {} [{} / {}]",
|
||||
notification.title, notification.section, notification.priority
|
||||
);
|
||||
telegram.send_message(&text)?;
|
||||
store.mark_notification_sent(notification.task_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Config {
|
||||
fn from_env() -> Result<Self, String> {
|
||||
let generation_days = parse_env("ROUTINE_GENERATION_DAYS", 62)?;
|
||||
let worker_interval_seconds = parse_env("ROUTINE_WORKER_INTERVAL_SECONDS", 60)?;
|
||||
if worker_interval_seconds == 0 {
|
||||
return Err("ROUTINE_WORKER_INTERVAL_SECONDS must be positive".to_owned());
|
||||
}
|
||||
Ok(Self {
|
||||
bind: std::env::var("ROUTINE_BIND").unwrap_or_else(|_| "127.0.0.1:8090".to_owned()),
|
||||
database_url: std::env::var("ROUTINE_DATABASE_URL").unwrap_or_else(|_| {
|
||||
"host=/run/postgresql dbname=routine-server user=routine-server".to_owned()
|
||||
}),
|
||||
api_token: std::env::var("ROUTINE_API_TOKEN")
|
||||
.ok()
|
||||
.filter(|token| !token.is_empty()),
|
||||
generation_days,
|
||||
worker_interval: Duration::from_secs(worker_interval_seconds),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_env(name: &str, default: u64) -> Result<u64, String> {
|
||||
match std::env::var(name) {
|
||||
Ok(value) => value
|
||||
.parse()
|
||||
.map_err(|_| format!("{name} must be an unsigned integer")),
|
||||
Err(_) => Ok(default),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Section {
|
||||
Morning,
|
||||
Work,
|
||||
Evening,
|
||||
}
|
||||
|
||||
impl Section {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Morning => "morning",
|
||||
Self::Work => "work",
|
||||
Self::Evening => "evening",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Priority {
|
||||
Must,
|
||||
Should,
|
||||
Optional,
|
||||
}
|
||||
|
||||
impl Priority {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Must => "must",
|
||||
Self::Should => "should",
|
||||
Self::Optional => "optional",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Schedule {
|
||||
Daily,
|
||||
Weekly {
|
||||
/// ISO weekday numbers: Monday = 1, Sunday = 7.
|
||||
weekdays: Vec<u32>,
|
||||
},
|
||||
Monthly {
|
||||
days: Vec<u32>,
|
||||
#[serde(default = "default_true")]
|
||||
clamp_to_last_day: bool,
|
||||
},
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateTask {
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub notes: Option<String>,
|
||||
pub section: Section,
|
||||
pub priority: Priority,
|
||||
pub scheduled_date: String,
|
||||
#[serde(default)]
|
||||
pub reminder_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct RescheduleTask {
|
||||
pub scheduled_date: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Task {
|
||||
pub id: i64,
|
||||
pub routine_id: Option<i64>,
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub scheduled_date: String,
|
||||
pub reminder_time: Option<String>,
|
||||
pub status: String,
|
||||
pub completed_at: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateRoutine {
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub notes: Option<String>,
|
||||
pub section: Section,
|
||||
pub priority: Priority,
|
||||
pub schedule: Schedule,
|
||||
#[serde(default)]
|
||||
pub reminder_time: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Routine {
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub notes: Option<String>,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
pub schedule: Schedule,
|
||||
pub reminder_time: Option<String>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DueNotification {
|
||||
pub task_id: i64,
|
||||
pub title: String,
|
||||
pub section: String,
|
||||
pub priority: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IdResponse {
|
||||
pub id: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StatusResponse {
|
||||
pub status: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ErrorResponse<'a> {
|
||||
pub error: &'a str,
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use chrono::Local;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use tiny_http::{Header, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
use crate::model::{
|
||||
CreateRoutine, CreateTask, ErrorResponse, IdResponse, RescheduleTask, StatusResponse,
|
||||
};
|
||||
use crate::store::Store;
|
||||
|
||||
pub fn serve(bind: &str, store: Store, api_token: Option<String>) -> Result<(), String> {
|
||||
let server = Server::http(bind).map_err(|error| format!("failed to bind {bind}: {error}"))?;
|
||||
eprintln!("routine-server listening on {bind}");
|
||||
|
||||
for request in server.incoming_requests() {
|
||||
handle(request, &store, api_token.as_deref());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle(mut request: Request, store: &Store, api_token: Option<&str>) {
|
||||
let (path, query) = split_url(request.url());
|
||||
if path == "/health" && request.method() == &Method::Get {
|
||||
respond_json(request, 200, &StatusResponse { status: "ok" });
|
||||
return;
|
||||
}
|
||||
|
||||
if !authorized(&request, api_token) {
|
||||
respond_error(request, 401, "missing or invalid bearer token");
|
||||
return;
|
||||
}
|
||||
|
||||
match (request.method(), path.as_str()) {
|
||||
(&Method::Get, "/v1/tasks") => {
|
||||
let date = query_parameter(&query, "date")
|
||||
.unwrap_or_else(|| Local::now().date_naive().to_string());
|
||||
match store.list_tasks(&date) {
|
||||
Ok(tasks) => respond_json(request, 200, &tasks),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
}
|
||||
}
|
||||
(&Method::Post, "/v1/tasks") => {
|
||||
let result =
|
||||
parse_json::<CreateTask>(&mut request).and_then(|input| store.create_task(input));
|
||||
respond_created(request, result);
|
||||
}
|
||||
(&Method::Get, "/v1/routines") => match store.list_routines() {
|
||||
Ok(routines) => respond_json(request, 200, &routines),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
},
|
||||
(&Method::Post, "/v1/routines") => {
|
||||
let result = parse_json::<CreateRoutine>(&mut request)
|
||||
.and_then(|input| store.create_routine(input))
|
||||
.and_then(|id| {
|
||||
store.generate(Local::now().date_naive(), 62)?;
|
||||
Ok(id)
|
||||
});
|
||||
respond_created(request, result);
|
||||
}
|
||||
_ => handle_task_action(request, store, &path),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_task_action(mut request: Request, store: &Store, path: &str) {
|
||||
let segments: Vec<_> = path.trim_matches('/').split('/').collect();
|
||||
if segments.len() < 3 || segments[0] != "v1" || segments[1] != "tasks" {
|
||||
respond_error(request, 404, "route not found");
|
||||
return;
|
||||
}
|
||||
let id = segments[2]
|
||||
.parse::<i64>()
|
||||
.map_err(|_| "task id must be an integer".to_owned());
|
||||
let id = match id {
|
||||
Ok(id) => id,
|
||||
Err(error) => {
|
||||
respond_error(request, 400, &error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let changed = match (request.method(), segments.get(3).copied()) {
|
||||
(&Method::Post, Some("complete")) if segments.len() == 4 => store.complete_task(id),
|
||||
(&Method::Post, Some("reschedule")) if segments.len() == 4 => {
|
||||
parse_json::<RescheduleTask>(&mut request)
|
||||
.and_then(|input| store.reschedule_task(id, &input.scheduled_date))
|
||||
}
|
||||
(&Method::Delete, None) if segments.len() == 3 => store.delete_task(id),
|
||||
_ => {
|
||||
respond_error(request, 404, "route not found");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
match changed {
|
||||
Ok(true) => respond_json(request, 200, &StatusResponse { status: "ok" }),
|
||||
Ok(false) => respond_error(request, 404, "task not found or already completed"),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json<T: DeserializeOwned>(request: &mut Request) -> Result<T, String> {
|
||||
if request.body_length().unwrap_or(0) > 64 * 1024 {
|
||||
return Err("request body is too large".to_owned());
|
||||
}
|
||||
let mut body = String::new();
|
||||
request
|
||||
.as_reader()
|
||||
.read_to_string(&mut body)
|
||||
.map_err(|error| format!("failed to read request: {error}"))?;
|
||||
serde_json::from_str(&body).map_err(|error| format!("invalid JSON: {error}"))
|
||||
}
|
||||
|
||||
fn authorized(request: &Request, api_token: Option<&str>) -> bool {
|
||||
let Some(api_token) = api_token else {
|
||||
return true;
|
||||
};
|
||||
let expected = format!("Bearer {api_token}");
|
||||
request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|header| header.field.equiv("Authorization"))
|
||||
.map(|header| header.value.as_str() == expected)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn split_url(url: &str) -> (String, String) {
|
||||
match url.split_once('?') {
|
||||
Some((path, query)) => (path.to_owned(), query.to_owned()),
|
||||
None => (url.to_owned(), String::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn query_parameter(query: &str, key: &str) -> Option<String> {
|
||||
query.split('&').find_map(|part| {
|
||||
let (candidate, value) = part.split_once('=')?;
|
||||
(candidate == key).then(|| value.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
fn respond_json<T: Serialize>(request: Request, status: u16, value: &T) {
|
||||
let body = serde_json::to_string(value)
|
||||
.unwrap_or_else(|_| "{\"error\":\"serialization failed\"}".to_owned());
|
||||
let content_type =
|
||||
Header::from_bytes("Content-Type", "application/json").expect("static header is valid");
|
||||
let response = Response::from_string(body)
|
||||
.with_status_code(StatusCode(status))
|
||||
.with_header(content_type);
|
||||
if let Err(error) = request.respond(response) {
|
||||
eprintln!("failed to write response: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn respond_error(request: Request, status: u16, error: &str) {
|
||||
respond_json(request, status, &ErrorResponse { error });
|
||||
}
|
||||
|
||||
fn respond_created(request: Request, result: Result<i64, String>) {
|
||||
match result {
|
||||
Ok(id) => respond_json(request, 201, &IdResponse { id }),
|
||||
Err(error) => respond_failure(request, &error),
|
||||
}
|
||||
}
|
||||
|
||||
fn respond_failure(request: Request, error: &str) {
|
||||
if error.starts_with("database error:") {
|
||||
eprintln!("request failed: {error}");
|
||||
respond_error(request, 500, "database operation failed");
|
||||
} else {
|
||||
respond_error(request, 400, error);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn extracts_query_parameter() {
|
||||
assert_eq!(
|
||||
query_parameter("date=2026-10-14&unused=1", "date").as_deref(),
|
||||
Some("2026-10-14")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
use chrono::{Datelike, Days, NaiveDate, NaiveTime};
|
||||
use postgres::{Client, NoTls};
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, DueNotification, Routine, Schedule, Task};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, String>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
database_url: String,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(database_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
database_url: database_url.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&self) -> Result<Client> {
|
||||
Client::connect(&self.database_url, NoTls).map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn migrate(&self) -> Result<()> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.batch_execute(
|
||||
"CREATE TABLE IF NOT EXISTS routines (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
section TEXT NOT NULL,
|
||||
priority TEXT NOT NULL,
|
||||
schedule_json JSONB NOT NULL,
|
||||
reminder_time TIME,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
routine_id BIGINT REFERENCES routines(id),
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
section TEXT NOT NULL,
|
||||
priority TEXT NOT NULL,
|
||||
scheduled_date DATE NOT NULL,
|
||||
reminder_time TIME,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
completed_at TIMESTAMPTZ,
|
||||
notification_sent_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE(routine_id, scheduled_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS tasks_by_date
|
||||
ON tasks(scheduled_date, status);
|
||||
CREATE INDEX IF NOT EXISTS tasks_due_notification
|
||||
ON tasks(scheduled_date, reminder_time, notification_sent_at);",
|
||||
)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
|
||||
validate_title(&task.title)?;
|
||||
let scheduled_date = parse_date(&task.scheduled_date)?;
|
||||
let reminder_time = parse_reminder(task.reminder_time.as_deref())?;
|
||||
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO tasks (
|
||||
title, notes, section, priority, scheduled_date, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id",
|
||||
&[
|
||||
&task.title.trim(),
|
||||
&task.notes,
|
||||
&task.section.as_str(),
|
||||
&task.priority.as_str(),
|
||||
&scheduled_date,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn list_tasks(&self, date: &str) -> Result<Vec<Task>> {
|
||||
let date = parse_date(date)?;
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, routine_id, title, notes, section, priority,
|
||||
scheduled_date, reminder_time, status,
|
||||
EXTRACT(EPOCH FROM completed_at)::BIGINT
|
||||
FROM tasks
|
||||
WHERE scheduled_date = $1
|
||||
ORDER BY
|
||||
CASE section
|
||||
WHEN 'morning' THEN 0
|
||||
WHEN 'work' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
CASE priority
|
||||
WHEN 'must' THEN 0
|
||||
WHEN 'should' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
id",
|
||||
&[&date],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let scheduled_date: NaiveDate = row.get(6);
|
||||
let reminder_time: Option<NaiveTime> = row.get(7);
|
||||
Task {
|
||||
id: row.get(0),
|
||||
routine_id: row.get(1),
|
||||
title: row.get(2),
|
||||
notes: row.get(3),
|
||||
section: row.get(4),
|
||||
priority: row.get(5),
|
||||
scheduled_date: scheduled_date.to_string(),
|
||||
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
||||
status: row.get(8),
|
||||
completed_at: row.get(9),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn complete_task(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks
|
||||
SET status = 'completed', completed_at = now()
|
||||
WHERE id = $1 AND status != 'completed'",
|
||||
&[&id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn reschedule_task(&self, id: i64, date: &str) -> Result<bool> {
|
||||
let date = parse_date(date)?;
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks
|
||||
SET scheduled_date = $1, notification_sent_at = NULL
|
||||
WHERE id = $2",
|
||||
&[&date, &id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn delete_task(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute("DELETE FROM tasks WHERE id = $1", &[&id])
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_routine(&self, routine: CreateRoutine) -> Result<i64> {
|
||||
validate_title(&routine.title)?;
|
||||
validate_schedule(&routine.schedule)?;
|
||||
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
|
||||
let schedule_json = serde_json::to_value(&routine.schedule).map_err(json_error)?;
|
||||
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO routines (
|
||||
title, notes, section, priority, schedule_json, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id",
|
||||
&[
|
||||
&routine.title.trim(),
|
||||
&routine.notes,
|
||||
&routine.section.as_str(),
|
||||
&routine.priority.as_str(),
|
||||
&schedule_json,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn list_routines(&self) -> Result<Vec<Routine>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, title, notes, section, priority, schedule_json,
|
||||
reminder_time, enabled
|
||||
FROM routines ORDER BY id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let schedule_json: serde_json::Value = row.get(5);
|
||||
let schedule = serde_json::from_value(schedule_json).map_err(json_error)?;
|
||||
let reminder_time: Option<NaiveTime> = row.get(6);
|
||||
Ok(Routine {
|
||||
id: row.get(0),
|
||||
title: row.get(1),
|
||||
notes: row.get(2),
|
||||
section: row.get(3),
|
||||
priority: row.get(4),
|
||||
schedule,
|
||||
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
||||
enabled: row.get(7),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn generate(&self, start: NaiveDate, horizon_days: u64) -> Result<usize> {
|
||||
let routines = self.list_routines()?;
|
||||
let mut client = self.connect()?;
|
||||
let mut inserted = 0_u64;
|
||||
|
||||
for offset in 0..=horizon_days {
|
||||
let date = start
|
||||
.checked_add_days(Days::new(offset))
|
||||
.ok_or_else(|| "generation date overflow".to_owned())?;
|
||||
for routine in routines.iter().filter(|routine| routine.enabled) {
|
||||
if !schedule_matches(&routine.schedule, date)? {
|
||||
continue;
|
||||
}
|
||||
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
|
||||
inserted += client
|
||||
.execute(
|
||||
"INSERT INTO tasks (
|
||||
routine_id, title, notes, section, priority,
|
||||
scheduled_date, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (routine_id, scheduled_date) DO NOTHING",
|
||||
&[
|
||||
&routine.id,
|
||||
&routine.title,
|
||||
&routine.notes,
|
||||
&routine.section,
|
||||
&routine.priority,
|
||||
&date,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
}
|
||||
}
|
||||
usize::try_from(inserted).map_err(|_| "generated task count overflow".to_owned())
|
||||
}
|
||||
|
||||
pub fn next_due_notification(&self, date: &str, time: &str) -> Result<Option<DueNotification>> {
|
||||
let date = parse_date(date)?;
|
||||
let time = parse_reminder(Some(time))?.expect("provided reminder is present");
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_opt(
|
||||
"SELECT id, title, section, priority
|
||||
FROM tasks
|
||||
WHERE scheduled_date = $1
|
||||
AND reminder_time IS NOT NULL
|
||||
AND reminder_time <= $2
|
||||
AND notification_sent_at IS NULL
|
||||
AND status = 'pending'
|
||||
ORDER BY reminder_time, id
|
||||
LIMIT 1",
|
||||
&[&date, &time],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.map(|row| DueNotification {
|
||||
task_id: row.get(0),
|
||||
title: row.get(1),
|
||||
section: row.get(2),
|
||||
priority: row.get(3),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn mark_notification_sent(&self, task_id: i64) -> Result<()> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks SET notification_sent_at = now() WHERE id = $1",
|
||||
&[&task_id],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_title(title: &str) -> Result<()> {
|
||||
if title.trim().is_empty() {
|
||||
Err("title must not be empty".to_owned())
|
||||
} else if title.len() > 300 {
|
||||
Err("title must be at most 300 bytes".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_date(date: &str) -> Result<NaiveDate> {
|
||||
NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| "date must use YYYY-MM-DD".to_owned())
|
||||
}
|
||||
|
||||
fn parse_reminder(reminder: Option<&str>) -> Result<Option<NaiveTime>> {
|
||||
reminder
|
||||
.map(|value| {
|
||||
NaiveTime::parse_from_str(value, "%H:%M")
|
||||
.map_err(|_| "reminder_time must use HH:MM".to_owned())
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn validate_schedule(schedule: &Schedule) -> Result<()> {
|
||||
match schedule {
|
||||
Schedule::Daily => Ok(()),
|
||||
Schedule::Weekly { weekdays } => {
|
||||
if weekdays.is_empty() || weekdays.iter().any(|day| !(1..=7).contains(day)) {
|
||||
Err("weekly weekdays must contain ISO values 1 through 7".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Schedule::Monthly { days, .. } => {
|
||||
if days.is_empty() || days.iter().any(|day| !(1..=31).contains(day)) {
|
||||
Err("monthly days must contain values 1 through 31".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_matches(schedule: &Schedule, date: NaiveDate) -> Result<bool> {
|
||||
match schedule {
|
||||
Schedule::Daily => Ok(true),
|
||||
Schedule::Weekly { weekdays } => {
|
||||
Ok(weekdays.contains(&date.weekday().number_from_monday()))
|
||||
}
|
||||
Schedule::Monthly {
|
||||
days,
|
||||
clamp_to_last_day,
|
||||
} => {
|
||||
let last_day = last_day_of_month(date)?;
|
||||
Ok(days.iter().any(|requested| {
|
||||
date.day() == *requested
|
||||
|| (*clamp_to_last_day && *requested > last_day && date.day() == last_day)
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn last_day_of_month(date: NaiveDate) -> Result<u32> {
|
||||
let (year, month) = if date.month() == 12 {
|
||||
(date.year() + 1, 1)
|
||||
} else {
|
||||
(date.year(), date.month() + 1)
|
||||
};
|
||||
let first_next = NaiveDate::from_ymd_opt(year, month, 1)
|
||||
.ok_or_else(|| "invalid month boundary".to_owned())?;
|
||||
let last = first_next
|
||||
.pred_opt()
|
||||
.ok_or_else(|| "invalid month boundary".to_owned())?;
|
||||
Ok(last.day())
|
||||
}
|
||||
|
||||
fn db_error(error: postgres::Error) -> String {
|
||||
format!("database error: {error}")
|
||||
}
|
||||
|
||||
fn json_error(error: serde_json::Error) -> String {
|
||||
format!("JSON error: {error}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn weekly_schedule_uses_iso_weekdays() {
|
||||
let monday = NaiveDate::from_ymd_opt(2026, 10, 19).unwrap();
|
||||
assert!(schedule_matches(
|
||||
&Schedule::Weekly {
|
||||
weekdays: vec![1, 3],
|
||||
},
|
||||
monday
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monthly_day_clamps_to_end_of_short_month() {
|
||||
let february_end = NaiveDate::from_ymd_opt(2027, 2, 28).unwrap();
|
||||
assert!(schedule_matches(
|
||||
&Schedule::Monthly {
|
||||
days: vec![31],
|
||||
clamp_to_last_day: true,
|
||||
},
|
||||
february_end,
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monthly_day_does_not_clamp_when_disabled() {
|
||||
let february_end = NaiveDate::from_ymd_opt(2027, 2, 28).unwrap();
|
||||
assert!(!schedule_matches(
|
||||
&Schedule::Monthly {
|
||||
days: vec![31],
|
||||
clamp_to_last_day: false,
|
||||
},
|
||||
february_end,
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Telegram {
|
||||
bot_token: String,
|
||||
chat_id: String,
|
||||
}
|
||||
|
||||
impl Telegram {
|
||||
pub fn from_env() -> Option<Self> {
|
||||
let bot_token = std::env::var("ROUTINE_TELEGRAM_BOT_TOKEN").ok()?;
|
||||
let chat_id = std::env::var("ROUTINE_TELEGRAM_CHAT_ID").ok()?;
|
||||
Some(Self { bot_token, chat_id })
|
||||
}
|
||||
|
||||
pub fn send_message(&self, text: &str) -> Result<(), String> {
|
||||
let url = format!("https://api.telegram.org/bot{}/sendMessage", self.bot_token);
|
||||
let payload = json!({
|
||||
"chat_id": self.chat_id,
|
||||
"text": text,
|
||||
})
|
||||
.to_string();
|
||||
let response = minreq::post(&url)
|
||||
.with_header("Content-Type", "application/json")
|
||||
.with_body(payload)
|
||||
.send()
|
||||
.map_err(|_| "Telegram request failed".to_owned())?;
|
||||
let body: Value = serde_json::from_str(
|
||||
response
|
||||
.as_str()
|
||||
.map_err(|_| "Telegram returned a non-UTF-8 response".to_owned())?,
|
||||
)
|
||||
.map_err(|_| "Telegram returned invalid JSON".to_owned())?;
|
||||
if body.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Telegram rejected the message".to_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user