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