Debian Codegraph @

lemonldap-ng-manager/lib/Lemonldap/NG/Manager/Notifications.pm

raw
1 package Lemonldap::NG::Manager::Notifications;
2
3 use strict;
4 use utf8;
5 use Mouse;
6 use JSON qw(from_json to_json);
7 use POSIX qw(strftime);
8 use MIME::Base64 qw(decode_base64);
9
10 use Lemonldap::NG::Common::Conf::Constants;
11 use Lemonldap::NG::Common::PSGI::Constants;
12 use Lemonldap::NG::Common::Conf::ReConstants;
13 require Lemonldap::NG::Common::Notifications;
14
15 extends qw(
16 Lemonldap::NG::Manager::Plugin
17 Lemonldap::NG::Common::PSGI::Router
18 Lemonldap::NG::Common::Conf::AccessLib
19 );
20
21 our $VERSION = '2.23.0';
22
23 has notifAccess => ( is => 'rw' );
24 has notifFormat => ( is => 'rw' );
25
26 #############################
27 # I. INITIALIZATION METHODS #
28 #############################
29
30 use constant defaultRoute => 'notifications.html';
31 use constant icon => 'bell';
32
33 sub init {
34 my ( $self, $conf ) = @_;
35
36 if ( $conf->{oldNotifFormat} ) {
37 Lemonldap::NG::Common::Notifications->import('XML');
38 $self->notifFormat('XML');
39 }
40 else {
41 Lemonldap::NG::Common::Notifications->import('JSON');
42 $self->notifFormat('JSON');
43 }
44
45 unless ( $self->setNotifAccess($conf) ) {
46 $self->addRoute( 'notifications.html', 'notEnabled', ['GET'] );
47 $self->addRoute( notifications => 'notEnabled', ['GET'] );
48 return ( $self->error ? 0 : 1 );
49 }
50 $self->{multiValuesSeparator} ||= '; ';
51
52 # HTML template
53 $self->addRoute( 'notifications.html', undef, ['GET'] )
54
55 # READ
56 ->addRoute(
57 'notifications' =>
58 { actives => 'activeNotifications', done => 'doneNotifications' },
59 ['GET']
60 )
61
62 # Create new notification
63 ->addRoute(
64 'notifications' => { actives => 'newNotification' },
65 ['POST']
66 )
67
68 # Update a notification (mark as done)
69 ->addRoute(
70 notifications =>
71 { actives => { ':notificationId' => 'updateNotification' } },
72 ['PUT']
73 )
74
75 # Delete a notification
76 ->addRoute(
77 notifications =>
78 { done => { ':notificationId' => 'deleteDoneNotification' } },
79 ['DELETE']
80 );
81 return 1;
82 }
83
84 sub setNotifAccess {
85 my ( $self, $conf ) = @_;
86
87 # TODO: refresh system
88 $self->{$_} //= $conf->{$_}
89 foreach (
90 qw/portal notification notificationStorage notificationStorageOptions/);
91
92 unless ( $self->{notification} ) {
93 return 0;
94 }
95
96 # TODO: old parameters (with table)
97 unless ( $self->{notificationStorage} ) {
98 $self->handlerAbort( notifications =>
99 'notificationStorage is not defined in configuration' );
100 return 0;
101 }
102 my $type =
103 "Lemonldap::NG::Common::Notifications::$self->{notificationStorage}";
104 $type =~ s/(?:C|R)DBI$/DBI/;
105 eval "require $type";
106 if ($@) {
107 $self->handlerAbort( notifications => "Unable to load $type: $@" );
108 return 0;
109 }
110
111 # Force table name
112 unless (
113 eval {
114 $self->notifAccess(
115 $type->new( {
116 %{ $self->{notificationStorageOptions} },
117 p => $self,
118 conf => $self
119 }
120 )
121 );
122 }
123 )
124 {
125 $self->handlerAbort( notifications => $@ );
126 return 0;
127 }
128 return $self->notifAccess();
129 }
130
131 #######################
132 # II. DISPLAY METHODS #
133 #######################
134
135 sub notEnabled {
136 my ( $self, $req ) = @_;
137 return $self->sendError( $req,
138 'Notifications are not enabled in your configuration', 400 );
139 }
140
141 sub activeNotifications {
142 my ( $self, $req, $notif ) = @_;
143 return $self->notifications( $req, $notif, 'actives' );
144 }
145
146 sub doneNotifications {
147 my ( $self, $req, $notif ) = @_;
148 return $self->notifications( $req, $notif, 'done' );
149 }
150
151 sub notifications {
152 my ( $self, $req, $notif, $type ) = @_;
153 my $sub = { actives => 'getAll', done => 'getDone' }->{$type}
154 or die "Unknown type $type";
155
156 # Case 1: a notification is required
157 if ($notif) {
158 my $params = $req->parameters();
159 return $self->notification( $req, $notif, $type, $params->{uid},
160 $params->{reference} );
161 }
162
163 # Case 2: list
164 my $params = $req->parameters();
165 my ( $notifs, $res );
166
167 $notifs = $self->notifAccess->$sub();
168 my $total = ( keys %$notifs );
169
170 # Restrict to wanted values
171 if (
172 my %filters =
173 map { /^(?:(?:group|order)By)$/ ? () : ( $_ => $params->{$_} ); }
174 keys %$params
175 )
176 {
177 while ( my ( $field, $value ) = each %filters ) {
178 $value =~ s/\*/\.\*/g;
179 $value = qr/^$value$/;
180 foreach my $k ( keys %$notifs ) {
181 delete $notifs->{$k}
182 unless ( $notifs->{$k}->{$field}
183 && $notifs->{$k}->{$field} =~ $value );
184 }
185 }
186 }
187
188 if ( my $groupBy = $req->params('groupBy') ) {
189 my ( $length, $start, $r ) = ( 0, 0 );
190 if ( $groupBy =~ /^substr\((\w+)(?:,(\d+)(?:,(\d+))?)?\)$/ ) {
191 ( $groupBy, $length, $start ) = ( $1, $2, $3 );
192 $start ||= 0;
193 $length = 1 if ( $length < 1 );
194 }
195 foreach my $k ( keys %$notifs ) {
196 my $s =
197 $length
198 ? substr( $notifs->{$k}->{$groupBy}, $start, $length )
199 : $notifs->{$k}->{$groupBy};
200 $r->{$s}++;
201 }
202 my $count = 0;
203 $res = [
204 map { $count += $r->{$_}; { value => $_, count => $r->{$_} } }
205 sort keys %$r
206 ];
207 return $self->sendJSONresponse(
208 $req,
209 {
210 result => 1,
211 count => $count,
212 values => $res,
213 total => $total
214 }
215 );
216 }
217 else {
218 my @r = map {
219 my $r = { notification => $_ };
220 foreach my $k (qw(uid date condition)) {
221 $r->{$k} = $notifs->{$_}->{$k};
222 }
223 $r->{reference} = $notifs->{$_}->{ref};
224 $r;
225 } keys %$notifs;
226
227 if ( my $orderBy = $req->params('orderBy') ) {
228 my @fields = split /,/, $orderBy;
229 while ( my $f = pop @fields ) {
230 @r = sort { $a->{$f} cmp $b->{$f} } @r;
231 }
232 }
233 return $self->sendJSONresponse(
234 $req,
235 {
236 result => 1,
237 count => scalar(@r),
238 values => \@r,
239 total => $total
240 }
241 );
242 }
243 }
244
245 sub notification {
246 my ( $self, $req, $id, $type ) = @_;
247 my $backend = $self->{notificationStorage};
248 $self->logger->debug("Notification storage backend: $backend");
249 $self->logger->debug("Notification id: $id");
250
251 if ( $type eq 'actives' ) {
252 my ( $uid, $ref ) = ( $id =~ /([^_]+?)_(.+)/ );
253 my $n = $self->notifAccess->get( $uid, $ref );
254 unless ($n) {
255 $self->logger->notice(
256 "Active notification $ref not found for user $uid");
257 return $self->sendJSONresponse(
258 $req,
259 {
260 result => 0,
261 error => "Active notification $ref not found for user $uid"
262 }
263 );
264 }
265 $self->logger->debug("Active notification $ref found for user $uid");
266 return $self->sendJSONresponse( $req,
267 { result => 1, count => 1, notifications => [ values %$n ] } );
268 }
269 else {
270 my ( $date, $uid, $ref ) =
271 $backend eq 'File'
272 ? ( $id =~ /([^_]+?)_(.+?)_(.+?)\.done/ )
273 : ( $id =~ /([^_]+?)_(.+?)_(.+)/ );
274 $ref = decode_base64($ref) if ( $backend eq 'File' );
275 my $n = $self->notifAccess->getAccepted( $uid, $ref );
276 unless ($n) {
277 my $msg =
278 $ref && $uid
279 ? "Done notification $ref not found for user $uid"
280 : 'Done notification not found';
281 $self->logger->notice($msg);
282 return $self->sendJSONresponse(
283 $req,
284 {
285 result => 0,
286 error => $msg
287 }
288 );
289 }
290 $self->logger->debug("Done notification $ref found for user $uid");
291 return $self->sendJSONresponse(
292 $req,
293 {
294 result => 1,
295 count => 1,
296 done => $id,
297 notifications => [ values %$n ]
298 }
299 );
300 }
301 }
302
303 sub newNotification {
304 my ( $self, $req, @other ) = @_;
305 return $self->sendError( $req,
306 'There is no subkey for "newNotification"', 200 )
307 if (@other);
308
309 my $json = $req->jsonBodyToObj;
310 unless ( defined($json) ) {
311 return $self->sendError( $req, undef, 200 );
312 }
313
314 $json->{reference} =~ s/_/-/g; # Remove underscores (#2135)
315
316 foreach my $r (qw(uid reference xml)) {
317 return $self->sendError( $req, "Missing $r", 200 )
318 unless ( $json->{$r} );
319 }
320
321 # Set default date value
322 my $dDate = strftime( "%Y-%m-%d", localtime() );
323 if ( $json->{date} ) {
324 $self->logger->debug(
325 "Posted data : uid = $json->{uid} - Ref = $json->{reference} - Date = $json->{date}"
326 );
327 }
328 else {
329 $self->logger->debug(
330 "Posted data : uid = $json->{uid} - Ref = $json->{reference} - Date = ???"
331 );
332 $json->{date} = $dDate;
333 }
334
335 # Check if posted date > today
336 unless ( $json->{date} ge $dDate ) {
337 $self->logger->debug("Posted Date < today");
338 $json->{date} = $dDate;
339 }
340 $self->logger->debug("Notification Date = $json->{date}");
341
342 unless ( $json->{date} =~ /^\d{4}-\d{2}-\d{2}$/ ) {
343 $self->logger->error("Malformed date");
344 return $self->sendError( $req, "Malformed date", 200 );
345 }
346
347 my $newNotif;
348 if ( $self->notifFormat eq 'XML' ) {
349 utf8::decode( $json->{xml} );
350 $newNotif = qq#<?xml version='1.0' encoding='UTF-8' standalone='no'?>
351 <root><notification #
352 . join(
353 ' ',
354 map {
355 if ( my $t = $json->{$_} ) { $t =~ s/"/'/g; qq#$_="$t"# }
356 else { () }
357 } (qw(uid date reference condition))
358 ) . ">$json->{xml}</notification></root>";
359 }
360 else {
361 eval {
362 my $tmp = from_json( $json->{xml}, { allow_nonref => 1 } );
363 $json->{$_} = $tmp->{$_} foreach ( keys %$tmp );
364 delete $json->{xml};
365 };
366 if ($@) {
367 $self->logger->error("Malformed notification $@");
368 return $self->sendError( $req, "Malformed notification: $@", 200 );
369 }
370 $newNotif = to_json($json);
371 }
372
373 unless ( eval { $self->notifAccess->newNotification($newNotif) } ) {
374 $self->logger->error("Notification not created: $@");
375 return $self->sendError( $req, "Notification not created: $@", 200 );
376 }
377 else {
378 return $self->sendJSONresponse( $req, { result => 1 } );
379 }
380 }
381
382 sub updateNotification {
383 my ( $self, $req ) = @_;
384
385 my $json = $req->jsonBodyToObj;
386 unless ( defined($json) ) {
387 return $self->sendError( $req, undef, 200 );
388 }
389
390 # For now, only "mark as done" is proposed
391 unless ( $json->{done} ) {
392 return $self->sendError( $req, 'Only "done=1" is accepted for now',
393 200 );
394 }
395 my $id = $req->params('notificationId') or die;
396 my ( $uid, $ref ) = ( $id =~ /([^_]+?)_(.+)/ );
397 my ( $n, $res );
398 unless ( $n = $self->notifAccess->get( $uid, $ref ) ) {
399 $self->logger->notice("Notification $ref not found for user $uid");
400 return $self->sendError( $req,
401 "Notification $ref not found for user $uid" );
402 }
403
404 # Delete notifications
405 my $status = 1;
406 foreach ( keys %$n ) {
407 $status = 0 unless ( $self->notifAccess->delete($_) );
408 }
409
410 unless ($status) {
411 $self->logger->error("Notification $ref for user $uid not deleted");
412 return $self->sendError( $req,
413 "Notification $ref for user $uid not deleted" );
414 }
415
416 else {
417 $self->logger->info("Notification $ref deleted for user $uid");
418 return $self->sendJSONresponse( $req, { result => 1 } );
419 }
420 }
421
422 sub deleteDoneNotification {
423 my ( $self, $req ) = @_;
424 my $res;
425
426 # Purge notification
427 my $id = $req->params('notificationId') or die;
428 my ( $uid, $ref, $date ) = ( $id =~ /([^_]+?)_([^_]+?)_(.+)/ );
429 my $identifier = $self->notifAccess->getIdentifier( $uid, $ref, $date );
430 unless ( eval { $self->notifAccess->purge($identifier) } ) {
431 $self->logger->warn("Notification $identifier not purged ($@)");
432 return $self->sendError( $req,
433 "Notification $identifier not purged ($@)", 400 );
434 }
435
436 $self->logger->info("Notification $identifier purged");
437 return $self->sendJSONresponse( $req, { result => 1 } );
438 }
439
440 1;