#!/usr/bin/env ruby # # Prints out the schedules for NFL team from espn.com to an output # dir. See this file for exact options. # # Examples: # # % ./nflschedules # Writes the schedules to 'out' # % ./nflschedules -d schedules # Writes the schedules to 'schedules' # % ./nflschedules -v # Tells you what the hell we're doing # % ./nflschedules -i # Download the icons only # require 'open-uri' require 'ics' # -------------------------------------------------- # Types # -------------------------------------------------- class NflSchedules attr_writer :verbose, :outdir, :icons def initialize @verbose = true @outdir = nil @icons = false end def start stations2events, teams2events, televised2events = collect_events return if @icons Dir.mkdir @outdir if !File.exists?(@outdir) log 'Wrote stations to ' + output_events('stations' , stations2events) log 'Wrote teams to ' + output_events('teams' , teams2events) log 'Wrote televised games to ' + output_events('televised' , teams2events) end private # Outputs all the events for each id in a subdir of 'outdir' def output_events(subdir,ids2events) dir = File.join @outdir, subdir Dir.mkdir dir if !File.exists?(dir) ids2events.each do |id,events| outfile = File.join dir, canonical_name(id) + ".ics" File.open outfile, "w" do |out| out.print ICS.header(id.to_s + ' Schedule: ' + Time.now.year.to_s) events.map { |e| out.print e.to_ics } out.print ICS.footer end end return dir end # Returns a canonical name for 'team' def canonical_name(team) team.gsub /\W/, '_' end # Returns a tuple of hashes # 1. stations2events # 2. teams2events # 3. televised2events # From crawling the ESPN page def collect_events # Collect the events into two maps # 1. stations to events # 2. teams to events # 3. televised games to events stations2events = {} teams2events = {} televised2events = {} date = nil inside = false team_home = nil team_away = nil month = nil day_of_month = nil day = nil hours = nil minutes = nil station = nil open('http://sports.espn.go.com/nfl/schedule').read.each "\n" do |line| # Find the abbreviations # option value="http://sports.espn.go.com/nfl/teams/schedule?team=ari&year=2008">Arizona if @icons line.scan /option value="http:[^"]+teams\/schedule\?team=(\w+)[^"]*">(.*)/ do |res| abbrev,team = res team = team.strip url = 'http://assets.espn.go.com/i/teamlogos/nfl/med/trans/' + abbrev + '.gif' file = File.basename url log 'Downloading ' + url system 'download -v ' + url newfile = File.join @outdir, canonical_name(team) + '.gif' log 'Moving ' + file + ' -> ' + newfile system 'mv ' + file + ' ' + newfile end next end #