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

+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>
+42
View File
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<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><%= 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: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; }
main { max-width: 26rem; width: 100%; background: var(--surface); border-radius: 12px; padding: 32px 24px; text-align: center;
box-shadow: 0 1px 3px rgb(0 0 0 / 0.1); }
img { width: 72px; height: 72px; }
h1 { font-size: 1.25rem; margin: 16px 0 8px; }
p { margin: 0 0 24px; color: var(--muted); }
#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><%= 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>
</body>
</html>
+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 %>