c72093d00fc1e0d4b13a606bc5dfe53ba7f770b0
[freeside.git] / FS / FS / part_export / netsapiens.pm
1 package FS::part_export::netsapiens;
2
3 use vars qw(@ISA $me %info);
4 use MIME::Base64;
5 use Tie::IxHash;
6 use FS::part_export;
7 use Date::Format qw( time2str );
8 use Regexp::Common qw/URI/;
9
10 @ISA = qw(FS::part_export);
11 $me = '[FS::part_export::netsapiens]';
12
13 #These export options set default values for the various commands
14 #to create/update objects.  Add more options as needed.
15
16 my %tristate = ( type => 'select', options => [ '', 'yes', 'no' ]);
17
18 tie my %subscriber_fields, 'Tie::IxHash',
19   'admin_vmail'     => { label=>'VMail Prov.', %tristate },
20   'dial_plan'       => { label=>'Dial Translation' },
21   'dial_policy'     => { label=>'Dial Permission' },
22   'call_limit'      => { label=>'Call Limit' },
23   'domain_dir'      => { label=>'Dir Lst', %tristate },
24 ;
25
26 tie my %registrar_fields, 'Tie::IxHash',
27   'authenticate_register' => { label=>'Authenticate Registration', %tristate },
28   'authentication_realm'  => { label=>'Authentication Realm' },
29 ;
30
31 tie my %dialplan_fields, 'Tie::IxHash',
32   'responder'       => { label=>'Application' }, #this could be nicer
33   'from_name'       => { label=>'Source Name Translation' },
34   'from_user'       => { label=>'Source User Translation' },
35 ;
36
37 my %features = (
38   'for' => 'Forward',
39   'fnr' => 'Forward Not Registered',
40   'fna' => 'Forward No Answer',
41   'fbu' => 'Forward Busy',
42   'dnd' => 'Do-Not-Disturb',
43   'sim' => 'Simultaneous Ring',
44 );
45
46 my %feature_param = (
47   'dnd' => 'n/a',
48   'sim' => '$phonenum',
49 );
50
51 tie my %options, 'Tie::IxHash',
52   'login'           => { label=>'NetSapiens tac2 User API username' },
53   'password'        => { label=>'NetSapiens tac2 User API password' },
54   'url'             => { label=>'NetSapiens tac2 User URL' },
55   'device_login'    => { label=>'NetSapiens tac2 Device API username' },
56   'device_password' => { label=>'NetSapiens tac2 Device API password' },
57   'device_url'      => { label=>'NetSapiens tac2 Device URL' },
58   'domain'          => { label=>'NetSapiens Domain' },
59   'domain_no_tld'   => { label=>'Omit TLD from domains', type=>'checkbox' },
60   'debug'           => { label=>'Enable debugging', type=>'checkbox' },
61   %subscriber_fields,
62   'features'        => { label        => 'Default features',
63                          type         => 'select',
64                          multiple     => 1,
65                          options      => [ keys %features ],
66                          option_label => sub { $features{$_[0]}; },
67                        },
68   %registrar_fields,
69   %dialplan_fields,
70   'did_countrycode' => { label=>'Use country code in DID destination',
71                          type =>'checkbox' },
72 ;
73
74 %info = (
75   'svc'        => [qw( svc_phone part_device )],
76   'desc'       => 'Provision phone numbers to NetSapiens',
77   'options'    => \%options,
78   'no_machine' => 1,
79   'notes'      => <<'END'
80 Requires installation of
81 <a href="http://search.cpan.org/dist/REST-Client">REST::Client</a>
82 from CPAN.
83 END
84 );
85
86 # http://devguide.netsapiens.com/
87
88 sub rebless { shift; }
89
90
91 sub check_options {
92   my ($self, $options) = @_;
93         
94   my $rex = qr/$RE{URI}{HTTP}{-scheme => qr|https?|}/;                  # match any "http:" or "https:" URL
95         
96   for my $key (qw/url device_url/) {
97     if ($$options{$key} && ($$options{$key} !~ $rex)) {
98       return "Invalid (URL): " . $$options{$key};
99     }
100   }
101   return '';
102 }
103
104
105
106 sub ns_command {
107   my $self = shift;
108   $self->_ns_command('', @_);
109 }
110
111 sub ns_device_command { 
112   my $self = shift;
113   $self->_ns_command('device_', @_);
114 }
115
116 sub _ns_command {
117   my( $self, $prefix, $method, $command ) = splice(@_,0,4);
118
119   # kludge to curb excessive paranoia in LWP 6.0+
120   local $ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
121   eval 'use REST::Client';
122   die $@ if $@;
123
124   my $ns = new REST::Client 'host'=>$self->option($prefix.'url');
125
126   my @args = ( $command );
127
128   if ( $method eq 'PUT' ) {
129     my $content = $ns->buildQuery( { @_ } );
130     $content =~ s/^\?//;
131     push @args, $content;
132   } elsif ( $method eq 'GET' ) {
133     $args[0] .= $ns->buildQuery( { @_ } );
134   }
135
136   warn "$me $method ". $self->option($prefix.'url'). join(', ', @args). "\n"
137     if $self->option('debug');
138
139   my $auth = encode_base64( $self->option($prefix.'login'). ':'.
140                             $self->option($prefix.'password')    );
141   push @args, { 'Authorization' => "Basic $auth" };
142
143   $ns->$method( @args );
144   $ns;
145 }
146
147 sub ns_domain {
148   my($self, $svc_phone) = (shift, shift);
149   my $domain = $svc_phone->domain || $self->option('domain');
150
151   $domain =~ s/\.\w{2,4}$//
152     if $self->option('domain_no_tld');
153   
154   $domain;
155 }
156
157 sub ns_subscriber {
158   my($self, $svc_phone) = (shift, shift);
159
160   my $domain = $self->ns_domain($svc_phone);
161   my $phonenum = $svc_phone->phonenum;
162
163   "/domains_config/$domain/subscriber_config/$phonenum";
164 }
165
166 sub ns_registrar {
167   my($self, $svc_phone) = (shift, shift);
168
169   $self->ns_subscriber($svc_phone).
170     '/registrar_config/'. $self->ns_devicename($svc_phone);
171 }
172
173 sub ns_feature {
174   my($self, $svc_phone, $feature) = (shift, shift, shift);
175
176   $self->ns_subscriber($svc_phone).
177     "/feature_config/$feature,*,*,*,*";
178
179 }
180
181 sub ns_devicename {
182   my( $self, $svc_phone ) = (shift, shift);
183
184   my $domain = $self->ns_domain($svc_phone);
185   #my $countrycode = $svc_phone->countrycode;
186   my $phonenum    = $svc_phone->phonenum;
187
188   #"sip:$countrycode$phonenum\@$domain";
189   "sip:$phonenum\@$domain";
190 }
191
192 sub ns_dialplan {
193   my($self, $svc_phone) = (shift, shift);
194
195   my $countrycode = $svc_phone->countrycode || '1';
196   my $phonenum    = $svc_phone->phonenum;
197   # Only in the dialplan destination, nowhere else
198   if ( $self->option('did_countrycode') ) {
199     $phonenum = $countrycode . $phonenum;
200   }
201
202   #"/dialplans/DID+Table/dialplan_config/sip:$countrycode$phonenum\@*"
203   "/domains_config/admin-only/dialplans/DID+Table/dialplan_config/sip:$phonenum\@*,*,*,*,*,*,*";
204 }
205
206 sub ns_device {
207   my($self, $svc_phone, $phone_device ) = (shift, shift, shift);
208
209   #my $countrycode = $svc_phone->countrycode;
210   #my $phonenum    = $svc_phone->phonenum;
211
212   "/phones_config/". lc($phone_device->mac_addr);
213 }
214
215 sub ns_create_or_update {
216   my($self, $svc_phone, $dial_policy) = (shift, shift, shift);
217
218   my $domain = $self->ns_domain($svc_phone);
219   #my $countrycode = $svc_phone->countrycode;
220   my $phonenum    = $svc_phone->phonenum;
221
222   #deal w/unaudited netsapiens services?
223   my $cust_main = $svc_phone->cust_svc->cust_pkg->cust_main;
224
225   my( $firstname, $lastname );
226   if ( $svc_phone->phone_name =~ /^\s*(\S+)\s+(\S.*\S)\s*$/ ) {
227     $firstname = $1;
228     $lastname  = $2;
229   } else {
230     $firstname = $cust_main->get('first');
231     $lastname  = $cust_main->get('last');
232   }
233
234   my ($email) = ($cust_main->invoicing_list_emailonly, '');
235   my $custnum = $cust_main->custnum;
236
237   ###
238   # Piece 1 (already done) - User creation
239   ###
240   
241   $phonenum =~ /^(\d{3})/;
242   my $area_code = $1;
243
244   my $ns = $self->ns_command( 'PUT', $self->ns_subscriber($svc_phone), 
245     'subscriber_login' => $phonenum.'@'.$domain,
246     'firstname'        => $firstname,
247     'lastname'         => $lastname,
248     'subscriber_pin'   => $svc_phone->pin,
249     'callid_name'      => "$firstname $lastname",
250     'callid_nmbr'      => $phonenum,
251     'callid_emgr'      => $phonenum,
252     'email_address'    => $email,
253     'area_code'        => $area_code,
254     'srv_code'         => $custnum,
255     'date_created'     => time2str('%Y-%m-%d %H:%M:%S', time),
256     $self->options_named(keys %subscriber_fields),
257     # allow this to be overridden for suspend
258     ( $dial_policy ? ('dial_policy' => $dial_policy) : () ),
259   );
260
261   if ( $ns->responseCode !~ /^2/ ) {
262      return $ns->responseCode. ' '.
263             join(', ', $self->ns_parse_response( $ns->responseContent ) );
264   }
265
266   ###
267   # Piece 1.5 - feature creation
268   ###
269   foreach $feature (split /\s+/, $self->option('features') ) {
270
271     my $param= exists($feature_param{$feature}) ? $feature_param{$feature} : '';
272     $param = $phonenum if $param eq '$phonenum';
273
274     my $nsf = $self->ns_command( 'PUT', $self->ns_feature($svc_phone, $feature),
275       'control'    => 'd', #User Control, disable
276       'expires'    => 'never',
277       #'ts'         => '', #?
278       'parameters' => $param,
279       'hour_match' => '*',
280       'time_frame' => '*',
281       'activation' => 'now',
282     );
283
284     if ( $nsf->responseCode !~ /^2/ ) {
285        return $nsf->responseCode. ' '.
286               join(', ', $self->ns_parse_response( $ns->responseContent ) );
287     }
288
289   }
290
291   ###
292   # Piece 2 - sip device creation 
293   ###
294
295   my $ns2 = $self->ns_command( 'PUT', $self->ns_registrar($svc_phone),
296     'termination_match' => $self->ns_devicename($svc_phone),
297     'authentication_key'=> $svc_phone->sip_password,
298     'srv_code'          => $custnum,
299     $self->options_named(keys %registrar_fields),
300   );
301
302   if ( $ns2->responseCode !~ /^2/ ) {
303      return $ns2->responseCode. ' '.
304             join(', ', $self->ns_parse_response( $ns2->responseContent ) );
305   }
306
307   ###
308   # Piece 3 - DID mapping to user
309   ###
310
311   my $ns3 = $self->ns_command( 'PUT', $self->ns_dialplan($svc_phone),
312     'to_user' => $phonenum,
313     'to_host' => $domain,
314     'plan_description' => "$custnum: $lastname, $firstname", #config?
315     $self->options_named(keys %dialplan_fields),
316   );
317
318   if ( $ns3->responseCode !~ /^2/ ) {
319      return $ns3->responseCode. ' '.
320             join(', ', $self->ns_parse_response( $ns3->responseContent ) );
321   }
322
323   '';
324 }
325
326 sub ns_delete {
327   my($self, $svc_phone) = (shift, shift);
328
329   # do the create steps in reverse order, though I'm not sure it matters
330
331   my $ns3 = $self->ns_command( 'DELETE', $self->ns_dialplan($svc_phone) );
332
333   if ( $ns3->responseCode !~ /^2/ ) {
334      return $ns3->responseCode. ' '.
335             join(', ', $self->ns_parse_response( $ns3->responseContent ) );
336   }
337
338   my $ns2 = $self->ns_command( 'DELETE', $self->ns_registrar($svc_phone) );
339
340   if ( $ns2->responseCode !~ /^2/ ) {
341      return $ns2->responseCode. ' '.
342             join(', ', $self->ns_parse_response( $ns2->responseContent ) );
343   }
344
345   my $ns = $self->ns_command( 'DELETE', $self->ns_subscriber($svc_phone) );
346
347   if ( $ns->responseCode !~ /^2/ ) {
348      return $ns->responseCode. ' '.
349             join(', ', $self->ns_parse_response( $ns->responseContent ) );
350   }
351
352   '';
353
354 }
355
356 sub ns_parse_response {
357   my( $self, $content ) = ( shift, shift );
358
359   #try to screen-scrape something useful
360   tie my %hash, Tie::IxHash;
361   while ( $content =~ s/^.*?<p>\s*<b>(.+?)<\/b>\s*(.+?)\s*<\/p>//is ) {
362     ( $hash{$1} = $2 ) =~ s/^\s*<(\w+)>(.+?)<\/\1>/$2/is;
363   }
364
365   %hash;
366 }
367
368 sub _export_insert {
369   my($self, $svc_phone) = (shift, shift);
370   $self->ns_create_or_update($svc_phone);
371 }
372
373 sub _export_replace {
374   my( $self, $new, $old ) = (shift, shift, shift);
375   return "can't change phonenum with NetSapiens (unprovision and reprovision?)"
376     if $old->phonenum ne $new->phonenum;
377   $self->_export_insert($new);
378 }
379
380 sub _export_delete {
381   my( $self, $svc_phone ) = (shift, shift);
382
383   $self->ns_delete($svc_phone);
384 }
385
386 sub _export_suspend {
387   my( $self, $svc_phone ) = (shift, shift);
388   $self->ns_create_or_update($svc_phone, 'Deny');
389 }
390
391 sub _export_unsuspend {
392   my( $self, $svc_phone ) = (shift, shift);
393   #$self->ns_create_or_update($svc_phone, 'Permit All');
394   $self->_export_insert($svc_phone);
395 }
396
397 sub export_device_insert {
398   my( $self, $svc_phone, $phone_device ) = (shift, shift, shift);
399
400   my $domain = $self->ns_domain($svc_phone);
401   my $countrycode = $svc_phone->countrycode;
402   my $phonenum    = $svc_phone->phonenum;
403
404   my $ns = $self->ns_device_command(
405     'PUT', $self->ns_device($svc_phone, $phone_device),
406       'line1_enable' => 'yes',
407       'device1'      => $self->ns_devicename($svc_phone),
408       'line1_ext'    => $phonenum,
409 ,
410       #'line2_enable' => 'yes',
411       #'device2'      =>
412       #'line2_ext'    =>
413
414       #'notes' => 
415       'server'       => 'SiPbx',
416       'domain'       => $domain,
417
418       'brand'        => $phone_device->part_device->devicename,
419       
420   );
421
422   if ( $ns->responseCode !~ /^2/ ) {
423      return $ns->responseCode. ' '.
424             join(', ', $self->ns_parse_response( $ns->responseContent ) );
425   }
426
427   '';
428
429 }
430
431 sub export_device_delete {
432   my( $self, $svc_phone, $phone_device ) = (shift, shift, shift);
433
434   my $ns = $self->ns_device_command(
435     'DELETE', $self->ns_device($svc_phone, $phone_device),
436   );
437
438   if ( $ns->responseCode !~ /^2/ ) {
439      return $ns->responseCode. ' '.
440             join(', ', $self->ns_parse_response( $ns->responseContent ) );
441   }
442
443   '';
444
445 }
446
447
448 sub export_device_replace {
449   my( $self, $svc_phone, $new_phone_device, $old_phone_device ) =
450     (shift, shift, shift, shift);
451
452   #?
453   $self->export_device_insert( $svc_phone, $new_phone_device );
454
455 }
456
457 sub export_links {
458   my($self, $svc_phone, $arrayref) = (shift, shift, shift);
459   #push @$arrayref, qq!<A HREF="http://example.com/~!. $svc_phone->username.
460   #                 qq!">!. $svc_phone->username. qq!</A>!;
461   '';
462 }
463
464 sub options_named {
465   my $self = shift;
466   map { 
467         my $v = $self->option($_);
468         length($v) ? ($_ => $v) : ()
469       } @_
470 }
471
472 1;