webhook2ntfy/lib/Webhook2Ntfy/Controller/Webhook.pm
Dominik Meyer 6ee392e55e
Some checks failed
continuous-integration/drone Build is failing
ADD: initial commit
2024-03-05 17:47:07 +01:00

106 lines
2.0 KiB
Perl

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));
}
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;
$data->{text} =~ /^<(.*)\|(.+)>\+\-\+(.+)\+<(.*)\|(.*)>\+.*\+by\+(.*)$/;
my $projectUrl=$1;
my $projectName=$2;
my $entity = $3;
my $entityUrl=$4;
my $entityName=$5;
my $author=$6;
$author =~ s/\+/ /g;
my $status;
if ($entity eq "Issue")
{
$entityName=~s/\+/ /g;
}
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;