AirTrail sync and export, GPS tracks, airport database with autocomplete

AirTrail (https://github.com/johanohly/AirTrail):
- File export (Flights → Export for AirTrail) in AirTrail's import
  format, validated against its schema; same-day repeat legs get leg
  numbers so AirTrail's de-duplication doesn't merge them.
- Automatic sync through AirTrail's REST API (Profile → AirTrail sync):
  per-user connection with an encrypted API key and scope check; flights
  are created/updated/deleted in background jobs; a full sync first
  links flights already in AirTrail (e.g. from a file import) instead of
  duplicating them; airports are resolved and cached, with manual
  mapping for unknown codes.
- GPS tracks: GPX, KML and CSV track logs are converted to AirTrail's
  track format for both sync and export; the flight page shows a summary.
- Aircraft ICAO type (e.g. C150) for AirTrail's aircraft type.

Airport database (OurAirports, the source AirTrail uses):
- Managed like AirTrail: downloaded in the background on first start,
  updated in place from Admin → Airports (adds, changes, removes; ids
  stable), with admin-managed custom airports that updates never touch.
- Each airport carries AirTrail's code, so logged codes translate to
  AirTrail's exactly (1B9 → K1B9, 4MB → K5M3).
- From/To autocomplete on new flights (airports this aircraft has used
  rank first); From is pre-filled with the last flight's destination;
  codes are normalized to uppercase.
- Flights → Standardize airport codes: rewrite logged codes to the
  standard code, and fix codes not in the database (typos such as 0R8 →
  08R are suggested).

Also: admin pages grouped under an Admin dropdown menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-05 19:40:20 -05:00
1 parent 0c4803d717
commit 5bf682502b
68 files changed
+2667 -10

No files matched your search

@@ -0,0 +1,63 @@
# Admin → Airports: OurAirports updates and custom airports.
class Admin::AirportsController < ApplicationController
before_action :require_admin!
before_action :set_airport, only: %i[edit update destroy]
def index
@total = Airport.count
@custom = Airport.custom.order(:ident)
@updates = AirportUpdate.recent_first.includes(:requested_by).limit(5)
@running = AirportUpdate.in_progress.exists?
@last_success = AirportUpdate.last_success
@query = params[:q].to_s.strip
@results = @query.present? ? Airport.search(@query, limit: 20) : []
end
# Queue a download + sync from OurAirports.
def refresh
if AirportUpdate.in_progress.exists?
redirect_to admin_airports_path, alert: "An update is already running."
else
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user)
AirportUpdateJob.perform_later(update.id)
redirect_to admin_airports_path, notice: "Airport update started. Refresh this page in a minute or two."
end
end
def new
@airport = Airport.new(custom: true, kind: "small_airport", ident: params[:ident])
end
def create
@airport = Airport.new(airport_params.merge(custom: true))
if @airport.save
redirect_to admin_airports_path, notice: "Custom airport #{@airport.ident} added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @airport.update(airport_params)
redirect_to admin_airports_path, notice: "#{@airport.ident} updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@airport.destroy!
redirect_to admin_airports_path, notice: "#{@airport.ident} removed."
end
private
# Only custom airports can be edited; OurAirports data comes from updates.
def set_airport = @airport = Airport.custom.find(params[:id])
def airport_params
params.require(:airport).permit(:ident, :name, :kind, :municipality, :region, :country, :latitude, :longitude, :elevation_ft, :gps_code, :local_code, :iata)
end
end
@@ -0,0 +1,94 @@
# The signed-in user's AirTrail sync settings (Profile → AirTrail).
class AirTrailConnectionsController < ApplicationController
before_action :set_connection, except: %i[show create]
def show
@connection = current_user.air_trail_connection || current_user.build_air_trail_connection
return unless @connection.persisted?
@counts = @connection.counts
@failed = @connection.syncs.failed.includes(flight_log: :aircraft).order(updated_at: :desc).limit(20)
@unresolved = @connection.unresolved_airport_codes
@flight_count = FlightLog.where(user: current_user).count
end
def create
@connection = current_user.build_air_trail_connection(connection_params)
save_and_verify
end
def update
attrs = connection_params
attrs.delete(:api_key) if attrs[:api_key].blank? # keep the stored key
url_changed = attrs[:base_url].present? && attrs[:base_url].chomp("/") != @connection.base_url
@connection.assign_attributes(attrs)
@connection.remote_user_id = nil if url_changed || attrs.key?(:api_key) # re-identify
save_and_verify
end
def test
verify
redirect_to air_trail_connection_path
end
# Link existing AirTrail flights and push everything else, in the background.
def sync
AirTrailBackfillJob.perform_later(@connection.id)
redirect_to air_trail_connection_path, notice: "Sync started. Refresh this page in a minute to see progress."
end
def map_airport
code = params[:code].to_s.strip.upcase
target = params[:airtrail_code].to_s.strip.upcase
match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target)
if match
AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it
redirect_to air_trail_connection_path, notice: "#{code} mapped to #{match['icao']} (#{match['name']}). Retrying affected flights."
else
redirect_to air_trail_connection_path, alert: "AirTrail has no airport matching “#{target}”."
end
rescue AirTrailClient::Error => e
redirect_to air_trail_connection_path, alert: e.message
end
# Stops syncing. Flights already in AirTrail are left there.
def destroy
@connection.destroy!
redirect_to air_trail_connection_path, notice: "AirTrail disconnected. Flights already in AirTrail were left as they are."
end
private
def set_connection
@connection = current_user.air_trail_connection or redirect_to(air_trail_connection_path)
end
def connection_params
params.require(:air_trail_connection).permit(:base_url, :api_key, :enabled)
end
def save_and_verify
if @connection.save
verify
redirect_to air_trail_connection_path
else
render :show, status: :unprocessable_entity
end
end
def verify
me = @connection.client.me
scopes = Array(me.dig("credential", "scopes"))
missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : []
@connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current,
status: missing.empty? ? "ok" : "error",
last_error: missing.empty? ? nil : "API key is missing scopes: #{missing.join(', ')}")
if missing.empty?
flash[:notice] = "Connected to AirTrail as #{me['username']}."
else
flash[:alert] = @connection.last_error
end
rescue AirTrailClient::Error => e
@connection.update!(status: "error", last_error: e.message, checked_at: Time.current)
flash[:alert] = e.message
end
end
@@ -0,0 +1,28 @@
# Download the aircraft's flights as an AirTrail import file.
class AirTrailExportsController < ApplicationController
include AircraftScoped
def new
@export = build_export
end
def create
@export = build_export
if @export.valid?
send_data @export.to_json, filename: @export.filename, type: "application/json", disposition: "attachment"
else
render :new, status: :unprocessable_entity
end
end
private
def build_export
AirTrailExport.new(@aircraft, username: params[:username].presence || default_username,
aircraft_type: params[:aircraft_type],
only_user: params[:scope] == "mine" ? current_user : nil)
end
# A reasonable guess for the AirTrail username: the part of the email before "@".
def default_username = current_user.email_address.to_s.split("@").first.to_s.gsub(/[^A-Za-z0-9._-]/, "").first(20)
end
+1 -1
View File
@@ -68,7 +68,7 @@ class AircraftController < ApplicationController
params.require(:aircraft).permit(
:tail_number, :make, :model, :serial_number, :description, :purchased, :status,
:tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset,
:airworthiness_enforcement, :picture
:airworthiness_enforcement, :picture, :icao_type
)
end
end
@@ -0,0 +1,19 @@
# Flights → Standardize airport codes (owners).
class AirportCodesController < ApplicationController
include AircraftScoped
before_action :require_owner!
def show
@standardizer = AirportCodeStandardizer.new(@aircraft)
end
def update
codes = Array(params[:codes]).map(&:to_s)
standardizer = AirportCodeStandardizer.new(@aircraft)
# Only codes that are actually unknown in this log, and only the ticked ones.
fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h
.select { |code, _| Array(params[:fix]).include?(code) }
updated = standardizer.apply!(codes, fixes: fixes)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Updated #{updated} airport entries across your flights."
end
end
+15
View File
@@ -0,0 +1,15 @@
class AirportsController < ApplicationController
# GET /airports/search?q=quonset → [{ code, name, place, airtrail_code, kind }]
def search
render json: Airport.search(params[:q], prefer: familiar_codes).map(&:as_suggestion)
end
private
# Airports this aircraft has flown from/to rank first.
def familiar_codes
aircraft = params[:aircraft_id].presence && current_user.accessible_aircraft.find_by(id: params[:aircraft_id])
return [] unless aircraft
aircraft.flight_logs.distinct.pluck(:departure_location, :destination_location).flatten.compact_blank.uniq
end
end
+11 -1
View File
@@ -9,11 +9,21 @@ class FlightLogsController < ApplicationController
def show
@flight_log = @aircraft.flight_logs.find(params[:id])
begin
@track = TrackParser.parse_attachment(@flight_log.track_log)
rescue TrackParser::Error => e
@track_error = "Couldn't read track: #{e.message}"
end
@air_trail_connection = @flight_log.user&.air_trail_connection
@air_trail_sync = @flight_log.air_trail_syncs.first
end
def new
# Aircraft almost always depart from where they last landed.
last = @aircraft.flight_logs.where.not(destination_location: [ nil, "" ]).recent_first.first
@flight_log = @aircraft.flight_logs.new(date: Date.current, tach_out: @aircraft.tach_time,
hobbs_out: @aircraft.hobbs_time)
hobbs_out: @aircraft.hobbs_time,
departure_location: last&.destination_location)
end
def create