Installed app: offline squawks and pre-flight pages, push notifications, shortcuts

Offline
- Flights and squawks saved offline are tagged with their user and only sent
  while that user is signed in; storage is made persistent; Background Sync
  sends them with the app closed (Chromium); unsent count on the app badge
- Report Squawk works offline (photos included, one-time key like flights)
- The Fleet page and, for each of your aircraft, the Overview, W&B, Log
  Flight and Report Squawk pages and photo are saved ahead of time, so the
  app opens and works without signal; copies say when they were saved
- Sign-out clears saved forms, pages and photos (asks first if items wait)
- Offline page rendered by Rails (localized, follows the theme, no inline
  script); service worker version follows the build

Install and notify
- Web Push (web-push gem, VAPID keys from env or storage/vapid_keys.json):
  grounding squawks, newly overdue items (daily, once each), signing
  requests; per-device on/off and test in Profile -> This device; only
  browser push service endpoints accepted
- Manifest shortcuts (Log Flight, Report Squawk via /go/...), lang and
  localized description; install help on Profile; reload notice after a
  release

Also
- Dockerfile: libssl-dev in the build stage (openssl gem); lockfile checksums
- Leftover English and %{_} interpolation names from the localization pass
- Guide and README updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-13 22:39:42 -05:00
1 parent 89ed0a76f9
commit 8d5f57da81
54 files changed
+1217 -203

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ FROM base AS build
# Install packages needed to build gems
RUN apt-get update -qq && \
apt-get install --no-install-recommends -y build-essential git libyaml-dev pkg-config && \
apt-get install --no-install-recommends -y build-essential git libssl-dev libyaml-dev pkg-config && \
rm -rf /var/lib/apt/lists /var/cache/apt/archives
# Install application gems
+3
View File
@@ -78,4 +78,7 @@ gem "omniauth-rails_csrf_protection", "~> 2.0"
gem "prawn", "~> 2.5" # printable logbook entries
gem "rotp", "~> 6.3" # authenticator app (TOTP) codes
# Push notifications to installed apps and browsers (Web Push, VAPID)
gem "web-push", "~> 3.1"
gem "rqrcode", "~> 3.1" # QR code for setting up the authenticator
+10
View File
@@ -171,6 +171,8 @@ GEM
bindata
faraday (~> 2.0)
faraday-follow_redirects
jwt (3.3.0)
base64
kamal (2.12.0)
activesupport (>= 7.0)
base64 (~> 0.2)
@@ -259,6 +261,7 @@ GEM
tzinfo
validate_url
webfinger (~> 2.0)
openssl (4.0.2)
opentelemetry-api (1.11.1)
logger
ostruct (0.6.3)
@@ -466,6 +469,9 @@ GEM
actionview (>= 8.0.0)
bindex (>= 0.4.0)
railties (>= 8.0.0)
web-push (3.1.0)
jwt (~> 3.0)
openssl (>= 3.0)
webfinger (2.1.3)
activesupport
faraday (~> 2.0)
@@ -526,6 +532,7 @@ DEPENDENCIES
turbo-rails
tzinfo-data
web-console
web-push (~> 3.1)
webmock (~> 3.34)
CHECKSUMS
@@ -598,6 +605,7 @@ CHECKSUMS
irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3
json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8
json-jwt (1.17.2) sha256=97e37c1c3e22e9e1d74a1c0d77319c5cdc8a636226e5dbb1664b0b34eddcf1c9
jwt (3.3.0) sha256=44cc34fbc341c148233cf66641522b4bce0dfb1ce55e8073f05c56f44f4ee546
kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa
language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0
lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87
@@ -630,6 +638,7 @@ CHECKSUMS
omniauth-rails_csrf_protection (2.0.1) sha256=c6e3204d7e3925bb537cb52d50fdfc9f05293f1a9d87c5d4ab4ca3a39ba8c32d
omniauth_openid_connect (0.8.0) sha256=1f2f3890386e2a742221cee0d2e903b78d874e6fab9ea3bfa31c1462f4793d25
openid_connect (2.5.0) sha256=659aff8edce0907798e3f6837e5f27ae2937ae8735216f3e900ab8daa29e39c4
openssl (4.0.2) sha256=1037ad2868ae58df9ad917891c0c0f9815a1172f6846d4bcdd508e4c2ee747c2
opentelemetry-api (1.11.1) sha256=d07f9987ea6240b3fd5ed5dd7450f93c58e403e0553e804069c23ae18ba61ff7
ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912
parallel (2.3.0) sha256=f75a3e904101ce6a1ccb6b8dc800cbafd42166d83330192438dcf29395167a6f
@@ -713,6 +722,7 @@ CHECKSUMS
useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844
validate_url (1.0.15) sha256=72fe164c0713d63a9970bd6700bea948babbfbdcec392f2342b6704042f57451
web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4
web-push (3.1.0) sha256=501ab00340c58fb70dabda59f28a86b3cccb0930c6f1f30721b2a5b24de7187d
webfinger (2.1.3) sha256=567a52bde77fb38ca6b67e55db755f988766ec4651c1d24916a65aa70540695c
webmock (3.34.0) sha256=72eed29dc8c00148d592acaedaaa6b869e2e397de57dfc8602b84aa834f46b33
websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146
+2 -1
View File
@@ -74,6 +74,7 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). |
| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. |
| `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. |
| `APP_LOCALE` | Optional. The app's language, e.g. `es` for `config/locales/es.yml` (see [Translating](#translating)). Default `en`. |
| `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. |
| `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). |
@@ -197,7 +198,7 @@ The MCP server for AI agents, invitation codes, per-aircraft feature switches, t
### Added in this port
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable PWA.
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
## Translating
+11
View File
@@ -0,0 +1,11 @@
# The page the installed app shows without a connection. The service worker
# keeps a copy when it installs, so it's rendered in the app's language; it
# has no session data and inline styles only (nothing else may be cached).
class OfflineController < ApplicationController
allow_unauthenticated_access
skip_before_action :redirect_to_setup
def show
render layout: false
end
end
@@ -0,0 +1,22 @@
# Notifications on this device (Profile): the browser's push subscription is
# saved here when the user turns them on, and removed when they turn them off.
class PushSubscriptionsController < ApplicationController
def create
sub = params.require(:subscription).permit(:endpoint, keys: %i[p256dh auth])
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)
end
def destroy
current_user.push_subscriptions.where(endpoint: params[:endpoint].to_s).destroy_all
head :no_content
end
# A notification to this user's devices, to check they arrive.
def test
PushNotifier.notify(current_user, :test, path: edit_profile_path, tag: "test")
head :accepted
end
end
+16
View File
@@ -0,0 +1,16 @@
# The installed app's home-screen shortcuts (Log Flight, Report Squawk): the
# form for your aircraft, or a list to choose from when you have several.
class ShortcutsController < ApplicationController
def log_flight = go(:log_flight, ->(a) { new_aircraft_flight_log_path(a) })
def report_squawk = go(:report_squawk, ->(a) { new_aircraft_squawk_path(a) })
private
def go(action, path)
aircraft = current_user.accessible_aircraft.ordered.to_a
return redirect_to(path.(aircraft.first)) if aircraft.one?
@title = t("shortcuts.choose.#{action}")
@choices = aircraft.map { [ _1, path.(_1) ] }
render :choose
end
end
@@ -17,8 +17,12 @@ class SigningInvitationsController < ApplicationController
@invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user))
if @invitation.save
SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later
if (invitee = User.active.find_by(email_address: @invitation.email))
PushNotifier.notify(invitee, :signing_request, path: invited_signing_path(@invitation.token), tag: "sign-#{@invitation.id}",
tail: @aircraft.tail_number, name: current_user.display_name)
end
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: @entry.date))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, _: SigningInvitation::VALID_FOR.inspect)
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
else
render :new, status: :unprocessable_entity
end
+10 -1
View File
@@ -15,9 +15,17 @@ class SquawksController < ApplicationController
end
def create
# Already received (sent again from the offline queue): don't report it twice.
if (key = params.dig(:squawk, :client_key).to_s.presence) && @aircraft.squawks.exists?(client_key: key.first(64))
return redirect_to(aircraft_squawks_path(@aircraft), notice: t("flash.squawks.already_reported"))
end
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save
log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
if @squawk.grounding?
PushNotifier.notify(@aircraft.users.merge(User.active).where.not(id: current_user.id), :grounding_squawk, path: aircraft_squawks_path(@aircraft),
tag: "squawk-#{@squawk.id}", tail: @aircraft.tail_number, issue: @squawk.issue_reported.truncate(120))
end
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
else
render :new, status: :unprocessable_entity
@@ -118,7 +126,8 @@ class SquawksController < ApplicationController
end
def squawk_params
params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, attachments: [])
params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, :client_key, attachments: [])
.tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) }
.tap { |p| p[:client_key] = p[:client_key].to_s.first(64).presence if p.key?(:client_key) }
end
end
+12
View File
@@ -1,4 +1,16 @@
module AircraftHelper
OFFLINE_AIRCRAFT = 10
# 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.
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
end
end
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
def aircraft_tabs(aircraft)
[
+1 -1
View File
@@ -24,7 +24,7 @@ module OilAnalysesHelper
value = analysis.value(element)
flagged = analysis.flagged?(element)
content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ],
title: (I18n.t("helpers.oil_analyses.over_the_lab_average", _: (OilAnalysis::FLAG_RATIO)) if flagged))
title: (I18n.t("helpers.oil_analyses.over_the_lab_average", ratio: OilAnalysis::FLAG_RATIO) if flagged))
avg = analysis.average(element)
avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content
end
+18 -1
View File
@@ -20,11 +20,28 @@ styleCharts()
document.addEventListener("turbo:load", restyleCharts)
window.addEventListener("theme:change", restyleCharts)
// Installable app (PWA): the service worker adds an offline page and caches static assets.
// Installable app (PWA): the service worker keeps an offline page, forms and
// pre-flight pages, sends saved items in the background and shows notifications.
if ("serviceWorker" in navigator) {
// A new release's worker takes over open pages: offer a reload (not on the first install).
const hadWorker = !!navigator.serviceWorker.controller
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (hadWorker) document.dispatchEvent(new CustomEvent("app:updated"))
})
// The worker sent saved items in the background: refresh the counts.
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data?.type === "queue-changed") document.dispatchEvent(new CustomEvent("offline-queue:changed"))
})
window.addEventListener("load", () => navigator.serviceWorker.register("/service-worker.js", { scope: "/" }).catch(() => {}))
}
// Chrome and Android offer to install the app; keep the offer for the button on the profile page.
window.addEventListener("beforeinstallprompt", (event) => {
event.preventDefault()
window.samInstallPrompt = event
document.dispatchEvent(new CustomEvent("install:available"))
})
// Label each table cell with its column header, so phone CSS can show rows as
// cards ("Status: In Service"). Skips tables marked .table-keep.
function labelTableCells(root = document) {
@@ -0,0 +1,15 @@
import { Controller } from "@hotwired/stimulus"
// After a release, offers to reload so this page picks up the new version.
export default class extends Controller {
static targets = [ "banner" ]
connect() {
this.show = () => this.bannerTarget.classList.remove("hidden")
document.addEventListener("app:updated", this.show)
}
disconnect() { document.removeEventListener("app:updated", this.show) }
reload() { location.reload() }
}
@@ -30,7 +30,7 @@ export default class extends Controller {
add(event) {
for (const file of event.target.files) {
const item = { file, path: file.webkitRelativePath || file.name, state: "pending", progress: 0 }
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: `over the ${Math.round(this.maxBytesValue / 1048576)} MB limit` })
if (file.size > this.maxBytesValue) Object.assign(item, { state: "error", error: t("bulk_upload.over_limit", { mb: Math.round(this.maxBytesValue / 1048576) }) })
this.items.push(item)
}
event.target.value = ""
@@ -0,0 +1,34 @@
import { Controller } from "@hotwired/stimulus"
// Profile → This device: install the app. Chrome and Android offer a button;
// iPhone and iPad install from Safari's Share menu; elsewhere the browser's menu.
export default class extends Controller {
static targets = [ "button", "installed", "ios", "other" ]
connect() {
this.offer = () => this.render()
document.addEventListener("install:available", this.offer)
this.render()
}
disconnect() { document.removeEventListener("install:available", this.offer) }
render() {
const installed = matchMedia("(display-mode: standalone)").matches || navigator.standalone === true
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
const prompt = !installed && !!window.samInstallPrompt
this.installedTarget.hidden = !installed
this.buttonTarget.hidden = !prompt
this.iosTarget.hidden = installed || prompt || !ios
this.otherTarget.hidden = installed || prompt || ios
}
async install() {
const offer = window.samInstallPrompt
if (!offer) return
offer.prompt()
await offer.userChoice
window.samInstallPrompt = null
this.render()
}
}
@@ -1,26 +1,28 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue, formFields, newKey } from "controllers/offline_queue"
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
// The Log Flight form: with no connection, the flight is kept on this device
// and sent later (see offline_sync_controller). The next leg starts where the
// last saved one ended.
// Log Flight and Report Squawk: with no connection, the form is kept on this
// device and sent later (see offline_sync_controller). For flights, the next
// leg starts where the last saved one ended.
export default class extends Controller {
static targets = [ "key", "notice" ]
static values = { tail: String }
static values = { kind: { type: String, default: "flight" }, tail: String }
async connect() {
if (!this.keyTarget.value) this.keyTarget.value = newKey()
try {
const mine = (await queue.all()).filter((i) => i.url === this.element.action)
const mine = (await queue.mine()).filter((i) => i.url === this.element.action)
if (mine.length) {
this.prefillFrom(mine[mine.length - 1])
this.say(`${mine.length} flight${mine.length > 1 ? "s" : ""} logged offline on this device, waiting to send. This one starts where the last ended.`)
if (this.flight) this.prefillFrom(mine[mine.length - 1])
this.say(t(`offline.${this.kindValue}.queued_here`, { count: mine.length }))
}
} catch (_) { /* no IndexedDB: nothing queued */ }
this.rememberForm()
}
get flight() { return this.kindValue === "flight" }
// No connection: keep it here instead of submitting.
async submit(event) {
if (navigator.onLine) return
@@ -36,8 +38,8 @@ export default class extends Controller {
if (this.pending) await this.save(this.pending)
}
// A proxy answered because the app is unreachable (502/503/504): keep the
// flight instead of showing the proxy's error page.
// A proxy answered because the app is unreachable (502/503/504): keep it
// instead of showing the proxy's error page.
async gatewayFailed(event) {
if (![ 502, 503, 504 ].includes(event.detail.fetchResponse.statusCode) || !this.pending) return
event.preventDefault()
@@ -45,19 +47,20 @@ export default class extends Controller {
}
async save(fields) {
const item = { id: this.keyTarget.value, url: this.element.action, tail: this.tailValue, savedAt: new Date().toISOString(), fields }
const item = { id: this.keyTarget.value, kind: this.kindValue, url: this.element.action, tail: this.tailValue,
user: currentUser(), savedAt: new Date().toISOString(), fields }
try {
await queue.add(item)
} catch (_) {
this.say(t("offline.no_storage"))
this.say(t(`offline.${this.kindValue}.no_storage`))
return
}
this.prefillFrom(item)
this.clearLegFields()
if (this.flight) this.prefillFrom(item)
this.clearFields()
this.keyTarget.value = newKey()
this.pending = null
window.scrollTo({ top: 0 })
this.say(t("offline.saved_on_device"))
this.say(t(`offline.${this.kindValue}.saved_on_device`))
document.dispatchEvent(new CustomEvent("offline-queue:changed"))
}
@@ -69,19 +72,22 @@ export default class extends Controller {
set("departure_location", value("destination_location"))
}
clearLegFields() {
for (const name of [ "tach_in", "tach_time", "hobbs_in", "hobbs_time", "destination_location", "route", "notes",
"oil_added", "oil_level_after", "fuel_added", "fuel_level_after", "track_log", "engine_data" ]) {
const el = this.element.querySelector(`[name="flight_log[${name}]"]`)
clearFields() {
const names = this.flight
? [ "tach_in", "tach_time", "hobbs_in", "hobbs_time", "destination_location", "route", "notes",
"oil_added", "oil_level_after", "fuel_added", "fuel_level_after", "track_log", "engine_data" ].map((n) => `flight_log[${n}]`)
: [ "squawk[issue_reported]", "squawk[attachments][]" ]
for (const name of names) {
const el = this.element.querySelector(`[name="${name}"]`)
if (el) el.value = ""
}
}
// Lets the offline page offer this form for this aircraft.
// Lets the offline page and the home-screen shortcuts offer this form.
rememberForm() {
try {
const forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
forms[location.pathname] = this.tailValue
forms[location.pathname] = { tail: this.tailValue, kind: this.kindValue }
localStorage.setItem("sam-offline-forms", JSON.stringify(forms))
} catch (_) { /* storage off */ }
}
@@ -0,0 +1,67 @@
import { Controller } from "@hotwired/stimulus"
import { currentUser } from "controllers/offline_queue"
// Saves, ahead of time, what's needed to work without signal: the Fleet page
// and, for each of your aircraft, its Overview, W&B, Log Flight and Report
// Squawk pages (fetching them through the service worker keeps a copy, see
// service-worker.js) and its photo (kept in sam-images, shown when offline). Done in the background at most once an hour, or when
// your aircraft change. Signing out clears it.
const EVERY = 60 * 60 * 1000
export default class extends Controller {
static values = { aircraft: Array }
connect() {
if (!navigator.onLine || !("serviceWorker" in navigator)) return
navigator.serviceWorker.ready.then(() => this.prepare()).catch(() => {})
}
async prepare() {
const signature = `${currentUser()}:${JSON.stringify(this.aircraftValue)}`
let last = {}
try { last = JSON.parse(localStorage.getItem("sam-offline-prep") || "{}") } catch (_) { /* storage off */ }
if (last.signature === signature && Date.now() - last.at < EVERY) return
if (!navigator.serviceWorker.controller) return // first visit: the worker takes over on the next page
const forms = {}
const paths = [ "/" ]
for (const a of this.aircraftValue) {
paths.push(...a.pages, a.flight, a.squawk)
forms[a.flight] = { tail: a.tail, kind: "flight" }
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
}
for (const path of paths) {
if (!navigator.onLine) return
// One at a time, after the page has settled, so it never competes with what you're doing.
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))
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() }))
} catch (_) { /* storage off */ }
}
// The aircraft photos: refreshed, and those of aircraft you no longer have dropped.
async savePictures(urls) {
try {
const cache = await caches.open("sam-images")
const wanted = urls.map((url) => [ url, imageKey(url) ]).filter(([ , key ]) => key)
for (const request of await cache.keys()) if (!wanted.some(([ , key ]) => key === request.url)) await cache.delete(request)
for (const [ url, key ] of wanted) {
const response = await fetch(url, { credentials: "same-origin" }).catch(() => null)
if (response?.ok) await cache.put(key, response)
}
} catch (_) { /* no Cache API */ }
}
}
// 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).
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}`
} catch (_) { return null }
}
+18 -5
View File
@@ -1,7 +1,9 @@
// Flights logged without a connection, kept in this browser (IndexedDB, so
// attached track and engine files are kept too) until they can be sent.
// Flights and squawks saved without a connection, kept in this browser
// (IndexedDB, so attached files are kept too) until they can be sent. Each
// is tagged with the user who saved it and only ever sent while they're
// signed in. The service worker reads the same store to send in the background.
const DB = "sam-offline"
const STORE = "flights"
const STORE = "flights" // holds every kind; the name predates squawks
function open() {
return new Promise((resolve, reject) => {
@@ -22,12 +24,23 @@ async function run(mode, fn) {
})
}
// item: { id, url, tail, savedAt, fields: [[name, value]], error }
// The signed-in user (from the layout), or "" on a page without one.
export const currentUser = () => document.querySelector("meta[name=current-user]")?.content || ""
// item: { id, kind: "flight" | "squawk", url, tail, user, savedAt, fields: [[name, value]], error }
export const queue = {
add: (item) => run("readwrite", (s) => s.put(item)),
add: async (item) => {
await run("readwrite", (s) => s.put(item))
// Ask the browser not to clear this site's storage under pressure, so
// unsent items aren't lost; and to send them even if the app is closed.
try { await navigator.storage?.persist?.() } catch (_) { /* not supported */ }
try { await (await navigator.serviceWorker?.ready)?.sync?.register("sam-queue") } catch (_) { /* not supported or turned off */ }
},
put: (item) => run("readwrite", (s) => s.put(item)),
remove: (id) => run("readwrite", (s) => s.delete(id)),
all: async () => ((await run("readonly", (s) => s.getAll())) || []).sort((a, b) => a.savedAt.localeCompare(b.savedAt)),
// Items this user saved (items from before tagging count as theirs).
mine: async () => (await queue.all()).filter((i) => !i.user || i.user === currentUser()),
}
export function formFields(form) {
@@ -2,8 +2,9 @@ import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
// On every page: sends flights logged offline once there's a connection, and
// says what happened. A rejected flight stays until it's discarded.
// On every page: sends the flights and squawks this user saved offline once
// there's a connection, says what happened, and shows the count on the app
// icon. A rejected item stays until it's discarded.
export default class extends Controller {
static targets = [ "banner" ]
@@ -21,21 +22,21 @@ export default class extends Controller {
async sync() {
let items
try { items = await queue.all() } catch (_) { return }
if (!items.length) return this.show("")
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); return this.show("") }
if (!navigator.onLine || this.running) return this.status(items)
this.running = true
let sent = 0
const sent = []
try {
for (const item of items.filter((i) => !i.error)) {
const result = await this.send(item)
if (result === "sent") { await queue.remove(item.id); sent++ }
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") break
else { item.error = result; await queue.put(item) }
}
} finally { this.running = false }
this.status(await queue.all(), sent)
this.status(await queue.mine(), sent)
}
async send(item) {
@@ -56,13 +57,22 @@ export default class extends Controller {
return message || t("offline.not_accepted", { status: response.status })
}
status(items, sent = 0) {
status(items, sent = []) {
const failed = items.filter((i) => i.error)
const waiting = items.length - failed.length
const waiting = items.filter((i) => !i.error)
const parts = []
if (sent) parts.push(t("offline.sent", { count: sent }))
if (waiting) parts.push(t("offline.waiting", { count: waiting }))
for (const kind of [ "flight", "squawk" ]) {
const count = (list) => list.filter((i) => (i.kind || "flight") === kind).length
if (count(sent)) parts.push(t(`offline.${kind}.sent`, { count: count(sent) }))
if (count(waiting)) parts.push(t(`offline.${kind}.waiting`, { count: count(waiting) }))
}
this.show(parts.join(" "), failed)
this.badge(items.length)
}
// The number of unsent items on the installed app's icon.
badge(count) {
try { count ? navigator.setAppBadge?.(count) : navigator.clearAppBadge?.() } catch (_) { /* not supported */ }
}
show(text, failed = []) {
@@ -72,7 +82,7 @@ export default class extends Controller {
for (const item of failed) {
const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || ""
const row = document.createElement("p")
row.textContent = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} `
row.textContent = `${t(`offline.${item.kind || "flight"}.rejected`, { tail: item.tail, date, error: item.error })} `
const discard = Object.assign(document.createElement("button"), { type: "button", textContent: t("offline.discard"), className: "btn-secondary btn-sm ml-1" })
discard.addEventListener("click", async () => { await queue.remove(item.id); this.sync() })
row.append(discard)
@@ -0,0 +1,21 @@
import { Controller } from "@hotwired/stimulus"
import { t, locale } from "i18n"
// Pages the service worker kept for use without a connection (an aircraft's
// overview and weight and balance, and the Log Flight / Report Squawk forms)
// say when they were saved when they're shown from that copy.
const STALE_AFTER = 5 * 60 * 1000
export default class extends Controller {
static targets = [ "banner" ]
connect() {
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
const stale = rendered && Date.now() - rendered > STALE_AFTER
if (stale) {
const when = new Date(rendered).toLocaleString(locale(), { dateStyle: "medium", timeStyle: "short" })
this.bannerTarget.textContent = t("offline.saved_copy", { time: when })
}
this.bannerTarget.classList.toggle("hidden", !stale)
}
}
@@ -0,0 +1,63 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Profile → This device: notifications on or off for this browser or app.
export default class extends Controller {
static targets = [ "status", "on", "off", "test" ]
static values = { key: String, url: String, testUrl: String }
async connect() {
if (!("serviceWorker" in navigator) || !("PushManager" in window) || !("Notification" in window)) {
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
return this.show(t(ios ? "push.ios_install_first" : "push.unsupported"), null)
}
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)
}
async turnOn() {
if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null)
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)
}
}
async turnOff() {
const subscription = await this.registration.pushManager.getSubscription()
if (subscription) {
await this.request("DELETE", this.urlValue, { endpoint: subscription.endpoint })
await subscription.unsubscribe()
}
this.show(t("push.off"), false)
}
async sendTest() {
await this.request("POST", this.testUrlValue, {})
this.statusTarget.textContent = t("push.test_sent")
}
// on: true / false, or null when it can't be changed here.
show(text, on) {
this.statusTarget.textContent = text
this.onTarget.hidden = on !== false
this.offTarget.hidden = on !== true
this.testTarget.hidden = on !== true
}
request(method, url, body) {
return fetch(url, { method, credentials: "same-origin", body: JSON.stringify(body),
headers: { "Content-Type": "application/json", "X-CSRF-Token": document.querySelector("meta[name=csrf-token]")?.content || "" } })
}
keyBytes() {
const base64 = (this.keyValue + "=".repeat((4 - this.keyValue.length % 4) % 4)).replace(/-/g, "+").replace(/_/g, "/")
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0))
}
}
@@ -0,0 +1,22 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
// Signing out clears what this device kept for working offline (forms and
// page copies with aircraft details). Unsent flights and squawks stay, tagged
// with their user, and are sent the next time that person signs in here.
export default class extends Controller {
async clean(event) {
if (this.cleaned) return
event.preventDefault()
try {
const unsent = (await queue.mine()).length
if (unsent && !confirm(t("sign_out.unsent", { count: unsent }))) return
} catch (_) { /* no IndexedDB */ }
try { await Promise.all([ "sam-forms", "sam-pages", "sam-images", "sam-flight-forms" ].map((name) => caches.delete(name))) } catch (_) { /* no Cache API */ }
try { [ "sam-offline-forms", "sam-offline-prep" ].forEach((key) => localStorage.removeItem(key)) } catch (_) { /* storage off */ }
try { navigator.clearAppBadge?.() } catch (_) { /* not supported */ }
this.cleaned = true
this.element.requestSubmit()
}
}
@@ -24,7 +24,7 @@ export default class extends Controller {
const fuel = input.dataset.fuel === "true"
const max = parseFloat(input.dataset.max) || 0
const label = input.closest("label").querySelector(".label").firstChild.textContent.trim()
if (max && qty > max) messages.push([ "bad", `${label}: ${qty} is over its maximum of ${max} ${fuel ? "gal" : "lb"}.` ])
if (max && qty > max) messages.push([ "bad", t(fuel ? "wb.over_station_gal" : "wb.over_station_lb", { label, qty, max }) ])
const lbs = fuel ? qty * this.fuelDensityValue : qty
weight += lbs
moment += lbs * arm
+20
View File
@@ -0,0 +1,20 @@
# Daily: tells owners about items that have newly become overdue or limit
# the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and
# becomes overdue again is sent again.
class OverdueNotificationJob < ApplicationJob
queue_as :default
def perform
Aircraft.includes(roles: :user).find_each do |aircraft|
issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) }
keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" }
fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) }
owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?)
if fresh.any?
PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size)
end
aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort
end
end
end
+23
View File
@@ -0,0 +1,23 @@
# Delivers one notification (see PushNotifier) to each of the users' devices.
# A device that's gone (the browser dropped the subscription) is forgotten.
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) }
end
private
def 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
subscription.destroy
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)}")
end
end
+32
View File
@@ -0,0 +1,32 @@
# The VAPID key pair that signs push notifications: VAPID_PUBLIC_KEY and
# VAPID_PRIVATE_KEY, or else a pair generated once and kept in
# storage/vapid_keys.json (backed up with the database). Changing the keys
# turns notifications off on every device until each turns them on again.
module PushKeys
FILE = Rails.root.join("storage", "vapid_keys.json")
module_function
def public_key = keys["public_key"]
def private_key = keys["private_key"]
# Who push services contact about these notifications.
def subject
from = ENV["MAIL_FROM"].to_s[/[^<\s]+@[^>\s]+/]
from ? "mailto:#{from}" : Sso.app_url
end
def keys
@keys ||= if ENV["VAPID_PUBLIC_KEY"].present? && ENV["VAPID_PRIVATE_KEY"].present?
{ "public_key" => ENV["VAPID_PUBLIC_KEY"], "private_key" => ENV["VAPID_PRIVATE_KEY"] }
elsif FILE.exist?
JSON.parse(FILE.read)
else
key = WebPush.generate_key
{ "public_key" => key.public_key, "private_key" => key.private_key }.tap do |pair|
FILE.dirname.mkpath
File.write(FILE, JSON.generate(pair), perm: 0o600)
end
end
end
end
+21
View File
@@ -0,0 +1,21 @@
# A browser or installed app where a user turned notifications on (Profile).
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/
belongs_to :user
validates :endpoint, presence: true, uniqueness: true
validates :p256dh, :auth, presence: true
validate :endpoint_is_a_push_service
private
def endpoint_is_a_push_service
uri = URI.parse(endpoint.to_s)
errors.add(:endpoint, :invalid) unless uri.is_a?(URI::HTTPS) && uri.host.to_s.match?(PUSH_SERVICES)
rescue URI::InvalidURIError
errors.add(:endpoint, :invalid)
end
end
+1
View File
@@ -2,6 +2,7 @@ class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy
has_many :push_subscriptions, dependent: :delete_all
has_many :aircraft, through: :aircraft_roles
has_one :air_trail_connection, dependent: :destroy
has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy
+2 -2
View File
@@ -71,7 +71,7 @@ module AircraftArchive
compressed += entry.compressed_size
raise Error, I18n.t("services.aircraft_archive.the_archive_is_too_large") if uncompressed > ARCHIVE_MAX_BYTES
end
raise Error, I18n.t("services.aircraft_archive.the_archive_is_compressed_suspiciously", _: MAX_RATIO) if compressed.positive? && uncompressed / compressed > MAX_RATIO
raise Error, I18n.t("services.aircraft_archive.the_archive_is_compressed_suspiciously", ratio: MAX_RATIO) if compressed.positive? && uncompressed / compressed > MAX_RATIO
entry = zip.find_entry("#{root_prefix(zip)}manifest.json") or raise Error, I18n.t("services.aircraft_archive.the_archive_has_no_manifest")
raise Error, I18n.t("services.aircraft_archive.manifest_json_is_too_large") if entry.size > MANIFEST_MAX_BYTES
@@ -84,7 +84,7 @@ module AircraftArchive
version = manifest["schema_version"]
unless version.is_a?(Integer) && version.between?(1, SCHEMA_VERSION)
raise Error, I18n.t("services.aircraft_archive.unsupported_archive_version_this_app", version: version.inspect, _: SCHEMA_VERSION)
raise Error, I18n.t("services.aircraft_archive.unsupported_archive_version_this_app", version: version.inspect, max: SCHEMA_VERSION)
end
required = TOP_LEVEL_KEYS - OPTIONAL_KEYS - (version < 2 ? %w[flight_logs] : [])
missing = required - manifest.keys
+13
View File
@@ -0,0 +1,13 @@
# Sends a notification to every device where the users turned notifications
# on. The text is push.<key>.title / .body in config/locales, filled in when
# it's sent.
# PushNotifier.notify(users, :grounding_squawk, path: "/aircraft/1/squawks", tail: "N12345", issue: "…")
module PushNotifier
module_function
def notify(users, key, path:, tag: nil, **vars)
ids = Array(users).map { _1.respond_to?(:id) ? _1.id : _1 }.compact.uniq
return if ids.empty? || !PushSubscription.exists?(user_id: ids)
PushNotificationJob.perform_later(ids, key.to_s, path, tag, vars.transform_values { _1.is_a?(Numeric) ? _1 : _1.to_s })
end
end
+1 -1
View File
@@ -2,7 +2,7 @@
<%= f.errors_summary %>
<%= f.field :name %>
<%= f.field :email_address, as: :email, label: t(".email"), required: true %>
<%= f.field :password, as: :password, hint: (user.persisted? ? t(".leave_blank_to_keep_current") : t(".at_least_characters_not_one", _: (User::PASSWORD_MIN))), autocomplete: "new-password" %>
<%= f.field :password, as: :password, hint: (user.persisted? ? t(".leave_blank_to_keep_current") : t(".at_least_characters_not_one", min: User::PASSWORD_MIN)), autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password %>
<%= f.field :admin, as: :checkbox, label: t(".administrator"), hint: t(".admins_can_see_and_edit") %>
<div class="flex gap-2"><%= f.submit t(".save") %><%= link_to t(".cancel"), admin_users_path, class: "btn-secondary" %></div>
+1
View File
@@ -1,4 +1,5 @@
<% content_for :title, @aircraft.tail_number %>
<% content_for :head do %><meta name="aircraft-tail" content="<%= @aircraft.tail_number %>"><% end %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-3">
+4 -4
View File
@@ -1,10 +1,10 @@
<% content_for :title, t(".log_flight") %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl",
data: { controller: "offline-flight", offline_flight_tail_value: @aircraft.tail_number,
action: "submit->offline-flight#submit turbo:submit-start->offline-flight#remember turbo:fetch-request-error->offline-flight#networkFailed turbo:before-fetch-response->offline-flight#gatewayFailed" } do |f| %>
<%= f.hidden_field :client_key, data: { offline_flight_target: "key" } %>
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-flight-target="notice" role="status"></div>
data: { controller: "offline-form", offline_form_kind_value: "flight", offline_form_tail_value: @aircraft.tail_number,
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } do |f| %>
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :date, as: :date, required: true %>
+9 -3
View File
@@ -18,11 +18,17 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
<meta name="rendered-at" content="<%= Time.current.iso8601 %>">
<% if current_user %><meta name="current-user" content="<%= current_user.id %>"><% end %>
<script type="application/json" id="i18n" nonce="<%= content_security_policy_nonce %>"><%= json_escape(t("js").to_json).html_safe %></script>
</head>
<body class="min-h-full text-slate-800" data-controller="offline-sync">
<body class="min-h-full text-slate-800" data-controller="offline-sync page-age app-update<%= " offline-prep" if current_user %>"<% if current_user %> data-offline-prep-aircraft-value="<%= offline_pages.to_json %>"<% end %>>
<%= t(".skip_to_content_html") %>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-page-age-target="banner" role="status"></div>
<div class="hidden bg-sky-50 px-4 py-2 text-center text-sm text-sky-900 ring-1 ring-sky-200" data-app-update-target="banner" role="status">
<%= t(".updated") %> <button type="button" class="btn-secondary btn-sm ml-1" data-action="app-update#reload"><%= t(".reload") %></button>
</div>
<div class="hidden space-y-1 bg-amber-50 px-4 py-2 text-center text-sm text-amber-900 ring-1 ring-amber-200" data-offline-sync-target="banner" role="status"></div>
<header class="bg-header text-white">
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
@@ -47,7 +53,7 @@
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
<% end %>
<% end %>
<div class="border-t border-slate-100"><%= button_to t(".sign_out"), session_path, method: :delete, class: "block w-full px-4 py-2.5 text-left hover:bg-slate-100" %></div>
<div class="border-t border-slate-100"><%= button_to t(".sign_out"), session_path, method: :delete, class: "block w-full px-4 py-2.5 text-left hover:bg-slate-100", form: { data: { controller: "sign-out", action: "submit->sign-out#clean" } } %></div>
</div>
</details>
</nav>
@@ -73,7 +79,7 @@
<%= link_to t(".help"), help_path, class: "hover:text-sky-300" %>
<%= link_to current_user.display_name, edit_profile_path, class: "text-white/70 hover:text-sky-300 hidden sm:inline" %>
<%= render "shared/theme_toggle" %>
<%= button_to t(".sign_out"), session_path, method: :delete, class: "rounded bg-white/10 px-2 py-1 hover:bg-white/20" %>
<%= button_to t(".sign_out"), session_path, method: :delete, class: "rounded bg-white/10 px-2 py-1 hover:bg-white/20", form: { data: { controller: "sign-out", action: "submit->sign-out#clean" } } %>
</nav>
<% end %>
</div>
@@ -1,16 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<html lang="<%= I18n.locale %>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="theme-color" content="#0f172a">
<title>Offline · Simple Aircraft Manager</title>
<title><%= t(".title") %></title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<style>
:root { --page: #f1f5f9; --surface: #fff; --text: #1e293b; --muted: #64748b; --accent: #0369a1; }
@media (prefers-color-scheme: dark) {
:root { --page: #0b1220; --surface: #0f172a; --text: #e2e8f0; --muted: #94a3b8; }
:root:not([data-theme="light"]) { --page: #0b1220; --surface: #0f172a; --text: #e2e8f0; --muted: #94a3b8; }
}
:root[data-theme="dark"] { --page: #0b1220; --surface: #0f172a; --text: #e2e8f0; --muted: #94a3b8; }
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
background: var(--page); color: var(--text); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
@@ -19,18 +20,21 @@
img { width: 72px; height: 72px; }
h1 { font-size: 1.25rem; margin: 16px 0 8px; }
p { margin: 0 0 24px; color: var(--muted); }
#forms a { display: block; margin-top: 8px; color: var(--accent); font-weight: 600; }
#forms a, #pages a { display: block; margin-top: 8px; color: var(--accent); font-weight: 600; }
button { font: inherit; font-weight: 600; color: #fff; background: var(--accent); border: 0; border-radius: 6px; padding: 10px 20px; cursor: pointer; }
</style>
</head>
<body>
<main>
<img src="/icon.svg" alt="">
<h1>You're offline</h1>
<p>Simple Aircraft Manager needs a connection to load your aircraft. Check your signal and try again.</p>
<button type="button" onclick="location.reload()">Try again</button>
<div id="forms" hidden>
<p style="margin:24px 0 8px">You can still log a flight; it's sent when you're back online:</p>
<h1><%= t(".heading") %></h1>
<p><%= t(".needs_connection") %></p>
<button type="button" id="retry"><%= t(".try_again") %></button>
<div id="forms" hidden data-flight="<%= t(".log_flight") %>" data-squawk="<%= t(".report_squawk") %>">
<p style="margin:24px 0 8px"><%= t(".still_can") %></p>
</div>
<div id="pages" hidden data-label="<%= t(".saved_overview") %>">
<p style="margin:24px 0 8px"><%= t(".saved_pages") %></p>
</div>
</main>
<script src="/offline.js"></script>
+22
View File
@@ -88,6 +88,28 @@
<% end %>
</section>
<section class="card card-body mt-5 max-w-md space-y-4" id="device">
<h2 class="card-title"><%= t(".this_device") %></h2>
<div data-controller="install">
<h3 class="text-sm font-semibold"><%= t(".install_heading") %></h3>
<p class="hint"><%= t(".install_why") %></p>
<p class="mt-2 text-sm text-emerald-700" data-install-target="installed" hidden><%= t(".installed") %></p>
<button type="button" class="btn-secondary btn-sm mt-2" data-install-target="button" data-action="install#install" hidden><%= t(".install") %></button>
<p class="mt-2 text-sm text-slate-600" data-install-target="ios" hidden><%= t(".install_ios_html") %></p>
<p class="mt-2 text-sm text-slate-600" data-install-target="other" hidden><%= t(".install_other") %></p>
</div>
<div data-controller="push" data-push-key-value="<%= PushKeys.public_key %>" data-push-url-value="<%= push_subscription_path %>" data-push-test-url-value="<%= test_push_subscription_path %>">
<h3 class="text-sm font-semibold"><%= t(".notifications_heading") %></h3>
<p class="hint"><%= t(".notifications_what") %></p>
<p class="mt-2 text-sm text-slate-600" data-push-target="status" role="status"></p>
<div class="mt-2 flex flex-wrap gap-2">
<button type="button" class="btn-secondary btn-sm" data-push-target="on" data-action="push#turnOn" hidden><%= t(".notifications_on") %></button>
<button type="button" class="btn-secondary btn-sm" data-push-target="off" data-action="push#turnOff" hidden><%= t(".notifications_off") %></button>
<button type="button" class="btn-secondary btn-sm" data-push-target="test" data-action="push#sendTest" hidden><%= t(".notifications_test") %></button>
</div>
</div>
</section>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title"><%= t(".sessions") %></h2>
<% others = @user.sessions.where.not(id: Current.session.id).count %>
+6 -1
View File
@@ -2,7 +2,8 @@
"id": "/",
"name": "Simple Aircraft Manager",
"short_name": "SAM",
"description": "Maintenance, inspections, ADs, squawks and flight logs for your aircraft.",
"description": <%= raw t("pwa.description").to_json %>,
"lang": "<%= I18n.locale %>",
"start_url": "/",
"scope": "/",
"display": "standalone",
@@ -15,5 +16,9 @@
{ "src": "/icon.png", "type": "image/png", "sizes": "512x512", "purpose": "any" },
{ "src": "/icon-maskable.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" },
{ "src": "/icon.svg", "type": "image/svg+xml", "sizes": "any", "purpose": "any" }
],
"shortcuts": [
{ "name": <%= raw t("pwa.log_flight").to_json %>, "url": "/go/log-flight", "icons": [ { "src": "/icon-192.png", "sizes": "192x192" } ] },
{ "name": <%= raw t("pwa.report_squawk").to_json %>, "url": "/go/report-squawk", "icons": [ { "src": "/icon-192.png", "sizes": "192x192" } ] }
]
}
-94
View File
@@ -1,94 +0,0 @@
// Makes the app installable and gives it an offline page. Cached: public,
// static files (the offline page, icons, fingerprinted /assets/) and, so a
// flight can be logged without signal, the Log Flight forms you've opened
// (tail number and meter readings only). Other aircraft pages are never cached.
const VERSION = "v5"
const FORM_CACHE = "sam-flight-forms"
const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/
const SHELL_CACHE = `sam-shell-${VERSION}`
const ASSET_CACHE = "sam-assets"
const MAX_ASSETS = 80
// A proxy in front of the app (Traefik, Authentik) answers these when the app
// itself can't be reached: treat them like no connection.
const UNREACHABLE = [ 502, 503, 504 ]
const SHELL = [ "/offline.html", "/offline.js", "/icon.svg", "/icon-192.png" ]
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
})
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((k) => k.startsWith("sam-shell-") && k !== SHELL_CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
)
})
self.addEventListener("fetch", (event) => {
const request = event.request
if (request.method !== "GET") return
const url = new URL(request.url)
if (url.origin !== self.location.origin) return
// Turbo opens pages with fetch(), not a navigation, so match those too or
// the form is never kept when reached by tapping "Log Flight".
const wantsHtml = request.mode === "navigate" || (request.headers.get("Accept") || "").includes("text/html")
if (wantsHtml && FLIGHT_FORM.test(url.pathname)) {
event.respondWith(flightForm(request))
} else if (request.mode === "navigate") {
// Always go to the network for pages; show the offline page if it's unreachable.
event.respondWith(fetch(request)
.then((response) => UNREACHABLE.includes(response.status) ? caches.match("/offline.html") : response)
.catch(() => caches.match("/offline.html")))
} else if (SHELL.includes(url.pathname)) {
// The offline page's own script and icon: fresh when online, kept copy when not.
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
.catch(() => caches.match(url.pathname)))
} else if (url.pathname.startsWith("/assets/")) {
event.respondWith(cachedAsset(request))
}
})
// Fingerprinted assets never change, so serve them from cache once fetched.
async function cachedAsset(request) {
const cache = await caches.open(ASSET_CACHE)
const hit = await cache.match(request)
if (hit) return hit
const response = await fetch(request)
if (response.ok) {
await cache.put(request, response.clone())
trim(cache)
}
return response
}
// Old deploys' assets pile up; keep only the most recent entries.
async function trim(cache) {
const keys = await cache.keys()
await Promise.all(keys.slice(0, Math.max(0, keys.length - MAX_ASSETS)).map((k) => cache.delete(k)))
}
// The Log Flight form: fresh from the network when there is one (and kept),
// the kept copy when there isn't.
async function flightForm(request) {
const cache = await caches.open(FORM_CACHE)
const key = request.url.split("?")[0]
try {
const response = await fetch(request)
if (UNREACHABLE.includes(response.status)) {
const kept = await cache.match(key)
if (kept) return kept
return request.mode === "navigate" ? caches.match("/offline.html") : response
}
const html = (response.headers.get("Content-Type") || "").includes("text/html")
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
return response
} catch (error) {
const kept = await cache.match(key)
if (kept) return kept
// A Turbo fetch gets the error, so Turbo falls back to a full page load.
if (request.mode !== "navigate") throw error
return caches.match("/offline.html")
}
}
+214
View File
@@ -0,0 +1,214 @@
// Makes the app installable and keeps what's needed to work without signal:
// - the offline page (rendered in the app's language) and its script and icons;
// - fingerprinted /assets/ once fetched;
// - the Log Flight and Report Squawk forms you've opened (tail number and
// meter readings only), so they can be filled in offline and sent later;
// - the Fleet page and each aircraft's Overview and weight and balance page,
// so the app opens and you can get around without signal (shown with the
// time they were saved).
// - each aircraft's photo (put in sam-images ahead of time), shown when offline.
// The forms and pages are saved ahead of time for all your aircraft
// (offline_prep_controller.js), not only the ones you've opened.
// Nothing else is cached; signing out clears the forms and pages.
// The version changes with every build, so a release refreshes the cached shell.
const VERSION = "<%= j "#{SystemInfo.new.revision}-#{I18n.locale}" %>"
const SHELL_CACHE = `sam-shell-${VERSION}`
const FORM_CACHE = "sam-forms"
const PAGE_CACHE = "sam-pages"
const IMAGE_CACHE = "sam-images"
const ASSET_CACHE = "sam-assets"
const MAX_ASSETS = 80
const FORMS = /^\/aircraft\/\d+\/(flight_logs|squawks)\/new$/
const PAGES = /^\/$|^\/aircraft\/\d+(\/weight_balance)?$/
const SHORTCUTS = { "/go/log-flight": "flight_logs", "/go/report-squawk": "squawks" }
// A proxy in front of the app (Traefik, Authentik) answers these when the app
// itself can't be reached: treat them like no connection.
const UNREACHABLE = [ 502, 503, 504 ]
const SHELL = [ "/offline", "/offline.js", "/icon.svg", "/icon-192.png" ]
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
})
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((k) => (k.startsWith("sam-shell-") && k !== SHELL_CACHE) || k === "sam-flight-forms").map((k) => caches.delete(k))))
.then(() => self.clients.claim())
)
})
self.addEventListener("fetch", (event) => {
const request = event.request
if (request.method !== "GET") return
const url = new URL(request.url)
if (url.origin !== self.location.origin) return
// Turbo opens pages with fetch(), not a navigation, so match those too or
// the form is never kept when reached by tapping a link.
const wantsHtml = request.mode === "navigate" || (request.headers.get("Accept") || "").includes("text/html")
if (wantsHtml && FORMS.test(url.pathname)) {
event.respondWith(keptPage(request, FORM_CACHE))
} else if (wantsHtml && PAGES.test(url.pathname)) {
event.respondWith(keptPage(request, PAGE_CACHE))
} else if (request.mode === "navigate" && SHORTCUTS[url.pathname]) {
event.respondWith(shortcut(request, SHORTCUTS[url.pathname]))
} else if (request.mode === "navigate") {
// Always go to the network for pages; show the offline page if it's unreachable.
event.respondWith(fetch(request)
.then((response) => UNREACHABLE.includes(response.status) ? offlinePage() : response)
.catch(() => offlinePage()))
} else if (SHELL.includes(url.pathname)) {
// The offline page's own script and icon: fresh when online, kept copy when not.
event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r))
.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/")) {
// Uploaded files come from the network; an aircraft photo saved for
// offline use stands in when there's none.
event.respondWith(fetch(request)
.then((response) => UNREACHABLE.includes(response.status) ? savedImage(request, response) : response)
.catch(() => savedImage(request)))
}
})
const offlinePage = () => caches.match("/offline")
const savedImage = async (request, response) => {
const key = imageKey(request.url)
return (key && await caches.open(IMAGE_CACHE).then((c) => c.match(key))) || response || Response.error()
}
// 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).
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}`
} catch (_) { return null }
}
// Fingerprinted assets never change, so serve them from cache once fetched.
async function cachedAsset(request) {
const cache = await caches.open(ASSET_CACHE)
const hit = await cache.match(request)
if (hit) return hit
const response = await fetch(request)
if (response.ok) {
await cache.put(request, response.clone())
trim(cache)
}
return response
}
// Old deploys' assets pile up; keep only the most recent entries.
async function trim(cache) {
const keys = await cache.keys()
await Promise.all(keys.slice(0, Math.max(0, keys.length - MAX_ASSETS)).map((k) => cache.delete(k)))
}
// A kept form or page: fresh from the network when there is one (and kept),
// the kept copy when there isn't.
async function keptPage(request, cacheName) {
const cache = await caches.open(cacheName)
const key = request.url.split("?")[0]
try {
const response = await fetch(request)
if (UNREACHABLE.includes(response.status)) {
const kept = await cache.match(key)
if (kept) return kept
return request.mode === "navigate" ? offlinePage() : response
}
const html = (response.headers.get("Content-Type") || "").includes("text/html")
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
return response
} catch (error) {
const kept = await cache.match(key)
if (kept) return kept
// A Turbo fetch gets the error, so Turbo falls back to a full page load.
if (request.mode !== "navigate") throw error
return offlinePage()
}
}
// The home-screen shortcuts: offline, open the kept form if there's only one
// of that kind (one aircraft), otherwise the offline page, which lists them.
async function shortcut(request, kind) {
try {
const response = await fetch(request)
if (!UNREACHABLE.includes(response.status)) return response
} catch (_) { /* offline */ }
const cache = await caches.open(FORM_CACHE)
const forms = (await cache.keys()).filter((r) => new URL(r.url).pathname.includes(`/${kind}/new`))
return forms.length === 1 ? cache.match(forms[0]) : offlinePage()
}
// ---- Sending saved items in the background (Chrome, Edge, Android) ----
// The page normally sends them (offline_sync_controller); this also does it
// when the app is closed. Anything the server doesn't accept is left for the
// page to report.
self.addEventListener("sync", (event) => {
if (event.tag === "sam-queue") event.waitUntil(sendQueued())
})
function queueStore(mode) {
return new Promise((resolve, reject) => {
const req = indexedDB.open("sam-offline", 1)
req.onupgradeneeded = () => req.result.createObjectStore("flights", { keyPath: "id" })
req.onsuccess = () => resolve(req.result.transaction("flights", mode).objectStore("flights"))
req.onerror = () => reject(req.error)
})
}
const idb = (store, method, arg) => new Promise((resolve, reject) => {
const req = store[method](arg)
req.onsuccess = () => resolve(req.result)
req.onerror = () => reject(req.error)
})
async function sendQueued() {
const items = ((await idb(await queueStore("readonly"), "getAll")) || []).filter((i) => !i.error)
.sort((a, b) => a.savedAt.localeCompare(b.savedAt))
if (!items.length) return
// A page of the app gives the session's CSRF token and who's signed in.
const page = await fetch("/profile/edit", { credentials: "same-origin", headers: { Accept: "text/html" } })
if (!page.ok || page.redirected) return
const html = await page.text()
const token = (html.match(/<meta name="csrf-token" content="([^"]+)"/) || [])[1]
const user = (html.match(/<meta name="current-user" content="([^"]+)"/) || [])[1]
if (!token || !user) return
let sent = 0
for (const item of items) {
if (item.user && item.user !== user) continue
const body = new FormData()
for (const [ name, value ] of item.fields) body.append(name, value)
body.append("authenticity_token", token)
const response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
if (UNREACHABLE.includes(response.status)) break
if (!response.ok || response.url.includes("/session/new")) continue // left for the page to report
await idb(await queueStore("readwrite"), "delete", item.id)
sent++
}
if (sent) (await self.clients.matchAll()).forEach((client) => client.postMessage({ type: "queue-changed" }))
}
// ---- Push notifications ----
self.addEventListener("push", (event) => {
let data = {}
try { data = event.data ? event.data.json() : {} } catch (_) { data = { title: event.data?.text() } }
event.waitUntil(self.registration.showNotification(data.title || "Simple Aircraft Manager", {
body: data.body, tag: data.tag, icon: "/icon-192.png", badge: "/icon-192.png", data: { path: data.path || "/" }
}))
})
self.addEventListener("notificationclick", (event) => {
event.notification.close()
const target = new URL(event.notification.data?.path || "/", self.location.origin).href
event.waitUntil(self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((windows) => {
const open = windows.find((w) => w.url.startsWith(self.location.origin))
if (open) return open.navigate(target).then((w) => (w || open).focus())
return self.clients.openWindow(target)
}))
})
+14
View File
@@ -0,0 +1,14 @@
<% content_for :title, @title %>
<h1 class="mb-4 text-xl font-bold"><%= @title %></h1>
<% if @choices.any? %>
<ul class="card max-w-md divide-y divide-slate-100">
<% @choices.each do |aircraft, path| %>
<li><%= link_to path, class: "flex items-baseline justify-between gap-3 px-4 py-3 hover:bg-slate-50" do %>
<span class="font-semibold"><%= aircraft.tail_number %></span>
<span class="text-sm text-slate-500"><%= [ aircraft.make, aircraft.model ].compact_blank.join(" ") %></span>
<% end %></li>
<% end %>
</ul>
<% else %>
<%= empty_state t("shortcuts.choose.no_aircraft") %>
<% end %>
+7 -1
View File
@@ -1,4 +1,10 @@
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl" do |f| %>
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
data: (squawk.new_record? ? { controller: "offline-form", offline_form_kind_value: "squawk", offline_form_tail_value: aircraft.tail_number,
action: "submit->offline-form#submit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : {}) do |f| %>
<% if squawk.new_record? %>
<%= f.hidden_field :client_key, data: { offline_form_target: "key" } %>
<div class="hidden rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-offline-form-target="notice" role="status"></div>
<% end %>
<%= f.errors_summary %>
<%= f.field :priority, as: :select, collection: Squawk::PRIORITIES.invert, hint: t(".ground_aircraft_makes_the_aircraft") %>
<%= f.field :issue_reported, as: :textarea, label: t(".issue"), required: true, autofocus: true %>
+97 -13
View File
@@ -898,6 +898,7 @@ en:
squawk_deleted_2: Squawk deleted
corrected_text: 'Corrected: %{issue}'
resolved_logged: Squawk resolved and recorded in the logbook.
already_reported: Squawk already reported.
logbook_prints:
choose_the_entries_to: Choose the entries to print.
logbook_entries_printed: Logbook entries printed (%{count})
@@ -964,7 +965,7 @@ en:
too_many_invitations_try: Too many invitations; try again later.
this_entry_is_already: This entry is already signed.
email_isn_t_set: Email isn't set up, so invitations can't be sent (Admin → About).
invitation_sent_to_the: Invitation sent to %{email}. The link works once, for %{_}.
invitation_sent_to_the: Invitation sent to %{email}. The link works once, for %{days} days.
signature_requested_from_entry: Signature requested from %{email} (%{date} entry)
standard_inspections:
added_record_when_each: Added %{items}. Record when each was last done to see when it's next due.
@@ -1551,7 +1552,7 @@ en:
save: Save
cancel: Cancel
delete_user: Delete user
at_least_characters_not_one: At least %{_} characters; not one known from a data breach.
at_least_characters_not_one: At least %{min} characters; not one known from a data breach.
leave_blank_to_keep_current: Leave blank to keep current password.
index:
users: Users
@@ -2457,6 +2458,8 @@ en:
settings: Settings
users: Users
about: About
updated: Simple Aircraft Manager has been updated.
reload: Reload
public:
skip_to_content_html: <a href="#main" class="skip-link">Skip to content</a>
simple_aircraft_manager: Simple Aircraft Manager
@@ -2965,6 +2968,18 @@ en:
you_re_signed_in_on:
one: You're signed in on %{count} other device or browser.
other: You're signed in on %{count} other devices or browsers.
this_device: This device
install_heading: Install the app
install_why: Installed, it opens like an app, works for logging flights and squawks without signal, keeps each aircraft's overview for pre-flight, and can show notifications.
installed: 'Installed: you''re using the app.'
install: Install the app
install_ios_html: 'On iPhone or iPad: in Safari, tap <strong>Share</strong>, then <strong>Add to Home Screen</strong>.'
install_other: 'Use your browser''s menu: Install app, or Add to Home screen.'
notifications_heading: Notifications
notifications_what: A grounding squawk on your aircraft, items newly overdue on aircraft you own, and requests to sign a logbook entry.
notifications_on: Turn on
notifications_off: Turn off
notifications_test: Send a test
record_versions:
index:
record_history: "%{tail_number} Record history"
@@ -3380,7 +3395,7 @@ en:
fuel_flow: Fuel flow
oil_pressure: Oil pressure
oil_analyses:
over_the_lab_average: Over %{_}× the lab average
over_the_lab_average: Over %{ratio}× the lab average
form:
interval_unit: "%{label} unit"
services:
@@ -3586,12 +3601,12 @@ en:
the_archive_contains_a_link: The archive contains a link (%{entry}), which isn't allowed.
the_archive_contains_an_unsafe: 'The archive contains an unsafe path: %{entry}'
the_archive_is_too_large: The archive is too large once unpacked.
the_archive_is_compressed_suspiciously: The archive is compressed suspiciously well (over %{_}:1).
the_archive_is_compressed_suspiciously: The archive is compressed suspiciously well (over %{ratio}:1).
the_archive_has_no_manifest: The archive has no manifest.json. Is it a .sam.zip export?
manifest_json_is_too_large: manifest.json is too large.
manifest_json_couldn_t_be: manifest.json couldn't be read (%{truncate})
manifest_json_isn_t_a: manifest.json isn't a JSON object.
unsupported_archive_version_this_app: Unsupported archive version %{version} (this app reads versions 1–%{_}).
unsupported_archive_version_this_app: Unsupported archive version %{version} (this app reads versions 1–%{max}).
manifest_json_is_missing: manifest.json is missing %{to_sentence}.
manifest_json_must_be_a: manifest.json %{key} must be a list.
component_unknown_component_type_skipped: 'Component %{manufacturer} %{model}: unknown component type, skipped.'
@@ -3751,6 +3766,8 @@ en:
landing: Landing
outside: "%{name} CG %{cg} in at %{weight} lb is outside the envelope."
within_limits: Within the limits entered here.
over_station_gal: "%{label}: %{qty} is over its maximum of %{max} gal."
over_station_lb: "%{label}: %{qty} is over its maximum of %{max} lb."
insert_text:
confirm: Replace what's in the box with the suggested text?
entry_template:
@@ -3758,15 +3775,34 @@ en:
offline:
sign_in: Sign in to send the flights logged offline.
not_accepted: Not accepted (%{status}).
sent:
one: Sent %{count} flight logged offline.
other: Sent %{count} flights logged offline.
waiting:
one: "%{count} flight logged offline waiting for a connection."
other: "%{count} flights logged offline waiting for a connection."
discard: Discard
no_storage: No connection, and this browser can't store the flight. Write it down and log it when you're back online.
saved_on_device: 'No connection: flight saved on this device. It''s sent automatically when you''re back online. Log the next leg below, or close the app.'
flight:
queued_here:
one: "%{count} flight logged offline on this device, waiting to send. This one starts where the last ended."
other: "%{count} flights logged offline on this device, waiting to send. This one starts where the last ended."
saved_on_device: 'No connection: flight saved on this device. It''s sent automatically when you''re back online. Log the next leg below, or close the app.'
no_storage: No connection, and this browser can't store the flight. Write it down and log it when you're back online.
sent:
one: Sent %{count} flight logged offline.
other: Sent %{count} flights logged offline.
waiting:
one: "%{count} flight logged offline waiting for a connection."
other: "%{count} flights logged offline waiting for a connection."
rejected: "%{tail} flight %{date} logged offline wasn't accepted: %{error}"
squawk:
queued_here:
one: "%{count} squawk reported offline on this device, waiting to send."
other: "%{count} squawks reported offline on this device, waiting to send."
saved_on_device: 'No connection: squawk saved on this device, with its photos. It''s sent automatically when you''re back online.'
no_storage: No connection, and this browser can't store the squawk. Write it down and report it when you're back online.
sent:
one: Sent %{count} squawk reported offline.
other: Sent %{count} squawks reported offline.
waiting:
one: "%{count} squawk reported offline waiting for a connection."
other: "%{count} squawks reported offline waiting for a connection."
rejected: "%{tail} squawk reported offline wasn't accepted: %{error}"
saved_copy: Offline copy saved %{time}. It may be out of date; it updates when you're back online.
theme:
label: 'Theme: %{choice}'
system: 'Theme: System (%{theme})'
@@ -3786,6 +3822,7 @@ en:
remove_red: Remove the files marked in red first.
uploading: Uploading %{done} of %{total}…
saving: Saving…
over_limit: over the %{mb} MB limit
next_due:
permanent: 'Permanent compliance or not applicable: never due again.'
one_time: 'One-time: no recurring due date.'
@@ -3796,6 +3833,18 @@ en:
markdown:
loading: Loading preview…
load_failed: Couldn't load the preview (%{message}).
sign_out:
unsent:
one: "%{count} item saved offline hasn't been sent yet. It stays on this device and is sent the next time you sign in here. Sign out?"
other: "%{count} items saved offline haven't been sent yet. They stay on this device and are sent the next time you sign in here. Sign out?"
push:
'on': Notifications are on for this device.
'off': Notifications are off for this device.
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.
counts:
problem:
one: "%{count} problem"
@@ -3827,3 +3876,38 @@ en:
file:
one: "%{count} file"
other: "%{count} files"
offline:
show:
title: Offline · Simple Aircraft Manager
heading: You're offline
needs_connection: Simple Aircraft Manager needs a connection to load your aircraft. Check your signal and try again.
try_again: Try again
still_can: 'You can still log a flight or report a squawk; it''s sent when you''re back online:'
log_flight: 'Log a flight: %{tail}'
report_squawk: 'Report a squawk: %{tail}'
saved_pages: 'Saved for pre-flight (may be out of date):'
saved_overview: "%{tail} overview"
push:
grounding_squawk:
title: "%{tail} grounded by a squawk"
body: "%{issue}"
signing_request:
title: Please sign a logbook entry for %{tail}
body: "%{name} asked you to sign it. Tap to review and sign."
overdue:
title:
one: "%{tail}: %{count} item overdue"
other: "%{tail}: %{count} items overdue"
body: "%{items}"
test:
title: Notifications are working
body: This device will get notifications from Simple Aircraft Manager.
shortcuts:
choose:
log_flight: 'Log Flight: choose the aircraft'
report_squawk: 'Report Squawk: choose the aircraft'
no_aircraft: You don't have access to any aircraft yet.
pwa:
description: Maintenance, inspections, ADs, squawks and flight logs for your aircraft.
log_flight: Log Flight
report_squawk: Report Squawk
+3
View File
@@ -28,6 +28,9 @@ production:
document_text:
class: DocumentTextJob
schedule: every day at 2am
overdue_notifications:
class: OverdueNotificationJob
schedule: every day at 7am
records_integrity:
class: RecordsIntegrityJob
schedule: every day at 3:30am
+7
View File
@@ -21,6 +21,12 @@ Rails.application.routes.draw do
resources :passwords, param: :token, only: %i[new create edit update]
resource :setup, only: %i[new create], controller: "setup"
resource :profile, only: %i[edit update]
resource :push_subscription, path: "profile/push", only: %i[create destroy] do
post :test
end
# Home-screen shortcuts: the form for your aircraft, or a choice of aircraft.
get "go/log-flight", to: "shortcuts#log_flight", as: :log_flight_shortcut
get "go/report-squawk", to: "shortcuts#report_squawk", as: :report_squawk_shortcut
resources :certificates, path: "profile/certificates", controller: "user_certificates", only: %i[create update destroy]
resource :air_trail_connection, path: "profile/airtrail", only: %i[show create update destroy] do
post :test
@@ -173,6 +179,7 @@ Rails.application.routes.draw do
get "up" => "rails/health#show", as: :rails_health_check
get "manifest" => "rails/pwa#manifest", as: :pwa_manifest
get "offline" => "offline#show", as: :offline
get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker
root "aircraft#index"
end
@@ -0,0 +1,21 @@
class AddPushAndOfflineSquawks < ActiveRecord::Migration[8.1]
def change
# Web Push subscriptions: one per browser or installed app a user turned notifications on in.
create_table :push_subscriptions do |t|
t.references :user, null: false, foreign_key: true
t.text :endpoint, null: false
t.string :p256dh, null: false
t.string :auth, null: false
t.string :user_agent
t.timestamps
end
add_index :push_subscriptions, :endpoint, unique: true
# Squawks reported offline are sent later with a one-time key, like flights.
add_column :squawks, :client_key, :string
add_index :squawks, [ :aircraft_id, :client_key ], unique: true
# Overdue items owners were already notified about (so each is sent once).
add_column :aircraft, :notified_issue_keys, :json, null: false, default: []
end
end
Generated
+17 -1
View File
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do
ActiveRecord::Schema[8.1].define(version: 2026_11_13_010000) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
@@ -150,6 +150,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do
t.string "ad_watch_terms"
t.datetime "ad_watch_checked_at"
t.date "electronic_records_since"
t.json "notified_issue_keys", default: [], null: false
end
create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t|
@@ -695,6 +696,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do
t.index ["number"], name: "index_procedures_revisions_on_number", unique: true
end
create_table "push_subscriptions", force: :cascade do |t|
t.integer "user_id", null: false
t.text "endpoint", null: false
t.string "p256dh", null: false
t.string "auth", null: false
t.string "user_agent"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["endpoint"], name: "index_push_subscriptions_on_endpoint", unique: true
t.index ["user_id"], name: "index_push_subscriptions_on_user_id"
end
create_table "record_versions", force: :cascade do |t|
t.integer "aircraft_id"
t.string "item_type", null: false
@@ -788,6 +801,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do
t.string "deferral_action"
t.text "deferral_notes"
t.integer "logbook_entry_id"
t.string "client_key"
t.index ["aircraft_id", "client_key"], name: "index_squawks_on_aircraft_id_and_client_key", unique: true
t.index ["aircraft_id"], name: "index_squawks_on_aircraft_id"
t.index ["component_id"], name: "index_squawks_on_component_id"
t.index ["logbook_entry_id"], name: "index_squawks_on_logbook_entry_id"
@@ -907,6 +922,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do
add_foreign_key "oil_analyses", "aircraft"
add_foreign_key "oil_analyses", "components"
add_foreign_key "procedures_revisions", "users", column: "adopted_by_id", on_delete: :nullify
add_foreign_key "push_subscriptions", "users"
add_foreign_key "sessions", "users"
add_foreign_key "share_tokens", "aircraft"
add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify
+1 -1
View File
@@ -13,7 +13,7 @@ Every hour flown is added to the aircraft and to each installed component, which
### With no signal
On a phone or tablet with the app installed (see [Getting started](getting-started.md)), you can log a flight without a connection, as long as you've opened **Log Flight** for that aircraft on that device before. Without signal, the form opens from the copy the device kept, and **Log Flight** saves the flight on the device instead of sending it. The next leg starts where the last one ended. When the connection is back, the app sends the saved flights by itself and says so at the top of the page. A flight that's rejected (for example a typo in the tach) stays there with the reason, to log again by hand or discard. Sending twice never logs a flight twice.
On a phone or tablet with the app installed (see [Getting started](getting-started.md)), you can log a flight without a connection. While you're online, the app saves what it needs on the device for each of your aircraft (up to 10), so without signal you open the app, tap the aircraft and **Log Flight** as usual: the form opens from the saved copy, and **Log Flight** saves the flight on the device instead of sending it. The next leg starts where the last one ended. When the connection is back, the app sends the saved flights by itself (on Android, even if the app is closed) and says so at the top of the page. The device asks the browser to keep them safe until then. A flight that's rejected (for example a typo in the tach) stays there with the reason, to log again by hand or discard. Sending twice never logs a flight twice.
Track and engine data files attached offline are kept and sent too.
+10 -1
View File
@@ -42,6 +42,15 @@ Anyone can add an aircraft and becomes its owner. You only see aircraft you have
## On a phone
The app works on phones. The tabs collapse into a **Section** menu, and wide tables scroll sideways. You can install it like an app: in Safari use **Share → Add to Home Screen**, in Chrome **Install app**.
The app works on phones. The tabs collapse into a **Section** menu, and wide tables scroll sideways.
Install it like an app from **Profile → This device** (or in Safari: **Share → Add to Home Screen**). Installed, it:
- opens from the home screen, with **Log Flight** and **Report Squawk** shortcuts on a long press of its icon;
- logs flights and reports squawks without signal and sends them when the connection is back (see [Flights](flights.md) and [Squawks](squawks.md)); the number waiting shows on the icon;
- opens without signal: while you're online it saves the **Fleet** page and, for each of your aircraft (up to 10), the **Overview**, **W&B**, **Log Flight** and **Report Squawk** pages and its photo, refreshed at most hourly. So at the plane you can check airworthiness and loading, and log or report as usual. A copy shown offline says when it was saved;
- can show notifications (**Profile → This device**).
When a new version is installed on the server, a notice offers **Reload**. Signing out clears the forms and pages the device kept; flights or squawks not yet sent stay and are sent the next time you sign in on that device. They're only ever sent under the account that saved them.
The sun/moon button switches between light and dark themes.
+12
View File
@@ -34,6 +34,18 @@ Add each certificate you sign maintenance records with: its kind (A&P, IA, airfr
If the app offers single sign-on, **Link** your account to it here so you can sign in with it, or **Unlink** it.
## This device
**Install the app** adds Simple Aircraft Manager to the home screen (or the computer's apps), for offline flights and squawks, pre-flight pages without signal and notifications; see [On a phone](getting-started.md#on-a-phone). On iPhone and iPad, install from Safari's **Share → Add to Home Screen**.
**Notifications → Turn on** lets this device show:
- a **Ground Aircraft** squawk on an aircraft you have access to (not one you reported);
- items that newly become overdue, or newly limit the aircraft (VFR only, no transponder), on aircraft you own; checked each morning, each item once;
- a request to sign a logbook entry sent to your email address.
Turn it on on each phone or computer you want them on; **Send a test** checks it works. On iPhone and iPad, notifications work in the installed app (iOS 16.4 or later). If the browser blocked them, allow notifications for the site in its settings.
## Sessions
**Sign out everywhere else** ends your sessions on other devices, for example after using a shared computer or losing a phone.
+4
View File
@@ -6,6 +6,10 @@ A squawk is a problem found with the aircraft. Anyone on the aircraft can report
**Report Squawk** asks for the issue, a priority, optionally the component, attachments (photos, PDFs) and notes.
Without signal (in the installed app: open it, tap the aircraft and **Report Squawk** as usual), the squawk and its photos are saved on the device and sent when the connection is back, like [flights](flights.md#with-no-signal). Sending twice never reports it twice.
A **Ground Aircraft** squawk notifies the aircraft's other owners and pilots who turned on notifications.
| Priority | Meaning |
|---|---|
| **Ground Aircraft** | The aircraft isn't airworthy until it's resolved. |
+47 -20
View File
@@ -1,20 +1,47 @@
// The offline page: reload when the connection is back, and link to the Log
// Flight forms this device has kept (so a flight can be logged offline).
window.addEventListener("online", function () { location.reload() })
try {
var forms = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
var box = document.getElementById("forms")
Object.keys(forms).forEach(function (path) {
if (!/^\/aircraft\/\d+\/flight_logs\/new$/.test(path)) return
// Only offer forms the service worker actually kept; others just loop back here.
var kept = window.caches ? caches.open("sam-flight-forms").then(function (c) { return c.match(location.origin + path) }) : Promise.resolve(null)
kept.then(function (hit) {
if (!hit) return
var a = document.createElement("a")
a.href = path
a.textContent = "Log a flight: " + forms[path]
box.appendChild(a)
box.hidden = false
}).catch(function () {})
})
} catch (e) { /* storage off */ }
// The offline page: follows the chosen theme, reloads when the connection is
// back, and links to what this device kept for working without one: the Log
// Flight and Report Squawk forms, and aircraft overviews saved for pre-flight.
(function () {
try {
var choice = localStorage.getItem("theme")
if (choice === "light" || choice === "dark") document.documentElement.dataset.theme = choice
} catch (e) { /* storage off */ }
window.addEventListener("online", function () { location.reload() })
document.getElementById("retry").addEventListener("click", function () { location.reload() })
if (!window.caches) return
var forms = document.getElementById("forms")
try {
var kept = JSON.parse(localStorage.getItem("sam-offline-forms") || "{}")
Object.keys(kept).forEach(function (path) {
if (!/^\/aircraft\/\d+\/(flight_logs|squawks)\/new$/.test(path)) return
var info = typeof kept[path] === "string" ? { tail: kept[path], kind: "flight" } : kept[path]
// Only offer forms the service worker actually kept; others just loop back here.
caches.open("sam-forms").then(function (c) { return c.match(location.origin + path) }).then(function (hit) {
if (!hit) return
var a = document.createElement("a")
a.href = path
a.textContent = forms.dataset[info.kind === "squawk" ? "squawk" : "flight"].replace("%{tail}", info.tail)
forms.appendChild(a)
forms.hidden = false
}).catch(function () {})
})
} catch (e) { /* storage off */ }
var pages = document.getElementById("pages")
caches.open("sam-pages").then(function (c) { return c.keys() }).then(function (keys) {
keys.forEach(function (request) {
var path = new URL(request.url).pathname
var m = path.match(/^\/aircraft\/(\d+)$/)
if (!m) return
caches.match(request).then(function (r) { return r && r.text() }).then(function (html) {
var tail = html && (html.match(/<meta name="aircraft-tail" content="([^"]+)"/) || [])[1]
var a = document.createElement("a")
a.href = path
a.textContent = pages.dataset.label.replace("%{tail}", tail || path)
pages.appendChild(a)
pages.hidden = false
})
})
}).catch(function () {})
})()
+3 -4
View File
@@ -12,9 +12,9 @@ class OfflineFlightsTest < ActionDispatch::IntegrationTest
test "the form carries a one-time key and the offline controller; the same key is logged once" do
get new_aircraft_flight_log_path(@a)
assert_select "form[data-controller=offline-flight][data-offline-flight-tail-value=N12345]"
assert_select "form[data-controller=offline-form][data-offline-form-kind-value=flight][data-offline-form-tail-value=N12345]"
assert_select "input[type=hidden][name='flight_log[client_key]']"
assert_select "body[data-controller=offline-sync] [data-offline-sync-target=banner]"
assert_select "body[data-controller~=offline-sync] [data-offline-sync-target=banner]"
params = { flight_log: { date: "2026-11-08", tach_out: 1000, tach_in: 1001.2, departure_location: "KOQU", destination_location: "KBID", client_key: "key-1" } }
post aircraft_flight_logs_path(@a), params: params
@@ -27,8 +27,7 @@ class OfflineFlightsTest < ActionDispatch::IntegrationTest
test "the service worker keeps Log Flight forms and the offline page links them" do
get pwa_service_worker_path(format: :js)
assert_includes response.body, "FLIGHT_FORM"
assert_includes response.body, %q(const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/)
assert_includes response.body, %q(const FORMS = /^\/aircraft\/\d+\/(flight_logs|squawks)\/new$/)
assert Rails.public_path.join("offline.js").read.include?("sam-offline-forms")
end
end
+180
View File
@@ -0,0 +1,180 @@
require "test_helper"
# The installed app: the offline page, offline squawks, the per-user offline
# queue and sign-out cleanup, home-screen shortcuts, and push notifications.
class PwaFeaturesTest < ActionDispatch::IntegrationTest
include ActiveJob::TestHelper
setup do
@owner = create_user("owner@example.com")
@pilot = create_user("pilot@example.com")
@a = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345")
end
test "the offline page is public, in the app's language, and has no inline script" do
get offline_path
assert_response :success
assert_select "html[lang=en]"
assert_select "h1", "You're offline"
assert_select "script[src='/offline.js']"
assert_no_match(/onclick=/, response.body)
assert_select "#forms[data-flight='Log a flight: %{tail}'][data-squawk='Report a squawk: %{tail}']"
end
test "pages say who's signed in and when they were rendered; signing out clears the device" do
sign_in @owner
get aircraft_path(@a)
assert_select "meta[name=current-user][content='#{@owner.id}']"
assert_select "meta[name=rendered-at]"
assert_select "meta[name=aircraft-tail][content=N12345]" # the offline page lists saved overviews by tail
assert_select "body[data-controller~=page-age] [data-page-age-target=banner]"
assert_select "form[action='#{session_path}'][data-controller=sign-out]", minimum: 1
end
test "every page lists what to save ahead of time for working offline: each of your aircraft's forms and pages" do
other = create_aircraft(tail_number: "N99999") # not this pilot's
sign_in @pilot
get root_path
assert_select "body[data-controller~=offline-prep]"
saved = JSON.parse(css_select("body").first["data-offline-prep-aircraft-value"])
assert_equal [ { "tail" => "N12345", "pages" => [ aircraft_path(@a), aircraft_weight_balance_records_path(@a) ],
"flight" => new_aircraft_flight_log_path(@a), "squawk" => new_aircraft_squawk_path(@a) } ], saved
assert_not_includes saved.to_s, aircraft_path(other)
@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)
end
test "squawks can be reported offline and are received once" do
sign_in @pilot
get new_aircraft_squawk_path(@a)
assert_select "form[data-controller=offline-form][data-offline-form-kind-value=squawk][data-offline-form-tail-value=N12345]"
assert_select "input[type=hidden][name='squawk[client_key]']"
params = { squawk: { priority: 1, issue_reported: "Left landing light inop", client_key: "sq-1" } }
2.times { post aircraft_squawks_path(@a), params: params } # resent after a dropped connection
assert_equal 1, @a.squawks.where(client_key: "sq-1").count
get edit_aircraft_squawk_path(@a, @a.squawks.last) # pilots can't edit; owners' edit form isn't queued
sign_in @owner
get edit_aircraft_squawk_path(@a, @a.squawks.last)
assert_select "form[data-controller=offline-form]", count: 0
end
test "home-screen shortcuts open the form for your only aircraft, or let you choose" do
sign_in @pilot
get log_flight_shortcut_path
assert_redirected_to new_aircraft_flight_log_path(@a)
get report_squawk_shortcut_path
assert_redirected_to new_aircraft_squawk_path(@a)
other = create_aircraft(pilot: @pilot, tail_number: "N54321")
get report_squawk_shortcut_path
assert_response :success
assert_select "a[href='#{new_aircraft_squawk_path(@a)}']", /N12345/
assert_select "a[href='#{new_aircraft_squawk_path(other)}']", /N54321/
end
test "the service worker keeps pre-flight pages, sends in the background and shows notifications" do
get pwa_service_worker_path(format: :js)
body = response.body
assert_includes body, %q(const PAGES = /^\/$|^\/aircraft\/\d+(\/weight_balance)?$/) # the Fleet page too: the app opens offline
assert_includes body, 'addEventListener("sync"'
assert_includes body, 'addEventListener("push"'
assert_includes body, 'addEventListener("notificationclick"'
assert_includes body, "if (item.user && item.user !== user) continue" # only the signed-in user's items
end
test "the profile offers installing and notifications for this device" do
sign_in @owner
get edit_profile_path
assert_select "#device [data-controller=install] [data-action='install#install']"
assert_select "#device [data-controller=push][data-push-key-value='#{PushKeys.public_key}'][data-push-url-value='#{push_subscription_path}']"
end
test "devices subscribe and unsubscribe; only browser push services; signed-in users only" do
post push_subscription_path, params: { subscription: subscription_params("https://fcm.googleapis.com/fcm/send/a") }, as: :json
assert_redirected_to new_session_path
sign_in @owner
post push_subscription_path, params: { subscription: subscription_params("https://fcm.googleapis.com/fcm/send/a") }, as: :json
assert_response :created
post push_subscription_path, params: { subscription: subscription_params("https://internal.example.com/b") }, as: :json
assert_response :unprocessable_entity
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 "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")
stub_request(:post, live.endpoint).to_return(status: 201)
stub_request(:post, gone.endpoint).to_return(status: 410)
PushNotificationJob.perform_now([ @pilot.id ], "grounding_squawk", "/aircraft/#{@a.id}/squawks", "t", { "tail" => "N12345", "issue" => "Mag drop" })
assert_requested(:post, live.endpoint) { |req| req.headers["Content-Encoding"] == "aes128gcm" && req.headers["Authorization"].start_with?("vapid ") }
assert PushSubscription.exists?(live.id)
assert_not PushSubscription.exists?(gone.id)
end
test "a grounding squawk notifies the aircraft's other people; a minor one doesn't" do
subscribe(@owner, "https://fcm.googleapis.com/fcm/send/owner")
subscribe(@pilot, "https://fcm.googleapis.com/fcm/send/pilot")
sign_in @pilot
assert_enqueued_with(job: PushNotificationJob, args: ->(args) { args[0] == [ @owner.id ] && args[1] == "grounding_squawk" }) do
post aircraft_squawks_path(@a), params: { squawk: { priority: 0, issue_reported: "Mag drop over 200 rpm" } }
end
assert_no_enqueued_jobs(only: PushNotificationJob) do
post aircraft_squawks_path(@a), params: { squawk: { priority: 3, issue_reported: "Seat cushion worn" } }
end
end
test "a request to sign reaches someone who already has an account" do
mechanic = create_user("mech@example.com")
subscribe(mechanic, "https://fcm.googleapis.com/fcm/send/mech")
entry = @a.logbook_entries.create!(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC", text: "Oil changed")
sign_in @owner
assert_enqueued_with(job: PushNotificationJob, args: ->(args) { args[0] == [ mechanic.id ] && args[1] == "signing_request" }) do
post aircraft_logbook_entry_signing_invitations_path(@a, entry), params: { signing_invitation: { email: "mech@example.com" } }
end
end
test "owners hear once about each item that becomes overdue" do
subscribe(@owner, "https://fcm.googleapis.com/fcm/send/owner")
annual = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12).tap { _1.aircraft << @a }
@a.inspection_records.create!(inspection_type: annual, date: 13.months.ago.to_date)
assert_enqueued_with(job: PushNotificationJob, args: ->(args) { args[0] == [ @owner.id ] && args[1] == "overdue" && args[4][:count] == 1 }) do
OverdueNotificationJob.perform_now
end
assert_no_enqueued_jobs(only: PushNotificationJob) { OverdueNotificationJob.perform_now } # already told
@a.inspection_records.create!(inspection_type: annual, date: Date.current) # done: forgotten
OverdueNotificationJob.perform_now
assert_empty @a.reload.notified_issue_keys
end
private
def file_fixture_png = Base64.decode64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")
def subscribe(user, endpoint) = user.push_subscriptions.create!(endpoint: endpoint, **device_keys)
def subscription_params(endpoint) = { endpoint: endpoint, keys: device_keys }
# A browser's subscription keys: its P-256 public key and a 16-byte secret.
def device_keys
key = OpenSSL::PKey::EC.generate("prime256v1")
{ p256dh: Base64.urlsafe_encode64(key.public_key.to_octet_string(:uncompressed), padding: false),
auth: Base64.urlsafe_encode64(SecureRandom.random_bytes(16), padding: false) }
end
end
+10 -2
View File
@@ -9,6 +9,8 @@ class PwaTest < ActionDispatch::IntegrationTest
assert_equal "standalone", manifest["display"]
assert_includes manifest["icons"].map { _1["purpose"] }, "maskable"
manifest["icons"].each { |icon| assert Rails.public_path.join(icon["src"].delete_prefix("/")).exist?, icon["src"] }
assert_equal "en", manifest["lang"]
assert_equal %w[/go/log-flight /go/report-squawk], manifest["shortcuts"].map { _1["url"] }
end
test "service worker is public and precaches files that exist" do
@@ -16,8 +18,14 @@ class PwaTest < ActionDispatch::IntegrationTest
assert_response :success
assert_match "javascript", response.media_type
shell = response.body[/const SHELL = \[(.*?)\]/, 1].scan(/"([^"]+)"/).flatten
assert_includes shell, "/offline.html"
shell.each { |path| assert Rails.public_path.join(path.delete_prefix("/")).exist?, path }
assert_includes shell, "/offline"
shell.each do |path|
next assert(Rails.public_path.join(path.delete_prefix("/")).exist?, path) if path.include?(".")
get path
assert_response :success, path # rendered pages (the offline page) work signed out
end
get pwa_service_worker_path(format: :js)
assert_match(/const VERSION = "#{SystemInfo.new.revision}-en"/, response.body) # a new build refreshes the cached shell
end
test "signed-in and shared pages link the manifest and register the worker" do