summaryrefslogtreecommitdiff
path: root/localmarkdown2sms
blob: 729358311ba70eede0c65a6beff5cb04a66448e9 (plain)
  1. #!/usr/bin/perl
  2. #
  3. # /usr/local/sbin/localmarkdown2sms
  4. # Copyright 2009 Jonas Smedegaard <dr@jones.dk>
  5. #
  6. # Send series of messages through Kannel from simplified Markdown files
  7. # * Lines starting with "#" are "keywords" activating a message series
  8. # * write only a single word
  9. # * use each keyword only once across the whole system
  10. # * use only minuscles (not majuscles, i.e. CAPITAL LETTERS)
  11. # * Lines starting with "##" express pauses
  12. # * a pause is a number + a single letter, without spaces between
  13. # * a pause line can contain multiple pauses, separated by space
  14. # Suggestion for writing style:
  15. #
  16. # * Write explicitly how to activate next series
  17. # * pick keywords tied to nex series rather than the previous
  18. # * use same instruction jargon across all series in the system
  19. use strict;
  20. use warnings;
  21. use Env qw[$debug $info $warn $dummy $nosleep $urldecode];
  22. use Log::Log4perl qw(:easy);
  23. use File::Spec;
  24. use File::Slurp;
  25. use Time::Duration::Parse;
  26. use Text::Unidecode;
  27. use Encode 2.12 qw(encode decode_utf8 _utf8_off); # need v2.12 to support coderef
  28. use LWP::UserAgent;
  29. use URI::Escape;
  30. use Proc::Daemon;
  31. Proc::Daemon::Init unless ($debug);
  32. my $sms_url = $ENV{SMS_URL} || "http://localhost:13013/cgi-bin/sendsms";
  33. my $sms_user = $ENV{SMS_USER} || "tester";
  34. my $sms_pw = $ENV{SMS_PW} || "foobar";
  35. my $sms_phone = $ENV{SMS_PHONE};
  36. my $sms_smsc = $ENV{SMS_SMSC};
  37. my $sms_msgtag = $ENV{SMS_MSGTAG} || "text";
  38. my $sms_cp = $ENV{SMS_CP} || "utf8";
  39. my $path = $ENV{mdpath};
  40. my (%file, %delay, %reply);
  41. # decode data if passed from kannel
  42. if ($urldecode) {
  43. @ARGV = uri_unescape(@ARGV);
  44. }
  45. my ($phone) = shift @ARGV;
  46. my ($key) = lc (shift @ARGV);
  47. # strip international prefix
  48. # (prefix is optional some places and illegal at other places - forgot where)
  49. $phone =~ s/\+/ /g;
  50. # strip non-word chars from keyword (and use only first chunk of word chars)
  51. $key =~ s/.*?(\w+).*?/$1/;
  52. if ($debug) {
  53. Log::Log4perl->easy_init($DEBUG);
  54. } elsif ($INFO) {
  55. Log::Log4perl->easy_init($INFO);
  56. } elsif ($WARN) {
  57. Log::Log4perl->easy_init($WARN);
  58. } elsif ($ERROR) {
  59. Log::Log4perl->easy_init($ERROR);
  60. }
  61. unless ($path and -d $path) {
  62. ERROR "environment variable \"mdpath\" missing or wrong.";
  63. exit 1;
  64. }
  65. foreach my $file (read_dir( $path )) {
  66. my ($key, $i, $skipkeysection, $skipcontent);
  67. # suppress repeated warnings for same issue
  68. my ($warn_nonkey_delay, $warn_nonkey_content);
  69. next unless ($file =~ /\.mdwn$/);
  70. foreach my $line (read_file( File::Spec->catfile($path, $file))) {
  71. chomp $line;
  72. my $content;
  73. # headline
  74. if ($line =~ /^(#+)\s*(.*?)\s*$/) {
  75. # tidy latest reply
  76. if (defined($key) and defined($reply{$key}[$i])) {
  77. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  78. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  79. }
  80. my $level = length($1);
  81. $content = $2;
  82. # key
  83. if ($level == 1 and $content =~ /(\w+)/) {
  84. $key = lc($1);
  85. $i = 0;
  86. $skipkeysection = undef;
  87. $skipcontent = undef;
  88. if (lc($content) ne $key) {
  89. WARN "key \"$key\" extracted from fuzzy string \"$content\" in file \"$file\"";
  90. }
  91. if (!defined( $delay{$key})) {
  92. $delay{$key}[0] = 0;
  93. $warn_nonkey_delay = undef;
  94. $warn_nonkey_content = undef;
  95. } else {
  96. WARN "skipping non-unique key \"$key\" in file \"$file\"";
  97. $key = undef;
  98. $skipkeysection = 1;
  99. $skipcontent = 1;
  100. }
  101. # delay
  102. } elsif ($level == 2 and $content =~ /((\d+[sm]\s?)+)/) {
  103. $skipcontent = undef;
  104. if (defined( $key)) {
  105. my $delay = parse_duration($1);
  106. if (defined($reply{$key}[$i])) {
  107. $i++;
  108. $delay{$key}[$i] = $delay{$key}[$i - 1];
  109. }
  110. # $delay{$key}[$i] += $delay; # accumulate: forked replies
  111. $delay{$key}[$i] = $delay; # simple: queued replies
  112. if ($content ne $1) {
  113. WARN "delay (${delay}s) resolved from fuzzy string \"$content\" in file \"$file\"";
  114. }
  115. } elsif ($skipkeysection or $warn_nonkey_delay) {
  116. # skipping - already warned about it...
  117. } else {
  118. WARN "ignoring non-key'ed delay line \"$1\" in file \"$file\"";
  119. $warn_nonkey_delay = 1;
  120. $skipcontent = 1;
  121. }
  122. } else {
  123. WARN "ignoring non-parsable headline \"$line\" in file \"$file\"";
  124. $skipcontent = 1;
  125. }
  126. # reply
  127. } else {
  128. $content = $line . "\n";
  129. # ikiwiki directives - strip from content and parse for tags
  130. $content =~ s/(?<!\\)\[\[([^\[\]]*)(?<!\\)\]\]//gs and do {
  131. my $directive_string = $1;
  132. my ($directive, $directive_content);
  133. $directive_string =~ /^\s*\!(tag|taglink)\s*((\s*?\b\w+)+)/ and $file{$file}{'directive'}{'tag'} = [ split /\s+/, $2 ];
  134. };
  135. if ( defined( $key ) and not ($skipcontent)) {
  136. $reply{$key}[$i] .= $content;
  137. } elsif ($skipkeysection or $skipcontent or $warn_nonkey_content) {
  138. # skipping - already warned about it...
  139. } else {
  140. $content =~ /\S/s && WARN "skipping non-key'ed content \"$line\" in file \"$file\"";
  141. $warn_nonkey_content = 1;
  142. }
  143. }
  144. }
  145. # tidy latest reply
  146. if (defined($key) and defined($reply{$key}[$i])) {
  147. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  148. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  149. }
  150. }
  151. sub tidymsg {
  152. my $msg = shift @_;
  153. $msg =~ s/^\h*$//g; # clean virtually empty lines
  154. $msg =~ s/(\S)\h$/$1/g; # strip single trailing space
  155. $msg =~ s/\n\n+/\n\n/g; # strip excess newlines
  156. $msg =~ s/(\S)\n([^\n])/$1 $2/g; # convert newline to space
  157. $msg =~ s/\h*$//g; # strip all trailing spaces
  158. $msg =~ s/^\s*(\w*?.*?)\s*$/$1/s; # strip surrounding space
  159. return $msg;
  160. }
  161. # based on Text::Unidecode bug#8017: http://rt.cpan.org/Ticket/Display.html?id=8017#txn-322351
  162. sub transliterate {
  163. my ($tocharset, $string) = @_;
  164. my $res = encode($tocharset, decode_utf8($string), sub {
  165. my $ascii = unidecode(chr $_[0]);
  166. _utf8_off($ascii);
  167. $ascii;
  168. });
  169. return $res;
  170. }
  171. sub sendmsg {
  172. my ($phone, $desc, $msg) = @_;
  173. unless ($dummy) {
  174. my $ua = LWP::UserAgent->new(agent => "localmarkdown2sms");
  175. $ua->timeout(10);
  176. my $url = $sms_url
  177. . '?username=' . uri_escape($sms_user)
  178. . '&password=' . uri_escape($sms_pw)
  179. . '&to=' . uri_escape($phone);
  180. $url .= '&from=' . uri_escape($sms_phone) if ($sms_phone);
  181. $url .= '&smsc=' . uri_escape($sms_smsc) if ($sms_smsc);
  182. $url .= '&' . $sms_msgtag . '=' . uri_escape(transliterate($sms_cp, $msg));
  183. my $response = $ua->request(HTTP::Request->new('GET', $url));
  184. unless ($response->is_success) {
  185. ERROR $response->status_line;
  186. }
  187. DEBUG "Done $desc";
  188. } else {
  189. print STDERR "\n --> $phone: $desc\n";
  190. print STDERR $msg . "\n";
  191. }
  192. }
  193. my $num_children = $#{ $reply{$key} } + 1; # How many children we'll create
  194. if (0 == $num_children) {
  195. &sendmsg($phone, "fallback message", "Sorry, the sms code \"$key\" is unknown.\nPlease send only sms codes to this number.");
  196. exit;
  197. }
  198. if ($debug) {
  199. DEBUG "queueing $num_children replies:";
  200. for my $num ( 0 .. $num_children - 1 ) {
  201. DEBUG " [" . $delay{$key}[$num] . "s]";
  202. }
  203. # DEBUG "\n";
  204. }
  205. for my $num ( 0 .. $num_children - 1 ) {
  206. sleep($delay{$key}[$num]) unless ($nosleep);
  207. &sendmsg($phone, "reply #$num [" . $delay{$key}[$num] . "s]", $reply{$key}[$num]);
  208. }
  209. 1;