Sha256: 74c324416cba1ce94ae73f103f125052a8b0aef892cb7297e1dde2aa0a85b5be

Contents?: true

Size: 1.86 KB

Versions: 2

Compression:

Stored size: 1.86 KB

Contents

module IcalImporter
  class Parser
    attr_reader :feed, :bare_feed, :url

    def initialize(url)
      @url = url
      @bare_feed = open_ical
      if should_parse?
        @bare_feed.pos = 0
        begin
          @feed = RiCal.parse @bare_feed
        rescue Exception => e
          # I know, I'm dirty, fix this to log to a config'd log
        end
      end
    end

    def should_parse?
      bare_feed.present?
    end

    def worth_parsing?
      should_parse? && feed.present? && feed.first.present?
    end

    def all_events(&block)
      tap_and_each (@imported_single_events || []) + (@imported_recurrence_events || []), &block
    end

    def single_events(&block)
      tap_and_each (@imported_single_events || []), &block
    end

    def recurrence_events(&block)
      tap_and_each (@imported_recurrence_events || []), &block
    end

    def parse(&block)
      if worth_parsing?
        collected = Collector.new(feed.first.events).collect
        @imported_single_events = collected.single_events
        @imported_recurrence_events = collected.recurrence_events
        tap_and_each (@imported_single_events + @imported_recurrence_events), &block
      end
    end

    private

    def tap_and_each(list)
      list.tap do |r|
        r.each do |event|
          yield event if block_given?
        end
      end
    end

    def open_ical(protocol = 'http')
      raise ArgumentError, "Must be http or https" unless %w[http https].include? protocol
      begin
        Timeout::timeout(5) do
          open prepped_uri(protocol)
        end
      rescue
        return open_ical 'https' if protocol == 'http'
        nil
      end
    end

    def prepped_uri(protocol)
      uri = url.strip.gsub(/^[Ww]ebcal:/, "#{protocol}:")
      uri = begin
              URI.unescape(uri)
            rescue URI::InvalidURIError
            end
      URI.escape(uri)
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ical_importer-0.0.11 lib/ical_importer/parser.rb
ical_importer-0.0.10 lib/ical_importer/parser.rb