3682c398c32ea1b7d4d2eab32d069415d3fa1303
[tpope-extra.git] / perl / sct6
1 #!/usr/bin/perl -w
2 # $Id$
3 # -*- perl -*- vim: ft=perl sw=4 sts=4
4
5 # Brief usage instructions:
6 # Create a ~/.sct6rc that has SID=yourssn and PIN=yourpin
7 # You'll need to change the url below if you go anywhere but TAMUK.
8
9 # Update: This tool now only outputs in XML.  For other formats, convert
10 # with schedproc
11
12 use strict;
13 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);
14 use Date::Calendar::Profiles qw($Profiles);
15 use Date::Calendar::Year;
16 use HTML::TableExtract;
17 use LWP::UserAgent;
18 use XML::Simple;
19 use vars qw($ua %opts %faculty);
20
21 my ($response);
22
23 $opts{'holidays'} = { # %{$Profiles->{'US-TX'}},
24     "Martin Luther King Day"    => "3/Mon/Jan",
25     "Good Friday"               => "-2",
26     "Spring Break Monday"       => \&Spring_Break,
27     "Spring Break Tuesday"      => \&Spring_Break,
28     "Spring Break Wednesday"    => \&Spring_Break,
29     "Spring Break Thursday"     => \&Spring_Break,
30     "Spring Break Friday"       => \&Spring_Break,
31     "Spring Break Saturday"     => \&Spring_Break,
32     "Study Day"                 => "4/Thu/Apr", # ?
33     "Memorial Day"              => "5/Mon/May",
34     "Independence Day"          => \&US_Independence,
35     "Labor Day"                 => \&US_Labor,
36     #"Columbus Day"              => "2/Mon/Oct",
37     "Thanksgiving Day"          => "4/Thu/Nov",
38     "Thanksgiving Friday"       => \&Thanksgiving_Friday,
39 };
40
41 sub Spring_Break {
42     my($year,$label) = @_;
43     $label =~ s/^Spring Break //;
44     return( Add_Delta_Days(
45             Nth_Weekday_of_Month_Year($year,1,1,1),
46             7*(11-1) # This is for the 11th Monday of the year
47             +Decode_Day_of_Week($label)-1) );
48 }
49
50 sub Thanksgiving_Friday {
51     my($year,$label) = @_;
52     return( Add_Delta_Days(Nth_Weekday_of_Month_Year($year,11,4,4), 1) );
53 }
54 sub US_Independence # Fourth of July
55 {
56     my($year,$label) = @_;
57     return( &Date::Calendar::Profiles::Nearest_Workday($year,7,4) );
58 }
59 sub US_Labor # First Monday after the first Sunday in September
60 {
61     my($year,$label) = @_;
62     return( Add_Delta_Days(
63         Nth_Weekday_of_Month_Year($year,9,7,1), +1) );
64 }
65
66 my $config = $ENV{HOME} . "/.sct6rc";
67 if (($ARGV[0] || "") eq '-F') {
68     shift;
69     $config = shift;
70 }
71
72 my $arg = "";
73 $arg = shift if (defined($ARGV[0]) && $ARGV[0] =~ /^-\w$/);
74
75 if (-r $config) {
76     open CONFIG, $config;
77     while(<CONFIG>) {
78         s/\#.*//;
79         next unless m/^([^=]*)=(.*)/;
80         $opts{$1}=$2;
81     }
82     close CONFIG;
83 }
84 my $domain = $opts{'domain'} || "as1.tamuk.edu:9003";
85 my $url = "https://$domain/pls/PROD/";
86 $url = $opts{'url'} if(defined($opts{'url'}));
87
88 $ua = LWP::UserAgent->new;
89 $ua->timeout(10);
90 $ua->env_proxy;
91 $ua->cookie_jar( {} );
92 $ua->get("${url}twbkwbis.P_WWWLogin") or die "$!";
93 $response = $ua->post("${url}twbkwbis.P_ValLogin", { sid => $opts{SID}, PIN => $opts{PIN} }) or die "$!";
94
95 $response = $ua->get("${url}bwskflib.P_SelDefTerm"); # Valid terms
96 die $response->status_line unless $response->is_success;
97 my @terms = grep {s/^<option value="([^"]*)">.*/$1/i} (split( /\r?\n/, $response->content)); # "
98 die "Site down. Try again later.\n" unless (@terms);
99
100 sub next_class {
101     my %class = @_;
102     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
103     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
104     my $firstday = Date::Calc->new($1,$2,$3);
105     my $lastday = Date::Calc->new($4,$5,$6);
106     my $today = Date::Calc->new(Date::Calc->localtime(time+3600*6)->date);
107     my @days=();
108     foreach(split(" ",$class{'days'})) {
109         push @days, Decode_Day_of_Week($_);
110     }
111     my @off = @{$class{'off'}};
112     for($today = ($today > $firstday ? $today : $firstday); $today < $lastday; $today++) {
113         next unless(grep($_ == Day_of_Week($today->date), @days));
114         next if(grep($_ == $today, @off));
115         return $today;
116     }
117     $today = Date::Calc->new(Date::Calc->gmtime->date);
118     for($today = ($today < $lastday ? $today : $lastday); $today > $firstday; $today--) {
119         next unless(grep($_ == Day_of_Week($today->date), @days));
120         next if(grep($_ == $today, @off));
121         return $today;
122     }
123     return undef;
124 }
125
126 sub off_for_holidays {
127     my %class = @_;
128     my %days = (M => "Mon", T => "Tue", W => "Wed", R => "Thu", F => "Fri", S => "Sat", U => "SU");
129     my $d = $class{'days'};
130     $d =~ s/([MTWRFS])/ $days{$1}/g;
131     $d =~ s/^ //;
132     $class{'duration'} =~ /(\d\d\d\d)(\d\d)(\d\d)-(\d\d\d\d)(\d\d)(\d\d)/;
133     my $days = Delta_Days($1,$2,$3,$4,$5,$6);
134     my $firstday = Date::Calc->new($1,$2,$3);
135     my $lastday = Date::Calc->new($4,$5,$6);
136     my $year = Date::Calendar::Year->new($1, $opts{'holidays'});
137     my @holidays=();
138     my @days=();
139     foreach(split(" ",$d)) {
140         $days[Decode_Day_of_Week($_)] = 1;
141     }
142     foreach ($year->search("")) {
143         my $good=1;
144         #foreach my $x ($year->labels($_)) {
145         #    $good=0 if ($x =~ /Veteran/ or $x =~ /President/);
146         #}
147         next unless ($year->is_full($_) && $_>=$firstday && $_<=$lastday);
148         push @holidays, $_
149             if (defined($days[Day_of_Week($_->date)]) && $good > 0);
150     }
151     return wantarray ? @holidays : "@holidays";
152 }
153
154 sub off_for_exams {
155     my %class = @_;
156     my $time = $class{'begin'} . "-" . $class{'end'};
157     $class{'duration'} =~ /\d{8}-(\d\d\d\d)(\d\d)(\d\d)/;
158     my $lastday = Date::Calc->new($1,$2,$3);
159     return wantarray ? () : undef unless (Day_of_Week($lastday->date) == 7);
160     my $beginning="(08:00-09:15|11:00-12:15|14:00-15:15|17:00-18:15|17:30-18:45|20:00-21:15|20:30-21:45)";
161     my $ending   ="(06:30-07:45|09:30-10:45|12:30-13:45|15:30-16:45|18:30-19:45|19:00-20:15)";
162     my $days = join(" ",map {Decode_Day_of_Week($_)} split(/ /, $class{'days'}));
163     if($days eq "1 3") {
164         if($time =~ /$beginning/) {
165             return $lastday-4;
166         } elsif($time =~ /$ending/) {
167             return $lastday-6;
168         }
169     } elsif($days eq "2 4") {
170         if($time =~ /$beginning/) {
171             return $lastday-3;
172         } elsif($time =~ /$ending/) {
173             return $lastday-5;
174         }
175     } elsif($days eq "5") {
176         return $lastday-2;
177     }
178     return wantarray ? () : "";
179 }
180
181 sub capitalize {
182     local $_ = shift || "";
183     s/ +$//;
184     s/\b([A-Z])([A-Z]*)\b/$1\L$2/g;
185     s/\b(I)(i*)\b/$1\U$2/g;
186     s/\bUs\b/US/g;
187     s/ (And|For|Of|Or|The|To|With) / \l$1 /g;
188     s/\b(Mc)([a-z])/$1\u$2/g;
189     s/\b(Tcp\/Ip|Pc|Tba)\b/\U$&/g;
190     s/\bThru\b/Through/g;
191     s/\bAcct\b/Accounting/g;
192     s/\bAmer\b/American/g;
193     s/\bChem\b/Chemistry/g;
194     s/\bComp\b/Composition/g;
195     s/\bFed\b/Federal/g;
196     s/\bGen\b/General/g;
197     s/\bIntro\b/Introduction/g;
198     s/\bPrgm\b/Programming/g;
199     s/\bOp Sys\b/Operating System/g;
200     #s/\bGovt\b/Government/g;
201     s/\bLit\b/Literature/g;
202     s/\bPrin\b/Principles/g;
203     s/\bBus\b/Business/g;
204     s/\bSyst\b/Sys/g;
205     return $_;
206 }
207
208 sub get_schedule_terms {
209     my (@sterms, @a);
210     @a=('10','20','30','40');   # Fall, Spring, Summer I, Summer II
211                                 # Last 3 are currently guesses
212     my @localtime=localtime();
213     if ($localtime[4]<3) { # Through Mar 31
214         @sterms=((1900+$localtime[5]).$a[1]);
215     } elsif ($localtime[4]<5) { # Through May 31
216         @sterms=((1900+$localtime[5]).$a[1],(1900+$localtime[5]).$a[2]);
217     } elsif ($localtime[4]<7) { # through July 31
218         @sterms=((1900+$localtime[5]).$a[2],(1900+$localtime[5]).$a[3]);
219     } elsif ($localtime[4]<8) { # through Aug 31
220         @sterms=((1900+$localtime[5]).$a[3],(1901+$localtime[5]).$a[0]);
221     } elsif ($localtime[4]<10) { # through Oct 31
222         @sterms=((1901+$localtime[5]).$a[0]);
223     } else {
224         @sterms=((1901+$localtime[5]).$a[0],(1901+$localtime[5]).$a[1]);
225     }
226     return @sterms;
227 }
228
229 sub get_schedule {
230     my @readheaders = ("Type", "Time", "Days", "Where", "Date Range", "Schedule Type", "Instructors");
231     my @class;
232     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
233     my (@schedule, @terms, $classid, $title, $begin, $end, $times, $days, $session);
234     @terms = get_schedule_terms();
235     foreach (@_ ? @_ : @terms) {
236         $response = $ua->get("${url}bwskfshd.P_CrseSchdDetl?term_in=$_" );
237         die $response->status_line unless $response->is_success;
238         $te->parse($response->content);
239         foreach my $l (split (/\n/, $response->content)) {
240             next unless $l =~ s/.*<CAPTION class=[^>]*>(.* - .... \d\d\d\d \d\d\d)<\/caption>.*/$1/i;
241             push @class, $l;
242         }
243     }
244     foreach my $ts ($te->table_states) {
245         foreach my $row ($ts->rows) {
246             #map { s/\xa0//g; $_} @$row;
247             #$row->[0] =~ s/.*launchWebCT\("([^"]*)"\).*/$1/s;
248             #$row->[0] =~ s/(.*) ?<[Bb][Rr][^>]*>(.*)/capitalize($2)/eg;
249             $classid = (shift @class);
250             $title = $classid;
251             $classid =~ s/.* - //;
252             $classid =~ s/ /-/g;
253             $title =~ s/ - .*//;
254             $row->[6] =~ s/\b([A-Z]r?)$/$1./;
255             $row->[6] = capitalize($row->[6]);
256             $row->[6] =~ s/ *\([A-Z]\)//;
257             $row->[1] =~ s/ ?([ap])m/\u$1M/g;
258             $row->[1] =~ s/ - /-/;
259             ($begin, $end) = split(/ ?- ?/, $row->[1]);
260             $begin =~ s/^(\d):/0$1:/;
261             $end =~ s/^(\d):/0$1:/;
262             if (($begin=~/PM$/ && $begin!~/^12/)||($begin=~/^12:..AM/)) {
263                 $begin =~ s/^(\d?\d)/($1+12)%24/e;
264             }
265             if (($end=~/PM$/ && $end!~/^12/)||($end=~/^12:..AM/)) {
266                 $end =~ s/^(\d?\d)/($1+12)%24/e;
267             }
268             $begin =~ s/ ?[AP]M//;
269             $end =~ s/ ?[AP]M//;
270             $row->[4] =~ s/([A-Za-z]{3,9})/(Decode_Month($1)<10?"0":"").Decode_Month($1)/eg;
271             $row->[4] =~ s/(\d\d?) (\d\d), (\d\d\d\d)/$3$1$2/g;
272             $row->[4] =~ s/ - /-/;
273             $row->[3] =~ s/(ON|MAIN) CAMPUS\n|Palo Alto Building \d* //ig;
274             $row->[3] =~ s/\n/ /g;
275             my %class = (
276                 id => $classid,
277                 title => capitalize($title),
278                 instructor => $row->[6],
279                 days => $row->[2],
280                 #'time' => $row->[1],
281                 begin => $begin,
282                 end => $end || undef,
283                 duration => $row->[4],
284                 location => $row->[3],
285             );
286             my @off = ( map { "$_"; } (off_for_holidays(%class), off_for_exams(%class)));
287             $class{'off'} = [ @off ] if (@off);
288             push @schedule, \%class;
289         }
290     }
291     return @schedule;
292 }
293
294 sub do_xml_schedule {
295     my $file = shift if (defined $_[0] and $_[0] !~ /^\d/);
296     my $schedule = { class => [ get_schedule(@_) ] };
297     my $xml = XMLout($schedule, NoAttr => 1, RootName => 'schedule');
298     if($file) {
299         open FH, ">$file";
300         print FH $xml;
301         close FH;
302     } else {
303         print $xml;
304     }
305 }
306
307 #sub do_xml_grades {
308 #    print "<grades>\n</grades>\n";
309 #}
310
311 sub do_xml_grades {
312     #my @readheaders = ("Subject", "Course", "Section", "Course Title", "Final Grade", "Attempted", "Earned", "GPA Hours", "Quality Points");
313     my @readheaders = ("Subject", "Course", "Section", "CTitle", "Final Grade", "Attempted", "Earned", "GPA Hours", "Quality Points");
314     my ($row, $lastrow);
315     my $te = new HTML::TableExtract( headers => [ @readheaders ] );
316     my $response = $ua->get("$url/bwskogrd.P_ViewTermGrde"); # Valid grading terms
317     die $response->status_line unless $response->is_success;
318     #my @terms = reverse grep {s/^<option value="([^"]*)">.*/$1/} (split( /\r\n/, $response->content));
319     my @grades = ();
320     my @terms = ();
321     my $year = Date::Calc->localtime->year;
322     for(my $y=$year-3;$y<=$year+1;$y++) { push @terms, ($y.10,$y.20,$y.30,$y.40); }
323     foreach(@_ ? @_ : @terms) {
324         $response = $ua->get("$url/bwskogrd.P_ViewGrde?term_in=".($_) );
325         die $response->status_line unless $response->is_success;
326         my $content = $response->content;
327         $content =~ s/Course Title/CTitle/g;
328         $te->parse($content);
329     }
330     foreach my $ts ($te->table_states) {
331         foreach my $row ($ts->rows) {
332             map { s/^\s+//; s/\xa0|\r//g; s/\n/<br \/>/g; $_} @$row;
333             $row->[3] = capitalize($row->[3]);
334             $row->[3] =~ s/&/&amp;/g;
335             #$row->[0] =~ s/Cumulative through/Cumulative: through/;
336             #$row->[0] =~ s/Cumulative:(.*) (\d{4}) (.*)/Cumulative:$1 $3 $2/;
337             $lastrow=$row;
338             next if $row->[0] =~ /:|Current Term/;
339             push @grades, {
340                 id => $row->[0]."-".$row->[1]."-".$row->[2],
341                 title => $row->[3],
342                 grade => $row->[4],
343                 attempted => $row->[5],
344                 earned => $row->[6],
345                 hours => $row->[7],
346                 points => $row->[8]
347             };
348         }
349     }
350     $lastrow->[0] =~ s/Cumulative:? *through *//i;
351     my $cumulative = { term => capitalize($lastrow->[0]),
352                        gpa => $lastrow->[6],
353                        earned => $lastrow->[3],
354                        hours => $lastrow->[4],
355                        points => $lastrow->[5]
356                    };
357     my $xml = XMLout({class => [@grades], cumulative => []}, NoAttr => 1, RootName => 'grades');
358     print $xml;
359     return;
360 }
361
362 sub do_transcripts {
363     print "Not implemented.\n";
364 }
365
366 if ($arg eq "-g") {
367     do_xml_grades(@ARGV);
368 } elsif ($arg eq "-t") {
369     do_transcripts;
370 } elsif ($arg eq "-x" || $arg eq "-s" || 1) {
371     do_xml_schedule(@ARGV);
372 }
373
374 $ua->get("${url}twbkwbis.P_Logout"); # Logout