blob: 1e78ca04a7f94396d88c798d0257380063487fc5 (
plain)
| 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
 | module STIF
  class NetexFile
    CALENDAR_FILE_NAME = 'calendriers.xml'
    LINE_FILE_FORMAT   = %r{\A offre_ (?<line_object_id> .*?) _ .* \. xml \z}x
    XML_NAME_SPACE     = "http://www.netex.org.uk/netex"
    def initialize(file_name)
      @file_name = file_name
    end
    def frames
      frames = Hash.new { |h,k| h[k] = NetexFile::Frame.new(k) }
      Zip::File.open(@file_name) do |zipfile|
        zipfile.each do |entry|
          add_frame(to_frames: frames, from_entry: entry) if entry.ftype == :file
        end
      end
      frames.values
    end
    private
    def add_frame(to_frames:, from_entry:)
      entry_dir_name, entry_file_name = File.split(from_entry.name)
      if CALENDAR_FILE_NAME === entry_file_name
        from_entry.get_input_stream do |stream|
          to_frames[entry_dir_name].parse_calendars(stream.read)
        end
        return
      end
      line_file_match =  LINE_FILE_FORMAT.match( entry_file_name )
      if line_file_match
        to_frames[entry_dir_name].add_offer_file( line_file_match['line_object_id'])
      end
    end
    class Frame
      class << self
        def get_short_id file_name
          base_name = File.basename(file_name)
          STIF::NetexFile::LINE_FILE_FORMAT.match(base_name).try(:[], 'line_object_id')
        end
        def parse_calendars calendars
          # <netex:ValidBetween>
          #  <netex:FromDate>2017-03-01</netex:FromDate>
          #  <netex:ToDate>2017-03-31</netex:ToDate>
          # </netex:ValidBetween>
          xml = Nokogiri::XML(calendars)
          from_date = nil
          to_date = nil
          xml.xpath("//netex:ValidBetween", "netex" => NetexFile::XML_NAME_SPACE).each do |valid_between|
            from_date = valid_between.xpath("netex:FromDate").try :text
            to_date = valid_between.xpath("netex:ToDate").try :text
          end
          from_date = from_date && Date.parse(from_date)
          to_date = to_date && Date.parse(to_date)
          Range.new from_date, to_date
        end
      end
      attr_accessor :name
      def initialize(name)
        @name = name
      end
      def parse_calendars(calendars)
        periods << self.class.parse_calendars(calendars)
      end
      def add_offer_file(line_object_id)
        line_refs << line_object_id
      end
      def periods
        @periods ||= []
      end
      def line_refs
        @line_refs ||= []
      end
    end
  end
end
 |