Advertisement
Guest User

sms_recv.pl

a guest
May 4th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.65 KB | None | 0 0
  1. #!/usr/bin/perl -w
  2.  
  3. use 5.012;
  4. use strict;
  5. use File::Copy;
  6.  
  7. my $sourcedir="/var/spool/sms/incoming";
  8. my $destdir = "/home/pi/sms-inbox";
  9. my $movedir = "/home/pi/sms-inbox/source";
  10. my $maxsize = 1024 * 100; # refuse xml files bigger than 100 KB
  11.  
  12. opendir(my $dir,$sourcedir);
  13.  
  14. while(my $sourcename = readdir $dir) {
  15.     $sourcename =~ /^\.+$/ and next;
  16.     # ignore items which are not files (like dir or symlink)
  17.     -f "$sourcedir/$sourcename" or next;
  18.  
  19.     my $filepath = "$sourcedir/$sourcename";
  20.     my @stat = stat($filepath);
  21.     $stat[7] > $maxsize and warn "ignoring $sourcename: bigger than $maxsize" and next;
  22.  
  23.     print "opening $filepath...\n";
  24.     open(my $smsfile, "<$filepath") or warn "Error opening $sourcename" and next;
  25.  
  26.     my $from;
  27.     my $sent;
  28.     my $text="";
  29.     my $textmode=0;
  30.  
  31.     while(<$smsfile>) {
  32.         if($textmode) {
  33.             $text .= $_;
  34.         } else {
  35.             /^From:\s+(.+)$/ and $from = $1;
  36.             /^Sent:\s+(.+)$/ and $sent = $1;
  37.             /^$/ and $textmode = 1;
  38.         }
  39.     }
  40.     close($smsfile);
  41.  
  42.     if($from and $sent and $text) {
  43.         my $date = $sent;
  44.         $date =~ s/:/-/g;
  45.         $date =~ s/ /_/g;
  46.  
  47.         my $destname = "${from}_${date}.csv";
  48.         $text =~ s/"/\\"/;
  49.         my $smsfilepath = "$destdir/$destname";
  50.         open(my $outfile, ">$smsfilepath") or warn "cannot open $smsfilepath: $!" and next;
  51.         print $outfile "\"$from\",\"$sent\",\"$text\"";
  52.         close $outfile;
  53.  
  54.         move($filepath, "$movedir/$sourcename" ) or warn "Error moving $filepath to $movedir: $!";
  55.         #unlink $filepath or warn "Error deleting $filepath: $!";
  56.     }
  57. }
  58.  
  59. closedir($dir);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement