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