Class: Rzdtc::Base

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/rzdtc/base.rb

Instance Method Summary collapse

Instance Method Details

#base_pathObject



10
11
12
# File 'lib/rzdtc/base.rb', line 10

def base_path
  "/timetable/public/ru?STRUCTURE_ID=735&layer_id=5371&tfl=3&dir=0&checkSeats=1"
end

#check_tickets(from, to, date) ⇒ Object



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
# File 'lib/rzdtc/base.rb', line 28

def check_tickets(from, to, date)
  code0 = get_city_id(from)
  code1 = get_city_id(to)
  begin
    date = Date.parse(date.to_s).strftime('%d.%m.%Y')
  rescue ArgumentError, 'invalid date'
    return
  end

  # from station
  station0 = "&st0=#{URI.escape(from)}"
  station_code0 = "&code0=#{code0}"
  date0 = "&dt0=#{date}"

  # to station
  station1 = "&st1=#{URI.escape(to)}"
  station_code1 = "&code1=#{code1}"

  # first request to get rid and JSESSIONID
  url1 = "#{base_path}#{station0}#{station_code0}#{date0}
  #{station1}#{station_code1}".gsub(" ", "")

  begin
    resp = self.class.get(url1)
  rescue URI::InvalidURIError, 'URI must be ascii only'
    return
  end
  session_id = resp.headers["set-cookie"].split(",")[2].match('\JSESSIONID=(.*);')[1]
  rid = JSON.parse(resp.body)['rid']

  # add rid to first url and set session cookie
  url2 = url1 + "&rid=#{rid}"
  sleep(1)
  result = self.class.get(url2, headers: {"Cookie" => "JSESSIONID=#{session_id}"})
  data = JSON.parse(result.body)
  if data['result'] == "Error"
    []
  else
    data["tp"][0]["list"]
  end
end

#get_city_id(city) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rzdtc/base.rb', line 14

def get_city_id(city)
  city = city.mb_chars.upcase.to_s
  url = "/suggester?stationNamePart=#{URI.escape(city)}\
        &lang=ru&lat=0&compactMode=y"

  suggestions = self.class.get(url)
  for suggestion in suggestions
    if suggestion["n"] == city
      return suggestion["c"]
    end
  end
  nil
end