Actually works
[tpope-extra.git] / perl / schedproc
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.schedprocrc that has schedule=/path/to/schedule.xml and
7 # grades=/path/to/grades.xml.  HTTP URLs are acceptable
8
9 use strict;
10 use Date::Calc::Object qw(Day_of_Week Decode_Day_of_Week Decode_Month Week_of_Year Monday_of_Week Day_of_Week_Abbreviation Delta_Days Add_Delta_Days Nth_Weekday_of_Month_Year Gmtime Mktime);
11 use Date::Calendar::Profiles qw($Profiles);
12 use Date::Calendar::Year;
13 use Getopt::Long;
14 use LWP::UserAgent;
15 use XML::Simple;
16 use vars qw(%opts %faculty %facurl);
17
18 $opts{'config'} = $ENV{HOME} . "/.schedprocrc";
19
20 my $arg = $ARGV[0] || "";
21 if($arg eq "-x") {
22     shift;
23     $opts{'format'} = "xml";
24 } elsif($arg eq "-h") {
25     shift;
26     $opts{'format'} = "html";
27 } elsif($arg eq "-m") {
28     shift;
29     $opts{'format'} = "mhc";
30 } elsif($arg eq "-c") {
31     shift;
32     $opts{'format'} = "csv";
33 } elsif($arg eq "-v") {
34     shift;
35     $opts{'format'} = "vcs";
36 } elsif($arg eq "-g") {
37     shift;
38     $opts{'format'} = "grades";
39 }
40
41 Getopt::Long::Configure ("bundling", "auto_help");
42 die "Invalid arguments\n" unless
43 GetOptions(\%opts, 'schedule|S=s', 'grades|G=s', 'faculty=s', 'name|n=s', 'format|f=s', 'config|F=s', 'out|o=s');
44
45 if (-r $opts{'config'}) {
46     open CONFIG, $opts{'config'} or die $!;
47     while(<CONFIG>) {
48         s/\#.*//;
49         next unless m/^([^=]*)=(.*)/;
50         my ($l, $r) = ($1, $2);
51         if ($l =~ /^(schedule|grades|name|faculty)$/) {
52             $opts{$l}||=$r;
53         } else {
54             warn "Unknown config file option $l.\n";
55         }
56     }
57     close CONFIG;
58 }
59
60 $opts{'schedule'} ||= "~/schedule.xml";
61 $opts{'grades'} ||= "~/grades.xml";
62 $opts{'faculty'} ||= "";
63
64 $opts{'schedule'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
65 $opts{'grades'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
66 $opts{'faculty'} =~ s/(^|,)~\//$1$ENV{HOME}\//;
67
68 if(!defined($opts{'out'}) && defined($ARGV[0])) {
69     $opts{'out'} = shift;
70 }
71
72 if(!defined($opts{'format'}) && defined($opts{'out'})) {
73     $opts{'format'} = $opts{'out'};
74     $opts{'format'} =~ s/.*\.//;
75     $opts{'format'} =~ s/^(.*\/|)\.?schedule$/mhc/;
76     undef $opts{'out'} if($opts{'out'} =~ /^(html|mhc|csv|vcs|xml|grades)$/);
77 }
78
79 $opts{'format'} ||= "";
80 undef $opts{'out'} if(($opts{'out'}||"") eq "-");
81
82 sub generate_id {
83     my ($section, $number) = split("-", shift);
84     my $id = 0;
85     foreach (split //, $section) {$id=26*$id+(ord($_)-1)%32;}
86     $id=10000*$id+$number;
87     return $id;
88 }
89
90 sub next_class {
91     my %class = @_;
92     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
93     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
94     my $firstday = Date::Calc->new($1,$2,$3);
95     my $lastday = Date::Calc->new($4,$5,$6);
96     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
97     my @days=();
98     foreach(split(" ",$class{'days'})) {
99         push @days, Decode_Day_of_Week($_);
100     }
101     my @off = ();
102     @off = @{$class{'off'}} if ($class{'off'});
103     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
104         next unless(grep($_ == Day_of_Week($today->date), @days));
105         next if(grep($_ == "$today", @off));
106         return $today;
107     }
108     $today = Date::Calc->new(Date::Calc->gmtime->date);
109     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
110         next unless(grep($_ == Day_of_Week($today->date), @days));
111         next if(grep($_ == "$today", @off));
112         return $today;
113     }
114     return undef;
115 }
116
117 sub capitalize {
118     local $_ = shift || "";
119     s/ +$//;
120     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
121     s/\b(I)(i*)\b/$1\U$2/g;
122     s/\bUs\b/US/g;
123     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
124     s/\b(Mc)([a-z])/$1\u$2/g;
125     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
126     s/\bThru\b/Through/g;
127     s/\bAcct\b/Accounting/g;
128     s/\bAmer\b/American/g;
129     s/\bChem\b/Chemistry/g;
130     s/\bComp\b/Composition/g;
131     s/\bFed\b/Federal/g;
132     s/\bGen\b/General/g;
133     s/\bIntro\b/Introduction/g;
134     s/\bPrgm\b/Programming/g;
135     s/\bOp Sys\b/Operating System/g;
136     #s/\bGovt\b/Government/g;
137     s/\bLit\b/Literature/g;
138     s/\bPrin\b/Principles/g;
139     s/\bBus\b/Business/g;
140     s/\bSyst\b/Sys/g;
141     return $_;
142 }
143
144 sub read_fileurl {
145     my $content;
146     my $url=shift;
147     if($url =~ /:\/\//) {
148         my $ua = LWP::UserAgent->new;
149         $ua->timeout(10);
150         $ua->env_proxy;
151 #       $ua->cookie_jar( {} );
152         my $response = $ua->get("$url") or die "$!";
153         die $response->status_line unless $response->is_success;
154         $content = $response->content;
155     } else {
156         open(F,$url) || die "$!";
157         $content = join ("", <F>);
158         close F;
159     }
160     return $content;
161     #my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative', 'off' ], KeyAttr => "");
162     #return @{$ref->{'class'}};
163 }
164
165 sub get_schedule {
166     my $content = read_fileurl($opts{'schedule'});
167     my $ref = XMLin($content, ForceArray => [ 'class', 'off' ], KeyAttr => "");
168     die "Could not load schedule.\n" unless $ref->{'class'};
169     return @{$ref->{'class'}};
170 }
171
172 sub get_grades {
173     my $content = read_fileurl($opts{'grades'});
174     my $ref = XMLin($content, ForceArray => [ 'class', 'cumulative' ], KeyAttr => "");
175     return $ref;
176 }
177
178 sub load_faculty {
179     my ($name, $email, $url, $content);
180     if(($opts{'faculty'}) && ! %faculty) {
181         $content = read_fileurl($opts{'faculty'});
182         foreach $_ (split("\n", $content)) {
183             m/"([^"]*)",([^,]*),([^,]*)/; # "
184             ($name, $email, $url) = ($1, $2, $3);
185             next unless ($name);
186             $name =~ s/ [A-Z]\.//g;
187             $name = lc $name;
188             $name =~ s/\W//g;
189             $faculty{$name} = $email if($email);
190             $facurl{$name} = $url if ($url);
191         }
192     }
193 }
194
195 sub get_faculty_email {
196     load_faculty();
197     my ($name);
198     $name = shift;
199     $name =~ s/ [A-Z]r?\.//g;
200     $name = lc $name;
201     $name =~ s/\W//g;
202     return $faculty{$name};
203 }
204
205 sub get_faculty_url {
206     load_faculty();
207     my ($name);
208     $name = shift;
209     $name =~ s/ [A-Z]r?\.//g;
210     $name = lc $name;
211     $name =~ s/\W//g;
212     return $facurl{$name};
213 }
214
215 sub get_mhc_header {
216 return (
217 "X-SC-Subject: New Years Day\nX-SC-Category: Holiday\nX-SC-Cond: 1 Jan\nX-SC-Duration: 00010101-\nX-SC-Record-Id: <New_Years_Day\@from.sctweb>\n",
218 "X-SC-Subject: Martin Luther King, Jr. Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Jan\nX-SC-Duration: 19870119-\nX-SC-Record-Id: <Martin_Luther_King_Jr_Day\@from.sctweb>\n",
219 "X-SC-Subject: Presidents Day\nX-SC-Category: Holiday\nX-SC-Cond: 3rd Mon Feb\nX-SC-Duration: 19710515-\nX-SC-Record-Id: <Presidents_Day\@from.sctweb>\n",
220 "X-SC-Subject: Memorial Day\nX-SC-Category: Holiday\nX-SC-Cond: Last Mon May\nX-SC-Duration: 19710531-\nX-SC-Record-Id: <Memorial_Day\@from.sctweb>\n",
221 "X-SC-Subject: Independence Day\nX-SC-Category: Holiday\nX-SC-Cond: 4 Jul\nX-SC-Duration: 17760704-\nX-SC-Record-Id: <Independence_Day\@from.sctweb>\n",
222 "X-SC-Subject: Labor Day\nX-SC-Category: Holiday\nX-SC-Cond: 1st Mon Sep\nX-SC-Duration: 18840901-\nX-SC-Record-Id: <Labor_Day\@from.sctweb>\n",
223 "X-SC-Subject: Columbus Day\nX-SC-Category: Holiday\nX-SC-Cond: 2nd Mon Oct\nX-SC-Duration: 19711011-\nX-SC-Record-Id: <Columbus_Day\@from.sctweb>\n",
224 "X-SC-Subject: Veterans Day\nX-SC-Category: Holiday\nX-SC-Cond: 11 Nov\nX-SC-Duration: 19261111-\nX-SC-Record-Id: <Veterans_Day\@from.sctweb>\n",
225 "X-SC-Subject: Thanksgiving\nX-SC-Category: Holiday\nX-SC-Cond: 4th Thu Nov\nX-SC-Duration: 14921122-\nX-SC-Record-Id: <Thanksgiving\@from.sctweb>\n",
226 "X-SC-Subject: Christmas\nX-SC-Category: Holiday\nX-SC-Cond: 25 Dec\nX-SC-Duration: 00011225-\nX-SC-Record-Id: <Christmas\@from.sctweb>\n",
227 );
228 }
229
230 sub do_mhc_schedule {
231     $| = 1;
232     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
233     my @mon = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
234     my ($file, $current, @mhc, @schedule);
235     $file = $opts{'out'};
236     @schedule = get_schedule(@_);
237     @mhc = get_mhc_header;
238     if(defined($file) && (-d $file)) {
239         my @mhc2;
240         foreach (@mhc) {
241             $_ =~ s/X-SC-Subject: ([^\n]*)/X-SC-Subject: $1\nSubject: $1/;
242             $_ =~ s/X-SC-Category: ([^\n]*)/X-SC-Category: $1\nFrom: $1/;
243             $_ =~ s/X-SC-Duration: (\d\d\d\d)(\d\d)(\d\d)-/"X-SC-Duration: $1$2$3-\nDate: $3 " . $mon[$2-1] . " 1970 12:00:00 +0000"/e;
244             push @mhc2, $_;
245         }
246         @mhc = @mhc2;
247     }
248     foreach my $row (@schedule) {
249         map {s/\n/-/g if defined; $_} %$row;
250         my $id=generate_id($row->{'id'});
251         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
252         $row->{'days'} =~ s/^ //;
253         #$row->{'duration'} =~ s/(\d\d)-(\d\d)-(\d\d)/20$3$1$2/g;
254         my @day = ();
255         @day = map { "!" . $_ } (@{$row->{'off'}}) if ($row->{'off'});
256         $current = "";
257         #print "# $id\n";
258         $current .= "X-SC-Subject: " . $row->{'title'} . "\n";
259         $current .= "X-SC-Location: " . $row->{'location'} . "\n";
260         $current .= "X-SC-Category: School\n";
261         $current .= "X-SC-Cond: " . $row->{'days'} . "\n";
262         $current .= "X-SC-Time: ".$row->{'begin'}."-".$row->{'end'}."\n";
263         $current .= "X-SC-Duration: " . $row->{'duration'} . "\n";
264         $current .= "X-SC-Day: @day\n" if(exists $day[0]);
265         $current .= "X-SC-Alarm: 15 minutes\n";
266         $current .= "X-SC-Record-Id: <".$row->{'id'}."\@from.sctweb>\n";
267         if(defined($file) && (-d $file)) {
268             my $email = get_faculty_email $row->{'instructor'};
269             $row->{'instructor'} = '"' . $row->{'instructor'} . '" <'. ($email || ($1 || "unknown") . "\@from.sctweb") . ">";
270             $row->{'duration'} =~ /^(\d\d\d\d)(\d\d)(\d\d)-\d{8}$/;
271             $row->{'begin'} =~ /^(\d\d):(\d\d)$/;
272             my $next = next_class(%$row);
273             my @date = Gmtime(Mktime($next->date,$1,$2,0));
274             $current .= sprintf "Date: %s, %2d %s %4d %02d:%02d:00 +0000\n", Day_of_Week_Abbreviation($date[7]), $date[2], $mon[$date[1]-1], $date[0], $date[3], $date[4], $date[5];
275             $current .= "Subject: " . $row->{'title'} . "\n";
276             $current .= "From: " . $row->{'instructor'} . "\n";
277         }
278         #print "\n$current";
279         push @mhc, $current;
280     }
281     if(defined($file) && (-d $file)) {
282         my @lines;
283         foreach my $name (<$file/[1-9]*>) {
284             next unless $name =~ /^$file\/[1-9][0-9]*$/;
285             open (FH, $name) || die $!;
286             @lines = <FH>;
287             close FH;
288             foreach (@lines) {
289                 unlink $name if /^X-SC-Record-Id: <.*\@from.sctweb>/;
290             }
291         }
292         my $i=0;
293         foreach (@mhc) {
294             while(-f ++$i) {}
295             open (FH, ">$file/$i") || die $!;
296             print FH $_;
297             close FH;
298         }
299     } else {
300         open(STDOUT, ">" . $file) || die $! if(defined($file));
301         print "# MHC school schedule\n# Autogenerated by sctweb ".localtime()."\n\n";
302         print join("\n", @mhc);
303     }
304 }
305
306 sub do_csv_schedule {
307     $| = 1;
308     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
309     my @mon = qw(Jan. Feb. Mar. Apr. May June July Aug. Sept. Oct. Nov. Dec.);
310     my ($current, @mhc, @schedule);
311     @schedule = get_schedule(@_);
312     open(STDOUT, ">" . $opts{'out'}) || die $! if(defined($opts{'out'}));
313     foreach my $row (@schedule) {
314         map {s/\n/-/g if defined; $_} %$row;
315         my $id=generate_id($row->{'id'});
316         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
317         $row->{'days'} =~ s/^ //;
318         my $next = next_class(%$row);
319         $current = "";
320         #print "# $id\n";
321         $current .= $row->{'id'} . ",";
322         $current .= $row->{'title'} . ",";
323         my $instructor = $row->{'instructor'};
324         $instructor =~ s/ [A-Z. ]* / /;
325         $current .= '"' . $instructor . '",';
326         $next =~ /^(\d\d\d\d)(\d\d)(\d\d)$/;
327         $current .= $1 . "-". $2 ."-" . $3 . "\n";
328         print $current;
329     }
330 }
331
332 sub do_vcalendar_schedule {
333     $| = 1;
334     my %days = (M => "MO", T => "TU", W => "WE", R => "TH", F => "FR", S => "SA", U => "SU");
335     my $file = $opts{'out'};
336     my @schedule = get_schedule(@_);
337     open(STDOUT, ">>" . $file) || die $! if(defined($file) && (! -d $file));
338     open(STDOUT, ">/dev/null") || die $! if(defined($file) && (-d $file));
339     print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
340     foreach my $row (@schedule) {
341         map { s/\n/-/g; $_} %$row;
342         $row->{'days'} =~ s/([MTWRFS])/ $days{$1}/g;
343         $row->{'days'} =~ s/^ //;
344         my @day = ();
345         @day = @{$row->{'off'}} if ($row->{'off'});
346         my $day = "";
347         if(exists($day[0])) {
348             $day = join(";", @day);
349             $day =~ s/\b(\d{8})\b/$1T000000/g;
350         }
351         my ($starttime, $stoptime)=($row->{'begin'}, $row->{'end'});
352         my ($startdate, $stopdate)=split(/-/, $row->{'duration'});
353         $starttime =~ s/://;
354         $stoptime =~ s/://;
355         if(defined($file) && (-d $file)) {
356             open FH, ">$file/" . $row->{'id'} . ".vcs" or die "$!";
357             select FH;
358             print "BEGIN:VCALENDAR\r\nVERSION:1.0\r\n";
359         }
360         print "BEGIN:VEVENT\r\n";
361         print "SUMMARY:", $row->{'title'}, "\r\n";
362         print "DESCRIPTION:", $row->{'id'}, "\r\n";
363         print "LOCATION:", $row->{'location'}, "\r\n";
364         print "CATEGORIES:Education\r\n";
365         print "DTSTART:", $startdate."T".$starttime, "00\r\n";
366         print "DTEND:", $startdate."T".$stoptime, "00\r\n";
367         print "RRULE:W1 ", $row->{'days'} . " $stopdate", "T000000\r\n";
368         print("EXDATE:$day\r\n") if($day);
369         print "ATTENDEE;ROLE=OWNER;STATUS=CONFIRMED:", $opts{'name'}, "\r\n" if(defined($opts{'name'}));
370         print "ATTENDEE;ROLE=ORGANIZER;STATUS=CONFIRMED:", $row->{'instructor'}, " <" . (get_faculty_email($row->{'instructor'}) || "fake\@ddress"), ">\r\n";
371         print "END:VEVENT\r\n";
372         if(defined($file) && (-d $file)) {
373             print "END:VCALENDAR\r\n";
374             close FH;
375             select STDOUT;
376         }
377     }
378     print "END:VCALENDAR\r\n";
379 }
380
381 sub do_xml_schedule {
382     my $file = $opts{'out'};
383     my $schedule = { class => [ get_schedule(@_) ] };
384     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
385     if($file) {
386         open FH, ">$file" || die $!;
387         print FH $xml;
388         close FH;
389     } else {
390         print $xml;
391     }
392 }
393
394 sub do_html_schedule {
395     my @showheaders = ("Section ID/Title", "Instructor", "Days", "Time", "Duration", "Location");
396     my $shade = "dark";
397     my @schedule = get_schedule(@_);
398     if($opts{'out'}) {
399         open (FH, ">".$opts{'out'}) || die $!;
400         select FH;
401     }
402     print '<table id="schedule" cellpadding="3" cellspacing="0">'."\n<tr><th>";
403     print join("</th><th>",@showheaders);
404     print "</th></tr>\n";
405         foreach my $row (@schedule) {
406             map { s/\n/<br \/>/g; $_} %$row;
407             $row->{'duration'} =~ s/-/<br \/>/g;
408             $row->{'duration'} =~ s/\d\d(\d\d)(\d\d)(\d\d)/$2-$3-$1/g;
409             print '<tr class="'.$shade.'">';
410             $shade = ($shade eq "dark"?"light":"dark");
411             print '<td class="idtitle">';
412             print '<span class="sectionid">' .$row->{'id'}. '</span><br />';
413             print '<span class="coursetitle">' .$row->{'title'}. '</span></td>';
414             my $instructor = $row->{'instructor'};
415             #$instructor =~ s/ [A-Z. ]* / /;
416             my $url = get_faculty_url($row->{'instructor'});
417             if($url) {
418                 print '<td class="instructor"><a href="' . $url . '">'
419                 . $row->{'instructor'} . "</a></td>";
420             } else {
421                 print '<td class="instructor">' . $instructor . "</td>";
422             }
423             print "<td>" . $row->{'days'} . "</td>";
424             my ($a,$b) = ($row->{'begin'}, $row->{'end'});
425             $b .= "AM";
426             $a=~s/(1[3-9]|2\d|00):(\d\d)/sprintf "%d:%02d",abs $1-12,$2/e;
427             $b=~s/(1[3-9]|2\d|00):(\d\d)AM/sprintf "%d:%02dPM",abs $1-12,$2/e;
428             print "<td>$a-<wbr />$b</td>";
429             print "<td>" . $row->{'duration'} . "</td>";
430             print "<td>" . $row->{'location'} . "</td>";
431             print "</tr>\n";
432         }
433     print "</table>\n";
434     select STDOUT;
435 }
436
437 sub do_html_grades {
438     my $grades;
439     my @showheaders = ("Section ID", "Course Title", "Grade", "Earned<br />Hours", "Quality<br />Hours", "Quality<br />Points");
440     $grades = get_grades(@_);
441     my ($row);
442     my $shade = "dark";
443     if($opts{'out'}) {
444         open (FH, ">".$opts{'out'}) || die $!;
445         select FH;
446     }
447     print '<table id="grades" cellpadding="3" cellspacing="0">'."\n<tr>";
448     print '<th align="left" class="sectionid">', $showheaders[0];
449     print '</th><th align="left" class="coursetitle">', $showheaders[1];
450     print '</th><th align="center" class="grade">';
451     print join('</th><th align="center" class="right-number">',@showheaders[2 .. 5]);
452     print "</th></tr>\n";
453     foreach my $ts ($grades->{'class'}) {
454         foreach my $row (@$ts) {
455             print '<tr class="'.$shade.'">';
456             $shade = ($shade eq "dark"?"light":"dark");
457             print '<td align="left" class="sectionid">', $row->{'id'}, '</td>';
458             print '<td align="left" class="coursetitle">', $row->{'title'}, '</td>';
459             print '<td align="center" class="grade">';
460             #print join('</td><td>', @$row[0 .. 1]);
461             print join('</td><td align="right" class="right-number">', ($row->{'grade'},$row->{'earned'},$row->{'hours'},$row->{'points'}));
462             print "</td></tr>\n";
463         }
464     }
465     my $lastrow = $grades->{'cumulative'}->[scalar @{$grades->{'cumulative'}}-1];
466     print '<tr class="cumulative '.$shade.'"><td id="cumulative" colspan="2">Cumulative: through ', capitalize($lastrow->{'term'});
467     print '</td><td align="center" id="gpa" class="grade">';
468     print $lastrow->{'gpa'};
469     print '</td><td align="right" class="right-number">';
470     print join('</td><td align="right" class="right-number">', ($lastrow->{'earned'}, $lastrow->{'hours'}, $lastrow->{'points'}));
471     print "</td></tr>\n";
472     print "</table>\n";
473     select STDOUT;
474 }
475
476
477 if ($opts{'format'} eq "xml") {
478     do_xml_schedule(@ARGV);
479 } elsif ($opts{'format'} eq "html") {
480     do_html_schedule(@ARGV);
481 } elsif ($opts{'format'} eq "mhc") {
482     do_mhc_schedule(@ARGV);
483 } elsif ($opts{'format'} eq "csv") {
484     do_csv_schedule(@ARGV);
485 } elsif ($opts{'format'} eq "vcs") {
486     do_vcalendar_schedule(@ARGV);
487 } elsif ($opts{'format'} eq "grades") {
488     do_html_grades(@ARGV);
489 } else {
490     die "Unknown format.  Try specifying --format.\n"
491 }