You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.5 KiB
PowerShell

#!/usr/bin/env pwsh
<#
.SYNOPSIS
Takes a screenshot and puts the URL into the clipboard
.DESCRIPTION
Uses grim and slurp to create a screenshot and uploads it into a matrix content repository.
A GETable URL is placed into the clipboard via wl-copy and optionally sent to the specified room.
.NOTES
Example config at $HOME/.config/matrix-screenshot.ps1:
```
$roomId = '!XpxHNLnPsnNEbScyeh:imninja.net'
$accessToken = 'NotaReALaCceSSTOk3n'
$homeserverUrl = 'https://imninja.net'
```
#>
[CmdletBinding()]
param (
# Takes a fullscreen screenshot instead of selecting an area.
[switch]
$Fullscreen
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version 3.0
# import config
. (Join-Path $env:HOME '.config/matrix-screenshot.ps1')
$tmp = New-TemporaryFile
$tmpPath = $tmp.FullName
$webpPath = $tmpPath -replace 'tmp$','webp'
if ($Fullscreen) {
grim $tmpPath
} else {
grim -g $(slurp) $tmpPath
}
if ((Get-Item $tmpPath).Length -eq 0) {
Write-Error ('Temp file "{0}" is empty' -f $tmpPath) -ErrorAction Continue
Remove-Item $tmpPath
exit
}
magick $tmpPath $webpPath
if ((Get-Item $webpPath).Length -eq 0) {
Write-Error ('WebP file "{0}" is empty' -f $webpPath) -ErrorAction Continue
Remove-Item $webpPath
exit
} else {
Remove-Item $tmpPath
}
$mediaSplat = @{
Authentication = 'Bearer'
Token = $accessToken | ConvertTo-SecureString -AsPlainText
Headers = @{
'Content-Type' = 'image/webp'
}
Method = 'Post'
Uri = ($homeserverUrl+'/_matrix/media/r0/upload')
InFile = $webpPath
}
$media = Invoke-RestMethod @mediaSplat
Remove-Item $webpPath
$serverName = $media.content_uri.Split('/')[2]
$mediaId = $media.content_uri.Split('/')[3]
$mediaUrl = '{0}/_matrix/media/r0/download/{1}/{2}' -f $homeserverUrl,$serverName,$mediaId
$mediaUrl | wl-copy --trim-newline
notify-send 'Screenshot URL in clipboard' --expire-time=1000
if ($roomId) {
$fileName = $webpPath | Split-Path -Leaf
$eventSplat = @{
Authentication = 'Bearer'
Token = $accessToken | ConvertTo-SecureString -AsPlainText
Method = 'Put'
Uri = '{0}/_matrix/client/r0/rooms/{1}/send/{2}/{3}' -f $homeserverUrl,$roomId,'m.room.message',$filename
Body = @{
body = $fileName
msgtype = 'm.image'
url = $media.content_uri
} | ConvertTo-Json
}
$event_id = (Invoke-RestMethod @eventSplat).event_id
Write-Output ('{0}' -f $event_id)
}