require 'rubygems'
require 'simple-daemon'
require 'open-uri'
require 'hpricot'
require 'iconv'
require 'json'
require 'memcache'
class Crawler < SimpleDaemon::Base
SimpleDaemon::WORKING_DIRECTORY = "/Users/dirs/Sites/toy/iPhonePush/ruby"
def initialize
@memcache = MemCache::new('127.0.0.1:11211')
end
def self.start
# vamos verificar se o jogo está acontecendo de 5 em 5 minutos
loop do
# entra na espn
content = open("http://espnbrasil.terra.com.br/temporeal").read
content = Iconv.conv('utf-8', 'ISO-8859-1', content)
doc = Hpricot(content)
loop do
# e se saiu gol a cada 30 segundos
(doc/"div.bloco_jogos").each do |bloco|
# verifica se está ocorrendo
if (bloco/".noticia_dia").inner_html.strip == 'Agora'
# se estiver pega os nomes dos times
time_da_casa = (bloco/".time1/a").inner_html.strip
time_de_fora = (bloco/".time2/a").inner_html.strip
# link e id do jogo para acessar os dados em real-time
link = (bloco/".placar/a").first.attributes['href']
id = /realTimeMatch\.id=(.*)/.match(link)[1]
real_time = JSON.parse(open("http://espnbrasil.terra.com.br/temporeal/acoes.narracao.logic?realTimeMatch.id=#{id}").read)
gols_time_da_casa = real_time['match']['mandatoryGol']
gols_time_de_fora = real_time['match']['visitingGol']
jogo = {time_da_casa => gols_time_da_casa, time_de_fora => gols_time_de_fora}
if @memcache[id].nil?
@memcache[id] = jogo
else
# verifica se alguem fez um gol
if jogo[time_da_casa] > @memcache[id][time_da_casa] || jogo[time_de_fora] > @memcache[id][time_de_foram]
comentario = real_time['match']['commentaries'][0]
tempo_do_gol = comentario['title']
periodo_do_gol = comentario['period'] == "PT" ? '1˚ Tempo' : '2˚ Tempo'
p "GOL! #{time_da_casa} #{jogo[time_da_casa]} - #{time_de_fora} #{jogo[time_de_foram]} aos #{tempo_do_gol} do #{periodo_do_gol}"
@memcache[id] = jogo
end
end
end
end
sleep 30
end
sleep 300
end
end
def self.stop
puts "Stopping processor"
end
end
Crawler.daemonize