dirs (owner)

Revisions

gist: 170770 Download_button fork
public
Public Clone URL: git://gist.github.com/170770.git
Embed All Files: show embed
livescore_br.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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