aboutsummaryrefslogtreecommitdiff
path: root/bin/events2md.pl
blob: 84880af14c6619bb0768cd8e5acbf9789b8f6ed5 (plain)
  1. #!/usr/bin/perl
  2. use v5.14;
  3. use utf8;
  4. use open qw(:std :encoding(UTF-8));
  5. use strictures;
  6. use autodie;
  7. use POSIX qw(locale_h);
  8. use locale;
  9. use Encode qw(decode_utf8); # TODO: modernize CalDAV access instead
  10. use Net::Netrc;
  11. use List::Util qw(pairs);
  12. use IO::Interactive::Tiny;
  13. use Log::Any qw($log);
  14. use Log::Any::Adapter;
  15. use URI;
  16. use IO::Prompter;
  17. use Cal::DAV;
  18. use Data::ICal;
  19. use iCal::Parser;
  20. use List::Util qw(first);
  21. use List::MoreUtils qw(nsort_by sort_by);
  22. use DateTime;
  23. use Try::Tiny;
  24. use Path::Tiny;
  25. if ( IO::Interactive::Tiny::is_interactive() ) {
  26. Log::Any::Adapter->set( 'Screen', default_level => 'info' );
  27. }
  28. # set defaults and parse command-line options
  29. my ( $BASE_URI, $CALENDAR_URI, $OUTPUT_FILE );
  30. $BASE_URI = $ENV{CAL_DAV_URL_BASE};
  31. $CALENDAR_URI = $ENV{CAL_DAV_URL_CALENDAR};
  32. $BASE_URI ||= shift @ARGV
  33. if @ARGV;
  34. $CALENDAR_URI ||= shift @ARGV
  35. if @ARGV;
  36. $OUTPUT_FILE = shift @ARGV
  37. if @ARGV;
  38. # use system locale to format DateTime objects parsed from iCal data
  39. DateTime->DefaultLocale( setlocale(LC_TIME) );
  40. # resolve calendar URIs
  41. my ( $base_uri, $calendar_uri, $calendar );
  42. $base_uri = URI->new($BASE_URI)
  43. if ($BASE_URI);
  44. $base_uri
  45. or $log->fatal('required base URI not provided') && exit 2;
  46. $base_uri->scheme
  47. or $base_uri->scheme('file');
  48. if ( $base_uri->scheme eq 'http' or $base_uri->scheme eq 'https' ) {
  49. $log->infof( 'will use base URI %s', $base_uri );
  50. $calendar_uri = URI->new( $CALENDAR_URI || $base_uri );
  51. $calendar_uri and $calendar_uri->authority
  52. or $log->fatal('bad calendar URI: must be an internet URI') && exit 2;
  53. $base_uri->eq($calendar_uri) and $calendar_uri = undef
  54. or $log->infof( 'will use calendar URI %s', $calendar_uri );
  55. # resolve credentials
  56. $log->debug('resolve credentials...');
  57. my ( $mach, $user, $pass );
  58. ( $user, $pass ) = split ':', $base_uri->userinfo
  59. if $base_uri->userinfo;
  60. $user ||= $ENV{CAL_DAV_USER};
  61. $pass ||= $ENV{CAL_DAV_PASS};
  62. $mach = Net::Netrc->lookup( $base_uri->host, $user )
  63. if !$user or !$pass;
  64. if ($mach) {
  65. $user ||= $mach->login;
  66. $pass ||= $mach->password;
  67. $log->infof( 'will use .netrc provided credentials for user %s', $user );
  68. }
  69. elsif ( IO::Interactive::Tiny::is_interactive() ) {
  70. $log->warn('will ask for missing info - this will fail in headless mode');
  71. $user ||= prompt 'Enter your username';
  72. $pass ||= prompt 'Enter your password', -echo => '*';
  73. }
  74. $log->debugf( 'resolved credentials for user %s', $user );
  75. # fetch and parse CalDAV calendar data
  76. $log->debug('fetch and parse CalDAV calendar data...');
  77. $calendar = Cal::DAV->new(
  78. user => $user,
  79. pass => $pass,
  80. url => $base_uri,
  81. );
  82. $calendar->get($calendar_uri)
  83. if $calendar_uri;
  84. }
  85. elsif ( $base_uri->scheme eq 'file' ) {
  86. defined $base_uri->file
  87. or $log->fatal('bad base URI: cannot open file') && exit 2;
  88. $log->infof( 'will use base URI %s', $base_uri );
  89. # parse local calendar data
  90. $log->debug('parse local calendar data...');
  91. my $path = path( $base_uri->file );
  92. if ( $path->is_file ) {
  93. $calendar = Data::ICal->new( data => $path->slurp_raw );
  94. }
  95. else {
  96. my $data;
  97. $path->visit( sub { $data .= $_->slurp_raw if $_->is_file } );
  98. $calendar = Data::ICal->new( data => $data );
  99. }
  100. }
  101. if ( $log->is_trace ) {
  102. use DDP;
  103. p $calendar;
  104. }
  105. # index calendar entries
  106. $log->debug('index calendar entries...');
  107. my %calendar_entries;
  108. for ( @{ $calendar->entries } ) {
  109. if ( 'VEVENT' eq $_->ical_entry_type ) {
  110. my $uid = try { $_->property('uid')->[0]->value };
  111. $uid ||= Data::ICal::Entry::Event->new()->property('uid')->[0]->value;
  112. $calendar_entries{VEVENT}{$uid} = $_;
  113. }
  114. else {
  115. # TODO
  116. next;
  117. }
  118. }
  119. if ( $log->is_trace ) {
  120. use DDP;
  121. p %calendar_entries;
  122. }
  123. # TODO: if list is empty and no calendar uri was explicitly supplied,
  124. # warn on stdout with list of abailable collections using this sequence:
  125. # 1. PROPFIND on base-URL for {DAV:}current-user-principal
  126. # 2. PROPFIND for calendar-home-set property in caldav namespace
  127. # 3. PROPFIND with depth: 1
  128. # as documented at <https://stackoverflow.com/a/11673483>
  129. # serialize calendar events
  130. $log->debug('serialize calendar events...');
  131. my $start = DateTime->now;
  132. my $end = $start->clone->add( months => 1 );
  133. my $parser = iCal::Parser->new( start => $start, end => $end );
  134. my $events = $parser->parse_strings( $calendar->as_string );
  135. if ( $log->is_trace ) {
  136. use DDP;
  137. p $events;
  138. }
  139. my $output_path;
  140. if ($OUTPUT_FILE) {
  141. $output_path = path($OUTPUT_FILE);
  142. $output_path->parent->mkpath;
  143. $output_path->remove;
  144. }
  145. for my $year ( map { $_->value }
  146. nsort_by { $_->key } pairs %{ $events->{events} } )
  147. {
  148. for my $month ( map { $_->value } nsort_by { $_->key } pairs %$year ) {
  149. for my $day ( map { $_->value } nsort_by { $_->key } pairs %$month ) {
  150. for (
  151. sort_by {
  152. $_->value->{DTSTART}
  153. . $_->value->{DTEND}
  154. . ( $_->value->{SUMMARY} || '' )
  155. }
  156. pairs %$day
  157. )
  158. {
  159. print_event(
  160. $calendar_entries{VEVENT}{ $_->key },
  161. $_->value->{DTSTART},
  162. $_->value->{DTEND},
  163. $output_path,
  164. );
  165. }
  166. }
  167. }
  168. }
  169. sub print_event
  170. {
  171. my ( $entry, $start, $end, $path ) = @_;
  172. if ( $log->is_trace ) {
  173. use DDP;
  174. p $entry;
  175. p $start;
  176. p $end;
  177. p $path;
  178. }
  179. my $summary = get_property_string( $entry, 'summary' );
  180. my $description = get_property_string( $entry, 'description' );
  181. $description =~ s/\n\n[Pp]ris:\s*((?!\n).+)\s*\z//m;
  182. my $price = $1;
  183. my @attendees;
  184. if ( $entry->property('attendee') ) {
  185. for ( @{ $entry->property('attendee') } ) {
  186. push @attendees, decode_utf8 $_->parameters->{'CN'}
  187. || $_->value =~ s/^mailto://r;
  188. }
  189. }
  190. my $location = get_property_string( $entry, 'location' );
  191. my $time_begin = ucfirst( $start->strftime('%A') );
  192. $time_begin .= $start->strftime(' %e. %B kl. %k.%M');
  193. my $time_end = $end->strftime('%k.%M');
  194. my %attachments;
  195. if ( $entry->property('attach') ) {
  196. for ( @{ $entry->property('attach') } ) {
  197. my $uri = try { URI->new( $_->value ) }
  198. or next;
  199. $uri->authority and $uri->host
  200. or next;
  201. push @{ $attachments{ $uri->host } }, $uri;
  202. }
  203. }
  204. $_ = "### $time_begin.";
  205. $_ .= " $summary"
  206. if $summary;
  207. $_ .= "\n$description";
  208. $_ .= " \nMed " . join( ' og ', @attendees ) . '.'
  209. if @attendees;
  210. $_ .= " \n**Mødested:** $location"
  211. if $location;
  212. $_ .= " \n**Tid:** ${time_begin}-${time_end}."
  213. if $time_begin and $time_end;
  214. $_ .= " \n**Pris:** $price"
  215. if $price;
  216. $_ .= " \n[Køb billet på Billetto]($attachments{'billetto.dk'}[0])"
  217. if $attachments{'billetto.dk'};
  218. $_ .= " \n[Læs mere her]($attachments{'byvandring.nu'}[0])"
  219. if $attachments{'byvandring.nu'};
  220. $_ .= "\n\n---\n\n";
  221. if ($path) {
  222. $path->append_utf8($_);
  223. }
  224. else {
  225. print $_;
  226. }
  227. }
  228. sub get_property_string
  229. {
  230. my ( $entry, $key ) = @_;
  231. return ''
  232. unless $entry->property($key);
  233. return decode_utf8 $entry->property($key)->[0]->value;
  234. }
  235. 1;