summaryrefslogtreecommitdiff
path: root/localmarkdown2sms
blob: 86b0f6da30e5e85c4a3a1eb836a91a4e5387ac86 (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 utf8; # this document itself is UTF-8 encoded.
  22. use Env qw[$debug $info $warn $dummy $nosleep $urldecode];
  23. use Log::Log4perl qw(:easy);
  24. use File::Spec;
  25. use File::Slurp;
  26. use Time::Duration::Parse;
  27. use Text::Unidecode;
  28. use Encode 2.12 qw(encode decode _utf8_off); # need v2.12 to support coderef
  29. use LWP::UserAgent;
  30. use URI::Escape;
  31. use Proc::Daemon;
  32. # TODO: Use Coro instead
  33. Proc::Daemon::Init unless ($debug);
  34. my $sms_url = $ENV{SMS_URL} || "http://localhost:13013/cgi-bin/sendsms";
  35. my $sms_usertag = $ENV{SMS_USERTAG} || "username";
  36. my $sms_user = $ENV{SMS_USER} || "tester";
  37. my $sms_pw = $ENV{SMS_PW} || "foobar";
  38. my $sms_api = $ENV{SMS_API};
  39. my $sms_callback = $ENV{SMS_CALLBACK};
  40. my $sms_phone = $ENV{SMS_PHONE};
  41. my $sms_errfrom = $ENV{SMS_ERRFROM} || $sms_phone;
  42. my $sms_errto1 = $ENV{SMS_ERRTO1};
  43. my $sms_errto2 = $ENV{SMS_ERRTO2};
  44. my $sms_smsc = $ENV{SMS_SMSC};
  45. my $sms_msgtag = $ENV{SMS_MSGTAG} || "text";
  46. my $sms_cp = $ENV{SMS_CP} || "utf8";
  47. my $sms_concatenation = $ENV{SMS_CONCATENATION};
  48. my $sms_concat = $ENV{SMS_CONCAT};
  49. my $sms_dlr_mask = $ENV{SMS_DLR_MASK};
  50. my $sms_dlr_url = $ENV{SMS_DLR_URL};
  51. my $sms_escalate = $ENV{SMS_ESCALATE};
  52. my $sms_validity = $ENV{SMS_VALIDITY};
  53. my $sms_req_feat = $ENV{SMS_REQ_FEAT};
  54. my $sms_binfo = $ENV{SMS_BINFO};
  55. my $stripprefix = $ENV{stripprefix};
  56. my $path = $ENV{mdpath};
  57. my (%file, %delay, %reply);
  58. # decode data if passed from kannel
  59. if ($urldecode) {
  60. @ARGV = uri_unescape(@ARGV);
  61. }
  62. my ($phone) = shift @ARGV;
  63. my $inputstring = decode('UTF-8', join(' ', @ARGV));
  64. my ($key) = lc(decode('UTF-8', shift @ARGV));
  65. # strip international prefix
  66. # (prefix is optional some places and illegal at other places - forgot where)
  67. if ($stripprefix) {
  68. $phone =~ s/^\+//g;
  69. $sms_phone =~ s/^\+//g;
  70. $sms_errfrom =~ s/^\+//g;
  71. $sms_errto1 =~ s/^\+//g;
  72. $sms_errto2 =~ s/^\+//g;
  73. }
  74. # strip non-word chars from keyword
  75. $key = transliterate($key);
  76. # use only first chunk of word chars as keyword
  77. $key =~ s/^(\S+).*?$/$1/;
  78. if ($debug) {
  79. Log::Log4perl->easy_init($DEBUG);
  80. } elsif ($INFO) {
  81. Log::Log4perl->easy_init($INFO);
  82. } elsif ($WARN) {
  83. Log::Log4perl->easy_init($WARN);
  84. } elsif ($ERROR) {
  85. Log::Log4perl->easy_init($ERROR);
  86. }
  87. unless ($path and -d $path) {
  88. ERROR "environment variable \"mdpath\" missing or wrong.";
  89. exit 1;
  90. }
  91. foreach my $file (read_dir( $path )) {
  92. my ($key, $i, $skipkeysection, $skipcontent);
  93. # suppress repeated warnings for same issue
  94. my ($warn_nonkey_delay, $warn_nonkey_content);
  95. next unless ($file =~ /\.mdwn$/);
  96. foreach my $line (read_file( File::Spec->catfile($path, $file))) {
  97. $line = &transliterate(decode('UTF-8', $line));
  98. chomp $line;
  99. my $content;
  100. # headline
  101. if ($line =~ /^(#+)\s*(.*?)\s*$/) {
  102. # tidy latest reply
  103. if (defined($key) and defined($reply{$key}[$i])) {
  104. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  105. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  106. }
  107. my $level = length($1);
  108. $content = $2;
  109. # key
  110. if ($level == 1 and $content =~ /(\w+)/) {
  111. $key = lc($1);
  112. $i = 0;
  113. $skipkeysection = undef;
  114. $skipcontent = undef;
  115. if (lc($content) ne $key) {
  116. WARN "key \"$key\" extracted from fuzzy string \"$content\" in file \"$file\"";
  117. }
  118. if (!defined( $delay{$key})) {
  119. $delay{$key}[0] = 0;
  120. $warn_nonkey_delay = undef;
  121. $warn_nonkey_content = undef;
  122. } else {
  123. WARN "skipping non-unique key \"$key\" in file \"$file\"";
  124. $key = undef;
  125. $skipkeysection = 1;
  126. $skipcontent = 1;
  127. }
  128. # delay
  129. } elsif ($level == 2 and $content =~ /((\d+[sm]\s?)+)/) {
  130. $skipcontent = undef;
  131. if (defined( $key)) {
  132. my $delay = parse_duration($1);
  133. if (defined($reply{$key}[$i])) {
  134. $i++;
  135. $delay{$key}[$i] = $delay{$key}[$i - 1];
  136. }
  137. # $delay{$key}[$i] += $delay; # accumulate: forked replies
  138. $delay{$key}[$i] = $delay; # simple: queued replies
  139. if ($content ne $1) {
  140. WARN "delay (${delay}s) resolved from fuzzy string \"$content\" in file \"$file\"";
  141. }
  142. } elsif ($skipkeysection or $warn_nonkey_delay) {
  143. # skipping - already warned about it...
  144. } else {
  145. WARN "ignoring non-key'ed delay line \"$1\" in file \"$file\"";
  146. $warn_nonkey_delay = 1;
  147. $skipcontent = 1;
  148. }
  149. } else {
  150. WARN "ignoring non-parsable headline \"$line\" in file \"$file\"";
  151. $skipcontent = 1;
  152. }
  153. # reply
  154. } else {
  155. $content = $line . "\n";
  156. # ikiwiki directives - strip from content and parse for tags
  157. $content =~ s/(?<!\\)\[\[([^\[\]]*)(?<!\\)\]\]//gs and do {
  158. my $directive_string = $1;
  159. my ($directive, $directive_content);
  160. $directive_string =~ /^\s*\!(tag|taglink)\s*((\s*?\b\w+)+)/ and $file{$file}{'directive'}{'tag'} = [ split /\s+/, $2 ];
  161. };
  162. if ( defined( $key ) and not ($skipcontent)) {
  163. $reply{$key}[$i] .= $content;
  164. } elsif ($skipkeysection or $skipcontent or $warn_nonkey_content) {
  165. # skipping - already warned about it...
  166. } else {
  167. $content =~ /\S/s && WARN "skipping non-key'ed content \"$line\" in file \"$file\"";
  168. $warn_nonkey_content = 1;
  169. }
  170. }
  171. }
  172. # tidy latest reply
  173. if (defined($key) and defined($reply{$key}[$i])) {
  174. $reply{$key}[$i] = &tidymsg($reply{$key}[$i]);
  175. ($reply{$key}[$i]) || delete $reply{$key}[$i];
  176. }
  177. }
  178. sub tidymsg {
  179. my $msg = shift @_;
  180. $msg =~ s/^\h*$//g; # clean virtually empty lines
  181. $msg =~ s/(\S)\h$/$1/g; # strip single trailing space
  182. $msg =~ s/\n\n+/\n\n/g; # strip excess newlines
  183. $msg =~ s/(\S)\n([^\n])/$1 $2/g; # convert newline to space
  184. $msg =~ s/\h*$//g; # strip all trailing spaces
  185. $msg =~ s/^\s*(\w*?.*?)\s*$/$1/s; # strip surrounding space
  186. $msg =~ s/’/'/g; #'simplify non-GSM chars
  187. $msg =~ s/…/.../g; # simplify ellipsis
  188. $msg =~ s/\.\.+/.../g; # multiple dots → psudo-ellipsis
  189. return $msg;
  190. }
  191. # based on Text::Unidecode bug#8017: http://rt.cpan.org/Ticket/Display.html?id=8017#txn-322351
  192. sub transliterate {
  193. my $string = shift @_;
  194. my $res = decode('GSM0338', encode('GSM0338', $string, sub {
  195. my $ascii = unidecode(chr $_[0]);
  196. _utf8_off($ascii);
  197. $ascii;
  198. }));
  199. return $res || "";
  200. }
  201. sub sendmsg {
  202. my ($from, $to, $desc, $msg) = @_;
  203. my $ua = LWP::UserAgent->new(agent => "localmarkdown2sms");
  204. $ua->timeout(10);
  205. my $url = $sms_url
  206. . '?' . $sms_usertag . '=' . uri_escape($sms_user)
  207. . '&password=' . uri_escape($sms_pw)
  208. . '&to=' . uri_escape($to);
  209. $url .= '&api_id=' . uri_escape($sms_api) if ($sms_api);
  210. $url .= '&callback=' . uri_escape($sms_callback) if ($sms_callback);
  211. $url .= '&from=' . uri_escape($from) if ($from);
  212. $url .= '&smsc=' . uri_escape($sms_smsc) if ($sms_smsc);
  213. $url .= '&concatenation=true' if ($sms_concatenation);
  214. $url .= '&concat=' . uri_escape($sms_concat) if ($sms_concat);
  215. $url .= '&dlr-mask=' . uri_escape($sms_dlr_mask) if ($sms_dlr_mask);
  216. $url .= '&dlr-url=' . uri_escape($sms_dlr_url) if ($sms_dlr_url);
  217. $url .= '&escalate=' . uri_escape($sms_escalate) if ($sms_escalate);
  218. $url .= '&validity=' . uri_escape($sms_validity) if ($sms_validity);
  219. $url .= '&req_feat=' . uri_escape($sms_req_feat) if ($sms_req_feat);
  220. $url .= '&binfo=' . uri_escape($sms_binfo) if ($sms_binfo);
  221. $url .= '&' . $sms_msgtag . '=' . uri_escape(encode($sms_cp, $msg));
  222. unless ($dummy) {
  223. DEBUG "Sending request: $url";
  224. my $response = $ua->request(HTTP::Request->new('GET', $url));
  225. unless ($response->is_success) {
  226. ERROR $response->status_line;
  227. }
  228. DEBUG "Done $desc";
  229. } else {
  230. DEBUG "[DUMMY] Sending request: $url";
  231. print STDERR "\n [$from --> $to: $desc]\n\n";
  232. print STDERR $msg . "\n";
  233. }
  234. }
  235. my $num_children = $#{ $reply{$key} } + 1; # How many children we'll create
  236. if (0 == $num_children) {
  237. my $err_da = "Ikke genkendt som et nøgleord: Check venligst for tastefejl og prøv igen.";
  238. my $err_en = "Sorry, not recognized as a keyword: Please check spelling and try again.";
  239. my $err_hu = "Érvénytelen kulcsszó. Kérjük, ellenőrizd és próbáld újra.";
  240. my $err_it = "Spiacente, non riconosco come parola chiave: Controlla l'ortografia e riprova.";
  241. my $errmsg = "[warning] $phone requested unknown keyword \"$key\"\nFull text: $inputstring";
  242. # FIXME: Make use of local errormsg optional and configurable.
  243. &sendmsg($sms_phone, $phone, "fallback message", "$key?\n$err_hu\n$err_en");
  244. ($sms_errto1) and &sendmsg($sms_errfrom, $sms_errto1, "warning", $errmsg);
  245. ($sms_errto2) and &sendmsg($sms_errfrom, $sms_errto2, "warning", $errmsg);
  246. exit;
  247. }
  248. if ($debug) {
  249. DEBUG "queueing $num_children replies:";
  250. for my $num ( 0 .. $num_children - 1 ) {
  251. DEBUG " [" . $delay{$key}[$num] . "s]";
  252. }
  253. # DEBUG "\n";
  254. }
  255. for my $num ( 0 .. $num_children - 1 ) {
  256. sleep($delay{$key}[$num]) unless ($nosleep);
  257. &sendmsg($sms_phone, $phone, "reply #$num [" . $delay{$key}[$num] . "s]", $reply{$key}[$num]);
  258. }
  259. 1;