summaryrefslogtreecommitdiff
path: root/localmarkdown2sms
blob: 2f91108288782aeb884e9c7f5cbd3674e681477b (plain)
  1. #!/usr/bin/perl
  2. #
  3. # /usr/local/sbin/localmarkdown2sms
  4. # Copyright 2009-2010, 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_usertag = $ENV{SMS_USERTAG} || "username";
  34. my $sms_user = $ENV{SMS_USER} || "tester";
  35. my $sms_pw = $ENV{SMS_PW} || "foobar";
  36. my $sms_api = $ENV{SMS_API};
  37. my $sms_phone = $ENV{SMS_PHONE};
  38. my $sms_smsc = $ENV{SMS_SMSC};
  39. my $sms_msgtag = $ENV{SMS_MSGTAG} || "text";
  40. my $sms_cp = $ENV{SMS_CP} || "utf8";
  41. my $sms_concat = $ENV{SMS_CONCAT};
  42. my $sms_dlr_mask = $ENV{SMS_DLR_MASK};
  43. my $path = $ENV{mdpath};
  44. my (%file, %delay, %reply);
  45. # decode data if passed from kannel
  46. if ($urldecode) {
  47. @ARGV = uri_unescape(@ARGV);
  48. }
  49. my ($phone) = shift @ARGV;
  50. my ($key) = lc (shift @ARGV);
  51. # strip international prefix
  52. # (prefix is optional some places and illegal at other places - forgot where)
  53. $phone =~ s/\+/ /g;
  54. # strip non-word chars from keyword (and use only first chunk of word chars)
  55. $key =~ s/.*?(\w+).*?/$1/;
  56. if ($debug) {
  57. Log::Log4perl->easy_init($DEBUG);
  58. } elsif ($INFO) {
  59. Log::Log4perl->easy_init($INFO);
  60. } elsif ($WARN) {
  61. Log::Log4perl->easy_init($WARN);
  62. } elsif ($ERROR) {
  63. Log::Log4perl->easy_init($ERROR);
  64. }
  65. unless ($path and -d $path) {
  66. ERROR "environment variable \"mdpath\" missing or wrong.";
  67. exit 1;
  68. }
  69. foreach my $file (read_dir( $path )) {
  70. my ($key, $i, $skipkeysection, $skipcontent);
  71. # suppress repeated warnings for same issue
  72. my ($warn_nonkey_delay, $warn_nonkey_content);
  73. next unless ($file =~ /\.mdwn$/);
  74. foreach my $line (read_file( File::Spec->catfile($path, $file))) {
  75. chomp $line;
  76. my $content;
  77. # headline
  78. if ($line =~ /^(#+)\s*(.*?)\s*$/) {
  79. # tidy latest reply
  80. if (defined($key) and defined($reply{$key}[$i])) {
  81. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  82. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  83. }
  84. my $level = length($1);
  85. $content = $2;
  86. # key
  87. if ($level == 1 and $content =~ /(\w+)/) {
  88. $key = lc($1);
  89. $i = 0;
  90. $skipkeysection = undef;
  91. $skipcontent = undef;
  92. if (lc($content) ne $key) {
  93. WARN "key \"$key\" extracted from fuzzy string \"$content\" in file \"$file\"";
  94. }
  95. if (!defined( $delay{$key})) {
  96. $delay{$key}[0] = 0;
  97. $warn_nonkey_delay = undef;
  98. $warn_nonkey_content = undef;
  99. } else {
  100. WARN "skipping non-unique key \"$key\" in file \"$file\"";
  101. $key = undef;
  102. $skipkeysection = 1;
  103. $skipcontent = 1;
  104. }
  105. # delay
  106. } elsif ($level == 2 and $content =~ /((\d+[sm]\s?)+)/) {
  107. $skipcontent = undef;
  108. if (defined( $key)) {
  109. my $delay = parse_duration($1);
  110. if (defined($reply{$key}[$i])) {
  111. $i++;
  112. $delay{$key}[$i] = $delay{$key}[$i - 1];
  113. }
  114. # $delay{$key}[$i] += $delay; # accumulate: forked replies
  115. $delay{$key}[$i] = $delay; # simple: queued replies
  116. if ($content ne $1) {
  117. WARN "delay (${delay}s) resolved from fuzzy string \"$content\" in file \"$file\"";
  118. }
  119. } elsif ($skipkeysection or $warn_nonkey_delay) {
  120. # skipping - already warned about it...
  121. } else {
  122. WARN "ignoring non-key'ed delay line \"$1\" in file \"$file\"";
  123. $warn_nonkey_delay = 1;
  124. $skipcontent = 1;
  125. }
  126. } else {
  127. WARN "ignoring non-parsable headline \"$line\" in file \"$file\"";
  128. $skipcontent = 1;
  129. }
  130. # reply
  131. } else {
  132. $content = $line . "\n";
  133. # ikiwiki directives - strip from content and parse for tags
  134. $content =~ s/(?<!\\)\[\[([^\[\]]*)(?<!\\)\]\]//gs and do {
  135. my $directive_string = $1;
  136. my ($directive, $directive_content);
  137. $directive_string =~ /^\s*\!(tag|taglink)\s*((\s*?\b\w+)+)/ and $file{$file}{'directive'}{'tag'} = [ split /\s+/, $2 ];
  138. };
  139. if ( defined( $key ) and not ($skipcontent)) {
  140. $reply{$key}[$i] .= $content;
  141. } elsif ($skipkeysection or $skipcontent or $warn_nonkey_content) {
  142. # skipping - already warned about it...
  143. } else {
  144. $content =~ /\S/s && WARN "skipping non-key'ed content \"$line\" in file \"$file\"";
  145. $warn_nonkey_content = 1;
  146. }
  147. }
  148. }
  149. # tidy latest reply
  150. if (defined($key) and defined($reply{$key}[$i])) {
  151. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  152. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  153. }
  154. }
  155. sub tidymsg {
  156. my $msg = shift @_;
  157. $msg =~ s/^\h*$//g; # clean virtually empty lines
  158. $msg =~ s/(\S)\h$/$1/g; # strip single trailing space
  159. $msg =~ s/\n\n+/\n\n/g; # strip excess newlines
  160. $msg =~ s/(\S)\n([^\n])/$1 $2/g; # convert newline to space
  161. $msg =~ s/\h*$//g; # strip all trailing spaces
  162. $msg =~ s/^\s*(\w*?.*?)\s*$/$1/s; # strip surrounding space
  163. return $msg;
  164. }
  165. # based on Text::Unidecode bug#8017: http://rt.cpan.org/Ticket/Display.html?id=8017#txn-322351
  166. sub transliterate {
  167. my ($tocharset, $string) = @_;
  168. my $res = encode($tocharset, decode_utf8($string), sub {
  169. my $ascii = unidecode(chr $_[0]);
  170. _utf8_off($ascii);
  171. $ascii;
  172. });
  173. return $res;
  174. }
  175. sub sendmsg {
  176. my ($phone, $desc, $msg) = @_;
  177. unless ($dummy) {
  178. my $ua = LWP::UserAgent->new(agent => "localmarkdown2sms");
  179. $ua->timeout(10);
  180. my $url = $sms_url
  181. . '?' . $sms_usertag . '=' . uri_escape($sms_user)
  182. . '&password=' . uri_escape($sms_pw)
  183. . '&to=' . uri_escape($phone);
  184. $url .= '&api_id=' . uri_escape($sms_api) if ($sms_api);
  185. $url .= '&from=' . uri_escape($sms_phone) if ($sms_phone);
  186. $url .= '&smsc=' . uri_escape($sms_smsc) if ($sms_smsc);
  187. $url .= '&concat=' . uri_escape($sms_concat) if ($sms_concat);
  188. $url .= '&dlr-mask=' . uri_escape($sms_dlr_mask) if ($sms_dlr_mask);
  189. $url .= '&' . $sms_msgtag . '=' . uri_escape(transliterate($sms_cp, $msg));
  190. DEBUG "Sending request: $url";
  191. my $response = $ua->request(HTTP::Request->new('GET', $url));
  192. unless ($response->is_success) {
  193. ERROR $response->status_line;
  194. }
  195. DEBUG "Done $desc";
  196. } else {
  197. print STDERR "\n --> $phone: $desc\n";
  198. print STDERR $msg . "\n";
  199. }
  200. }
  201. my $num_children = $#{ $reply{$key} } + 1; # How many children we'll create
  202. if (0 == $num_children) {
  203. &sendmsg($phone, "fallback message", "Sorry, the sms code \"$key\" is unknown.\nPlease send only sms codes to this number.");
  204. exit;
  205. }
  206. if ($debug) {
  207. DEBUG "queueing $num_children replies:";
  208. for my $num ( 0 .. $num_children - 1 ) {
  209. DEBUG " [" . $delay{$key}[$num] . "s]";
  210. }
  211. # DEBUG "\n";
  212. }
  213. for my $num ( 0 .. $num_children - 1 ) {
  214. sleep($delay{$key}[$num]) unless ($nosleep);
  215. &sendmsg($phone, "reply #$num [" . $delay{$key}[$num] . "s]", $reply{$key}[$num]);
  216. }
  217. 1;