Initial scaffolding
This commit is contained in:
1 parent
15a0ff43de
commit
989415ec1f
20 files changed
+743
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package Mnemosyne::Config;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# Loads mnemosyne.conf (INI-style) and exposes a simple accessor.
|
||||
# Usage:
|
||||
# my $cfg = Mnemosyne::Config->new('/path/to/mnemosyne.conf');
|
||||
# my $token = $cfg->get('bot', 'token');
|
||||
# my $href = $cfg->section('bot'); # all keys in [bot]
|
||||
|
||||
sub new {
|
||||
my ($class, $path) = @_;
|
||||
die "Config file not specified\n" unless defined $path;
|
||||
die "Config file not found: $path\n" unless -f $path;
|
||||
|
||||
my $self = bless { _path => $path, _data => {} }, $class;
|
||||
$self->_parse;
|
||||
return $self;
|
||||
}
|
||||
|
||||
sub _parse {
|
||||
my ($self) = @_;
|
||||
open my $fh, '<', $self->{_path}
|
||||
or die "Cannot open config '$self->{_path}': $!\n";
|
||||
|
||||
my $section = '_default';
|
||||
while (my $line = <$fh>) {
|
||||
chomp $line;
|
||||
$line =~ s/\s*#.*$//; # strip inline comments
|
||||
$line =~ s/^\s+|\s+$//g; # trim
|
||||
next unless length $line;
|
||||
|
||||
if ($line =~ /^\[(\w+)\]$/) {
|
||||
$section = lc $1;
|
||||
}
|
||||
elsif ($line =~ /^([\w_]+)\s*=\s*(.*)$/) {
|
||||
my ($key, $val) = (lc $1, $2);
|
||||
$val =~ s/\s+$//;
|
||||
$self->{_data}{$section}{$key} = $val;
|
||||
}
|
||||
else {
|
||||
warn "Config: unrecognised line in $self->{_path}: $line\n";
|
||||
}
|
||||
}
|
||||
close $fh;
|
||||
}
|
||||
|
||||
sub get {
|
||||
my ($self, $section, $key) = @_;
|
||||
$section = lc $section;
|
||||
$key = lc $key;
|
||||
return $self->{_data}{$section}{$key};
|
||||
}
|
||||
|
||||
sub section {
|
||||
my ($self, $section) = @_;
|
||||
return { %{ $self->{_data}{lc $section} // {} } };
|
||||
}
|
||||
|
||||
# Returns the list of allowed chat IDs as an array ref (parsed from the
|
||||
# comma-separated 'allowed_chat_ids' value in [bot]).
|
||||
sub allowed_chat_ids {
|
||||
my ($self) = @_;
|
||||
my $raw = $self->get('bot', 'allowed_chat_ids') // '';
|
||||
my @ids = grep { /^\d+$/ } map { s/^\s+|\s+$//gr } split /,/, $raw;
|
||||
return \@ids;
|
||||
}
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,137 @@
|
||||
package Mnemosyne::DB;
|
||||
use strict;
|
||||
use warnings;
|
||||
use DBI;
|
||||
use File::Basename qw(dirname);
|
||||
use File::Spec;
|
||||
use Carp qw(croak);
|
||||
|
||||
# Opens (and initialises if new) the Mnemosyne SQLite database.
|
||||
# Usage:
|
||||
# my $db = Mnemosyne::DB->new('/var/lib/mnemosyne/mnemosyne.db');
|
||||
# my $dbh = $db->dbh;
|
||||
|
||||
sub new {
|
||||
my ($class, $path) = @_;
|
||||
croak "Database path required" unless defined $path;
|
||||
|
||||
# Ensure parent directory exists
|
||||
my $dir = dirname($path);
|
||||
unless (-d $dir) {
|
||||
require File::Path;
|
||||
File::Path::make_path($dir) or croak "Cannot create DB directory '$dir': $!";
|
||||
}
|
||||
|
||||
my $dbh = DBI->connect(
|
||||
"dbi:SQLite:dbname=$path", '', '',
|
||||
{
|
||||
RaiseError => 1,
|
||||
AutoCommit => 1,
|
||||
sqlite_unicode => 1,
|
||||
}
|
||||
) or croak "Cannot connect to SQLite '$path': " . $DBI::errstr;
|
||||
|
||||
my $self = bless { _dbh => $dbh, _path => $path }, $class;
|
||||
$self->_configure;
|
||||
$self->_apply_schema;
|
||||
return $self;
|
||||
}
|
||||
|
||||
sub dbh { $_[0]->{_dbh} }
|
||||
|
||||
sub _configure {
|
||||
my ($self) = @_;
|
||||
my $dbh = $self->{_dbh};
|
||||
$dbh->do('PRAGMA foreign_keys = ON');
|
||||
$dbh->do('PRAGMA journal_mode = WAL');
|
||||
$dbh->do('PRAGMA synchronous = NORMAL'); # safe with WAL, faster than FULL
|
||||
}
|
||||
|
||||
sub _apply_schema {
|
||||
my ($self) = @_;
|
||||
|
||||
# Schema DDL is kept here alongside the canonical share/schema.sql.
|
||||
# share/schema.sql is the human-readable reference; this is what runs at startup.
|
||||
# Both must be kept in sync when the schema changes.
|
||||
my @statements = (
|
||||
q{
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
class TEXT NOT NULL
|
||||
CHECK(class IN ('monthly_date','monthly_weekday',
|
||||
'every_n_period','interval','floating')),
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
day_of_month INTEGER,
|
||||
weekday INTEGER,
|
||||
ordinal INTEGER,
|
||||
interval_n INTEGER,
|
||||
period_unit TEXT CHECK(period_unit IN ('day','week','month') OR period_unit IS NULL),
|
||||
anchor_date TEXT,
|
||||
interval_days INTEGER,
|
||||
priority TEXT CHECK(priority IN ('high','medium','low') OR priority IS NULL),
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
|
||||
)},
|
||||
q{
|
||||
CREATE TABLE IF NOT EXISTS completions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
completed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
|
||||
)},
|
||||
q{CREATE INDEX IF NOT EXISTS idx_completions_task_id ON completions(task_id)},
|
||||
q{
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)},
|
||||
);
|
||||
|
||||
my @config_defaults = (
|
||||
[ 'digest_time', '06:30' ],
|
||||
[ 'timezone', 'UTC' ],
|
||||
[ 'last_digest_sent', '' ],
|
||||
[ 'upcoming_horizon', '7' ],
|
||||
[ 'medium_float_days', '3' ],
|
||||
);
|
||||
|
||||
my $dbh = $self->{_dbh};
|
||||
$dbh->begin_work;
|
||||
eval {
|
||||
$dbh->do($_) for @statements;
|
||||
my $ins = $dbh->prepare('INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)');
|
||||
$ins->execute(@$_) for @config_defaults;
|
||||
$dbh->commit;
|
||||
};
|
||||
if ($@) {
|
||||
$dbh->rollback;
|
||||
croak "Schema initialisation failed: $@";
|
||||
}
|
||||
}
|
||||
|
||||
# --- Config table helpers ---
|
||||
|
||||
sub config_get {
|
||||
my ($self, $key) = @_;
|
||||
my ($val) = $self->{_dbh}->selectrow_array(
|
||||
'SELECT value FROM config WHERE key = ?', undef, $key
|
||||
);
|
||||
return $val;
|
||||
}
|
||||
|
||||
sub config_set {
|
||||
my ($self, $key, $value) = @_;
|
||||
$self->{_dbh}->do(
|
||||
'INSERT INTO config (key, value) VALUES (?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value',
|
||||
undef, $key, $value
|
||||
);
|
||||
}
|
||||
|
||||
sub DESTROY {
|
||||
my ($self) = @_;
|
||||
$self->{_dbh}->disconnect if $self->{_dbh};
|
||||
}
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,27 @@
|
||||
package Mnemosyne::Digest;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# Assembles the "Day at a Glance" digest content and sends it via Telegram.
|
||||
# Also used by the /today and /glance commands for on-demand delivery.
|
||||
#
|
||||
# Sections (in order), each omitted when empty:
|
||||
# 1. Overdue — dated tasks past their due date with no completion
|
||||
# 2. Today — tasks due today
|
||||
# 3. Upcoming — tasks due in the next upcoming_horizon days (default 7)
|
||||
# 4. Floating — priority-driven selection per Schedule::_floating_show rules
|
||||
#
|
||||
# Each actionable line gets a Mark Done inline keyboard button.
|
||||
# A friendly "all clear" line is shown when all sections are empty.
|
||||
#
|
||||
# TODO: build($db, $config, $today_dt) — returns an arrayref of message segments
|
||||
# (Telegram has a 4096-char limit; split into multiple messages if needed)
|
||||
#
|
||||
# TODO: send($db, $config, $telegram, $chat_id, $today_dt)
|
||||
# — calls build(), sends via Telegram, records last_digest_sent in config table
|
||||
#
|
||||
# TODO: already_sent_today($db, $today_dt)
|
||||
# — checks last_digest_sent config row; returns true if digest was sent today
|
||||
# — used by mnemosyne-digest script to prevent duplicate sends
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,36 @@
|
||||
package Mnemosyne::Schedule;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# Resolves whether a task is due/upcoming/overdue/irrelevant for a given date.
|
||||
# This module is the heart of the scheduling logic and must be well unit-tested.
|
||||
#
|
||||
# Public interface (all take a task hashref + a DateTime object for "today"):
|
||||
#
|
||||
# TODO: status($task, $today_dt) — returns one of: 'overdue', 'due', 'upcoming', 'inactive'
|
||||
# Dispatches to the appropriate class handler below.
|
||||
#
|
||||
# TODO: next_due_date($task, $today_dt) — returns a DateTime of the next occurrence,
|
||||
# or undef if the task has no upcoming date (e.g. inactive).
|
||||
#
|
||||
# --- Per-class handlers ---
|
||||
#
|
||||
# TODO: _monthly_date_due($task, $today_dt)
|
||||
# Rule: fires on day_of_month each month.
|
||||
# Short-month rule: if day_of_month > days-in-month, fire on last day of month.
|
||||
#
|
||||
# TODO: _monthly_weekday_due($task, $today_dt)
|
||||
# Rule: fires on the Nth weekday (ordinal 1-4, or -1 for last) each month.
|
||||
#
|
||||
# TODO: _every_n_period_due($task, $today_dt)
|
||||
# Rule: occurrences = anchor_date + k * (interval_n period_units), k=0,1,2,...
|
||||
# Calendar-anchored; NOT reset by completion.
|
||||
#
|
||||
# TODO: _interval_due($task, $today_dt, $last_completion_dt)
|
||||
# Rule: next_due = last_completion_dt + interval_days (or created_at if never done).
|
||||
#
|
||||
# TODO: _floating_show($task, $today_dt, $last_completion_dt)
|
||||
# Rule: high → always; medium → every medium_float_days; low → weekly + randomised.
|
||||
# Returns true/false (floating tasks are never "overdue", just shown or not).
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,17 @@
|
||||
package Mnemosyne::Task;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# CRUD operations for the tasks table, plus class-specific field validation.
|
||||
#
|
||||
# TODO: create($dbh, \%fields) — insert a new task, validate class + required fields
|
||||
# TODO: get($dbh, $id) — fetch one task by id (returns hashref or undef)
|
||||
# TODO: list($dbh, %filters) — list tasks; filters: class, active, priority
|
||||
# TODO: update($dbh, $id, \%fields) — partial update; sets updated_at
|
||||
# TODO: delete($dbh, $id) — hard delete (completions cascade)
|
||||
# TODO: disable($dbh, $id) — set active=0
|
||||
# TODO: complete($dbh, $id) — insert into completions; for floating, also sets active=0
|
||||
# TODO: undo_completion($dbh, $completion_id) — delete a completion row (misclick undo)
|
||||
# TODO: last_completion($dbh, $id) — returns the most recent completions row for a task
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,35 @@
|
||||
package Mnemosyne::Telegram;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# Bot API client. All outbound calls use Mojo::UserAgent.
|
||||
# Never use Telegram::Bot or other heavyweight frameworks.
|
||||
#
|
||||
# Constructor:
|
||||
# TODO: new($token) — stores token; lazily creates Mojo::UserAgent
|
||||
#
|
||||
# Sending messages:
|
||||
# TODO: send_message($chat_id, $text, %opts)
|
||||
# — opts: parse_mode (default 'HTML'), reply_markup (inline keyboard hashref)
|
||||
# — returns the sent message's message_id (needed for later edits)
|
||||
#
|
||||
# TODO: edit_message($chat_id, $message_id, $text, %opts)
|
||||
# — wraps editMessageText; used to replace "pending" with "✓ Done — [Undo]"
|
||||
#
|
||||
# TODO: edit_reply_markup($chat_id, $message_id, $reply_markup)
|
||||
# — wraps editMessageReplyMarkup; strips buttons after undo window expires
|
||||
#
|
||||
# TODO: answer_callback_query($callback_query_id, %opts)
|
||||
# — must be called promptly to stop the client spinner; opts: text, show_alert
|
||||
#
|
||||
# Keyboard helpers:
|
||||
# TODO: mark_done_keyboard($task_id) — returns inline_keyboard hashref with one
|
||||
# "Mark Done" button; callback_data encodes action + task_id
|
||||
#
|
||||
# TODO: undo_keyboard($completion_id) — "Undo" button after a mark-done action
|
||||
#
|
||||
# Setup:
|
||||
# TODO: set_webhook($url, $secret_token) — calls setWebhook; idempotent
|
||||
# TODO: delete_webhook() — calls deleteWebhook
|
||||
|
||||
1;
|
||||
@@ -0,0 +1,37 @@
|
||||
package Mnemosyne::Webhook;
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
# Mojolicious controller / update router for inbound Telegram webhook POSTs.
|
||||
#
|
||||
# Security gates (must run in this order before any processing):
|
||||
# 1. Validate X-Telegram-Bot-Api-Secret-Token header matches config.
|
||||
# Reject with 403 (not 200) — this is not a Telegram client, it's a rogue POST.
|
||||
# 2. Validate chat_id is in the allowed_chat_ids whitelist.
|
||||
# Respond 200 (so Telegram stops retrying) but do not process the update.
|
||||
#
|
||||
# Update types handled:
|
||||
# TODO: handle_message($update, $db, $config, $telegram)
|
||||
# — routes slash commands: /today /glance /list /add /done /edit /disable /delete
|
||||
# /settime /help; plus free-text during multi-step flows (e.g. /add wizard)
|
||||
#
|
||||
# TODO: handle_callback_query($update, $db, $config, $telegram)
|
||||
# — handles Mark Done and Undo button taps; calls answerCallbackQuery immediately
|
||||
# then does DB work + message edit; idempotent (tolerate Telegram redelivery)
|
||||
#
|
||||
# Command handlers (each returns a Telegram reply or edits the original message):
|
||||
# TODO: cmd_today($chat_id, $db, $config, $telegram)
|
||||
# TODO: cmd_list($chat_id, $args, $db, $config, $telegram)
|
||||
# TODO: cmd_add($chat_id, $args, $db, $config, $telegram) — starts guided flow
|
||||
# TODO: cmd_done($chat_id, $args, $db, $config, $telegram)
|
||||
# TODO: cmd_edit($chat_id, $args, $db, $config, $telegram)
|
||||
# TODO: cmd_disable($chat_id, $args, $db, $config, $telegram)
|
||||
# TODO: cmd_delete($chat_id, $args, $db, $config, $telegram) — confirmation required
|
||||
# TODO: cmd_settime($chat_id, $args, $db, $config, $telegram)
|
||||
# TODO: cmd_help($chat_id, $telegram)
|
||||
#
|
||||
# Conversation state for multi-step flows (e.g. /add wizard):
|
||||
# TODO: decide and document storage mechanism (in-memory hash keyed by chat_id,
|
||||
# or a small 'sessions' table in SQLite for persistence across restarts)
|
||||
|
||||
1;
|
||||
Reference in new issue
Block a user