diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css
index 232e4c1..377d2b2 100644
--- a/app/assets/tailwind/application.css
+++ b/app/assets/tailwind/application.css
@@ -184,3 +184,9 @@
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
.btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; }
}
+
+/* A label and its value on one row (label column, then value), e.g. a flight's details. */
+@utility detail-row {
+ @apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
+ & > dt { @apply text-slate-500; }
+}
diff --git a/app/controllers/push_subscriptions_controller.rb b/app/controllers/push_subscriptions_controller.rb
index 1636439..6b7503b 100644
--- a/app/controllers/push_subscriptions_controller.rb
+++ b/app/controllers/push_subscriptions_controller.rb
@@ -6,7 +6,13 @@ class PushSubscriptionsController < ApplicationController
record = PushSubscription.find_or_initialize_by(endpoint: sub[:endpoint].to_s)
record.assign_attributes(user: current_user, p256dh: sub.dig(:keys, :p256dh), auth: sub.dig(:keys, :auth),
user_agent: request.user_agent.to_s.first(250))
- record.save ? head(:created) : head(:unprocessable_entity)
+ if record.save
+ head :created
+ else
+ render json: { error: t("flash.push_subscriptions.not_saved", host: URI.parse(record.endpoint).host.to_s) }, status: :unprocessable_entity
+ end
+ rescue URI::InvalidURIError
+ render json: { error: t("flash.push_subscriptions.not_saved", host: "?") }, status: :unprocessable_entity
end
def destroy
@@ -14,9 +20,35 @@ class PushSubscriptionsController < ApplicationController
head :no_content
end
- # A notification to this user's devices, to check they arrive.
+ # A notification to each of this user's devices, sent now so the page can
+ # say which push services took it (and why one didn't).
def test
- PushNotifier.notify(current_user, :test, path: edit_profile_path, tag: "test")
- head :accepted
+ message = PushNotificationJob.message("test", edit_profile_path, "test")
+ devices = current_user.push_subscriptions.order(:created_at).map do |sub|
+ { device: device_name(sub.user_agent), error: PushNotificationJob.deliver(sub, message) }
+ end
+ render json: { devices: devices }
+ end
+
+ private
+
+ # "Chrome on Android" from the browser's description of itself.
+ def device_name(agent)
+ browser = case agent
+ when /Edg\//, /EdgA\// then "Edge"
+ when /SamsungBrowser/ then "Samsung Internet"
+ when /Firefox|FxiOS/ then "Firefox"
+ when /Chrome|CriOS/ then "Chrome"
+ when /Safari/ then "Safari"
+ end
+ system = case agent
+ when /Android/ then "Android"
+ when /iPhone/ then "iPhone"
+ when /iPad/ then "iPad"
+ when /Macintosh/ then "Mac"
+ when /Windows/ then "Windows"
+ when /Linux/ then "Linux"
+ end
+ [ browser, system ].compact.join(" · ").presence || t("flash.push_subscriptions.unknown_device")
end
end
diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb
index 8a52fb2..225bb4a 100644
--- a/app/helpers/aircraft_helper.rb
+++ b/app/helpers/aircraft_helper.rb
@@ -3,12 +3,12 @@ module AircraftHelper
# What the app saves ahead of time for use without signal (see
# offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
- # Log Flight and Report Squawk pages, and its photo.
+ # Log Flight and Report Squawk pages, and its photo (at both page sizes).
def offline_pages
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
- picture: (url_for(a.picture) if a.picture.attached?) }.compact
+ pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture.attached?) }.compact
end
end
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
diff --git a/app/javascript/controllers/offline_prep_controller.js b/app/javascript/controllers/offline_prep_controller.js
index 9e1c987..fc4e419 100644
--- a/app/javascript/controllers/offline_prep_controller.js
+++ b/app/javascript/controllers/offline_prep_controller.js
@@ -36,7 +36,7 @@ export default class extends Controller {
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
}
- await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
+ await this.savePictures(this.aircraftValue.flatMap((a) => a.pictures || []))
try {
localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms }))
localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() }))
@@ -58,10 +58,11 @@ export default class extends Controller {
}
// Photo links carry an expiry, so they change with every page; the saved copy
-// is filed under the upload's id instead (same rule in service-worker.js).
+// is filed under the upload's id (and size) instead (same rule in service-worker.js).
function imageKey(url) {
try {
- const signed = new URL(url, location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
- return `${location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
+ const [ , signed, size ] = new URL(url, location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
+ const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
+ return `${location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
} catch (_) { return null }
}
diff --git a/app/javascript/controllers/push_controller.js b/app/javascript/controllers/push_controller.js
index 936b429..494b499 100644
--- a/app/javascript/controllers/push_controller.js
+++ b/app/javascript/controllers/push_controller.js
@@ -14,18 +14,34 @@ export default class extends Controller {
this.registration = await navigator.serviceWorker.ready
const subscription = await this.registration.pushManager.getSubscription()
if (Notification.permission === "denied") return this.show(t("push.blocked"), null)
- this.show(t(subscription ? "push.on" : "push.off"), !!subscription)
+ if (!subscription) return this.show(t("push.off"), false)
+ // The browser keeps its subscription even if the app never recorded it
+ // (or forgot it), so record it again on every visit.
+ const error = await this.save(subscription)
+ this.show(error ? t("push.not_saved", { reason: error }) : t("push.on"), true)
}
async turnOn() {
if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null)
+ let subscription
+ try {
+ subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
+ } catch (e) {
+ return this.show(t("push.failed", { reason: e.message || e.name }), false)
+ }
+ const error = await this.save(subscription)
+ this.show(error ? t("push.failed", { reason: error }) : t("push.on"), !error)
+ if (error) await subscription.unsubscribe()
+ }
+
+ // Records the subscription with the app: null, or why it couldn't.
+ async save(subscription) {
try {
- const subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() })
- if (!response.ok) throw new Error(response.status)
- this.show(t("push.on"), true)
- } catch (_) {
- this.show(t("push.failed"), false)
+ if (response.ok) return null
+ return (await response.json().catch(() => ({}))).error || `HTTP ${response.status}`
+ } catch (e) {
+ return e.message
}
}
@@ -38,9 +54,18 @@ export default class extends Controller {
this.show(t("push.off"), false)
}
+ // Sends one to each of your devices and lists which push services took it.
async sendTest() {
- await this.request("POST", this.testUrlValue, {})
- this.statusTarget.textContent = t("push.test_sent")
+ this.statusTarget.textContent = t("push.test_sending")
+ try {
+ const { devices } = await (await this.request("POST", this.testUrlValue, {})).json()
+ const lines = devices.length
+ ? [ ...devices.map((d) => d.error ? t("push.test_failed", { device: d.device, reason: d.error }) : t("push.test_ok", { device: d.device })), t("push.test_hint") ]
+ : [ t("push.test_none") ]
+ this.statusTarget.textContent = lines.join("\n")
+ } catch (e) {
+ this.statusTarget.textContent = t("push.failed", { reason: e.message })
+ }
}
// on: true / false, or null when it can't be changed here.
diff --git a/app/jobs/push_notification_job.rb b/app/jobs/push_notification_job.rb
index 8fd8671..612c666 100644
--- a/app/jobs/push_notification_job.rb
+++ b/app/jobs/push_notification_job.rb
@@ -4,20 +4,32 @@ class PushNotificationJob < ApplicationJob
queue_as :default
def perform(user_ids, key, path, tag, vars)
- vars = vars.symbolize_keys
- message = JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag)
- PushSubscription.where(user_id: user_ids).find_each { deliver(_1, message) }
+ message = self.class.message(key, path, tag, vars)
+ PushSubscription.where(user_id: user_ids).find_each { self.class.deliver(_1, message) }
end
- private
+ def self.message(key, path, tag, vars = {})
+ vars = vars.symbolize_keys
+ JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag)
+ end
- def deliver(subscription, message)
+ # Sends to one device: nil when the push service took it, else why not.
+ def self.deliver(subscription, message)
WebPush.payload_send(message: message, endpoint: subscription.endpoint, p256dh: subscription.p256dh, auth: subscription.auth,
ttl: 1.day.to_i, urgency: "high",
vapid: { subject: PushKeys.subject, public_key: PushKeys.public_key, private_key: PushKeys.private_key })
- rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized
+ nil
+ rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized => e
subscription.destroy
+ failure(subscription, e)
rescue WebPush::Error, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
- Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{e.class}: #{e.message.truncate(200)}")
+ failure(subscription, e)
end
+
+ def self.failure(subscription, error)
+ reason = "#{error.class.name.demodulize}: #{error.message.truncate(200)}"
+ Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{reason}")
+ reason
+ end
+ private_class_method :failure
end
diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb
index f75c123..7938183 100644
--- a/app/models/aircraft.rb
+++ b/app/models/aircraft.rb
@@ -1,7 +1,12 @@
class Aircraft < ApplicationRecord
STATUSES = LabelSet.new("aircraft.statuses", %w[AVAILABLE MX GROUND UNAVAILABLE])
- has_one_attached :picture
+ # Small copies of the photo for the pages (the original can be several MB):
+ # made when it's uploaded; see #picture_for.
+ has_one_attached :picture do |picture|
+ picture.variant :thumb, resize_to_fill: [ 192, 192 ], preprocessed: true
+ picture.variant :card, resize_to_fill: [ 960, 432 ], preprocessed: true
+ end
has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :users, through: :roles
@@ -77,6 +82,12 @@ class Aircraft < ApplicationRecord
events.create!(category: category, event_name: event_name, user: user, notes: notes)
end
+ # The photo at a page's size (:thumb or :card), or the original when it
+ # isn't a kind that can be resized.
+ def picture_for(size)
+ picture.variable? ? picture.variant(size) : picture
+ end
+
private
def picture_is_image
diff --git a/app/models/push_subscription.rb b/app/models/push_subscription.rb
index 4177feb..ee4ea5b 100644
--- a/app/models/push_subscription.rb
+++ b/app/models/push_subscription.rb
@@ -2,7 +2,7 @@
class PushSubscription < ApplicationRecord
# The browsers' push services. The server posts to the endpoint, so only
# these hosts are accepted (not, say, an address inside the network).
- PUSH_SERVICES = /\A(fcm\.googleapis\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
+ PUSH_SERVICES = /\A(([\w-]+\.)*googleapis\.com|([\w-]+\.)*google\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
belongs_to :user
diff --git a/app/views/aircraft/index.html.erb b/app/views/aircraft/index.html.erb
index f6bd990..8881bd7 100644
--- a/app/views/aircraft/index.html.erb
+++ b/app/views/aircraft/index.html.erb
@@ -19,7 +19,7 @@
<%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>
<% if aircraft.picture.attached? %>
- <%= image_tag aircraft.picture, class: "h-full w-full object-cover", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
+ <%= image_tag aircraft.picture_for(:card), class: "h-full w-full object-cover", loading: "lazy", alt: t(".photo_of", tail_number: aircraft.tail_number) %>
<% else %>
✈
<% end %>
diff --git a/app/views/components/show.html.erb b/app/views/components/show.html.erb
index 0280826..a927753 100644
--- a/app/views/components/show.html.erb
+++ b/app/views/components/show.html.erb
@@ -11,28 +11,28 @@
<% end %>
-
- <%= t(".manufacturer") %> <%= @component.manufacturer %>
- <%= t(".model") %> <%= @component.model %>
- <%= t(".serial") %> <%= @component.serial_number.presence || "—" %>
- <%= t(".status") %> <%= @component.status_label %>
- <%= t(".parent") %> <%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %>
- <%= t(".location") %> <%= @component.install_location.presence || "—" %>
- <%= t(".in_service_since") %> <%= fmt_date(@component.date_in_service) %>
- <%= t(".last_oh_service") %> <%= fmt_date(@component.overhaul_date) %>
- <%= t(".hours_in_service") %> <%= hours(@component.hours_in_service) %>
- <%= t(".since_oh_service") %> <%= hours(@component.hours_since_overhaul) %>
- <%= t(".tbo") %> <%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %>
- <%= t(".replacement") %>
+
+
<%= t(".manufacturer") %> <%= @component.manufacturer %>
+
<%= t(".model") %> <%= @component.model %>
+
<%= t(".serial") %> <%= @component.serial_number.presence || "—" %>
+
<%= t(".status") %> <%= @component.status_label %>
+
<%= t(".parent") %> <%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %>
+
<%= t(".location") %> <%= @component.install_location.presence || "—" %>
+
<%= t(".in_service_since") %> <%= fmt_date(@component.date_in_service) %>
+
<%= t(".last_oh_service") %> <%= fmt_date(@component.overhaul_date) %>
+
<%= t(".hours_in_service") %> <%= hours(@component.hours_in_service) %>
+
<%= t(".since_oh_service") %> <%= hours(@component.hours_since_overhaul) %>
+
<%= t(".tbo") %> <%= @component.tbo_hours ? t(".h_remaining", tbo_hours: @component.tbo_hours, hours_to_tbo: (hours(@component.hours_to_tbo))) : "—" %>
+ <%= t(".replacement") %>
<%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence&.then { @component.replacement_from_install? ? t(".since_installed", interval: _1) : _1 } || "—" %>
<% if (d = @component.next_replacement_date) %><%= t(".next_by_html", d: (fmt_date(d))) %>
<% end %>
-
-
<%= t(".flags") %>
-
+
+
<%= t(".flags") %>
+
<% { tbo_critical: t(".tbo_critical"), replacement_critical: t(".replacement_critical"), on_condition: t(".on_condition") }.each do |flag, label| %>
<% if @component.public_send("#{flag}?") %><%= label %> <% end %>
<% end %>
-
+
<% if @component.notes.present? %><%= simple_format @component.notes %>
<% end %>
diff --git a/app/views/flight_logs/_engine_data.html.erb b/app/views/flight_logs/_engine_data.html.erb
index 25c36b4..933a329 100644
--- a/app/views/flight_logs/_engine_data.html.erb
+++ b/app/views/flight_logs/_engine_data.html.erb
@@ -17,15 +17,15 @@
<% if tail.present? && tail.upcase != @aircraft.tail_number.to_s.upcase %>
<%= t(".this_recording_is_from_not_html", tail: tail, tail_number: @aircraft.tail_number) %>
<% end %>
-
- <%= t(".recorded") %>
- <%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %>
- <%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %>
- <%= t(".engine_run") %> <%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %>
- <%= t(".fuel_burned") %> <%= engine_value(recording.fuel_burned, "gal", precision: 1) %>
- <%= t(".tach") %> <%= hours_line.(:tach, 2) %>
- <%= t(".engine_hrs") %> <%= hours_line.(:engine_hours, 2) %>
- <% if (flt = recording.last(:flight_hours)) %><%= t(".airborne") %> <%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %> <% end %>
+
+
<%= t(".recorded") %>
+ <%= t(".monitor_time_html", start: (recording.local(recording.started_at).strftime("%Y-%m-%d %H:%M")), end: (recording.local(recording.ended_at).strftime("%H:%M"))) %>
+ <%= t(".samples_html", file_format: recording.format, flight_number: (" flight ##{recording.metadata[:flight_number]}" if recording.metadata[:flight_number]), samples: (number_with_delimiter(recording.samples))) %>
+
<%= t(".engine_run") %> <%= recording.engine_start ? run_duration(recording.run_time) : t(".engine_not_run") %>
+
<%= t(".fuel_burned") %> <%= engine_value(recording.fuel_burned, "gal", precision: 1) %>
+
<%= t(".tach") %> <%= hours_line.(:tach, 2) %>
+
<%= t(".engine_hrs") %> <%= hours_line.(:engine_hours, 2) %>
+ <% if (flt = recording.last(:flight_hours)) %>
<%= t(".airborne") %> <%= flt.zero? ? t(".no_ground_run") : "#{number_with_precision(flt, precision: 2)} hrs" %> <% end %>
diff --git a/app/views/flight_logs/show.html.erb b/app/views/flight_logs/show.html.erb
index 251b260..8dd62a9 100644
--- a/app/views/flight_logs/show.html.erb
+++ b/app/views/flight_logs/show.html.erb
@@ -3,23 +3,24 @@
-
- <%= t(".tach") %> <%= hours(@flight_log.tach_time) %> <%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %>
- <%= t(".hobbs") %> <%= hours(@flight_log.hobbs_time) %> <%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %>
- <%= t(".route") %> <%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %>
- <%= t(".oil_added") %> <%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %>
- <%= t(".fuel_added") %> <%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %>
- <%= t(".pilot") %> <%= @flight_log.user&.display_name || "—" %>
- <%= t(".track_log") %> <%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
+ <%# One item per row on a phone (label, then value); two columns on wider screens. %>
+
+
<%= t(".tach") %> <%= hours(@flight_log.tach_time) %> <%= "(#{@flight_log.tach_out} → #{@flight_log.tach_in})" if @flight_log.tach_out && @flight_log.tach_in %>
+
<%= t(".hobbs") %> <%= hours(@flight_log.hobbs_time) %> <%= "(#{@flight_log.hobbs_out} → #{@flight_log.hobbs_in})" if @flight_log.hobbs_out && @flight_log.hobbs_in %>
+
<%= t(".route") %> <%= @flight_log.route_summary.presence || "—" %> <%= @flight_log.route %>
+
<%= t(".oil_added") %> <%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %>
+
<%= t(".fuel_added") %> <%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %>
+
<%= t(".pilot") %> <%= @flight_log.user&.display_name || "—" %>
+
<%= t(".track_log") %> <%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
<% if @track %> <%= t(".gps_points_html", points: (number_with_delimiter(@track.points)), max_altitude_ft: (t(".max_ft", max_altitude_ft: (number_with_delimiter(@track.max_altitude_ft))) if @track.max_altitude_ft)) %>
- <% elsif @track_error %> · <%= @track_error %> <% end %>
+ <% elsif @track_error %> · <%= @track_error %> <% end %>
<% if @air_trail_sync || @air_trail_connection %>
- <%= t(".airtrail") %>
-
+
<%= t(".airtrail") %>
+
<% if @air_trail_sync&.status == "synced" %><%= t(".synced") %> <%= t(".ago_html", synced_at: (time_ago_in_words(@air_trail_sync.synced_at))) %>
<% elsif @air_trail_sync&.status == "error" %><%= t(".not_synced") %> <%= @air_trail_sync.last_error %>
<% else %><%= t(".pending") %> <% end %>
-
+
<% end %>
<% if @flight_log.notes.present? %><%= simple_format @flight_log.notes %>
<% end %>
diff --git a/app/views/major_records/show.html.erb b/app/views/major_records/show.html.erb
index 1214f49..4ab3ff3 100644
--- a/app/views/major_records/show.html.erb
+++ b/app/views/major_records/show.html.erb
@@ -2,24 +2,24 @@
-
- <%= t(".date") %> <%= fmt_date(@record.date_performed) %>
- <%= t(".aircraft_hours") %> <%= hours(@record.aircraft_hours) %>
- <%= t(".performed_by") %> <%= @record.performed_by.presence || "—" %>
- <%= t(".component") %> <%= @record.component || "—" %>
- <%= t(".form_337") %> <%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %>
- <%= t(".stc") %> <%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %>
- <%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %>
- <%= t(".logbook") %> <%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %>
- <%= t(".weight_balance") %>
+
+
<%= t(".date") %> <%= fmt_date(@record.date_performed) %>
+
<%= t(".aircraft_hours") %> <%= hours(@record.aircraft_hours) %>
+
<%= t(".performed_by") %> <%= @record.performed_by.presence || "—" %>
+
<%= t(".component") %> <%= @record.component || "—" %>
+
<%= t(".form_337") %> <%= @record.form_337_document ? link_to(@record.form_337_document.name, aircraft_document_path(@aircraft, @record.form_337_document), class: "link") : "—" %>
+
<%= t(".stc") %> <%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %>
+ <%= link_to(t(".docs"), aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %>
+
<%= t(".logbook") %> <%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %>
+
<%= t(".weight_balance") %>
<% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %>
<%= link_to t(".lb_in", date: fmt_date(wb.date), weight: number_with_precision(wb.empty_weight, precision: 1), arm: number_with_precision(wb.empty_arm, precision: 2)), aircraft_weight_balance_records_path(@aircraft), class: "link" %>
<% elsif owner? %>
<%= link_to t(".record_the_new_w_b"), new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %>
<% else %>—<% end %>
-
- <%= t(".icas") %>
+
+
<%= t(".icas") %>
<%= @record.has_ica? ? t(".yes") : t(".no") %>
<% if (ica = @record.ica_inspection_type) %>
@@ -28,7 +28,7 @@
<% elsif @record.has_ica? && owner? %>
· <%= link_to t(".add_the_ica_s_recurring"), new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %>
<% end %>
-
+
<% [[t(".description"), @record.description], [t(".ica_notes"), @record.ica_notes], [t(".notes"), @record.notes]].each do |title, text| %>
<% if text.present? %>
<%= title %> <%= simple_format text %><% end %>
diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb
index f6080d5..3f963f6 100644
--- a/app/views/profiles/edit.html.erb
+++ b/app/views/profiles/edit.html.erb
@@ -108,7 +108,7 @@
<%= t(".notifications_heading") %>
<%= t(".notifications_what") %>
-
+
<%= t(".notifications_on") %>
<%= t(".notifications_off") %>
diff --git a/app/views/pwa/service-worker.js.erb b/app/views/pwa/service-worker.js.erb
index f4985ff..aecfc5f 100644
--- a/app/views/pwa/service-worker.js.erb
+++ b/app/views/pwa/service-worker.js.erb
@@ -64,7 +64,7 @@ self.addEventListener("fetch", (event) => {
.catch(() => caches.match(url.pathname)))
} else if (url.pathname.startsWith("/assets/")) {
event.respondWith(cachedAsset(request))
- } else if (url.pathname.startsWith("/rails/active_storage/blobs/redirect/")) {
+ } else if (/^\/rails\/active_storage\/(blobs|representations)\/redirect\//.test(url.pathname)) {
// Uploaded files come from the network; an aircraft photo saved for
// offline use stands in when there's none.
event.respondWith(fetch(request)
@@ -80,11 +80,12 @@ const savedImage = async (request, response) => {
}
// Photo links carry an expiry, so they change with every page; the saved copy
-// is filed under the upload's id instead (same rule in offline_prep_controller.js).
+// is filed under the upload's id (and size) instead (same rule in offline_prep_controller.js).
function imageKey(url) {
try {
- const signed = new URL(url, self.location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
- return `${self.location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
+ const [ , signed, size ] = new URL(url, self.location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
+ const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
+ return `${self.location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
} catch (_) { return null }
}
diff --git a/app/views/shared/_aircraft_header.html.erb b/app/views/shared/_aircraft_header.html.erb
index 2e1deb9..234f77b 100644
--- a/app/views/shared/_aircraft_header.html.erb
+++ b/app/views/shared/_aircraft_header.html.erb
@@ -3,7 +3,7 @@
<% if aircraft.picture.attached? %>
- <%= image_tag aircraft.picture, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
+ <%= image_tag aircraft.picture_for(:thumb), width: 48, height: 48, class: "h-12 w-12 rounded-md object-cover", alt: "" %>
<% end %>
diff --git a/app/views/shared/show.html.erb b/app/views/shared/show.html.erb
index 7fb0250..2866c42 100644
--- a/app/views/shared/show.html.erb
+++ b/app/views/shared/show.html.erb
@@ -1,7 +1,7 @@
<% content_for :title, @aircraft.tail_number %>
- <% if @aircraft.picture.attached? %><%= image_tag rails_blob_path(@aircraft.picture, disposition: :inline), class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
+ <% if @aircraft.picture.attached? %><%= image_tag @aircraft.picture_for(:thumb), width: 64, height: 64, class: "h-16 w-16 rounded-md object-cover", alt: t(".photo_of", tail_number: @aircraft.tail_number) %><% end %>
<%= @aircraft.tail_number %> <%= [@aircraft.make, @aircraft.model].compact_blank.join(" ") %>
diff --git a/config/locales/en.yml b/config/locales/en.yml
index e9874b1..4dfb9e9 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -704,6 +704,9 @@ en:
envelope_weights: Envelope weights must be more than 0
fuel_weight: Fuel weight per gallon must be between 4 and 9 lb
flash:
+ push_subscriptions:
+ not_saved: "This browser's push service (%{host}) isn't one the app sends to."
+ unknown_device: Unknown browser
sign_in_links:
try_again_later: Try again later.
try_again_later_2: Try again later.
@@ -3876,8 +3879,13 @@ en:
blocked: Notifications are blocked for this site in the browser's settings.
unsupported: This browser can't show notifications from the app.
ios_install_first: On iPhone and iPad, install the app first (above); notifications can then be turned on in it.
- failed: Couldn't turn notifications on. Try again.
- test_sent: Test notification sent; it should arrive in a few seconds.
+ failed: "Couldn't turn notifications on: %{reason}"
+ not_saved: "Notifications are on in this browser, but the app couldn't record it: %{reason}"
+ test_sending: Sending…
+ test_none: No device has notifications on. Turn them on again here.
+ test_ok: "%{device}: sent"
+ test_failed: "%{device}: not sent (%{reason})"
+ test_hint: Sent ones should arrive within a few seconds. If this device's doesn't, check that notifications are allowed for the app in the phone's settings.
hours:
tach: Tach %{from} → %{to} (%{delta})
hobbs: Hobbs %{from} → %{to} (%{delta})
diff --git a/test/integration/pwa_features_test.rb b/test/integration/pwa_features_test.rb
index 7446300..18a119c 100644
--- a/test/integration/pwa_features_test.rb
+++ b/test/integration/pwa_features_test.rb
@@ -57,12 +57,14 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
@a.picture.attach(io: StringIO.new(file_fixture_png), filename: "plane.png", content_type: "image/png")
get root_path
- picture = JSON.parse(css_select("body").first["data-offline-prep-aircraft-value"]).first["picture"]
- shown = css_select("img[src*='/rails/active_storage/blobs/redirect/']").first["src"]
- # Links expire, so they differ; both carry the same upload id, which the saved copy is filed under.
- blob_id = ->(url) { JSON.parse(Base64.decode64(CGI.unescape(url[%r{/blobs/redirect/([^/]+?)--}, 1])))["_rails"]["data"] }
- assert_equal @a.picture.blob.id, blob_id.(picture)
- assert_equal @a.picture.blob.id, blob_id.(shown)
+ pictures = JSON.parse(css_select("body").first["data-offline-prep-aircraft-value"]).first["pictures"]
+ shown = css_select("img[src*='/rails/active_storage/representations/redirect/']").first["src"]
+ # Links expire, so they differ; both carry the same upload id and size,
+ # which the saved copy is filed under (the thumbnail and the Fleet card).
+ key = ->(url) { url.match(%r{/representations/redirect/([^/]+?)--[^/]+/([^/]+)/}).then { [ JSON.parse(Base64.decode64(CGI.unescape(_1[1])))["_rails"]["data"], _1[2] ] } }
+ assert_equal 2, pictures.size
+ assert_equal [ @a.picture.blob.id ], pictures.map { key.(_1).first }.uniq
+ assert_includes pictures.map(&key), key.(shown)
end
test "squawks can be reported offline and are received once" do
@@ -121,13 +123,34 @@ class PwaFeaturesTest < ActionDispatch::IntegrationTest
assert_response :created
post push_subscription_path, params: { subscription: subscription_params("https://internal.example.com/b") }, as: :json
assert_response :unprocessable_entity
+ assert_includes response.parsed_body["error"], "internal.example.com"
assert_equal [ "https://fcm.googleapis.com/fcm/send/a" ], @owner.push_subscriptions.pluck(:endpoint)
- assert_enqueued_with(job: PushNotificationJob) { post test_push_subscription_path, as: :json }
delete push_subscription_path, params: { endpoint: "https://fcm.googleapis.com/fcm/send/a" }, as: :json
assert_empty @owner.push_subscriptions.reload
end
+ test "the test notification is sent now and says which devices took it" do
+ sign_in @owner
+ ok = subscribe(@owner, "https://fcm.googleapis.com/fcm/send/phone")
+ ok.update!(user_agent: "Mozilla/5.0 (Linux; Android 16; Pixel) AppleWebKit/537.36 Chrome/142.0 Mobile Safari/537.36")
+ refused = subscribe(@owner, "https://web.push.apple.com/tablet")
+ refused.update!(user_agent: "Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Safari/604.1")
+ stub_request(:post, ok.endpoint).to_return(status: 201)
+ stub_request(:post, refused.endpoint).to_return(status: 400, body: "BadJwtToken")
+
+ post test_push_subscription_path, as: :json
+ devices = response.parsed_body["devices"]
+ assert_equal [ "Chrome · Android", nil ], devices.first.values_at("device", "error")
+ assert_equal "Safari · iPad", devices.last["device"]
+ assert_match "BadJwtToken", devices.last["error"]
+ end
+
+ test "Google's other push hosts are accepted" do
+ assert subscribe(@owner, "https://jmt17.google.com/fcm/send/x").persisted?
+ assert subscribe(@owner, "https://fcm.googleapis.com/wp/y").persisted?
+ end
+
test "notifications are encrypted to each device; gone devices are forgotten" do
live = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/live")
gone = subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/gone")
diff --git a/test/integration/workflow_polish_test.rb b/test/integration/workflow_polish_test.rb
index 129fad3..c7fc60c 100644
--- a/test/integration/workflow_polish_test.rb
+++ b/test/integration/workflow_polish_test.rb
@@ -74,4 +74,22 @@ class WorkflowPolishTest < ActionDispatch::IntegrationTest
get aircraft_path(@a)
assert_select "[data-controller=dismiss]", 0
end
+
+ test "aircraft pages show a small copy of the photo, made when it's uploaded" do
+ perform_enqueued_jobs { @a.picture.attach(io: StringIO.new(Vips::Image.black(1200, 900).jpegsave_buffer), filename: "plane.jpg", content_type: "image/jpeg") }
+ assert_equal 2, @a.picture.blob.variant_records.count, "both sizes are made on upload"
+ sign_in @owner
+ get aircraft_path(@a)
+ assert_select "img[src*='/representations/'][width='48']"
+ get aircraft_index_path
+ assert_select "img[src*='/representations/'][loading='lazy']"
+ end
+
+ test "a flight's details are one label and value per row" do
+ flight = @a.flight_logs.create!(date: Date.current, tach_out: 100, tach_in: 101, hobbs_out: 50, hobbs_in: 51, user: @owner)
+ sign_in @owner
+ get aircraft_flight_log_path(@a, flight)
+ assert_select "dl > div.detail-row > dt", minimum: 6
+ assert_select "dl dd.col-span-3", 0
+ end
end
diff --git a/test/services/aircraft_archive_test.rb b/test/services/aircraft_archive_test.rb
index db68edd..982705b 100644
--- a/test/services/aircraft_archive_test.rb
+++ b/test/services/aircraft_archive_test.rb
@@ -208,7 +208,7 @@ class AircraftArchiveTest < ActiveSupport::TestCase
assert_raises(RuntimeError) { importer.run }
assert_equal before[0, 2], [ Aircraft.count, Component.count ]
assert_equal 0, Aircraft.where(tail_number: "N999").count
- perform_enqueued_jobs
+ perform_enqueued_jobs(only: ActiveStorage::PurgeJob) # (the stand-in photo isn't a real image to resize)
assert_equal before[2], ActiveStorage::Blob.count
end
end