MT#6497 API cfdestinationsets

agranig/subprof
Gerhard Jungwirth 12 years ago
parent 64015835d5
commit d4cf98646d

@ -0,0 +1,240 @@
package NGCP::Panel::Controller::API::CFDestinationSets;
use Sipwise::Base;
use namespace::sweep;
use boolean qw(true);
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Headers qw();
use HTTP::Status qw(:constants);
use MooseX::ClassAttribute qw(class_has);
use NGCP::Panel::Utils::DateTime;
BEGIN { extends 'Catalyst::Controller::ActionRole'; }
require Catalyst::ActionRole::ACL;
require Catalyst::ActionRole::CheckTrailingSlash;
require Catalyst::ActionRole::HTTPMethods;
require Catalyst::ActionRole::RequireSSL;
class_has 'api_description' => (
is => 'ro',
isa => 'Str',
default =>
'Defines a collection of CallForward Destination Sets, including their destination, which can be set '.
'to define CallForwards using <a href="#cfmappings">CFMappings</a>.',
);
class_has 'query_params' => (
is => 'ro',
isa => 'ArrayRef',
default => sub {[
{
param => 'subscriber_id',
description => 'Filter for destination sets belonging to a specific subscriber',
query => {
first => sub {
my $q = shift;
{ subscriber_id => $q };
},
second => sub {},
},
},
{
param => 'name',
description => 'Filter for contacts matching a destination set name pattern',
query => {
first => sub {
my $q = shift;
{ name => { like => $q } };
},
second => sub {},
},
},
]},
);
with 'NGCP::Panel::Role::API::CFDestinationSets';
class_has('resource_name', is => 'ro', default => 'cfdestinationsets');
class_has('dispatch_path', is => 'ro', default => '/api/cfdestinationsets/');
class_has('relation', is => 'ro', default => 'http://purl.org/sipwise/ngcp-api/#rel-cfdestinationsets');
__PACKAGE__->config(
action => {
map { $_ => {
ACLDetachTo => '/api/root/invalid_user',
AllowedRole => [qw/admin reseller/],
Args => 0,
Does => [qw(ACL CheckTrailingSlash RequireSSL)],
Method => $_,
Path => __PACKAGE__->dispatch_path,
} } @{ __PACKAGE__->allowed_methods },
},
action_roles => [qw(HTTPMethods)],
);
sub auto :Private {
my ($self, $c) = @_;
$self->set_body($c);
$self->log_request($c);
return 1;
}
sub GET :Allow {
my ($self, $c) = @_;
my $page = $c->request->params->{page} // 1;
my $rows = $c->request->params->{rows} // 10;
{
my $dsets = $self->item_rs($c);
my $total_count = int($dsets->count);
$dsets = $dsets->search(undef, {
page => $page,
rows => $rows,
});
my (@embedded, @links);
for my $dset ($dsets->search({}, {order_by => {-asc => 'me.id'}})->all) {
push @embedded, $self->hal_from_item($c, $dset, "cfdestinationsets");
push @links, Data::HAL::Link->new(
relation => 'ngcp:'.$self->resource_name,
href => sprintf('%s%d', $self->dispatch_path, $dset->id),
);
}
push @links,
Data::HAL::Link->new(
relation => 'curies',
href => 'http://purl.org/sipwise/ngcp-api/#rel-{rel}',
name => 'ngcp',
templated => true,
),
Data::HAL::Link->new(relation => 'profile', href => 'http://purl.org/sipwise/ngcp-api/'),
Data::HAL::Link->new(relation => 'self', href => sprintf('%s?page=%s&rows=%s', $self->dispatch_path, $page, $rows));
if(($total_count / $rows) > $page ) {
push @links, Data::HAL::Link->new(relation => 'next', href => sprintf('%s?page=%d&rows=%d', $self->dispatch_path, $page + 1, $rows));
}
if($page > 1) {
push @links, Data::HAL::Link->new(relation => 'prev', href => sprintf('%s?page=%d&rows=%d', $self->dispatch_path, $page - 1, $rows));
}
my $hal = Data::HAL->new(
embedded => [@embedded],
links => [@links],
);
$hal->resource({
total_count => $total_count,
});
my $response = HTTP::Response->new(HTTP_OK, undef,
HTTP::Headers->new($hal->http_headers(skip_links => 1)), $hal->as_json);
$c->response->headers($response->headers);
$c->response->body($response->content);
return;
}
return;
}
sub HEAD :Allow {
my ($self, $c) = @_;
$c->forward(qw(GET));
$c->response->body(q());
return;
}
sub OPTIONS :Allow {
my ($self, $c) = @_;
my $allowed_methods = $self->allowed_methods;
$c->response->headers(HTTP::Headers->new(
Allow => $allowed_methods->join(', '),
Accept_Post => 'application/hal+json; profile=http://purl.org/sipwise/ngcp-api/#rel-'.$self->resource_name,
));
$c->response->content_type('application/json');
$c->response->body(JSON::to_json({ methods => $allowed_methods })."\n");
return;
}
sub POST :Allow {
my ($self, $c) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $schema = $c->model('DB');
my $resource = $self->get_valid_post_data(
c => $c,
media_type => 'application/json',
);
last unless $resource;
my $form = $self->get_form($c);
last unless $self->validate_form(
c => $c,
resource => $resource,
form => $form,
);
my $dset;
unless(defined $resource->{subscriber_id}) {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Required: 'subscriber_id'");
last;
}
my $subscriber = $schema->resultset('provisioning_voip_subscribers')->find({
id => $resource->{subscriber_id},
});
unless($subscriber) {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid 'subscriber_id'.");
last;
}
if (! exists $resource->{destinations} ) {
$resource->{destinations} = [];
}
if (ref $resource->{destinations} ne "ARRAY") {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid field 'destinations'. Must be an array.");
last;
}
try {
my $primary_nr_rs = $subscriber->voip_subscriber->primary_number;
my $number;
if ($primary_nr_rs) {
$number = $primary_nr_rs->cc . ($primary_nr_rs->ac //'') . $primary_nr_rs->sn;
} else {
$number = ''
}
my $domain = $subscriber->domain->domain // '';
$dset = $schema->resultset('voip_cf_destination_sets')->create({
name => $resource->{name},
subscriber_id => $resource->{subscriber_id},
});
for my $d ( @{$resource->{destinations}} ) {
delete $d->{destination_set_id};
$d->{destination} = NGCP::Panel::Utils::Subscriber::field_to_destination(
destination => $d->{destination},
number => $number,
domain => $domain,
uri => $d->{destination},
);
$dset->create_related("voip_cf_destinations", $d);
}
} catch($e) {
$c->log->error("failed to create cfdestinationset: $e");
$self->error($c, HTTP_INTERNAL_SERVER_ERROR, "Failed to create cfdestinationset.");
last;
}
$guard->commit;
$c->response->status(HTTP_CREATED);
$c->response->header(Location => sprintf('/%s%d', $c->request->path, $dset->id));
$c->response->body(q());
}
return;
}
sub end : Private {
my ($self, $c) = @_;
$self->log_response($c);
return 1;
}
# vim: set tabstop=4 expandtab:

