webhook2ntfy/lib/Webhook2Ntfy/Controller/Webhook.pm

121 lines
2.2 KiB
Perl
Raw Normal View History

2024-03-06 08:34:02 +01:00
package Webhook2Ntfy::Controller::Webhook;
use Mojo::Base 'Mojolicious::Controller', -signatures;
use JSON;
use Data::Dumper;
use URI::Escape;
use Encode qw/encode decode/;
use MIME::Base64;
use LWP::UserAgent;
use HTTP::Request::Common qw{ POST };
sub publish
{
my $self = shift;
my $msg = shift;
my $ntfyServer = $ENV{NTFY_SERVER};
my $ntfyToken = $self->prepareAuthToken($ENV{NTFY_TOKEN});
my $ua = LWP::UserAgent->new();
my $url = $ntfyServer . "/?auth=$ntfyToken";
my $response = $ua->post( $url, Markdown=>'yes', Content => to_json($msg));
if ($response->is_success)
{
$self->log->info("successfull delivery");
}
else
{
$self->log->error("delivery failed: " . $response->status_line);
}
2024-03-06 08:34:02 +01:00
}
sub prepareAuthToken
{
my $self = shift;
my $token = shift;
my $auth=encode_base64("".":".$token, "");
my $authString = encode_base64("Basic " . $auth, "");
$authString =~ s/=+$//;
return $authString;
}
sub redmine2ntfy
{
my $self = shift;
my $data = shift;
2024-03-06 08:49:52 +01:00
$self->log->info("Preparing message from redmine");
2024-03-06 08:34:02 +01:00
$data->{text} =~ /^<(.*)\|(.+)>\+\-\+(.+)\+<(.*)\|(.*)>\+.*\+by\+(.*)$/;
my $projectUrl=$1;
my $projectName=$2;
my $entity = $3;
my $entityUrl=$4;
my $entityName=$5;
my $author=$6;
2024-03-09 19:37:47 +01:00
2024-03-06 08:34:02 +01:00
$author =~ s/\+/ /g;
2024-03-09 19:37:47 +01:00
$projectName=~ s/\+/ /g;
2024-03-06 08:34:02 +01:00
my $status;
if ($entity eq "Issue")
{
$entityName=~s/\+/ /g;
}
2024-03-09 19:37:47 +01:00
2024-03-06 08:34:02 +01:00
my $title = "$entity update for $projectName";
my $text = "There has been an $entity update for project [$projectName]($projectUrl) by $author on [$entityName]($entityUrl)";
my $message = {
topic => $data->{channel},
title => $title,
message => $text
};
}
sub toNtfyMessage
{
my $self = shift;
my $data = shift;
if ($ENV{IS_REDMINE})
{
return $self->redmine2ntfy($data);
}
my $message = {
topic => $data->{channel},
message => $data->{text}
};
return $message;
}
# This action will render a template
sub call {
my $self = shift;
my $body = $self->req->body;
$body=uri_unescape($body);
$body=substr($body,8,length($body));
my $data=from_json($body);
$self->publish($self->toNtfyMessage($data));
# Render template "example/welcome.html.ep" with message
$self->render(msg => 'accepted');
}
1;