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