@ -0,0 +1,200 @@
package NGCP::Panel::Controller::API::CFDestinationSetsItem;
use Sipwise::Base;
use namespace::sweep;
use boolean qw(true);
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Headers qw();
use HTTP::Status qw(:constants);
use MooseX::ClassAttribute qw(class_has);
use NGCP::Panel::Utils::ValidateJSON qw();
use NGCP::Panel::Utils::DateTime;
use Path::Tiny qw(path);
use Safe::Isa qw($_isa);
BEGIN { extends 'Catalyst::Controller::ActionRole'; }
require Catalyst::ActionRole::ACL;
require Catalyst::ActionRole::HTTPMethods;
require Catalyst::ActionRole::RequireSSL;
with 'NGCP::Panel::Role::API::CFDestinationSets';
class_has('resource_name', is => 'ro', default => 'cfdestinationsets');
class_has('dispatch_path', is => 'ro', default => '/api/cfdestinationsets/');
class_has('relation', is => 'ro', default => 'http://purl.org/sipwise/ngcp-api/#rel-cfdestinationsets');
__PACKAGE__->config(
action => {
map { $_ => {
ACLDetachTo => '/api/root/invalid_user',
AllowedRole => [qw/admin reseller/],
Args => 1,
Does => [qw(ACL RequireSSL)],
Method => $_,
Path => __PACKAGE__->dispatch_path,
} } @{ __PACKAGE__->allowed_methods },
},
action_roles => [qw(HTTPMethods)],
);
sub auto :Private {
my ($self, $c) = @_;
$self->set_body($c);
$self->log_request($c);
return 1;
}
sub GET :Allow {
my ($self, $c, $id) = @_;
{
last unless $self->valid_id($c, $id);
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, dset => $dset);
my $hal = $self->hal_from_item($c, $dset, "cfdestinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
(map { # XXX Data::HAL must be able to generate links with multiple relations
s|rel="(http://purl.org/sipwise/ngcp-api/#rel-resellers)"|rel="item $1"|r
=~ s/rel=self/rel="item self"/r;
} $hal->http_headers),
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->body($response->content);
return;
}
return;
}
sub HEAD :Allow {
my ($self, $c, $id) = @_;
$c->forward(qw(GET));
$c->response->body(q());
return;
}
sub OPTIONS :Allow {
my ($self, $c, $id) = @_;
my $allowed_methods = $self->allowed_methods;
$c->response->headers(HTTP::Headers->new(
Allow => $allowed_methods->join(', '),
Accept_Patch => 'application/json-patch+json',
));
$c->response->content_type('application/json');
$c->response->body(JSON::to_json({ methods => $allowed_methods })."\n");
return;
}
sub PATCH :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $preference = $self->require_preference($c);
last unless $preference;
my $json = $self->get_valid_patch_data(
c => $c,
id => $id,
media_type => 'application/json-patch+json',
ops => [qw/add replace remove copy/],
);
last unless $json;
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, destinationset => $dset);
my $old_resource = $self->hal_from_item($c, $dset, "destinationsets")->resource;
my $resource = $self->apply_patch($c, $old_resource, $json);
last unless $resource;
my $form = $self->get_form($c);
$dset = $self->update_item($c, $dset, $old_resource, $resource, $form);
last unless $dset;
$guard->commit;
if ('minimal' eq $preference) {
$c->response->status(HTTP_NO_CONTENT);
$c->response->header(Preference_Applied => 'return=minimal');
$c->response->body(q());
} else {
my $hal = $self->hal_from_item($c, $dset, "destinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
$hal->http_headers,
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->header(Preference_Applied => 'return=representation');
$c->response->body($response->content);
}
}
return;
}
sub PUT :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $preference = $self->require_preference($c);
last unless $preference;
my $dset = $self->item_by_id($c, $id);
last unless $self->resource_exists($c, destinationset => $dset);
my $resource = $self->get_valid_put_data(
c => $c,
id => $id,
media_type => 'application/json',
);
last unless $resource;
my $old_resource = { $dset->get_inflated_columns };
my $form = $self->get_form($c);
$dset = $self->update_item($c, $dset, $old_resource, $resource, $form);
last unless $dset;
$guard->commit;
if ('minimal' eq $preference) {
$c->response->status(HTTP_NO_CONTENT);
$c->response->header(Preference_Applied => 'return=minimal');
$c->response->body(q());
} else {
my $hal = $self->hal_from_item($c, $dset, "destinationsets");
my $response = HTTP::Response->new(HTTP_OK, undef, HTTP::Headers->new(
$hal->http_headers,
), $hal->as_json);
$c->response->headers($response->headers);
$c->response->header(Preference_Applied => 'return=representation');
$c->response->body($response->content);
}
}
return;
}
sub DELETE :Allow {
my ($self, $c, $id) = @_;
my $guard = $c->model('DB')->txn_scope_guard;
{
my $rule = $self->item_by_id($c, $id, "rules");
last unless $self->resource_exists($c, rule => $rule);
try {
$rule->delete;
} catch($e) {
$c->log->error("Failed to delete rewriterule with id '$id': $e");
$self->error($c, HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error");
last;
}
$guard->commit;
$c->response->status(HTTP_NO_CONTENT);
$c->response->body(q());
}
return;
}
sub end : Private {
my ($self, $c) = @_;
$self->log_response($c);
return 1;
}
# vim: set tabstop=4 expandtab:

@ -0,0 +1,53 @@
package NGCP::Panel::Form::CFDestinationSetAPI;
use HTML::FormHandler::Moose;
use HTML::FormHandler::Widget::Block::Bootstrap;
use Moose::Util::TypeConstraints;
extends 'HTML::FormHandler';
has_field 'id' => (
type => 'Hidden',
);
has_field 'subscriber' => ( # Workaround for validate_form
type => 'Compound',
);
has_field 'subscriber.id' => (
type => 'PosInteger',
);
has_field 'name' => (
type => 'Text',
label => 'Name',
wrapper_class => [qw/hfh-rep-field/],
required => 1,
);
has_field 'destinations' => (
type => 'Repeatable',
);
has_field 'destinations.id' => (
type => 'Hidden',
);
has_field 'destinations.destination' => (
type => 'Text',
label => 'Destination',
);
has_field 'destinations.timeout' => (
type => '+NGCP::Panel::Field::PosInteger',
label => 'for (seconds)',
default => 300,
);
has_field 'destinations.priority' => (
type => '+NGCP::Panel::Field::PosInteger',
label => 'Priority',
default => 1,
);
1;
# vim: set tabstop=4 expandtab:

@ -0,0 +1,157 @@
package NGCP::Panel::Role::API::CFDestinationSets;
use Moose::Role;
use Sipwise::Base;
with 'NGCP::Panel::Role::API' => {
-alias =>{ item_rs => '_item_rs', },
-excludes => [ 'item_rs' ],
};
use boolean qw(true);
use TryCatch;
use Data::HAL qw();
use Data::HAL::Link qw();
use HTTP::Status qw(:constants);
use JSON::Types;
use NGCP::Panel::Utils::Subscriber;
use NGCP::Panel::Form::CFDestinationSetAPI;
sub get_form {
my ($self, $c) = @_;
return NGCP::Panel::Form::CFDestinationSetAPI->new;
}
sub hal_from_item {
my ($self, $c, $item, $type) = @_;
my $form;
my %resource = $item->get_inflated_columns;
my @destinations;
for my $dest ($item->voip_cf_destinations->all) {
my ($d, $duri) = NGCP::Panel::Utils::Subscriber::destination_to_field($dest->destination);
$d = $duri if $d eq "uri";
my $destelem = {$dest->get_inflated_columns,
destination => $d,
};
delete @{$destelem}{'id', 'destination_set_id'};
push @destinations, $destelem;
}
$resource{destinations} = \@destinations;
my $b_subs_id = $item->subscriber->voip_subscriber->id;
my $hal = Data::HAL->new(
links => [
Data::HAL::Link->new(
relation => 'curies',
href => 'http://purl.org/sipwise/ngcp-api/#rel-{rel}',
name => 'ngcp',
templated => true,
),
Data::HAL::Link->new(relation => 'collection', href => sprintf("%s", $self->dispatch_path)),
Data::HAL::Link->new(relation => 'profile', href => 'http://purl.org/sipwise/ngcp-api/'),
Data::HAL::Link->new(relation => 'self', href => sprintf("%s%d", $self->dispatch_path, $item->id)),
Data::HAL::Link->new(relation => "ngcp:$type", href => sprintf("/api/%s/%d", $type, $item->id)),
Data::HAL::Link->new(relation => "ngcp:subscribers", href => sprintf("/api/subscribers/%d", $b_subs_id)),
],
relation => 'ngcp:'.$self->resource_name,
);
$form //= $self->get_form($c);
return unless $self->validate_form(
c => $c,
form => $form,
resource => \%resource,
run => 0,
);
$hal->resource(\%resource);
return $hal;
}
sub item_rs {
my ($self, $c) = @_;
my $item_rs;
if($c->user->roles eq "admin") {
$item_rs = $c->model('DB')->resultset('voip_cf_destination_sets');
} elsif ($c->user->roles eq "reseller") {
}
return $item_rs;
}
sub item_by_id {
my ($self, $c, $id) = @_;
my $item_rs = $self->item_rs($c);
return $item_rs->find($id);
}
sub update_item {
my ($self, $c, $item, $old_resource, $resource, $form) = @_;
delete $resource->{id};
my $schema = $c->model('DB');
return unless $self->validate_form(
c => $c,
form => $form,
resource => $resource,
);
if (! exists $resource->{destinations} ) {
$resource->{destinations} = [];
}
if (ref $resource->{destinations} ne "ARRAY") {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid field 'destinations'. Must be an array.");
return;
}
for my $d (@{ $resource->{destinations} }) {
if (exists $d->{timeout} && ! $d->{timeout}->is_integer) {
$c->log->error("Invalid field 'timeout'.");
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid field 'timeout'.");
return;
}
}
my $subscriber = $schema->resultset('provisioning_voip_subscribers')->find($resource->{subscriber_id});
unless ($subscriber) {
$self->error($c, HTTP_UNPROCESSABLE_ENTITY, "Invalid 'subscriber_id'.");
return;
}
try {
my $primary_nr_rs = $subscriber->voip_subscriber->primary_number;
my $number;
if ($primary_nr_rs) {
$number = $primary_nr_rs->cc . ($primary_nr_rs->ac //'') . $primary_nr_rs->sn;
} else {
$number = ''
}
my $domain = $subscriber->domain->domain // '';
$item->update({
name => $resource->{name},
subscriber_id => $resource->{subscriber_id},
})->discard_changes;
$item->voip_cf_destinations->delete;
for my $d ( @{$resource->{destinations}} ) {
delete $d->{destination_set_id};
$d->{destination} = NGCP::Panel::Utils::Subscriber::field_to_destination(
destination => $d->{destination},
number => $number,
domain => $domain,
uri => $d->{destination},
);
$item->create_related("voip_cf_destinations", $d);
}
} catch($e) {
$c->log->error("failed to create cfdestinationset: $e");
$self->error($c, HTTP_INTERNAL_SERVER_ERROR, "Failed to create cfdestinationset.");
return;
};
return $item;
}
1;
# vim: set tabstop=4 expandtab:

@ -190,7 +190,6 @@ sub update_item {
}
}
for my $d (@{ $resource->{$type}{destinations} }) {
$c->log->debug("fooobar $d");
delete $d->{destination_set_id};
$d->{destination} = NGCP::Panel::Utils::Subscriber::field_to_destination(
destination => $d->{destination},

@ -63,6 +63,7 @@ $ua->ssl_opts(
domainpreferences => 1,
subscribers => 1,
callforwards => 1,
cfdestinationsets => 1,
};
foreach my $link(@links) {
my $rex = qr/^<\/api\/[a-z]+\/>; rel=\"collection http:\/\/purl\.org\/sipwise\/ngcp-api\/#rel-([a-z]+s)\"$/;

Loading…
Cancel
Save