Skip to content

Commit

Permalink
Commit for initial Github release
Browse files Browse the repository at this point in the history
  • Loading branch information
philipmgrant committed Aug 30, 2022
0 parents commit 6a57202
Show file tree
Hide file tree
Showing 59 changed files with 2,324 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vscode
124 changes: 124 additions & 0 deletions CreateNotification.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
. $PSScriptRoot/DllLoad.ps1
. $PSScriptRoot/Logging.ps1
. $PSScriptRoot/NotificationXmlBuilder.ps1


function ShowNotification ([Windows.Data.Xml.Dom.XmlDocument]$xml, [string]$source_app_id) {
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($source_app_id).Show($toast)
}


function GetMessageParts ([string[]]$file_content) {
$directives = @{}
$content = @()
foreach ($line in $file_content) {
if ($line.StartsWith("#")) {
# comment
} elseif ($line.StartsWith("||") -or $line.StartsWith("|#") ) {
# escape sequence, remove the initial | and interpret the rest as text
$content += $line.Substring(1, $line.Length - 1)
} elseif ($line.StartsWith("|")) {
# directive
$parts = $line.Substring(1, $line.Length - 1) -Split ":", 2
$k = $parts[0].Trim()
if ($k.StartsWith("!")) {
# negative boolean directive
$k = $k.Substring(1, $k.Length - 1)
$directives[$k] = $false
} else {
$v = if ($parts.Count -gt 1) {$parts[1].Trim()} else {$true}
$directives[$k] = $v
}
} else {
# message text
$content += $line
}
}
return (@{Directives=$directives; Content=$content})
}


function BuildToastDataFromContent ([string[]] $file_content, [string]$log_file_path = $null,
[Nullable[datetime]]$timestamp = $null,
[bool]$enable_web_images = $false, [int]$max_web_image_size_bytes = 0,
[hashtable]$default_directives = @{}) {
$message = GetMessageParts($file_content)
$text_content = $message.Content
$directives = $default_directives.Clone()
foreach ($k in $message.Directives.Keys) {
$directives[$k] = $message.Directives.$k
}
$builder = [NotificationXmlBuilder]::new($text_content, $directives, $timestamp, $log_file_path, $enable_web_images, $max_web_image_size_bytes)
return $builder.GetNotificationData()
}


function NotifyFromFile ([string]$file_path, [string]$app_id, [string]$log_file_path,
[switch]$timestamp_from_file = $false,
[switch]$enable_web_images = $false, [int]$max_web_image_size_bytes = 0,
[hashtable]$default_directives = @{}) {
try {
WriteLogMessage "Attempting to process $file_path" $log_file_path
if ($timestamp_from_file) {
$private:file_time = (Get-Item -Path $file_path).LastWriteTime
} else {
$private:file_time = $null
}

$private:file_content = Get-Content -Path $file_path
if ($null -eq $file_content) {
WriteLogMessage "Got no content for $file_path" $log_file_path
return
}
if ($file_content.GetType().Name -eq "String") {
$file_content = @($file_content)
}

$toast_data = BuildToastDataFromContent $file_content -log_file_path:$log_file_path -timestamp:$file_time `
-default_directives:$default_directives `
-enable_web_images:$enable_web_images -max_web_image_size_bytes:$max_web_image_size_bytes
if (!$toast_data.Source_App_Id) {
$toast_data['Source_App_Id'] = $app_id
}
WriteLogMessage "Firing toast with XML:" $log_file_path
WriteLogMessage $toast_data.Xml.GetXml() $log_file_path
ShowNotification @toast_data

Remove-Item -Path $file_path
WriteLogMessage "Processed and deleted $file_path" $log_file_path
} catch {
WriteLogMessage "Error raising toast for $file_path" $log_file_path
WriteLogMessage $_ $log_file_path
}
}


