-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReminderEngine.psm1
More file actions
339 lines (293 loc) · 12.1 KB
/
ReminderEngine.psm1
File metadata and controls
339 lines (293 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#
# ReminderEngine.psm1
# Pure logic module for Vikunja Reminder Agent.
# Imported by main.ps1 (runtime) and ReminderEngine.Tests.ps1 (tests).
#
Set-StrictMode -Version Latest
# ── Plugin registry ────────────────────────────────────────────────────────────
# Case-sensitive so ContainsKey("Discord") != ContainsKey("discord") — keys are always stored lowercase
$script:_Plugins = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)
function Register-Plugin {
<#
.SYNOPSIS
Registers a notification plugin by name.
.PARAMETER Name
Lowercase plugin name. Must match the "plugin" field in rules.json providers.
.PARAMETER ScriptBlock
param([hashtable]$Payload, [hashtable]$Options) → $true | $false
#>
param(
[Parameter(Mandatory)][string] $Name,
[Parameter(Mandatory)][scriptblock] $ScriptBlock
)
$script:_Plugins[$Name.ToLower()] = $ScriptBlock
Write-Host " [plugin] Registered: $Name"
}
function Clear-PluginRegistry {
<#
.SYNOPSIS
Clears all registered plugins. Intended for use in tests only.
#>
# Case-sensitive so ContainsKey("Discord") != ContainsKey("discord") — keys are always stored lowercase
$script:_Plugins = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)
}
function Get-RegisteredPlugins {
# Returns a shallow copy so callers cannot mutate the registry directly.
return $script:_Plugins.Clone()
}
# ── Rules engine ───────────────────────────────────────────────────────────────
function Import-RulesConfig {
<#
.SYNOPSIS
Loads and parses rules.json from the given path.
.PARAMETER Path
Full path to the rules.json file.
#>
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path $Path)) {
throw "Rules config not found at '$Path'."
}
$config = Get-Content $Path -Raw | ConvertFrom-Json
if ($null -eq $config.providers) { throw "'providers' key missing from config." }
if ($null -eq $config.rules) { throw "'rules' key missing from config." }
return $config
}
function Test-Condition {
<#
.SYNOPSIS
Evaluates a single condition object against a Payload hashtable.
.OUTPUTS
[bool]
#>
param(
[Parameter(Mandatory)][hashtable] $Payload,
[Parameter(Mandatory)][PSCustomObject] $Condition
)
$field = $Condition.field
$op = $Condition.op
$want = $Condition.value
$got = switch ($field) {
"project_id" { $Payload.ProjectId }
"priority" { $Payload.Priority }
"percent_done" { $Payload.PercentDone }
"is_favorite" { $Payload.IsFavorite }
"has_attachments" { $Payload.HasAttachments }
"done" { $Payload.Done }
"title" { $Payload.TaskTitle }
"description" { $Payload.Description }
"labels" { $Payload.Labels.title }
"assignees" { $Payload.AssigneeCount }
default {
Write-Warning " [rules] Unknown condition field '$field' — treating as no-match."
return $false
}
}
switch ($op) {
"=" { return $got -eq $want }
"!=" { return $got -ne $want }
">" { return $got -gt $want }
">=" { return $got -ge $want }
"<" { return $got -lt $want }
"<=" { return $got -le $want }
"contains" { return ("$got" -like "*$want*") }
"not_contains"{ return ("$got" -notlike "*$want*") }
"in" {
if ($got -is [System.Array]) {
$wantArr = @($want)
$matches = @(@($got) | Where-Object { $wantArr -contains $_ })
return ($matches.Count -gt 0)
}
else {
return (@($want) -contains $got)
}
}
"not_in" {
if ($got -is [System.Array]) {
$wantArr = @($want)
$matches = @(@($got) | Where-Object { $wantArr -contains $_ })
return ($matches.Count -eq 0)
}
else {
return (@($want) -notcontains $got)
}
}
default {
Write-Warning " [rules] Unknown operator '$op' — treating as no-match."
return $false
}
}
}
function Resolve-MatchingProviders {
<#
.SYNOPSIS
Evaluates all rules against a Payload and returns the list of provider
instances to invoke, in order, without duplicates.
.OUTPUTS
[System.Collections.Generic.List[hashtable]]
Each entry: @{ InstanceName; PluginName; Options }
#>
param(
[Parameter(Mandatory)][hashtable] $Payload,
[Parameter(Mandatory)][PSCustomObject] $Config
)
$providerDefs = @{}
foreach ($prop in $Config.providers.PSObject.Properties) {
$providerDefs[$prop.Name] = $prop.Value
}
$dispatched = [System.Collections.Generic.HashSet[string]]::new()
$result = [System.Collections.Generic.List[hashtable]]::new()
foreach ($rule in $Config.rules) {
$conditions = @($rule.conditions)
$matched = if ($conditions.Count -eq 0) {
$true # empty conditions = catch-all
}
elseif ($rule.match -eq "any") {
(@($conditions | Where-Object { Test-Condition -Payload $Payload -Condition $_ })).Count -gt 0
}
else {
# Default: "all" (AND)
(@($conditions | Where-Object { -not (Test-Condition -Payload $Payload -Condition $_) })).Count -eq 0
}
if (-not $matched) { continue }
Write-Host " [rules] Matched rule: '$($rule.name)'"
foreach ($instanceName in $rule.providers) {
if ($dispatched.Contains($instanceName)) { continue }
if (-not $providerDefs.ContainsKey($instanceName)) {
Write-Warning " [rules] Unknown provider '$instanceName' referenced in rule '$($rule.name)' — skipping."
continue
}
$def = $providerDefs[$instanceName]
# validate required fields
$hasPlugin = $def.PSObject.Properties.Name.Contains('plugin')
if (-not $hasPlugin) {
Write-Warning " [rules] Provider '$instanceName' is missing required 'plugin' field — skipping."
continue
}
$options = @{}
$hasOptions = $def.PSObject.Properties.Name.Contains('options')
if (-not $hasOptions) {
Write-Host " [rules] Provider '$instanceName' is missing 'options' field — treating as empty."
}else {
if ($def.options) {
foreach ($p in $def.options.PSObject.Properties) { $options[$p.Name] = $p.Value }
}
}
$result.Add(@{
InstanceName = $instanceName
PluginName = $def.plugin.ToLower()
Options = $options
})
$dispatched.Add($instanceName) | Out-Null
}
if ($rule.stop_on_match -eq $true) { break }
}
Write-Output $result -NoEnumerate
}
function Invoke-Providers {
<#
.SYNOPSIS
Dispatches a Payload to every provider in the list.
.OUTPUTS
[int] Number of providers that returned $true.
#>
param(
[Parameter(Mandatory)][hashtable] $Payload,
[Parameter(Mandatory)] $ProviderList # List[hashtable] or array -- no type constraint to avoid unwrap coercion
)
$ok = 0
foreach ($provider in $ProviderList) {
$pluginName = $provider.PluginName
if (-not $script:_Plugins.ContainsKey($pluginName)) {
Write-Warning " [$($provider.InstanceName)] No plugin registered for '$pluginName' — skipping."
continue
}
try {
$result = & $script:_Plugins[$pluginName] $Payload $provider.Options
if ($result -eq $true) { $ok++ }
else { Write-Warning " [$($provider.InstanceName)] returned false." }
}
catch {
Write-Warning " [$($provider.InstanceName)] threw: $_"
}
}
return $ok
}
# ── Payload builder ────────────────────────────────────────────────────────────
function Build-Payload {
<#
.SYNOPSIS
Builds the normalised Payload hashtable passed to every plugin.
.PARAMETER Task
Raw task object from the Vikunja API.
.PARAMETER ReminderUtc
The specific reminder datetime (UTC) that triggered this notification.
.PARAMETER Tz
User's configured TimeZoneInfo (from Vikunja user settings).
.PARAMETER PublicBaseUrl
Base URL used to construct the task link, e.g. http://localhost:3456
#>
param(
[Parameter(Mandatory)][object] $Task,
[Parameter(Mandatory)][datetime] $ReminderUtc,
[Parameter(Mandatory)][System.TimeZoneInfo] $Tz,
[Parameter(Mandatory)][string] $PublicBaseUrl
)
$localTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($ReminderUtc, $Tz)
$offset = $Tz.GetUtcOffset($ReminderUtc)
$sign = if ($offset.TotalSeconds -ge 0) { '+' } else { '-' }
$offsetStr = "UTC{0}{1:hh\:mm}" -f $sign, $offset
return @{
TaskId = [int] $Task.id
TaskTitle = [string]$Task.title
TaskUrl = "$($PublicBaseUrl.TrimEnd('/'))/tasks/$($Task.id)"
Description = [string]$Task.description
ProjectId = [int] $Task.project_id
Done = [bool] $Task.done
Priority = [int] $Task.priority
PercentDone = [int] $Task.percent_done
IsFavorite = [bool] $Task.is_favorite
HasAttachments = ($null -ne $Task.attachments -and @($Task.attachments).Count -gt 0)
LabelCount = if ($null -eq $Task.labels) { 0 } else { @($Task.labels).Count }
Labels = if ($null -eq $Task.labels) { @() } else { $Task.labels }
AssigneeCount = if ($null -eq $Task.assignees) { 0 } else { @($Task.assignees).Count }
ReminderUtc = $ReminderUtc
ReminderLocal = $localTime
ReminderStr = "$($localTime.ToString('yyyy-MM-dd HH:mm')) ($offsetStr)"
Timezone = $Tz
}
}
# ── State helpers ──────────────────────────────────────────────────────────────
function Get-FiredReminders {
param([Parameter(Mandatory)][string]$Path)
$set = [System.Collections.Generic.HashSet[string]]::new()
if (Test-Path $Path) {
try {
$raw = Get-Content $Path -Raw | ConvertFrom-Json
foreach ($k in $raw) { $set.Add($k) | Out-Null }
}
catch { Write-Warning "Could not read state file '$Path', starting fresh. Error: $_" }
}
Write-Output $set -NoEnumerate
}
function Save-FiredReminders {
param(
[Parameter(Mandatory)][System.Collections.Generic.HashSet[string]]$Set,
[Parameter(Mandatory)][string]$Path
)
$entries = @($Set)
if ($entries.Count -gt 2000) { $entries = $entries | Select-Object -Last 2000 }
$entries | ConvertTo-Json | Set-Content $Path
}
# ── Exports ────────────────────────────────────────────────────────────────────
Export-ModuleMember -Function @(
'Register-Plugin'
'Clear-PluginRegistry'
'Get-RegisteredPlugins'
'Import-RulesConfig'
'Test-Condition'
'Resolve-MatchingProviders'
'Invoke-Providers'
'Build-Payload'
'Get-FiredReminders'
'Save-FiredReminders'
)