Skip to content

Instantly share code, notes, and snippets.

@spudtrooper
Created April 26, 2011 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spudtrooper/942321 to your computer and use it in GitHub Desktop.
Save spudtrooper/942321 to your computer and use it in GitHub Desktop.
Send email alerts for NJ transit
#!/usr/bin/env ruby
#
# Sends an email about alerts for NJ transit trains.
#
# Usage:
#
# njtransit email? city?
#
# Examples:
#
# njtransit
# njtransit user@domain.com
# njtransit user@domain.com "Atlantic City"
#
require 'open-uri'
require 'net/smtp'
STATE_NONE = 0
STATE_LOOKING_FOR_CITY = 1
STATE_LOOKING_FOR_ALERT = 2
def note(s)
STDERR.puts s
STDERR.flush
end
def sendmail(from,to,subject,message)
note "Sending to #{to}..."
msg = <<HERE
From: #{from}
To: #{to}
Subject: #{subject}
#{message}
HERE
Net::SMTP.start('localhost') do |smtp|
smtp.send_message msg, from, to
end
end
def main(argv)
addr = argv.shift || ENV['USER']
target = argv.shift || 'Morris & Essex'
real_target = target
target = target.downcase
target = target.gsub /&/,'&amp;'
note "Searching for #{real_target}"
url = 'http://www.njtransit.com/hp/hp_servlet.srv?hdnPageAction=HomePageTo'
state = STATE_NONE
open(url).read.split("\n").each do |line|
case state
when STATE_NONE
if line =~ /<img src="http:\/\/www.njtransit.com\/images\/status_\w+\.jpg"/
state = STATE_LOOKING_FOR_CITY
end
when STATE_LOOKING_FOR_CITY
line.scan /<td[^>]*>([^<]+)<\/td>/ do |res|
if res[0].downcase == target#~ /#{target}/
state = STATE_LOOKING_FOR_ALERT
else
state = STATE_NONE
end
end
when STATE_LOOKING_FOR_ALERT
case line
when />View Alert<\/a><\/td>/
note "Found alert for #{real_target}"
sendmail addr,addr,'NJ Transit',
"Check out http://njtransit.com for alerts on #{real_target}"
when /<\/tr>/
break
end
end
end
end
main ARGV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment