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