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