Class: Sources

Inherits:
Object
  • Object
show all
Defined in:
src/sources.rb

Constant Summary collapse

SOURCES =
[
  {post: 'https://e6bx.com/secure?api=adds',
   params: { params: { time: Time.now.to_i,
                       stations: { stationString: 'UUUU' },
                       metars: { stationString: 'UUUU', hoursBeforeNow: 3, mostRecentForEachStation: true },
                       tafs: {stationString: 'UUUU', hoursBeforeNow: 12, mostRecentForEachStation: true }
   }},
   json: ->(b){
     b[:metars].size > 0 ? { taf:   b[:tafs][0][:raw_text], metar: b[:metars][0][:raw_text] } : nil
   }
  },
  {
    get: 'https://metartaf.ru/UUUU.json',
    json: ->(body){ body.tap { |h|
      h[:metar] = h[:metar].lines.last
      h[:taf] = h[:taf].lines.last
    }}
  },
  { get: 'https://metar-taf.com/UUUU',
    text: ->(body){ { metar: body[/og:description" content="([^.]+)/, 1].gsub(/^METAR\s+/,'') } }
  },
  { get: 'https://beta.aviationweather.gov/cgi-bin/data/metar.php?ids=UUUU&hours=0&format=raw',
    text: ->(body){ body.rstrip.size > 0 ? { metar: body.rstrip } : nil }
  },
]

Class Method Summary collapse

Class Method Details

.first(test = 'fake', code:) ⇒ Object



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
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'src/sources.rb', line 67

def first(test = 'fake', code:)
  ctx_ = OpenTelemetry::Context.current if defined? OpenTelemetry
  responses = []
  threads = SOURCES.map do |src|
    Thread.new do
      with_otel(ctx_) do
        begin
          response = profile( src[:get] || src[:post] ) do
            case
             when src[:get]; Faraday.new(src[:get].gsub('UUUU', code), ssl: { verify: false } ).get
             when src[:post]; Faraday.new(src[:post], ssl: { verify: false }){_1.request :json}.post '', src[:params].gsub_s('UUUU', code)
             else nil
            end
          end
          if response.status == 200
            responses << case
                         when src[:json]; src[:json].call JSON.parse response.body, symbolize_names: true
                         when src[:text]; src[:text].call response.body
                         end
          else
            puts response.status
          end
        rescue => e
        end
      end
    end
  end

  waiter = ThreadsWait.new *threads
  while thread = waiter.next_wait rescue nil
    # p responses.last if responses.size > 0
    responses.compact!
    break if responses.size > 0
  end

  profile 'Stop all' do
    threads.each.each(&:kill).each(&:join)
  end
  responses.first
end