function NotifyFromDir ([string]$directory, [string]$app_id, [string]$log_file_path,
[double]$min_age_sec = 5, [string]$file_pattern = "*.*",
[hashtable]$default_directives = @{}, [switch]$timestamp_from_file = $false,
[switch]$enable_web_images = $false, [int]$max_web_image_size_bytes = 0,
[switch]$recurse = $false) {
if (!($directory)) {
WriteLogMessage "NotifyFromDir called with empty directory: pass '.' if you really want to use the working dir" $log_file_path
return
}
$ts = Get-Date
WriteLogMessage "Sweeping $directory" $log_file_path
if ($recurse) {
$files = Get-ChildItem -Path $directory -Filter $file_pattern -File -Recurse
} else {
$files = Get-ChildItem -Path $directory -Filter $file_pattern -File
}

$files | ForEach-Object {
$age = (New-TimeSpan -Start $_.LastWriteTime -End $ts).TotalSeconds
if ($age -ge $min_age_sec) {
NotifyFromFile $_.FullName $app_id $log_file_path -default_directives:$default_directives -timestamp_from_file:$timestamp_from_file `
-enable_web_images:$enable_web_images -max_web_image_size_bytes:$max_web_image_size_bytes
} else {
WriteLogMessage "Ignoring too recent file: $($_.FullPath)" $log_file_path
}
}
WriteLogMessage "Sweep complete for $directory" $log_file_path
}
10 changes: 10 additions & 0 deletions DllLoad.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
$legacy = $PSVersionTable.PSVersion.Major -eq 5

[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\dll\CommunityToolkit.WinUI.Notifications.dll")
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\dll\Microsoft.Windows.SDK.NET.dll")
[System.Reflection.Assembly]::LoadFrom("$PSScriptRoot\dll\WinRT.Runtime.dll")

if ($legacy) {
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType = WindowsRuntime] | Out-Null
}
71 changes: 71 additions & 0 deletions ImageCache.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
class ImageCache {
static [hashtable]$PathMap = @{}
static [hashtable]$BadUris = @{}
static [int]$DefaultMaxSizeInBytes = 256000
static [int]$MaximumAttempts = 3


static [void]Reset () {
[ImageCache]::PathMap = @{}
[ImageCache]::BadUris = @{}
}

static [string]StoreResponseData ([object]$response) {
$file_stream = $null
try {
$local_file = New-TemporaryFile
$local_file_path = $local_file.FullName
$file_stream = New-Object IO.FileStream($local_file, "Append", "Write", "Read")
$response.RawContentStream.CopyTo($file_stream)
WriteLogMessage "Saved to $local_file_path"
return $local_file_path
} finally {
if ($file_stream) {
$file_stream.Close()
}
}
}

static [string]FetchImage ([string]$uri, [string]$log_file_path, [nullable[int]]$max_size_bytes) {
if ([ImageCache]::PathMap.ContainsKey($uri)) {
$local_path = [ImageCache]::PathMap[$uri]
if (Test-Path $local_path) {
WriteLogMessage "Using already downloaded image from $uri" $log_file_path
return $local_path
}
}
if ([ImageCache]::BadUris.ContainsKey($uri)) {
$failures = [ImageCache]::BadUris[$uri]
if (([ImageCache]::MaximumAttempts -gt 0) -and $failures -ge [ImageCache]::MaximumAttempts) {
WriteLogMessage "Not retrying ($failures previous failures): $uri" $log_file_path
return ""
} elseif ($failures -eq -1) {
WriteLogMessage "Not retrying (too large): $uri" $log_file_path
return ""
}
}

if ($null -eq $max_size_bytes) {
$max_size_bytes = [ImageCache]::DefaultMaxSizeInBytes
}
$ret = ""
try {
$response = Invoke-WebRequest -Uri $uri
$response_size = $response.RawContentLength
WriteLogMessage "Downloaded image ($response_size bytes) from $uri" $log_file_path
if ($response_size -gt $max_size_bytes) {
[ImageCache]::BadUris[$uri] = -1
WriteLogMessage "Image too large: not saving"
} else {
$local_file_path = [ImageCache]::StoreResponseData($response)
[ImageCache]::PathMap[$uri] = $local_file_path
$ret = $local_file_path
}
} catch {
WriteLogMessage "Exception fetching image from $uri" $log_file_path
WriteLogMessage $_ $log_file_path
[ImageCache]::BadUris[$uri] = if ([ImageCache]::BadUris.ContainsKey($uri)) {[ImageCache]::BadUris[$uri] + 1} else {1}
}
return $ret
}
}
62 changes: 62 additions & 0 deletions Init.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
. $PSScriptRoot/Listener.ps1
. $PSScriptRoot/Logging.ps1


function InitalizeLogging ([string]$LogsDir) {
# Minimal initialization of logging (so logs can be available before more complicated initialization steps)
if ($null -eq $app_context) {
$global:app_context = @{}
}
New-Item -Path $LogsDir -ItemType Directory -ErrorAction SilentlyContinue
$ts = Get-Date -UFormat '%Y%m%d_%H%M%S'
$app_context["log_file_path"] = Join-Path -Path $LogsDir -ChildPath "toast_$ts.log"
}


function Initialize ([string[]]$WatchedDirs = @(), [string]$FilePattern = "*.toa", [switch]$TimestampFromFile = $false, [double]$SweepIntervalSec = 600,
[double]$SweepMinAgeSec = 5, [string]$LogsDir = "", [double]$PurgeLogsOlderThan = -1, [hashtable]$DefaultDirectives = @{},
[switch]$SweepOnStartup = $false, [switch]$Recurse = $false, [switch]$EnableWebImages = $false, [double]$MaxWebImageSizeKb = 256) {
if (!($WatchedDirs.Count)) {
throw "Empty array of directories supplied"
}

if ($null -eq $app_context) {
$global:app_context = @{}
}
$app_context["timestamp_from_file"] = $TimestampFromFile
$app_context["default_directives"] = $DefaultDirectives
$app_context["enable_web_images"] = $EnableWebImages
$app_context["max_web_image_size_bytes"] = [int]($MaxWebImageSizeKb * 1000)

$apps = Get-StartApps | Where-Object { $_.Name.ToLower() -match ("^(windows )?powershell") }
$app_context["app_id"] = $apps[0].AppID

if ($LogsDir) {
if (!($app_context.log_file_path)) {
InitalizeLogging $LogsDir
}

if ($PurgeLogsOlderThan -ge 0) {
$keep_after = (Get-Date).AddDays(-$PurgeLogsOlderThan)
Get-ChildItem -Path $LogsDir -File | Where-Object { $_.CreationTime -lt $keep_after } | Remove-Item -Force
}
} else {
$app_context["log_file_path"] = $null
}

WriteLogMessage "Setting up listeners for $( $WatchedDirs.Length ) directories" $log_file_path

# Resolve items like ~ in the path: the FileSystemWatcher needs the resolved path
$dir_full_paths = $WatchedDirs | % { $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_) }
foreach($dir in $dir_full_paths) {
New-Item -Path $dir -ItemType Directory -ErrorAction SilentlyContinue
}
CreateToastListeners $dir_full_paths -file_pattern:$FilePattern -recurse:$Recurse
CreateToastDirectorySweeper $dir_full_paths -interval_sec:$SweepIntervalSec -file_pattern:$FilePattern -min_age_sec:$SweepMinAgeSec -recurse:$Recurse
WriteLogMessage "Listener setup complete" $log_file_path

if ($SweepOnStartup) {
WriteLogMessage "Sweeping for files present on startup" $log_file_path
New-Event -SourceIdentifier "LightlyToastedSweepForce" -MessageData @{Directories = $dir_full_paths; Pattern = $FilePattern; Recurse = $Recurse}
}
}
7 changes: 7 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2022 Philip Grant.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
61 changes: 61 additions & 0 deletions Listener.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
. $PSScriptRoot/CreateNotification.ps1
. $PSScriptRoot/Logging.ps1


function global:HandleFileEvent ([System.Management.Automation.PSEventArgs]$ev) {
NotifyFromFile $ev.SourceArgs.FullPath $app_context.app_id $app_context.log_file_path `
-default_directives:$app_context.default_directives -timestamp_from_file:$app_context.timestamp_from_file `
-enable_web_images:$app_context.enable_web_images -max_web_image_size_bytes:$app_context.max_web_image_size_bytes
}


function global:HandleDirectoriesEvent ([System.Management.Automation.PSEventArgs]$ev) {
foreach($dir in $ev.MessageData.Directories) {
NotifyFromDir $dir $app_context.app_id $app_context.log_file_path `
-file_pattern:$ev.MessageData.Pattern -default_directives:$app_context.default_directives `
-timestamp_from_file:$app_context.timestamp_from_file `
-enable_web_images:$app_context.enable_web_images -max_web_image_size_bytes:$app_context.max_web_image_size_bytes `
-min_age_sec:$ev.MessageData.MinAgeSec -recurse:$ev.MessageData.Recurse
}
}


function CreateToastListeners ([string[]]$directories, [string]$file_pattern = "*.*", [switch]$recurse = $false) {
$i = 0
foreach($directory in $directories) {
WriteLogMessage "Creating listener for: $directory" $app_context.log_file_path
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $directory
$watcher.Filter = $file_pattern
$watcher.EnableRaisingEvents = $true
$watcher.IncludeSubdirectories = $recurse

foreach ($ev_name in @("Created", "Renamed")) {
Register-ObjectEvent -SourceIdentifier "LightlyToasted$i" `
-InputObject $watcher `
-EventName $ev_name `
-Action { try { HandleFileEvent $event } catch { WriteLogMessage $_.Exception.Message $app_context.log_file_path } }
$i++
}
}
}


