-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.rb
More file actions
395 lines (327 loc) · 17.3 KB
/
Copy pathserver.rb
File metadata and controls
395 lines (327 loc) · 17.3 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
##
## Copyright (C) 2026 Jordan Ritter <jpr5@darkridge.com>
##
## WebCal server for Tides, Currents, Sunset and Lunar information. Meant to
## replace sailwx.info/tides.mobilegeographics.com, which as of 2021 appears no
## longer to work.
##
require 'logger'
$LOG = Logger.new(STDOUT).tap do |log|
log.formatter = proc { |s, d, _, m| "#{d.strftime("%Y-%m-%d %H:%M:%S")} #{s} #{m}\n" }
end
require_relative 'webcaltides'
class Server < ::Sinatra::Base
set :app_file, File.expand_path(__FILE__)
set :root, File.expand_path(File.dirname(__FILE__))
set :cache_dir, settings.root + '/cache'
set :public_folder, settings.root + '/public'
set :views, settings.root + '/views'
set :static, true
# Warm caches in background thread to prevent blocking server startup
# Loads harmonics engine cache, tide stations cache, and current stations cache
def self.warm_caches
Thread.new do
begin
total_start = Time.now
$LOG.info "warming caches on bootup"
# Step 1: Harmonics engine cache (loads XTide + TICON data, deduplicates stations)
$LOG.info "warming harmonics engine cache"
start = Time.now
harmonics = WebCalTides.get_harmonics_client
harmonics.engine.stations # Force load
elapsed = (Time.now - start).round(2)
$LOG.info "harmonics engine cache warmed in #{elapsed}s"
# Step 2: Tide stations cache (loads NOAA, CHS, merges with harmonics)
$LOG.info "warming tide stations cache"
start = Time.now
WebCalTides.tide_stations # Force load and cache
elapsed = (Time.now - start).round(2)
$LOG.info "tide stations cache warmed in #{elapsed}s"
# Step 3: Current stations cache (loads NOAA currents, merges with harmonics)
$LOG.info "warming current stations cache"
start = Time.now
WebCalTides.current_stations # Force load and cache
elapsed = (Time.now - start).round(2)
$LOG.info "current stations cache warmed in #{elapsed}s"
# Step 4: Clean old cache files
$LOG.info "cleaning old cache files"
start = Time.now
WebCalTides.cleanup_old_cache_files
elapsed = (Time.now - start).round(2)
$LOG.info "cache cleanup completed in #{elapsed}s"
total_elapsed = (Time.now - total_start).round(2)
$LOG.info "all caches warmed in #{total_elapsed}s"
rescue => e
$LOG.error "cache warming failed: #{e.class} - #{e.message}"
$LOG.error e.backtrace.first(5).join("\n") if e.backtrace
end
end
end
configure do
enable :show_exceptions
disable :sessions, :logging
helpers ::Rack::Utils
# Configure timezone lookup provider (prefer Google, fallback to Geonames)
if ENV['GOOGLE_API_KEY']
$LOG.info "configuring Google Maps Time Zone API for timezone lookups"
Timezone::Lookup.config(:google) do |c|
c.api_key = ENV['GOOGLE_API_KEY']
end
elsif ENV['GEONAMES_USERNAME']
$LOG.info "configuring Geonames for timezone lookups (fallback)"
Timezone::Lookup.config(:geonames) do |c|
c.username = ENV['GEONAMES_USERNAME'] || ENV['USER']
end
else
$LOG.warn "no timezone API configured (GOOGLE_API_KEY or GEONAMES_USERNAME missing)"
$LOG.warn "timezone lookups will rely on region metadata and longitude approximation"
end
FileUtils.mkdir_p settings.cache_dir
# Warm caches on bootup in production/staging to prevent 45-60s first request delay
warm_caches if ENV['RACK_ENV'].to_s.in?(%w[production staging])
end
configure :development do
set :logging, $LOG
register Sinatra::Reloader
also_reload File.expand_path("./webcaltides.rb")
also_reload File.expand_path("./lib/gps.rb")
also_reload File.expand_path("./lib/harmonics_engine.rb")
after_reload { $LOG.debug 'reloaded' }
end
helpers do
# Generate static map URL with fallback chain:
# 1. Google Maps Static API (if GOOGLE_API_KEY is set)
# 2. Geoapify Static Maps (if GEOAPIFY_API_KEY is set)
# 3. nil (placeholder icon shown)
def static_map_url(lat:, lon:, accent_color:)
if ENV['GOOGLE_API_KEY'].to_s.strip.length > 0
# Google Maps Static API (preferred)
styles = [
"feature:water|color:#{accent_color}",
"feature:landscape|color:0x1e293b",
"feature:road|visibility:off",
"feature:poi|visibility:off",
"feature:transit|visibility:off",
"element:labels|visibility:off"
].map { |s| "style=#{s}" }.join("&")
"https://maps.googleapis.com/maps/api/staticmap?center=#{lat},#{lon}&zoom=11&size=200x200&scale=2&maptype=terrain&#{styles}&markers=color:#{accent_color}|#{lat},#{lon}&key=#{ENV['GOOGLE_API_KEY']}"
elsif ENV['GEOAPIFY_API_KEY'].to_s.strip.length > 0
# Geoapify fallback (free tier: 3,000 requests/day)
color = accent_color.sub('0x', '%23')
"https://maps.geoapify.com/v1/staticmap?style=dark-matter&width=400&height=400¢er=lonlat:#{lon},#{lat}&zoom=11&marker=lonlat:#{lon},#{lat};color:#{color};size:large&apiKey=#{ENV['GEOAPIFY_API_KEY']}"
else
nil # No map service configured - will show placeholder
end
end
end
##
## URL entry points
##
get "/" do
erb :index, locals: { searchtext: nil, units: nil }
end
# Autocomplete endpoint for station search
get "/api/stations/autocomplete" do
query = (params['q'] || '').strip.downcase
return { results: [] }.to_json if query.length < 2
# Search both tide and current stations
all_stations = WebCalTides.tide_stations + WebCalTides.current_stations
# Filter and dedupe by name
matches = all_stations
.select { |s| s.name.downcase.include?(query) || s.region&.downcase&.include?(query) }
.uniq { |s| [s.name, s.region] }
.first(10)
.map { |s| { name: s.name, region: s.region, type: s.depth ? 'current' : 'tide' } }
content_type :json
{ results: matches }.to_json
end
# API endpoint to compare predictions between multiple stations
# GET /api/stations/compare?type=tides&ids[]=noaa:123&ids[]=xtide:456
# GET /api/stations/compare?type=currents&ids[]=noaa:123&ids[]=xtide:456
get "/api/stations/compare" do
content_type :json
station_type = params['type'] || 'tides'
return { error: 'Invalid type' }.to_json unless station_type.in?(%w[tides currents])
station_ids = Array(params['ids'])
return { error: 'No station IDs provided' }.to_json if station_ids.empty?
return { error: 'Maximum 5 stations allowed' }.to_json if station_ids.length > 5
results = station_ids.map do |id|
station = case station_type
when 'tides' then WebCalTides.tide_station_for(id)
when 'currents' then WebCalTides.current_station_for(id)
end
next nil unless station
events = case station_type
when 'tides' then WebCalTides.next_tide_events(id)
when 'currents' then WebCalTides.next_current_events(id)
end
result = {
id: id,
name: station.name,
provider: station.provider,
events: (events || []).map { |e| e.merge(time: e[:time].iso8601) }
}
result[:depth] = station.depth if station.respond_to?(:depth) && station.depth
result
end.compact
return { error: 'No valid stations found' }.to_json if results.empty?
# Compute per-event deltas relative to first station (primary)
# Match events by type (High/Low for tides, Flood/Ebb/Slack for currents)
primary = results.first
primary_events = primary[:events]
results[1..].each do |alt|
alt_events = alt[:events]
event_deltas = []
# For each primary event, find matching type in alternative and compute delta
primary_events.each_with_index do |p_event, idx|
# Find matching event type in alternative (same index or same type)
a_event = alt_events[idx] if alt_events[idx] && alt_events[idx][:type] == p_event[:type]
a_event ||= alt_events.find { |e| e[:type] == p_event[:type] }
if a_event
time_diff = (Time.parse(a_event[:time]) - Time.parse(p_event[:time])).to_i
if station_type == 'currents'
# Skip velocity comparison for Slack events (no velocity)
if p_event[:type] != 'Slack' && p_event[:velocity] && a_event[:velocity]
velocity_diff = (a_event[:velocity].to_f - p_event[:velocity].to_f).round(2)
event_deltas << {
type: p_event[:type],
time: WebCalTides.format_time_delta(time_diff),
raw_value: velocity_diff,
units: 'kn'
}
else
event_deltas << {
type: p_event[:type],
time: WebCalTides.format_time_delta(time_diff),
raw_value: nil,
units: nil
}
end
else
height_diff = (a_event[:height].to_f - p_event[:height].to_f).round(2)
units = p_event[:units] || 'ft'
event_deltas << {
type: p_event[:type],
time: WebCalTides.format_time_delta(time_diff),
raw_value: height_diff,
units: units
}
end
end
end
alt[:event_deltas] = event_deltas
# Also compute a summary delta from first comparable events (for dropdown display)
first_delta = event_deltas.find { |d| d[:raw_value] } || event_deltas.first
if first_delta
alt[:delta] = {
time: first_delta[:time],
raw_value: first_delta[:raw_value],
units: first_delta[:units]
}
end
end
{ stations: results }.to_json
end
# API endpoint to get next tide/current event for a station
get "/api/stations/:type/:id/next" do
content_type :json
events = case params[:type]
when 'tides' then WebCalTides.next_tide_events(params[:id])
when 'currents' then WebCalTides.next_current_events(params[:id])
end
if events.nil?
$LOG.warn "No station data for #{params[:type]}/#{params[:id]}"
return { error: 'Station not found' }.to_json
end
if events.empty?
$LOG.debug "No future events for #{params[:type]}/#{params[:id]}"
end
# Return ISO 8601 timestamps - client will format based on user's timezone preference
formatted = events.map do |e|
e.merge(time: e[:time].iso8601)
end
{ events: formatted }.to_json
end
post "/" do
radius = params['within'].to_i
radius_units = params['units'] == 'metric' ? 'km' : 'mi'
searchparam = (params['searchtext'] || '').strip
searchtext = searchparam.dup.downcase.tr('“”', '""')
# ^^^ Depending on your font these quotes may look the same -- but they're not
return erb :index, locals: { searchtext: nil, units: nil } unless searchtext.length > 0
# If we see anything like "42.1234, 1234.0132" or "42.1234° N" then treat it like a GPS search
# Match degree/apostrophe/period symbols followed by digits OR hemisphere indicators
if searchtext.match(/\d[°'.]\s*[\d\-nsew]/)
how = "near"
unless tokens = WebCalTides.parse_gps(searchtext)
$LOG.warn "unable to parse '#{searchtext}' as GPS"
return erb :index, locals: { searchtext: nil, units: nil }
end
(lat, long) = *tokens
radius = 10 # default
tide_results = WebCalTides.find_tide_stations_by_gps(lat, long, within:radius, units: radius_units)
current_results = WebCalTides.find_current_stations_by_gps(lat, long, within:radius, units: radius_units)
else
how = "by"
# Parse search terms. Matched quotes are taken as-is (still
# lowercased), while everything else is tokenized via [ ,°'"]+.
# Strip degree/minute/second symbols and quotes as they're not useful for text search.
tokens = searchtext.scan(/["]([^"]+)["]/).flatten
searchtext.gsub!(/["]([^"]+)["]/, '')
tokens += searchtext.split(/[, °′'″"]+/).reject(&:empty?)
unless tokens.empty?
tide_results = WebCalTides.find_tide_stations(by:tokens, within:radius, units: radius_units)
current_results = WebCalTides.find_current_stations(by:tokens, within:radius, units: radius_units)
end
end
tide_results ||= []
current_results ||= []
# Group stations by proximity to deduplicate results from different providers
# Current stations are grouped by location only; depth selection happens in UI
tide_groups = WebCalTides.group_search_results(tide_results, compute_deltas: false)
current_groups = WebCalTides.group_search_results(current_results, compute_deltas: false, match_depth: false)
for_what = "#{tokens}"
for_what += " within #{radius}#{radius_units}" if radius
$LOG.info "search #{how} #{for_what} yields #{tide_groups.count + current_groups.count} grouped results (from #{tide_results.count + current_results.count} raw)"
erb :index, locals: { tide_results: tide_groups, current_results: current_groups,
tokens: tokens.map { |t| Rack::Utils.escape_html(t) }, how:how, radius: radius,
units: params['units'] == 'metric' ? 'metric' : 'imperial',
placeholder: Rack::Utils.escape_html(searchparam.empty? ? 'Station...' : searchparam)
}
end
# For currents, station can be either an ID (we'll use the first bin) or a BID (specific bin)
get "/:type/:station.ics" do
type = params[:type].tap { |type| type.in?(%w[tides currents]) or halt 404 }
id = params[:station].tap { |station| station.in?(WebCalTides.station_ids) or halt 404 }
date = Date.parse(params[:date]) rescue Time.current.utc # e.g. 20231201, for utility but unsupported in UI
units = params.fetch(:units, 'imperial').tap { |units| units.in?(%w[imperial metric]) or halt 422 }
no_solar = params[:solar].in?(%w[0 false]) # on by default
add_lunar = params[:lunar].in?(%w[1 true]) # off by default
stamp = date.utc.strftime("%Y%m")
version = type == "currents" ? Models::CurrentData.version : Models::TideData.version
cached_ics = "#{settings.cache_dir}/#{type}_v#{version}_#{id}_#{stamp}_#{units}_#{no_solar ?"0":"1"}_#{add_lunar ?"1":"0"}.ics"
# Cleanup old cache files if month has changed (thread-safe)
WebCalTides.cleanup_if_month_changed
# NOTE: Changed my mind on retval's. In the shit-fucked-up case, we end up sending out a
# full stack trace + 500, so really if we muck something up internally we should let the
# exception float up. Then we can assume that if we arrive without a calendar, then it's
# simply not there -> 404.
ics = File.read cached_ics rescue begin
calendar = case type
when "tides" then WebCalTides.tide_calendar_for(id, around: date, units: units) or halt 404
when "currents" then WebCalTides.current_calendar_for(id, around: date) or halt 404
else halt 404
end
# Add solar events if requested
WebCalTides.solar_calendar_for(calendar, around:date) unless no_solar
# Add lunar phase events if requested
WebCalTides.lunar_calendar_for(calendar, around:date) if add_lunar
calendar.publish
$LOG.debug "caching to #{cached_ics}"
WebCalTides.atomic_write(cached_ics, ical = calendar.to_ical)
ical
end
content_type 'text/calendar', charset: 'utf-8'
body ics
end
end