lemonldap-ng/lemonldap-ng-common/lib/Lemonldap/NG/Common/Notifications/JSON.pm

92 lines
2.2 KiB
Perl
Raw Normal View History

2017-01-31 23:10:26 +01:00
package Lemonldap::NG::Common::Notifications::JSON;
use strict;
use Mouse;
use JSON qw(from_json to_json);
2017-02-28 21:53:19 +01:00
our $VERSION = '2.0.0';
2017-01-31 23:10:26 +01:00
sub newNotification {
2017-02-01 07:16:33 +01:00
my ( $self, $jsonString ) = @_;
my $json;
eval { $json = from_json($jsonString) };
if ( my $err = $@ ) {
2017-02-15 07:41:50 +01:00
eval { $self->logger->error("Unable to decode JSON file: $err") };
2017-01-31 23:10:26 +01:00
return 0;
}
my @notifs;
$json = [$json] unless ( ref($json) eq 'ARRAY' );
foreach my $notif (@$json) {
my @datas;
# Mandatory information
foreach (qw(date uid reference)) {
my $tmp;
unless ( $tmp = $notif->{$_} ) {
2017-02-15 07:41:50 +01:00
$self->logger->error("Attribute $_ is missing");
2017-01-31 23:10:26 +01:00
return 0;
}
push @datas, $tmp;
}
push @datas, ( $notif->{condition} // '' );
2017-02-02 07:08:40 +01:00
push @notifs, [ @datas, $jsonString ];
2017-01-31 23:10:26 +01:00
}
my $count;
foreach (@notifs) {
$count++;
my ( $r, $err ) = $self->newNotif(@$_);
die "$err" unless ($r);
}
return $count;
}
sub deleteNotification {
my ( $self, $uid, $myref ) = @_;
my @data;
# Check input parameters
unless ( $uid and $myref ) {
2017-02-15 07:41:50 +01:00
$self->userLogger->error(
'REST service "delete notification" called without all parameters'
2017-01-31 23:10:26 +01:00
);
return 0;
}
2017-02-15 07:41:50 +01:00
$self->logger->debug(
"REST service deleteNotification called for uid $uid and reference $myref"
2017-01-31 23:10:26 +01:00
);
# Get notifications
my $user = $self->get($uid);
# Return 0 if no files were found
return 0 unless ($user);
# Counting
my $count = 0;
foreach my $ref ( keys %$user ) {
my $json = from_json( $user->{$ref} );
# Browse notification in file
foreach my $notif (@$json) {
# Get notification's data
if ( $notif->{reference} eq $myref ) {
push @data, $ref;
}
# Delete the notification (really)
foreach (@data) {
if ( $self->purge( $_, 1 ) ) {
2017-02-15 07:41:50 +01:00
$self->logger->debug("Notification $_ was removed.");
2017-01-31 23:10:26 +01:00
$count++;
}
}
}
}
return $count;
}
1;