function CreateToastDirectorySweeper([string[]]$directories, [double]$interval_sec = 300, [string]$file_pattern = "*.*",
[double]$min_age_sec = 5, [switch]$recurse = $false) {
WriteLogMessage "Creating directory sweeper for $( $directories.Length ) directories:" $app_context.log_file_path
$directories | % { WriteLogMessage " $_" $app_context.log_file_path }
$timer = New-Object System.Timers.Timer
$timer.Interval = $interval_sec * 1000
$timer.AutoReset = $true
$timer.Enabled = $true

Register-ObjectEvent -SourceIdentifier "LightlyToastedSweep" `
-InputObject $timer `
-EventName "Elapsed" `
-MessageData @{Directories = $directories; Pattern = $file_pattern; MinAgeSec = $min_age_sec; Recurse = $recurse} `
-Action { try { HandleDirectoriesEvent $event } catch { WriteLogMessage $_.Exception.Message $app_context.log_file_path } }

Register-EngineEvent -SourceIdentifier "LightlyToastedSweepForce" `
-Action {try { HandleDirectoriesEvent $event } catch { WriteLogMessage $_.Exception.Message $app_context.log_file_path } }
}
12 changes: 12 additions & 0 deletions Logging.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function global:WriteLogMessage ([string] $msg, [string]$log_file_path, [bool]$ToConsole = $true) {
$ts = Get-Date -UFormat '%Y-%m-%d %H:%M:%S'
if ($log_file_path) {
if ($ToConsole) {
"[$ts] $msg" | Tee-Object -FilePath $log_file_path -Append | Write-Host
} else {
"[$ts] $msg" | Out-File -FilePath $log_file_path -Append
}
} elseif ($ToConsole) {
"[$ts] $msg" | Write-Host
}
}
Loading

0 comments on commit 6a57202

Please sign in to comment.