default to a session cookie instead of setting an explicit timeout, weird timezone...
[freeside.git] / bin / cdr.http_and_import
1 #!/usr/bin/perl
2 #
3 # Usage:
4 #  cdr.http_and_import [ -p prefix ] [ -e extension ] [ -v ] user format URL
5 #
6 # -e: file extension, defaults to .csv
7 # -d: if specified, moves files to the specified folder when done
8
9 use strict;
10 use Getopt::Std;
11 use WWW::IndexParser;
12 #use LWP::UserAgent;
13 use FS::UID qw(adminsuidsetup datasrc dbh);
14 use FS::cdr;
15
16 ###
17 # parse command line
18 ###
19
20 use vars qw( $opt_p $opt_e $opt_v );
21 getopts('p:e:v');
22
23 $opt_e ||= 'csv';
24 #$opt_e = ".$opt_e" unless $opt_e =~ /^\./;
25 $opt_e =~ s/^\.//;
26
27 my $user = shift or die &usage;
28 adminsuidsetup $user;
29
30 # %%%FREESIDE_CACHE%%%
31 my $cachedir = '/usr/local/etc/freeside/cache.'. datasrc. '/cdrs';
32 mkdir $cachedir unless -d $cachedir;
33
34 my $format = shift or die &usage;
35
36 use vars qw( $URL );
37 $URL = shift or die &usage;
38
39 ###
40 # get the file list
41 ###
42
43 warn "Retreiving directory listing\n" if $opt_v;
44
45 my @files = WWW::IndexParser->new(url => $URL);
46
47 ###
48 # import each file
49 ###
50
51 foreach my $file ( @files ) {
52
53   my $filename = $file->{filename};
54
55   if ( $opt_p ) { next unless $filename =~ /^$opt_p/ };
56   if ( $opt_e ) { next unless $filename =~ /\.$opt_e$/i };
57
58   #check and see if we've gotten this file already!!!
59   #just going to cheat with filenames in the cache for now
60   if ( -e "$cachedir/$filename" ) {
61     warn "Already have unprocessed $cachedir/$filename; skipping\n"; # if $opt_v;
62     next;
63   }
64   if ( -e "$cachedir/$filename.DONE" ) {
65     warn "Already processed $cachedir/$filename; skipping\n" if $opt_v;
66     next;
67   }
68
69   warn "Downloading $filename\n" if $opt_v;
70
71   #get the file
72
73   my $ua = LWP::UserAgent->new;
74   my $response = $ua->get("$URL/$filename");
75
76   unless ( $response->is_success ) {
77     die "Error retreiving $URL/$filename: ". $response->status_line;
78   }
79
80   open(FILE, ">$cachedir/$filename")
81     or die "can't open $cachedir/$filename: $!";
82   print FILE $response->content;
83   close FILE or die "can't close $cachedir/$filename: $!";
84
85   warn "Processing $filename\n" if $opt_v;
86
87   my $error = FS::cdr::batch_import( {
88     'file'            => "$cachedir/$filename",
89     'format'          => $format,
90     'batch_namevalue' => $filename,
91     'empty_ok'        => 1,
92   } );
93   die $error if $error;
94
95   close FILE;
96
97   rename("$cachedir/$filename", "$cachedir/$filename.DONE");
98
99 }
100
101 ###
102 # sub
103 ###
104
105 sub usage {
106   "Usage: \n  cdr.http_and_import  [ -p prefix ] [ -e extension ] [ -v ] user format URL\n";
107 }
108