mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
Compare commits
9
Commits
v2026.11.5
...
v2026.11.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34879e7310 | ||
|
|
e8b0cd030e | ||
|
|
e4bc3a5b7b | ||
|
|
d9de1be562 | ||
|
|
66fa5f4423 | ||
|
|
2e8d789975 | ||
|
|
e4c27c6ff7 | ||
|
|
bffdea937c | ||
|
|
ec0f43019f |
No files matched your search
@@ -2,6 +2,22 @@
|
||||
|
||||
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
|
||||
|
||||
## 2026.11.6
|
||||
|
||||
### Changes
|
||||
|
||||
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
|
||||
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
|
||||
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
|
||||
- **The activity log loads as you scroll** (it stopped at 200 events).
|
||||
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
|
||||
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
|
||||
|
||||
### For administrators
|
||||
|
||||
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
|
||||
- The update adds the API's tables; they're created automatically when the new version starts.
|
||||
|
||||
## 2026.11.5
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
|
||||
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
|
||||
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
|
||||
--color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */
|
||||
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
|
||||
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
|
||||
}
|
||||
@@ -62,6 +63,7 @@
|
||||
--color-page: oklch(15.5% 0.035 264);
|
||||
--color-surface: oklch(20.8% 0.042 265.755);
|
||||
--color-header: oklch(12.9% 0.042 264.695);
|
||||
--color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */
|
||||
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
|
||||
--color-accent-hover: oklch(54% 0.15 242);
|
||||
|
||||
@@ -190,3 +192,32 @@
|
||||
@apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
|
||||
& > dt { @apply text-slate-500; }
|
||||
}
|
||||
|
||||
/* The top bar's connection status (connection_controller.js, after
|
||||
SilverBullet): red when the server can't be reached, and a ring that fills
|
||||
with the percentage in its hole while saving for offline or sending. Amber
|
||||
and full while flights or squawks wait to send, with how many. */
|
||||
header.is-offline { --color-header: var(--color-header-offline); }
|
||||
.sync-ring {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
flex: none;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 9999px;
|
||||
background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0);
|
||||
}
|
||||
.sync-ring[hidden] { display: none; }
|
||||
.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */
|
||||
.sync-ring > span {
|
||||
position: absolute;
|
||||
inset: 2.5px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 9999px;
|
||||
background-color: var(--color-header);
|
||||
font-size: 9px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
|
||||
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
|
||||
# The token and webhook secret are shown once, right after they're made.
|
||||
class Admin::IntegrationsController < ApplicationController
|
||||
before_action :require_admin!
|
||||
before_action :set_integration, only: %i[show edit update destroy new_secret]
|
||||
|
||||
def index
|
||||
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
|
||||
end
|
||||
|
||||
def new
|
||||
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
|
||||
@endpoint = WebhookEndpoint.new(events: [])
|
||||
end
|
||||
|
||||
def create
|
||||
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
|
||||
@endpoint = build_endpoint(@integration)
|
||||
ApiToken.transaction do
|
||||
@integration.save!
|
||||
@endpoint&.save!
|
||||
end
|
||||
@secret = @endpoint&.secret
|
||||
render :created
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def show
|
||||
@endpoint = @integration.webhook_endpoints.first
|
||||
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
|
||||
end
|
||||
|
||||
def edit
|
||||
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
|
||||
end
|
||||
|
||||
def update
|
||||
@endpoint = @integration.webhook_endpoints.first
|
||||
ApiToken.transaction do
|
||||
@integration.update!(integration_params)
|
||||
if webhook_params[:url].present?
|
||||
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
|
||||
@endpoint.update!(webhook_params)
|
||||
else
|
||||
@endpoint&.destroy!
|
||||
end
|
||||
end
|
||||
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
|
||||
rescue ActiveRecord::RecordInvalid
|
||||
@endpoint ||= WebhookEndpoint.new(events: [])
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# A new webhook secret, shown once.
|
||||
def new_secret
|
||||
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
|
||||
@endpoint.update!(secret: WebhookEndpoint.new_secret)
|
||||
@secret = @endpoint.secret
|
||||
render :created
|
||||
end
|
||||
|
||||
def destroy
|
||||
@integration.revoke!
|
||||
@integration.webhook_endpoints.update_all(enabled: false)
|
||||
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_integration = @integration = ApiToken.integration.find(params[:id])
|
||||
|
||||
def integration_params
|
||||
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
|
||||
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
|
||||
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
|
||||
p
|
||||
end
|
||||
|
||||
def webhook_params
|
||||
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
|
||||
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
|
||||
p[:enabled] = p[:enabled] != "0"
|
||||
p
|
||||
end
|
||||
|
||||
def build_endpoint(integration)
|
||||
return if webhook_params[:url].blank?
|
||||
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
module Api
|
||||
module V1
|
||||
# The fleet this token reaches, and each aircraft's own lists.
|
||||
class AircraftController < BaseController
|
||||
before_action -> { require_scope!(:read) }
|
||||
|
||||
def index
|
||||
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
|
||||
end
|
||||
|
||||
# The parts tree (?all=1 includes disposed parts).
|
||||
def components
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.components.includes(:component_type)
|
||||
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
|
||||
render_page(scope) { ApiPresenter.component(_1) }
|
||||
end
|
||||
|
||||
# Everything coming due, soonest first (hours projected to dates).
|
||||
def due
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
|
||||
end
|
||||
|
||||
def inspections
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
|
||||
end
|
||||
|
||||
def ads
|
||||
aircraft = find_aircraft(params[:id])
|
||||
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
|
||||
end
|
||||
|
||||
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
|
||||
def logbook_entries
|
||||
aircraft = find_aircraft(params[:id])
|
||||
scope = aircraft.logbook_entries.includes(:signature)
|
||||
scope = scope.where(log_type: params[:log]) if params[:log].present?
|
||||
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
|
||||
render_page(scope) { ApiPresenter.logbook_entry(_1) }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,123 @@
|
||||
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
|
||||
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
|
||||
# and no CSRF tokens.
|
||||
#
|
||||
# A personal token acts as its owner. An integration token acts for the
|
||||
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
|
||||
# reaches only its aircraft that person can also see.
|
||||
module Api
|
||||
module V1
|
||||
class BaseController < ActionController::API
|
||||
include RejectsNullBytes
|
||||
|
||||
MAX_PAGE = 200
|
||||
|
||||
before_action :authenticate
|
||||
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
|
||||
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
|
||||
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
|
||||
|
||||
rescue_from ActiveRecord::RecordNotFound do
|
||||
render_error(:not_found, "not_found", "Not found, or not available to this token.")
|
||||
end
|
||||
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
|
||||
render_error(:bad_request, "bad_request", e.message.truncate(200))
|
||||
end
|
||||
rescue_from ActiveRecord::RecordInvalid do |e|
|
||||
render_invalid(e.record)
|
||||
end
|
||||
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
|
||||
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
|
||||
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :api_token
|
||||
|
||||
def acting_user = Current.api_user
|
||||
|
||||
def authenticate
|
||||
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
|
||||
@api_token = ApiToken.authenticate(token)
|
||||
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
|
||||
|
||||
Current.api_token = @api_token
|
||||
Current.ip_address = request.remote_ip
|
||||
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
|
||||
@api_token.used!(request.remote_ip)
|
||||
end
|
||||
|
||||
# The person an integration is acting for, if it named one.
|
||||
def on_behalf_of
|
||||
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
|
||||
User.active.find_by(email_address: email) ||
|
||||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
|
||||
end
|
||||
|
||||
def require_scope!(scope)
|
||||
return if api_token.allows?(scope)
|
||||
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
|
||||
end
|
||||
|
||||
# Writes always name a person, so the record history shows who.
|
||||
def require_person!
|
||||
return if acting_user
|
||||
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
|
||||
end
|
||||
|
||||
def aircraft_scope = api_token.aircraft_scope(acting_user)
|
||||
|
||||
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
|
||||
|
||||
def role_on(aircraft) = acting_user&.role_for(aircraft)
|
||||
def owner_of?(aircraft) = role_on(aircraft).in?(%w[admin owner])
|
||||
|
||||
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
|
||||
def paginate(scope)
|
||||
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
|
||||
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
|
||||
if params[:updated_since].present?
|
||||
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
|
||||
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
|
||||
end
|
||||
records = scope.reorder(:id).limit(limit + 1).to_a
|
||||
more = records.size > limit
|
||||
records = records.first(limit)
|
||||
[ records, (records.last.id if more) ]
|
||||
end
|
||||
|
||||
def render_page(scope, &present)
|
||||
records, next_after = paginate(scope)
|
||||
render json: { data: records.map(&present), next_after: next_after }
|
||||
end
|
||||
|
||||
def render_error(status, code, message, fields: nil)
|
||||
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
|
||||
end
|
||||
|
||||
def render_invalid(record)
|
||||
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
|
||||
end
|
||||
|
||||
# The same Idempotency-Key again (a retry) gets the first answer; the
|
||||
# same key with a different request is a conflict.
|
||||
def idempotent
|
||||
key = request.headers["Idempotency-Key"].to_s.strip
|
||||
return yield if key.empty? || api_token.nil?
|
||||
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
|
||||
|
||||
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
|
||||
if (seen = api_token.idempotency_keys.find_by(key: key))
|
||||
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
|
||||
response.headers["Idempotent-Replay"] = "true"
|
||||
return render(json: seen.response_body, status: seen.response_status)
|
||||
end
|
||||
yield
|
||||
return if response.status >= 500
|
||||
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
|
||||
response_body: response.body, created_at: Time.current)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,129 @@
|
||||
module Api
|
||||
module V1
|
||||
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
|
||||
# work items become one unsigned entry per logbook, signed in the app; the
|
||||
# squawks they resolve and inspections they complete are held until every
|
||||
# entry is signed. Like writing entries in the app, it's for the
|
||||
# aircraft's owners.
|
||||
class DraftBatchesController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
|
||||
|
||||
def index
|
||||
scope = find_aircraft.draft_batches.includes(entries: :signature)
|
||||
scope = scope.where(status: params[:status]) if params[:status].present?
|
||||
render_page(scope) { ApiPresenter.draft_batch(_1) }
|
||||
end
|
||||
|
||||
def lookup
|
||||
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
|
||||
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.draft_batch(find_batch) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/draft_batches
|
||||
def create
|
||||
@aircraft = find_aircraft
|
||||
return render_error(:forbidden, "owners_only", "Draft entries are for the aircraft's owners (act for an owner).") unless owner_of?(@aircraft)
|
||||
|
||||
input = params.require(:draft_batch)
|
||||
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
|
||||
errors = check(input, items)
|
||||
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
|
||||
|
||||
invitations = {}
|
||||
batch = DraftBatch.transaction do
|
||||
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
|
||||
signer_email: signer_email(input), held: held(input, items))
|
||||
items.group_by { _1[:log] }.each do |log, group|
|
||||
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
|
||||
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
|
||||
inspection_result: inspection_result_for(input, items, log),
|
||||
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
|
||||
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
|
||||
end
|
||||
b
|
||||
end
|
||||
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
|
||||
end
|
||||
|
||||
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
|
||||
def destroy
|
||||
batch = find_batch
|
||||
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can withdraw a draft.") unless owner_of?(batch.aircraft)
|
||||
unless batch.awaiting? && batch.entries.none?(&:signed?)
|
||||
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
|
||||
end
|
||||
batch.withdraw!
|
||||
render json: { data: ApiPresenter.draft_batch(batch.reload) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
|
||||
|
||||
def check(input, items)
|
||||
errors = Hash.new { |h, k| h[k] = [] }
|
||||
errors[:items] << "at least one item is needed" if items.empty?
|
||||
items.each_with_index do |item, i|
|
||||
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
|
||||
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
|
||||
end
|
||||
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
|
||||
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
|
||||
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
|
||||
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
|
||||
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
|
||||
Array(input[:completes_inspections]).each_with_index do |c, i|
|
||||
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
|
||||
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
|
||||
log = inspection_log(c, items)
|
||||
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
|
||||
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
|
||||
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
|
||||
end
|
||||
end
|
||||
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
|
||||
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
|
||||
end
|
||||
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
|
||||
email = input.dig(:signer, :email).to_s.strip
|
||||
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
|
||||
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
|
||||
errors
|
||||
end
|
||||
|
||||
# The inspection goes in the logbook named for it, else the airframe
|
||||
# log if there's an item for it, else the first item's.
|
||||
def inspection_log(c, items)
|
||||
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
|
||||
end
|
||||
|
||||
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
|
||||
|
||||
# approved | discrepancies, for the entry in that log that records inspections.
|
||||
def inspection_result_for(input, items, log)
|
||||
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
|
||||
end
|
||||
|
||||
def held(input, items)
|
||||
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
|
||||
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
|
||||
end
|
||||
|
||||
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
|
||||
|
||||
# A link for the signer to sign this entry with their own account,
|
||||
# returned to the caller to pass on; emailed too when asked.
|
||||
def invite(entry, email, send: false)
|
||||
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
|
||||
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
|
||||
invitation.token
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
module Api
|
||||
module V1
|
||||
# What this token is and who it's acting as: a quick check for a new integration.
|
||||
class MeController < BaseController
|
||||
def show
|
||||
render json: { data: {
|
||||
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
|
||||
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
|
||||
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
|
||||
aircraft_ids: aircraft_scope.ids,
|
||||
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
|
||||
} }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,66 @@
|
||||
module Api
|
||||
module V1
|
||||
# Squawks: list and report on an aircraft; find by external_ref; update.
|
||||
# Resolving happens through a signed logbook entry, not here.
|
||||
class SquawksController < BaseController
|
||||
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
|
||||
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
|
||||
|
||||
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
|
||||
def index
|
||||
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
|
||||
scope = case params.fetch(:status, "open")
|
||||
when "open" then scope.active
|
||||
when "resolved" then scope.resolved
|
||||
else scope
|
||||
end
|
||||
render_page(scope) { ApiPresenter.squawk(_1) }
|
||||
end
|
||||
|
||||
# GET /squawks?external_ref=redmine:issue:4512
|
||||
def lookup
|
||||
ref = params.require(:external_ref)
|
||||
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
|
||||
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
|
||||
end
|
||||
|
||||
def show
|
||||
render json: { data: ApiPresenter.squawk(find_squawk) }
|
||||
end
|
||||
|
||||
# POST /aircraft/:aircraft_id/squawks
|
||||
def create
|
||||
aircraft = find_aircraft
|
||||
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
|
||||
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
|
||||
squawk.save!
|
||||
SquawkReported.call(squawk, by: acting_user)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
|
||||
end
|
||||
|
||||
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
|
||||
# (issue, priority, component, notes) by the aircraft's owners, as in the app.
|
||||
def update
|
||||
squawk = find_squawk
|
||||
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
|
||||
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
|
||||
if (attrs.keys - %w[external_ref]).any? && !owner_of?(squawk.aircraft)
|
||||
return render_error(:forbidden, "owners_only", "Only the aircraft's owners can change a squawk's details.")
|
||||
end
|
||||
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
|
||||
squawk.update!(attrs)
|
||||
render json: { data: ApiPresenter.squawk(squawk) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
|
||||
|
||||
def create_params
|
||||
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
|
||||
p[:priority] = p.fetch(:priority, 2).to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
|
||||
# token is shown once, on the page right after it's made (not kept in the
|
||||
# flash or anywhere else).
|
||||
class ApiTokensController < ApplicationController
|
||||
def create
|
||||
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
|
||||
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
|
||||
if @token.save
|
||||
render :created
|
||||
else
|
||||
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
current_user.api_tokens.personal.active.find(params[:id]).revoke!
|
||||
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
|
||||
end
|
||||
end
|
||||
@@ -4,8 +4,8 @@ class ApplicationController < ActionController::Base
|
||||
include TimeZones
|
||||
allow_browser versions: :modern
|
||||
|
||||
include RejectsNullBytes
|
||||
prepend_before_action :redirect_to_setup
|
||||
prepend_before_action :reject_null_bytes
|
||||
before_action { Current.ip_address = request.remote_ip } # for record history
|
||||
helper_method :current_user
|
||||
|
||||
@@ -36,20 +36,6 @@ class ApplicationController < ActionController::Base
|
||||
|
||||
private
|
||||
|
||||
# No form sends a null byte; some libraries (password hashing, file paths)
|
||||
# raise on one, so refuse the request up front.
|
||||
def reject_null_bytes
|
||||
head :bad_request if contains_null_byte?(request.params)
|
||||
end
|
||||
|
||||
def contains_null_byte?(value)
|
||||
case value
|
||||
when String then value.include?("\0")
|
||||
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
|
||||
when Array then value.any? { contains_null_byte?(_1) }
|
||||
else false
|
||||
end
|
||||
end
|
||||
|
||||
def current_user = Current.user
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# No form or API client sends a null byte; some libraries (password hashing,
|
||||
# file paths) raise on one, so such requests are refused up front.
|
||||
module RejectsNullBytes
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included { prepend_before_action :reject_null_bytes }
|
||||
|
||||
private
|
||||
|
||||
def reject_null_bytes
|
||||
head :bad_request if contains_null_byte?(request.params)
|
||||
end
|
||||
|
||||
def contains_null_byte?(value)
|
||||
case value
|
||||
when String then value.include?("\0")
|
||||
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
|
||||
when Array then value.any? { contains_null_byte?(_1) }
|
||||
else false
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,10 +1,18 @@
|
||||
class EventsController < ApplicationController
|
||||
include AircraftScoped
|
||||
|
||||
EVENTS_PER_PAGE = 50
|
||||
|
||||
# A page at a time; the rest load as you scroll (each page ends in a lazy
|
||||
# frame that fetches the next).
|
||||
def index
|
||||
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
|
||||
scope = @aircraft.events.includes(:user)
|
||||
@page = [ params[:page].to_i, 1 ].max
|
||||
scope = @aircraft.events.includes(:user).reorder(created_at: :desc, id: :desc)
|
||||
scope = scope.where(category: @category) if @category
|
||||
@events = scope.limit(200)
|
||||
rows = scope.offset((@page - 1) * EVENTS_PER_PAGE).limit(EVENTS_PER_PAGE + 1).to_a
|
||||
@more = rows.size > EVENTS_PER_PAGE
|
||||
@events = rows.first(EVENTS_PER_PAGE)
|
||||
render(partial: "events/page", locals: { events: @events, page: @page, more: @more, category: @category }) if turbo_frame_request?
|
||||
end
|
||||
end
|
||||
@@ -21,11 +21,7 @@ class SquawksController < ApplicationController
|
||||
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
|
||||
SquawkReported.call(@squawk, by: current_user)
|
||||
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
|
||||
@@ -7,4 +7,15 @@ module HelpHelper
|
||||
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
|
||||
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||
end
|
||||
|
||||
# A piece of the guide's Markdown (an intro, one release's notes).
|
||||
def guide_markdown(markdown, class: nil)
|
||||
html = HelpGuide.render(markdown, link: method(:help_page_url_for))
|
||||
tag.div(html.html_safe, class: [ "markdown guide", binding.local_variable_get(:class) ]) # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
|
||||
end
|
||||
|
||||
# "4 changes · 3 fixes · 2 for administrators"
|
||||
def release_summary(release)
|
||||
release.counts.map { |key, count| t("help.changelog.counts.#{key}", count: count) }.join(" · ")
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,118 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
|
||||
// The top bar shows the connection at a glance (as SilverBullet does):
|
||||
// - it turns red when the server can't be reached: the device is offline, or
|
||||
// a request failed (signal but no internet, or the proxy answering for the
|
||||
// app). While red it checks /up every so often and turns back on its own;
|
||||
// - a ring fills while pages are being saved for offline use or flights and
|
||||
// squawks logged offline are being sent, with the percentage in its middle;
|
||||
// - while some are waiting to send, the ring is amber with how many.
|
||||
// Others report with events on document:
|
||||
// sam:progress { source, done, total } (done >= total when finished)
|
||||
// sam:waiting { count }
|
||||
// sam:unreachable / sam:reachable
|
||||
// and it says when the server answers again with sam:back-online (what was
|
||||
// logged offline is sent then).
|
||||
// The header is replaced on every page, so the state and the listeners live
|
||||
// in this module and the header on the page just shows them.
|
||||
const RETRY_EVERY = 15 * 1000
|
||||
const UNREACHABLE = [ 502, 503, 504 ]
|
||||
const OFFLINE_COLOR = "#b91c1c" // red-700, for the phone's status bar
|
||||
const state = { online: navigator.onLine, progress: {}, waiting: 0 }
|
||||
let header = null // the controller on the page
|
||||
let checking = null
|
||||
let timer = null
|
||||
let normalColor = null
|
||||
|
||||
// Any answer from the app (even a sign-in redirect) means it's reachable.
|
||||
async function check() {
|
||||
checking ||= fetch("/up", { cache: "no-store", redirect: "manual", credentials: "same-origin" })
|
||||
.then((response) => !UNREACHABLE.includes(response.status), () => false)
|
||||
.finally(() => { checking = null })
|
||||
setOnline(await checking)
|
||||
}
|
||||
|
||||
function setOnline(online) {
|
||||
clearTimeout(timer)
|
||||
if (!online) timer = setTimeout(check, RETRY_EVERY)
|
||||
if (state.online === online) return
|
||||
state.online = online
|
||||
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
|
||||
update()
|
||||
if (online) document.dispatchEvent(new CustomEvent("sam:back-online"))
|
||||
}
|
||||
|
||||
// Several reports often arrive together (done sending, then none waiting):
|
||||
// show them once, on the next frame, so the ring doesn't flicker between.
|
||||
let frame = null
|
||||
function update() {
|
||||
frame ||= requestAnimationFrame(() => { frame = null; header?.render() })
|
||||
}
|
||||
|
||||
window.addEventListener("online", check)
|
||||
window.addEventListener("offline", () => setOnline(false))
|
||||
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && !state.online) check() })
|
||||
document.addEventListener("sam:unreachable", () => setOnline(false))
|
||||
document.addEventListener("turbo:fetch-request-error", () => setOnline(false))
|
||||
document.addEventListener("sam:reachable", () => setOnline(true))
|
||||
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
|
||||
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
|
||||
|
||||
// Whether the server answered last time (false while the top bar is red).
|
||||
export const serverReachable = () => state.online
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = [ "ring", "label", "announce" ]
|
||||
|
||||
connect() {
|
||||
header = this
|
||||
this.themeColor = document.querySelector("meta[name=theme-color]")
|
||||
normalColor ||= this.themeColor?.content
|
||||
if (!navigator.onLine) setOnline(false)
|
||||
else if (!state.online || this.fromSavedCopy()) check() // a fresh page, or maybe the offline copy
|
||||
this.render()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
if (header === this) header = null
|
||||
}
|
||||
|
||||
fromSavedCopy() {
|
||||
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
|
||||
return rendered && Date.now() - rendered > 60 * 1000
|
||||
}
|
||||
|
||||
announce(text) {
|
||||
if (this.hasAnnounceTarget) this.announceTarget.textContent = text
|
||||
}
|
||||
|
||||
render() {
|
||||
this.element.classList.toggle("is-offline", !state.online)
|
||||
this.element.title = state.online ? "" : t("connection.offline")
|
||||
if (this.themeColor && normalColor) this.themeColor.content = state.online ? normalColor : OFFLINE_COLOR
|
||||
|
||||
const busy = Object.values(state.progress).filter((p) => p.total && p.done < p.total)
|
||||
if (busy.length) {
|
||||
const done = busy.reduce((sum, p) => sum + p.done, 0)
|
||||
const total = busy.reduce((sum, p) => sum + p.total, 0)
|
||||
const percent = Math.floor((done / total) * 100)
|
||||
const what = busy.some((p) => p.source === "send") ? "sending" : "saving"
|
||||
this.showRing({ percent, number: percent, waiting: false, text: t(`connection.${what}`, { percent }) })
|
||||
} else if (state.waiting) {
|
||||
this.showRing({ percent: 100, number: state.waiting, waiting: true, text: t("connection.waiting", { count: state.waiting }) })
|
||||
} else {
|
||||
this.ringTarget.hidden = true
|
||||
}
|
||||
}
|
||||
|
||||
showRing({ percent, number, waiting, text }) {
|
||||
const ring = this.ringTarget
|
||||
ring.hidden = false
|
||||
ring.classList.toggle("is-waiting", waiting)
|
||||
ring.style.setProperty("--progress", `${percent}%`)
|
||||
ring.title = text
|
||||
ring.setAttribute("aria-label", text)
|
||||
this.labelTarget.textContent = number
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
|
||||
import { serverReachable } from "controllers/connection_controller"
|
||||
|
||||
// How long to wait for the server before keeping it here instead. Photos
|
||||
// on a squawk take longer to send.
|
||||
const WAIT = 10 * 1000
|
||||
const WAIT_WITH_FILES = 60 * 1000
|
||||
|
||||
// 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.
|
||||
// leg starts where the last saved one ended. A signal so weak the server
|
||||
// doesn't answer counts as none: it's kept here too, and if it got through
|
||||
// after all, the server drops the copy sent later (same client_key).
|
||||
export default class extends Controller {
|
||||
static targets = [ "key", "notice" ]
|
||||
static values = { kind: { type: String, default: "flight" }, tail: String }
|
||||
@@ -23,14 +31,21 @@ export default class extends Controller {
|
||||
|
||||
get flight() { return this.kindValue === "flight" }
|
||||
|
||||
// No connection: keep it here instead of submitting.
|
||||
// No connection (or the top bar is red): keep it here instead of submitting.
|
||||
async submit(event) {
|
||||
if (navigator.onLine) return
|
||||
if (navigator.onLine && serverReachable()) return
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
await this.save(formFields(this.element))
|
||||
}
|
||||
|
||||
// Give up waiting after a while; the request then fails (networkFailed).
|
||||
limit(event) {
|
||||
const options = event.detail.fetchOptions
|
||||
const files = [ ...this.element.querySelectorAll("input[type=file]") ].some((input) => input.files?.length)
|
||||
options.signal = AbortSignal.any([ options.signal, AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) ].filter(Boolean))
|
||||
}
|
||||
|
||||
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
|
||||
remember() { this.pending = formFields(this.element) }
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
|
||||
// your aircraft change. Signing out clears it.
|
||||
const EVERY = 60 * 60 * 1000
|
||||
|
||||
// How far along it is, for the ring in the top bar (connection_controller.js).
|
||||
const progress = (done, total) => document.dispatchEvent(new CustomEvent("sam:progress", { detail: { source: "prep", done, total } }))
|
||||
|
||||
export default class extends Controller {
|
||||
static values = { aircraft: Array }
|
||||
|
||||
@@ -30,13 +33,22 @@ export default class extends Controller {
|
||||
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.flatMap((a) => a.pictures || []))
|
||||
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
|
||||
const total = paths.length + 1
|
||||
try {
|
||||
for (const [ index, path ] of paths.entries()) {
|
||||
progress(index, total)
|
||||
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 (_) {
|
||||
document.dispatchEvent(new CustomEvent("sam:unreachable"))
|
||||
return
|
||||
}
|
||||
}
|
||||
progress(paths.length, total)
|
||||
await this.savePictures(pictures)
|
||||
} finally { progress(total, total) }
|
||||
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() }))
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
import { queue } from "controllers/offline_queue"
|
||||
import { serverReachable } from "controllers/connection_controller"
|
||||
|
||||
// How long to wait for the server to take one before trying again later
|
||||
// (a weak signal can leave a request hanging for minutes). Photos take longer.
|
||||
const WAIT = 15 * 1000
|
||||
const WAIT_WITH_FILES = 60 * 1000
|
||||
|
||||
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
|
||||
|
||||
// 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.
|
||||
// icon. A rejected item stays until it's discarded. Nothing is tried while
|
||||
// the top bar is red; it goes again as soon as it turns back
|
||||
// (connection_controller.js), signal or not.
|
||||
export default class extends Controller {
|
||||
static targets = [ "banner" ]
|
||||
|
||||
@@ -12,30 +22,37 @@ export default class extends Controller {
|
||||
this.sync = this.sync.bind(this)
|
||||
window.addEventListener("online", this.sync)
|
||||
document.addEventListener("offline-queue:changed", this.sync)
|
||||
document.addEventListener("sam:back-online", this.sync)
|
||||
this.sync()
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
window.removeEventListener("online", this.sync)
|
||||
document.removeEventListener("offline-queue:changed", this.sync)
|
||||
document.removeEventListener("sam:back-online", this.sync)
|
||||
}
|
||||
|
||||
async sync() {
|
||||
let items
|
||||
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)
|
||||
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
|
||||
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
|
||||
this.running = true
|
||||
const sent = []
|
||||
const sending = items.filter((i) => !i.error)
|
||||
try {
|
||||
for (const item of items.filter((i) => !i.error)) {
|
||||
for (const [ index, item ] of sending.entries()) {
|
||||
report("sam:progress", { source: "send", done: index, total: sending.length })
|
||||
const result = await this.send(item)
|
||||
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
|
||||
if (result === "sent") { await queue.remove(item.id); sent.push(item); report("sam:reachable") }
|
||||
else if (result === "signin") { this.show(t("offline.sign_in")); return }
|
||||
else if (result === "offline") break
|
||||
else if (result === "offline") { report("sam:unreachable"); break }
|
||||
else { item.error = result; await queue.put(item) }
|
||||
}
|
||||
} finally { this.running = false }
|
||||
} finally {
|
||||
this.running = false
|
||||
report("sam:progress", { source: "send", done: 0, total: 0 })
|
||||
}
|
||||
this.status(await queue.mine(), sent)
|
||||
}
|
||||
|
||||
@@ -46,7 +63,9 @@ export default class extends Controller {
|
||||
if (token) body.append("authenticity_token", token)
|
||||
let response
|
||||
try {
|
||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
|
||||
const files = item.fields.some(([ , value ]) => value instanceof Blob)
|
||||
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
|
||||
signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
|
||||
} catch (_) { return "offline" }
|
||||
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
|
||||
if (response.url.includes("/session/new")) return "signin"
|
||||
@@ -68,6 +87,7 @@ export default class extends Controller {
|
||||
}
|
||||
this.show(parts.join(" "), failed)
|
||||
this.badge(items.length)
|
||||
report("sam:waiting", { count: waiting.length })
|
||||
}
|
||||
|
||||
// The number of unsent items on the installed app's icon.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { t } from "i18n"
|
||||
|
||||
// A PDF in the document viewer. Desktop browsers show it in their own viewer,
|
||||
// in a frame. Phones don't: Android shows nothing in a frame and iPhones only
|
||||
// the first page, so there every page is drawn with PDF.js (public/pdfjs,
|
||||
// loaded only here), each one as it scrolls into view, fetching only the
|
||||
// parts of the file those pages need.
|
||||
export default class extends Controller {
|
||||
static targets = [ "frame", "status", "pages" ]
|
||||
static values = { url: String, pdfjs: String }
|
||||
|
||||
// Starts over each time, as a page restored from Turbo's cache comes back
|
||||
// with blank pages.
|
||||
connect() {
|
||||
this.pagesTarget.replaceChildren()
|
||||
this.statusTarget.replaceChildren(t("pdf.loading"))
|
||||
this.statusTarget.hidden = false
|
||||
if (navigator.pdfViewerEnabled && !matchMedia("(pointer: coarse)").matches) return this.showFrame()
|
||||
this.draw().catch((error) => this.failed(error))
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.observer?.disconnect()
|
||||
this.loading?.destroy()
|
||||
}
|
||||
|
||||
showFrame() {
|
||||
this.statusTarget.hidden = true
|
||||
this.pagesTarget.append(this.frameTarget.content.cloneNode(true))
|
||||
}
|
||||
|
||||
async draw() {
|
||||
const base = this.pdfjsValue
|
||||
const pdfjs = await import(`${base}pdf.min.mjs`)
|
||||
pdfjs.GlobalWorkerOptions.workerSrc = `${base}pdf.worker.min.mjs`
|
||||
this.loading = pdfjs.getDocument({
|
||||
url: this.urlValue,
|
||||
withCredentials: true,
|
||||
// Only the parts needed for the pages being drawn, not the whole file
|
||||
// in the background (a long manual on a phone's data plan).
|
||||
disableAutoFetch: true,
|
||||
disableStream: true,
|
||||
wasmUrl: `${base}wasm/`,
|
||||
standardFontDataUrl: `${base}standard_fonts/`,
|
||||
iccUrl: `${base}iccs/`
|
||||
})
|
||||
const pdf = await this.loading.promise
|
||||
if (!this.element.isConnected) return
|
||||
|
||||
// Placeholders the size of the first page keep the scroll position steady
|
||||
// while pages are drawn; each takes its own shape once it's drawn.
|
||||
const first = (await pdf.getPage(1)).getViewport({ scale: 1 })
|
||||
// Pages are drawn as they come near the screen and let go once they're
|
||||
// far from it, so a long manual doesn't use up a phone's memory.
|
||||
this.observer = new IntersectionObserver((entries) => {
|
||||
for (const { target, isIntersecting } of entries) {
|
||||
target.dataset.near = isIntersecting
|
||||
if (isIntersecting && !target.dataset.drawn) this.drawPage(pdf, target)
|
||||
else if (!isIntersecting && target.dataset.drawn) { delete target.dataset.drawn; target.replaceChildren() }
|
||||
}
|
||||
}, { rootMargin: "200% 0px" })
|
||||
|
||||
for (let number = 1; number <= pdf.numPages; number++) {
|
||||
const page = document.createElement("div")
|
||||
page.className = "relative w-full bg-white shadow-sm ring-1 ring-slate-200"
|
||||
page.style.aspectRatio = `${first.width} / ${first.height}`
|
||||
page.dataset.page = number
|
||||
page.setAttribute("role", "img")
|
||||
page.setAttribute("aria-label", t("pdf.page", { page: number, pages: pdf.numPages }))
|
||||
this.pagesTarget.append(page)
|
||||
this.observer.observe(page)
|
||||
}
|
||||
this.statusTarget.hidden = true
|
||||
}
|
||||
|
||||
async drawPage(pdf, holder) {
|
||||
holder.dataset.drawn = "drawing"
|
||||
try {
|
||||
const page = await pdf.getPage(Number(holder.dataset.page))
|
||||
const natural = page.getViewport({ scale: 1 })
|
||||
holder.style.aspectRatio = `${natural.width} / ${natural.height}`
|
||||
// Sharp on the screen and when pinched in a little.
|
||||
const density = Math.min((window.devicePixelRatio || 1) * 1.25, 2.5)
|
||||
const viewport = page.getViewport({ scale: (holder.clientWidth * density) / natural.width })
|
||||
const canvas = document.createElement("canvas")
|
||||
canvas.width = Math.floor(viewport.width)
|
||||
canvas.height = Math.floor(viewport.height)
|
||||
canvas.className = "block h-auto w-full"
|
||||
await page.render({ canvas, canvasContext: canvas.getContext("2d"), viewport }).promise
|
||||
page.cleanup()
|
||||
if (holder.dataset.near !== "true") { canvas.width = canvas.height = 0; delete holder.dataset.drawn; return } // scrolled away meanwhile
|
||||
holder.dataset.drawn = "drawn"
|
||||
holder.replaceChildren(canvas)
|
||||
} catch (_) {
|
||||
holder.dataset.drawn = "failed"
|
||||
holder.replaceChildren(Object.assign(document.createElement("p"), { className: "p-6 text-center text-sm text-slate-500", textContent: t("pdf.page_failed") }))
|
||||
}
|
||||
}
|
||||
|
||||
// Can't draw it here (an old browser, or not a readable PDF): the browser's own viewer is one tap away.
|
||||
failed(error) {
|
||||
if (!this.element.isConnected) return
|
||||
console.warn("PDF viewer:", error)
|
||||
this.statusTarget.hidden = false
|
||||
this.statusTarget.replaceChildren(t("pdf.failed"), " ")
|
||||
this.statusTarget.append(Object.assign(document.createElement("a"), { href: this.urlValue, target: "_blank", rel: "noopener", className: "link", textContent: t("pdf.open") }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
require "net/http"
|
||||
|
||||
# Posts one webhook delivery. The body is signed so the receiver can check
|
||||
# it came from here and wasn't replayed:
|
||||
# SAM-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the endpoint's secret>
|
||||
# Anything but a 2xx answer is retried with growing waits, then marked failed.
|
||||
class WebhookDeliveryJob < ApplicationJob
|
||||
queue_as :default
|
||||
ATTEMPTS = 8
|
||||
|
||||
class Failed < StandardError; end
|
||||
|
||||
retry_on Failed, wait: :polynomially_longer, attempts: ATTEMPTS do |job, error|
|
||||
WebhookDelivery.find_by(id: job.arguments.first)&.update!(status: "failed", last_error: error.message.truncate(250))
|
||||
end
|
||||
|
||||
def perform(delivery_id)
|
||||
delivery = WebhookDelivery.includes(:webhook_endpoint).find_by(id: delivery_id) or return
|
||||
return if delivery.status == "delivered"
|
||||
endpoint = delivery.webhook_endpoint
|
||||
delivery.increment!(:attempts)
|
||||
response = post(endpoint, delivery)
|
||||
if response.code.to_i.between?(200, 299)
|
||||
delivery.update!(status: "delivered", response_status: response.code.to_i, delivered_at: Time.current, last_error: nil)
|
||||
else
|
||||
delivery.update!(response_status: response.code.to_i, last_error: "HTTP #{response.code}")
|
||||
raise Failed, "HTTP #{response.code}"
|
||||
end
|
||||
rescue OutboundAddress::Blocked => e
|
||||
# Pointed at an address the server won't send to: retrying won't help.
|
||||
delivery.update!(status: "failed", last_error: "blocked address (#{e.reason})")
|
||||
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
|
||||
delivery.update!(last_error: "#{e.class.name.demodulize}: #{e.message}".truncate(250))
|
||||
raise Failed, e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def post(endpoint, delivery)
|
||||
uri = URI.parse(endpoint.url)
|
||||
timestamp = Time.current.to_i
|
||||
signature = OpenSSL::HMAC.hexdigest("SHA256", endpoint.secret, "#{timestamp}.#{delivery.payload}")
|
||||
req = Net::HTTP::Post.new(uri)
|
||||
req["Content-Type"] = "application/json"
|
||||
req["User-Agent"] = "SimpleAircraftManager-Webhooks"
|
||||
req["SAM-Event"] = delivery.event
|
||||
req["SAM-Delivery"] = delivery.id.to_s
|
||||
req["SAM-Signature"] = "t=#{timestamp},v1=#{signature}"
|
||||
req.body = delivery.payload
|
||||
http = Net::HTTP.new(uri.host, uri.port)
|
||||
http.ipaddr = OutboundAddress.resolve!(uri.host, allow_private: true) # set up by an admin: the private network is fine
|
||||
http.use_ssl = uri.scheme == "https"
|
||||
http.open_timeout = 5
|
||||
http.read_timeout = 10
|
||||
http.start { _1.request(req) }
|
||||
end
|
||||
end
|
||||
@@ -16,6 +16,7 @@ class Aircraft < ApplicationRecord
|
||||
has_many :components, dependent: :destroy
|
||||
has_many :squawks, dependent: :destroy
|
||||
has_many :logbook_entries, dependent: :destroy
|
||||
has_many :draft_batches, dependent: :destroy
|
||||
has_many :logbook_imports, dependent: :destroy
|
||||
has_many :document_collections, dependent: :destroy
|
||||
has_many :documents, dependent: :destroy
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# A write sent with an Idempotency-Key header, and the answer it got: the
|
||||
# same key again (a retry) gets the same answer instead of a second record.
|
||||
class ApiIdempotencyKey < ApplicationRecord
|
||||
KEEP_FOR = 24.hours
|
||||
|
||||
belongs_to :api_token
|
||||
|
||||
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
|
||||
end
|
||||
@@ -0,0 +1,80 @@
|
||||
# A key for the REST API (docs/api.md). Only its SHA-256 digest is kept; the
|
||||
# token itself is shown once, when it's made.
|
||||
#
|
||||
# personal: acts as its owner, with exactly their aircraft and role.
|
||||
# integration: made by an admin for another system (e.g. Redmine), limited to
|
||||
# chosen aircraft and scopes. Its writes name the person they're
|
||||
# for (SAM-On-Behalf-Of), so the record history always shows who.
|
||||
class ApiToken < ApplicationRecord
|
||||
KINDS = %w[personal integration].freeze
|
||||
SCOPES = LabelSet.new("api_token.scopes", %w[read squawks:write drafts:write])
|
||||
PREFIX = "sam_"
|
||||
|
||||
belongs_to :user
|
||||
has_many :webhook_endpoints, dependent: :destroy
|
||||
has_many :idempotency_keys, class_name: "ApiIdempotencyKey", dependent: :delete_all
|
||||
|
||||
attr_reader :token # the plain token, only right after create
|
||||
|
||||
normalizes :name, with: ->(n) { n.to_s.strip }
|
||||
validates :name, presence: true, length: { maximum: 80 }
|
||||
validates :kind, inclusion: { in: KINDS }
|
||||
validate :scopes_known
|
||||
validate :integration_made_by_admin, on: :create
|
||||
|
||||
before_validation :generate, on: :create
|
||||
|
||||
scope :active, -> { where(revoked_at: nil) }
|
||||
scope :personal, -> { where(kind: "personal") }
|
||||
scope :integration, -> { where(kind: "integration") }
|
||||
|
||||
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
|
||||
|
||||
# The token for this string, if it's in use (and its owner is too).
|
||||
def self.authenticate(token)
|
||||
return unless token.to_s.start_with?(PREFIX)
|
||||
found = active.includes(:user).find_by(token_digest: digest(token))
|
||||
found if found && (found.integration? || !found.user.disabled?)
|
||||
end
|
||||
|
||||
def personal? = kind == "personal"
|
||||
def integration? = kind == "integration"
|
||||
def revoked? = revoked_at.present?
|
||||
def revoke! = update!(revoked_at: Time.current)
|
||||
def allows?(scope) = scopes.include?(scope.to_s)
|
||||
|
||||
# The aircraft this token reaches, acting for `user` (who must also have
|
||||
# access, for an integration acting on someone's behalf).
|
||||
def aircraft_scope(acting_user)
|
||||
if personal?
|
||||
user.accessible_aircraft
|
||||
else
|
||||
reachable = Aircraft.where(id: Array(aircraft_ids))
|
||||
acting_user ? reachable.where(id: acting_user.accessible_aircraft.select(:id)) : reachable
|
||||
end
|
||||
end
|
||||
|
||||
# Last use, at most once a minute (no write per request).
|
||||
def used!(ip)
|
||||
return if last_used_at && last_used_at > 1.minute.ago && last_used_ip == ip
|
||||
update_columns(last_used_at: Time.current, last_used_ip: ip)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def generate
|
||||
@token = "#{PREFIX}#{SecureRandom.base58(40)}"
|
||||
self.token_digest = self.class.digest(@token)
|
||||
self.token_hint = @token.first(PREFIX.length + 6)
|
||||
self.scopes = Array(scopes).map(&:to_s).compact_blank.uniq
|
||||
end
|
||||
|
||||
def scopes_known
|
||||
errors.add(:scopes, :blank) if scopes.blank?
|
||||
errors.add(:scopes, :inclusion) if (Array(scopes) - SCOPES.keys).any?
|
||||
end
|
||||
|
||||
def integration_made_by_admin
|
||||
errors.add(:kind, :admins_only) if integration? && !user&.admin?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,57 @@
|
||||
# The release notes (CHANGELOG.md) split into releases, so the app can show
|
||||
# the running version's notes on their own and fold away older ones. The
|
||||
# file stays one plain Markdown document (it reads the same on GitHub):
|
||||
#
|
||||
# # What's new
|
||||
# intro...
|
||||
# ## 2026.11.5
|
||||
# ### Changes
|
||||
# - ...
|
||||
# ### Fixes
|
||||
# - ...
|
||||
class Changelog
|
||||
PATH = Rails.root.join("CHANGELOG.md")
|
||||
# The section headings counted in a release's one-line summary; items
|
||||
# under any other heading (the first release's highlights) count as notes.
|
||||
SECTIONS = { "Changes" => :changes, "Fixes" => :fixes, "For administrators" => :administrators }.freeze
|
||||
|
||||
Release = Data.define(:version, :markdown) do
|
||||
def year = version.split(".")[0].to_i
|
||||
def month = version.split(".")[1].to_i
|
||||
def month_start = Date.new(year, month, 1)
|
||||
def anchor = "v#{version.tr('.', '-')}"
|
||||
|
||||
# { changes: 4, fixes: 3 }: the top-level items under each heading.
|
||||
def counts
|
||||
counts = markdown.split(/^### /).drop(1).each_with_object(Hash.new(0)) do |section, tally|
|
||||
heading, body = section.split("\n", 2)
|
||||
tally[SECTIONS.fetch(heading.strip, :notes)] += body.to_s.scan(/^- /).size
|
||||
end
|
||||
(SECTIONS.values + [ :notes ]).filter_map { |key| [ key, counts[key] ] if counts[key].positive? }.to_h
|
||||
end
|
||||
end
|
||||
|
||||
def self.load = new(PATH.file? ? PATH.read : "")
|
||||
|
||||
attr_reader :title, :intro, :releases
|
||||
|
||||
def initialize(markdown)
|
||||
head, *parts = markdown.split(/^## /)
|
||||
@title = head[/\A# (.+)$/, 1] || "What's new"
|
||||
@intro = head.sub(/\A# .+\n+/, "").strip
|
||||
@releases = parts.filter_map do |part|
|
||||
version, body = part.split("\n", 2)
|
||||
version = version.strip
|
||||
Release.new(version: version, markdown: body.to_s.strip) if version.match?(/\A\d{4}\.\d{1,2}\.\d+\z/)
|
||||
end
|
||||
end
|
||||
|
||||
def release(version) = releases.find { _1.version == version }
|
||||
|
||||
# Shown open: the running version and any newer (or the newest, when the
|
||||
# running version has no notes, such as in development).
|
||||
def open?(release, running:)
|
||||
index = releases.index { _1.version == running } || 0
|
||||
releases.index(release) <= index
|
||||
end
|
||||
end
|
||||
@@ -1,4 +1,7 @@
|
||||
class Current < ActiveSupport::CurrentAttributes
|
||||
attribute :session, :ip_address
|
||||
delegate :user, to: :session, allow_nil: true
|
||||
# api_token / api_user: an API request (see Api::V1::BaseController), which
|
||||
# acts as a person without a browser session.
|
||||
attribute :session, :ip_address, :api_token, :api_user
|
||||
|
||||
def user = api_user || session&.user
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
# One visit's work sent through the API as draft logbook entries: an
|
||||
# unsigned entry for each logbook it touches, signed in the app like any
|
||||
# other entry (by an aircraft user, or a mechanic invited to sign).
|
||||
#
|
||||
# What the work resolves (squawks, inspections) is held until every entry in
|
||||
# the batch is signed: a draft never clears a squawk or completes an
|
||||
# inspection on its own.
|
||||
class DraftBatch < ApplicationRecord
|
||||
include Versioned
|
||||
|
||||
STATUSES = %w[awaiting_signature completed withdrawn].freeze
|
||||
|
||||
belongs_to :aircraft
|
||||
belongs_to :api_token, optional: true
|
||||
belongs_to :created_by, class_name: "User", optional: true
|
||||
has_many :entries, class_name: "LogbookEntry", dependent: :nullify
|
||||
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
|
||||
def awaiting? = status == "awaiting_signature"
|
||||
|
||||
def held_squawks = Array(held["squawks"])
|
||||
def held_inspections = Array(held["inspections"])
|
||||
|
||||
# What signing will do, for the signer to see before they sign.
|
||||
def held_effects_for(entry)
|
||||
squawks = aircraft.squawks.where(id: held_squawks.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||
types = aircraft.applicable_inspection_types.where(id: held_inspections.select { _1["log"] == entry.log_type }.map { _1["id"] })
|
||||
{ squawks: squawks.to_a, inspections: types.to_a }
|
||||
end
|
||||
|
||||
# Called when one of its entries is signed: once they all are, the held
|
||||
# changes are made, attributed to the person who signed last.
|
||||
def entry_signed!
|
||||
return unless awaiting?
|
||||
with_lock do
|
||||
return unless awaiting? && entries.reload.all?(&:signed?)
|
||||
by_log = entries.index_by(&:log_type)
|
||||
aircraft.squawks.active.where(id: held_squawks.map { _1["id"] }).find_each do |squawk|
|
||||
entry = by_log[held_squawks.find { _1["id"] == squawk.id }["log"]]
|
||||
squawk.resolve!(logbook_entry: entry)
|
||||
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_resolved_2"), notes: squawk.issue_reported.truncate(200))
|
||||
end
|
||||
aircraft.applicable_inspection_types.where(id: held_inspections.map { _1["id"] }).find_each do |type|
|
||||
entry = by_log[held_inspections.find { _1["id"] == type.id }["log"]]
|
||||
aircraft.inspection_records.create!(inspection_type: type, logbook_entry: entry, date: entry.date, aircraft_hours: entry.aircraft_hours_at_entry)
|
||||
aircraft.log_event!("inspection", I18n.t("flash.logbook_entries.inspection_completed_logbook_entry",
|
||||
name: type.name, date: I18n.l(entry.date, format: :app)))
|
||||
end
|
||||
update!(status: "completed", completed_at: Time.current)
|
||||
end
|
||||
Webhooks.publish("draft_batch.completed", aircraft: aircraft, data: ApiPresenter.draft_batch(self))
|
||||
end
|
||||
|
||||
# Withdraws an unsigned batch: its entries are removed (kept in the record history).
|
||||
def withdraw!
|
||||
transaction do
|
||||
raise ActiveRecord::RecordInvalid, self if entries.any?(&:signed?)
|
||||
entries.each(&:destroy!)
|
||||
update!(status: "withdrawn")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -18,6 +18,13 @@ class EntrySignature < ApplicationRecord
|
||||
validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] }
|
||||
validates :logbook_entry_id, uniqueness: true
|
||||
before_create { self.seal ||= compute_seal unless imported? }
|
||||
# Integrations hear about it (webhooks); not for signatures carried over by an import.
|
||||
after_create_commit do
|
||||
next if imported?
|
||||
entry = logbook_entry
|
||||
Webhooks.publish("entry.signed", aircraft: entry.aircraft, data: ApiPresenter.logbook_entry(entry))
|
||||
entry.draft_batch&.entry_signed! # a draft from the API: its held changes once all its entries are signed
|
||||
end
|
||||
before_update { throw :abort } # signatures are permanent (2.1.2.7)
|
||||
before_destroy { throw :abort unless destroyed_by_association }
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
class HelpGuide
|
||||
DIR = Rails.root.join("docs/guide")
|
||||
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
|
||||
inspections ads documents major-records sharing administration disclaimer changelog].freeze
|
||||
inspections ads documents major-records sharing administration api disclaimer changelog].freeze
|
||||
OPTIONS = {
|
||||
parse: { smart: true },
|
||||
render: { hardbreaks: false, unsafe: false },
|
||||
@@ -27,7 +27,11 @@ class HelpGuide
|
||||
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
|
||||
# through `link` (slug, anchor) -> URL, or become plain text when nil.
|
||||
def self.html(page, link:, title: true)
|
||||
source = title ? page.markdown : page.markdown.sub(/\A# .+\n+/, "")
|
||||
render(title ? page.markdown : page.markdown.sub(/\A# .+\n+/, ""), link: link)
|
||||
end
|
||||
|
||||
# Any Markdown from the guide (or a part of it, such as one release of the changelog).
|
||||
def self.render(source, link:)
|
||||
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
|
||||
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
|
||||
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
|
||||
|
||||
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
|
||||
belongs_to :document, optional: true
|
||||
# For engine / propeller logs: which one, and its times at this entry.
|
||||
belongs_to :component, optional: true
|
||||
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
|
||||
# Sub-components it also covers (the oil filter on the engine…).
|
||||
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
|
||||
dependent: :destroy, autosave: true
|
||||
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
|
||||
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
|
||||
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
|
||||
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
|
||||
|
||||
# Fields that may still change on a signed entry: its link to a scanned
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
# editing a version breaks the chain and the nightly check reports it.
|
||||
class RecordVersion < ApplicationRecord
|
||||
belongs_to :user, optional: true
|
||||
belongs_to :api_token, optional: true
|
||||
|
||||
scope :chronological, -> { order(:id) }
|
||||
|
||||
@@ -15,10 +16,12 @@ class RecordVersion < ApplicationRecord
|
||||
def self.append!(item:, aircraft_id:, event:, changes:)
|
||||
now = Time.current
|
||||
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
|
||||
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
|
||||
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }
|
||||
payload["api_token_id"] = Current.api_token.id if Current.api_token # made through the API (part of the hashed payload)
|
||||
payload = payload.to_json
|
||||
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
|
||||
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
|
||||
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
||||
ip_address: Current.ip_address, api_token_id: Current.api_token&.id, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
|
||||
end
|
||||
|
||||
def changes_hash = JSON.parse(payload)["changes"]
|
||||
|
||||
@@ -11,6 +11,15 @@ class Squawk < ApplicationRecord
|
||||
belongs_to :logbook_entry, optional: true
|
||||
has_many_attached :attachments
|
||||
|
||||
# Integrations hear about squawks (webhooks), once the change is saved.
|
||||
after_create_commit { Webhooks.publish("squawk.created", aircraft: aircraft, data: ApiPresenter.squawk(self)) }
|
||||
after_update_commit do
|
||||
next if (saved_changes.keys - %w[updated_at]).empty?
|
||||
event = saved_change_to_resolved? && resolved? ? "squawk.resolved" : "squawk.updated"
|
||||
Webhooks.publish(event, aircraft: aircraft, data: ApiPresenter.squawk(self))
|
||||
end
|
||||
|
||||
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
|
||||
validates :priority, inclusion: { in: PRIORITIES.keys }
|
||||
validates :issue_reported, presence: true
|
||||
validates_uploads :attachments
|
||||
|
||||
@@ -3,6 +3,7 @@ class User < ApplicationRecord
|
||||
has_many :sessions, dependent: :destroy
|
||||
has_many :aircraft_roles, dependent: :destroy
|
||||
has_many :push_subscriptions, dependent: :delete_all
|
||||
has_many :api_tokens, dependent: :destroy
|
||||
|
||||
normalizes :time_zone, with: ->(z) { z.strip.presence }
|
||||
validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# One event sent (or being sent) to a webhook endpoint; the recent ones are
|
||||
# listed for the admin, with the answer the other system gave.
|
||||
class WebhookDelivery < ApplicationRecord
|
||||
KEEP_FOR = 30.days
|
||||
|
||||
belongs_to :webhook_endpoint
|
||||
|
||||
scope :recent, -> { order(created_at: :desc) }
|
||||
|
||||
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
|
||||
end
|
||||
@@ -0,0 +1,28 @@
|
||||
# Where an integration wants to hear about changes (squawks, signed entries):
|
||||
# SAM posts JSON there, signed with the shared secret (see WebhookDeliveryJob).
|
||||
class WebhookEndpoint < ApplicationRecord
|
||||
EVENTS = LabelSet.new("webhook_endpoint.events", %w[squawk.created squawk.updated squawk.resolved entry.signed draft_batch.completed])
|
||||
|
||||
belongs_to :api_token
|
||||
has_many :deliveries, class_name: "WebhookDelivery", dependent: :delete_all
|
||||
|
||||
encrypts :secret
|
||||
|
||||
normalizes :url, with: ->(u) { u.to_s.strip }
|
||||
validates :url, presence: true, format: { with: %r{\Ahttps?://[^\s/]+(:\d+)?(/\S*)?\z}i }
|
||||
validates :secret, presence: true, length: { minimum: 16 }
|
||||
validate :events_known
|
||||
|
||||
scope :enabled, -> { where(enabled: true) }
|
||||
|
||||
def self.new_secret = SecureRandom.hex(32)
|
||||
|
||||
def subscribed?(event) = events.include?(event.to_s)
|
||||
|
||||
private
|
||||
|
||||
def events_known
|
||||
errors.add(:events, :blank) if events.blank?
|
||||
errors.add(:events, :inclusion) if (Array(events) - EVENTS.keys).any?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,80 @@
|
||||
# What the API and webhooks send for each kind of record (docs/api.md).
|
||||
# Times are ISO 8601 UTC, hours decimals, codes rather than translated labels.
|
||||
module ApiPresenter
|
||||
module_function
|
||||
|
||||
def aircraft(a)
|
||||
aw = a.airworthiness
|
||||
{ id: a.id, tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
|
||||
icao_type: a.icao_type, status: a.status,
|
||||
airworthiness: { status: aw.status, issues: aw.issues.map { { category: _1.category, severity: _1.severity, title: _1.title } } },
|
||||
time_basis: a.time_basis, hours: dec(a.current_hours), tach: dec(a.tach_time), hobbs: dec(a.hobbs_time),
|
||||
updated_at: time(a.updated_at) }
|
||||
end
|
||||
|
||||
def component(c)
|
||||
{ id: c.id, aircraft_id: c.aircraft_id, parent_id: c.parent_component_id, type: c.component_type&.name,
|
||||
manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number.presence,
|
||||
location: c.install_location.presence, status: c.status, date_in_service: c.date_in_service&.iso8601,
|
||||
hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul),
|
||||
overhaul_date: c.overhaul_date&.iso8601, overhaul_kind: c.overhaul_kind.presence,
|
||||
tbo: { hours: c.tbo_hours, days: c.tbo_days, months: c.tbo_months, on_condition: c.on_condition, critical: c.tbo_critical }.compact,
|
||||
replacement: { hours: c.replacement_hours, days: c.replacement_days, months: c.replacement_months, critical: c.replacement_critical }.compact,
|
||||
expires_on: c.expires_on&.iso8601, updated_at: time(c.updated_at) }
|
||||
end
|
||||
|
||||
def due_item(i)
|
||||
{ key: i.key, title: i.title, kind: i.kind, due_date: i.date.iso8601, projected: i.projected,
|
||||
due_hours: dec(i.due_hours), overdue: i.overdue? }
|
||||
end
|
||||
|
||||
def squawk(s)
|
||||
{ id: s.id, aircraft_id: s.aircraft_id, component_id: s.component_id, issue_reported: s.issue_reported,
|
||||
priority: s.priority, grounding: s.grounding?, deferred: s.deferred?, resolved: !!s.resolved,
|
||||
resolved_at: time(s.resolved_at), notes: s.notes.presence, logbook_entry_id: s.logbook_entry_id,
|
||||
reported_by: s.reported_by&.display_name, external_ref: s.external_ref,
|
||||
attachments: s.attachments.map { _1.filename.to_s },
|
||||
created_at: time(s.created_at), updated_at: time(s.updated_at) }
|
||||
end
|
||||
|
||||
def logbook_entry(e)
|
||||
sig = e.signature
|
||||
{ id: e.id, aircraft_id: e.aircraft_id, component_id: e.component_id, log: e.log_type, entry_type: e.entry_type,
|
||||
date: e.date.iso8601, text: e.text, aircraft_hours: dec(e.aircraft_hours_at_entry),
|
||||
inspection_result: e.inspection_result.presence, verified: e.verified, superseded: e.superseded_at.present?,
|
||||
signed: sig.present?, signature: sig && signature(sig), draft_batch_id: e.draft_batch_id, external_ref: e.external_ref,
|
||||
signoff: sig ? nil : { person: e.signoff_person.presence, certificate_type: e.signoff_certificate_type.presence,
|
||||
certificate_number: e.signoff_certificate_number.presence }.compact.presence,
|
||||
created_at: time(e.created_at), updated_at: time(e.updated_at) }
|
||||
end
|
||||
|
||||
def draft_batch(b, invitations: {})
|
||||
urls = Rails.application.routes.url_helpers
|
||||
{ id: b.id, aircraft_id: b.aircraft_id, status: b.status, external_ref: b.external_ref, signer_email: b.signer_email,
|
||||
held: { resolves_squawks: b.held_squawks.map { _1["id"] }, completes_inspections: b.held_inspections.map { _1["id"] } },
|
||||
entries: b.entries.sort_by(&:log_type).map do |e|
|
||||
logbook_entry(e).merge(sign_url: "#{Sso.app_url}#{urls.new_aircraft_logbook_entry_signature_path(b.aircraft_id, e)}",
|
||||
invitation_url: invitations[e.id] && "#{Sso.app_url}#{urls.invited_signing_path(invitations[e.id])}")
|
||||
end,
|
||||
completed_at: time(b.completed_at), created_at: time(b.created_at) }
|
||||
end
|
||||
|
||||
def signature(sig)
|
||||
{ signer_name: sig.signer_name, certificate_kind: sig.certificate_kind, certificate_number: sig.certificate_number,
|
||||
signed_at: time(sig.signed_at) }
|
||||
end
|
||||
|
||||
def inspection(row)
|
||||
{ inspection_type_id: row.type.id, name: row.type.name, status: row.status, next_due_date: row.next_due_date&.iso8601,
|
||||
next_due_hours: dec(row.next_due_hours), last_done: row.latest&.date&.iso8601 }
|
||||
end
|
||||
|
||||
def ad(row)
|
||||
{ airworthiness_directive_id: row.ad.id, name: row.ad.name, description: row.ad.short_description.presence,
|
||||
status: row.status, next_due_date: row.next_due_date&.iso8601, next_due_hours: dec(row.next_due_hours),
|
||||
last_complied: row.latest&.date_complied&.iso8601 }
|
||||
end
|
||||
|
||||
def dec(value) = value&.to_d&.round(1)&.to_f
|
||||
def time(value) = value&.utc&.iso8601
|
||||
end
|
||||
@@ -30,9 +30,6 @@ class AirTrailClient
|
||||
@allow_private = allow_private || self.class.allowed_hosts.include?(@base.host.to_s.downcase)
|
||||
end
|
||||
|
||||
# Host name → IP addresses (replaceable in tests, which have no DNS).
|
||||
class_attribute :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
|
||||
|
||||
def self.allowed_hosts = ENV.fetch("AIRTRAIL_ALLOWED_HOSTS", "").split(",").map { _1.strip.downcase }.compact_blank
|
||||
|
||||
def me = request(:get, "/api/v1/me").fetch("data")
|
||||
@@ -85,24 +82,13 @@ class AirTrailClient
|
||||
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
|
||||
end
|
||||
|
||||
# The address to connect to: the host's first, once all of its addresses are
|
||||
# ones this connection may reach.
|
||||
# The address to connect to (see OutboundAddress).
|
||||
def address(host)
|
||||
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
|
||||
raise SocketError, "no address" if ips.empty?
|
||||
ips.each do |ip|
|
||||
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
|
||||
reason = if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) } then :never
|
||||
elsif (ip.private? || CGNAT.include?(ip)) && !@allow_private then :private
|
||||
end
|
||||
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{reason}", host: host) if reason
|
||||
end
|
||||
ips.first.to_s
|
||||
OutboundAddress.resolve!(host, allow_private: @allow_private)
|
||||
rescue OutboundAddress::Blocked => e
|
||||
raise BlockedAddress, I18n.t("services.air_trail.blocked_#{e.reason}", host: host)
|
||||
end
|
||||
|
||||
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
|
||||
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
|
||||
|
||||
def handle(response)
|
||||
status = response.code.to_i
|
||||
json = begin
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Checks where the server is about to send a request (AirTrail, webhooks):
|
||||
# resolves the host and returns the address to connect to, so the name can't
|
||||
# be pointed elsewhere in between. Never the server itself, link-local
|
||||
# addresses (cloud metadata) or multicast; the private network only when
|
||||
# allowed (admins, or hosts the admin listed).
|
||||
module OutboundAddress
|
||||
class Blocked < StandardError
|
||||
attr_reader :reason # :never | :private
|
||||
|
||||
def initialize(reason, host)
|
||||
@reason = reason
|
||||
super("#{host}: #{reason}")
|
||||
end
|
||||
end
|
||||
|
||||
UNREACHABLE = [ IPAddr.new("0.0.0.0/8"), IPAddr.new("::/128"), IPAddr.new("224.0.0.0/4"), IPAddr.new("ff00::/8") ].freeze
|
||||
CGNAT = IPAddr.new("100.64.0.0/10") # shared address space, e.g. Tailscale
|
||||
|
||||
# Host name → IP addresses (replaceable in tests, which have no DNS).
|
||||
mattr_accessor :resolver, default: ->(host) { Addrinfo.getaddrinfo(host, nil, nil, :STREAM).map(&:ip_address) }
|
||||
|
||||
module_function
|
||||
|
||||
def resolve!(host, allow_private:)
|
||||
ips = resolver.call(host).map { IPAddr.new(_1.sub(/%.*/, "")) }.uniq
|
||||
raise SocketError, "no address for #{host}" if ips.empty?
|
||||
ips.each do |ip|
|
||||
ip = ip.native # ::ffff:10.0.0.1 → 10.0.0.1
|
||||
raise Blocked.new(:never, host) if ip.loopback? || ip.link_local? || UNREACHABLE.any? { _1.include?(ip) }
|
||||
raise Blocked.new(:private, host) if (ip.private? || CGNAT.include?(ip)) && !allow_private
|
||||
end
|
||||
ips.first.to_s
|
||||
end
|
||||
end
|
||||
@@ -12,9 +12,10 @@ module ProceduresTemplates
|
||||
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
|
||||
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
|
||||
t(Sso.enabled? ? :signing_sso : :signing),
|
||||
api_sentence,
|
||||
t(:updates),
|
||||
t(:secret_key)
|
||||
].join("\n\n")
|
||||
].compact.join("\n\n")
|
||||
end
|
||||
|
||||
def additional
|
||||
@@ -37,6 +38,13 @@ module ProceduresTemplates
|
||||
end
|
||||
end
|
||||
|
||||
# Only when the API is in use: who can reach the records through it, and that signing stays in the app.
|
||||
def api_sentence
|
||||
integrations = ApiToken.integration.active.order(:name).pluck(:name)
|
||||
return if integrations.empty? && !ApiToken.personal.active.exists?
|
||||
t(:api, integrations: integrations.any? ? t(:api_integrations, names: integrations.to_sentence) : t(:api_no_integrations))
|
||||
end
|
||||
|
||||
def docker? = File.exist?("/.dockerenv")
|
||||
|
||||
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# What happens when a squawk is reported, from the form or the API: the
|
||||
# aircraft's activity log, and a push notification to its other people when
|
||||
# it grounds the aircraft.
|
||||
module SquawkReported
|
||||
module_function
|
||||
|
||||
def call(squawk, by:)
|
||||
aircraft = squawk.aircraft
|
||||
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_reported_2", priority_label: squawk.priority_label),
|
||||
user: by, notes: squawk.issue_reported.truncate(200))
|
||||
return unless squawk.grounding?
|
||||
PushNotifier.notify(aircraft.users.merge(User.active).where.not(id: by&.id), :grounding_squawk,
|
||||
path: Rails.application.routes.url_helpers.aircraft_squawks_path(aircraft),
|
||||
tag: "squawk-#{squawk.id}", tail: aircraft.tail_number, issue: squawk.issue_reported.truncate(120))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
# Tells integrations about changes (docs/api.md, "Webhooks"): each enabled
|
||||
# endpoint subscribed to the event, whose token is active and reaches the
|
||||
# aircraft, gets a delivery, sent by WebhookDeliveryJob after the change is
|
||||
# saved.
|
||||
module Webhooks
|
||||
module_function
|
||||
|
||||
def publish(event, aircraft:, data:)
|
||||
endpoints = WebhookEndpoint.enabled.joins(:api_token).merge(ApiToken.active).includes(:api_token)
|
||||
.select { _1.subscribed?(event) && Array(_1.api_token.aircraft_ids).include?(aircraft.id) }
|
||||
return if endpoints.empty?
|
||||
body = { event: event, id: SecureRandom.uuid, created_at: Time.current.utc.iso8601, aircraft_id: aircraft.id, data: data }.to_json
|
||||
endpoints.each do |endpoint|
|
||||
delivery = endpoint.deliveries.create!(event: event, payload: body)
|
||||
WebhookDeliveryJob.perform_later(delivery.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -20,6 +20,17 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<% if (notes = Changelog.load.release(info.version)) %>
|
||||
<%# This version's release notes; older ones are on the What's new page. %>
|
||||
<section class="card mb-5" id="whats-new">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title"><%= t(".whats_new_in", version: info.version) %></h2>
|
||||
<%= link_to t(".all_releases"), help_page_path("changelog"), class: "link text-sm" %>
|
||||
</div>
|
||||
<%= guide_markdown(notes.markdown, class: "card-body") %>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<div class="grid gap-5 lg:grid-cols-2">
|
||||
<section class="card">
|
||||
<div class="card-header"><h2 class="card-title"><%= t(".runtime") %></h2></div>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<%= form_with model: integration, url: (integration.persisted? ? admin_integration_path(integration) : admin_integrations_path), scope: :api_token,
|
||||
class: "card card-body max-w-2xl space-y-5", data: { turbo: false } do |f| %>
|
||||
<%= f.errors_summary %>
|
||||
<% if endpoint&.errors&.any? %><div class="rounded-md bg-red-50 p-3 text-sm text-red-700"><%= endpoint.errors.full_messages.to_sentence %></div><% end %>
|
||||
<%= f.field :name, hint: t(".name_hint") %>
|
||||
<fieldset>
|
||||
<legend class="label"><%= t(".scopes") %></legend>
|
||||
<% ApiToken::SCOPES.each do |key, label| %>
|
||||
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "api_token[scopes][]", key, integration.scopes.include?(key), id: "scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend class="label"><%= t(".aircraft") %></legend>
|
||||
<p class="hint mb-1"><%= t(".aircraft_hint") %></p>
|
||||
<% Aircraft.ordered.each do |a| %>
|
||||
<label class="mr-4 inline-flex items-center gap-2 text-sm"><%= check_box_tag "api_token[aircraft_ids][]", a.id, Array(integration.aircraft_ids).include?(a.id), id: "aircraft_#{a.id}" %> <%= a.tail_number %></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<fieldset class="space-y-2 border-t border-slate-200 pt-4">
|
||||
<legend class="label"><%= t(".webhook") %></legend>
|
||||
<p class="hint"><%= t(".webhook_hint") %></p>
|
||||
<%= url_field_tag "webhook[url]", endpoint&.url, class: "input", placeholder: "https://redmine.example.com/sam/webhook", "aria-label": t(".webhook_url") %>
|
||||
<% WebhookEndpoint::EVENTS.each do |key, label| %>
|
||||
<label class="flex items-start gap-2 text-sm"><%= check_box_tag "webhook[events][]", key, Array(endpoint&.events).include?(key), id: "event_#{key.parameterize}", class: "mt-1" %> <span><%= label %> <code class="text-xs text-slate-500"><%= key %></code></span></label>
|
||||
<% end %>
|
||||
<% if endpoint&.persisted? %>
|
||||
<%= hidden_field_tag "webhook[enabled]", "0", id: nil %>
|
||||
<label class="flex items-center gap-2 text-sm"><%= check_box_tag "webhook[enabled]", "1", endpoint.enabled %> <%= t(".webhook_enabled") %></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<%= f.submit integration.persisted? ? t(".save") : t(".create"), class: "btn-primary" %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,15 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<section class="card card-body max-w-xl space-y-3">
|
||||
<h1 class="card-title"><%= @integration.name %></h1>
|
||||
<p class="text-sm text-slate-600"><%= t(".copy_now") %></p>
|
||||
<% if @integration.token %>
|
||||
<label class="label" for="integration_token"><%= t(".token") %></label>
|
||||
<input id="integration_token" class="input font-mono text-sm" value="<%= @integration.token %>" readonly>
|
||||
<% end %>
|
||||
<% if @secret %>
|
||||
<label class="label" for="webhook_secret"><%= t(".webhook_secret") %></label>
|
||||
<input id="webhook_secret" class="input font-mono text-sm" value="<%= @secret %>" readonly>
|
||||
<p class="hint"><%= t(".secret_hint") %></p>
|
||||
<% end %>
|
||||
<p><%= link_to t(".done"), admin_integration_path(@integration), class: "btn-primary" %></p>
|
||||
</section>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<h1 class="mb-4 text-2xl font-bold"><%= @integration.name %></h1>
|
||||
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||
@@ -0,0 +1,17 @@
|
||||
<% content_for :title, t(".integrations") %>
|
||||
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold"><%= t(".integrations") %></h1><%= link_to t(".new_integration"), new_admin_integration_path, class: "btn-primary" %></div>
|
||||
<p class="mb-4 max-w-3xl text-sm text-slate-600"><%= t(".what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
|
||||
<% if @integrations.any? %>
|
||||
<section class="card"><table class="table">
|
||||
<thead><tr><th><%= t(".name") %></th><th><%= t(".aircraft") %></th><th><%= t(".webhook") %></th><th><%= t(".last_used") %></th></tr></thead>
|
||||
<tbody><% @integrations.each do |i| %><tr>
|
||||
<td><%= link_to i.name, admin_integration_path(i), class: "link font-medium" %> <% if i.revoked? %><span class="badge-red"><%= t(".revoked") %></span><% end %>
|
||||
<div class="text-xs text-slate-500"><code><%= i.token_hint %>…</code></div></td>
|
||||
<td class="text-xs"><%= Aircraft.where(id: Array(i.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></td>
|
||||
<td class="text-xs"><%= (e = i.webhook_endpoints.first) ? e.url : "—" %></td>
|
||||
<td class="text-xs text-slate-500"><%= i.last_used_at ? t(".ago", ago: time_ago_in_words(i.last_used_at)) : t(".never") %></td>
|
||||
</tr><% end %></tbody>
|
||||
</table></section>
|
||||
<% else %>
|
||||
<%= empty_state t(".none_yet") %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :title, t(".new_integration") %>
|
||||
<h1 class="mb-4 text-2xl font-bold"><%= t(".new_integration") %></h1>
|
||||
<%= render "form", integration: @integration, endpoint: @endpoint %>
|
||||
@@ -0,0 +1,49 @@
|
||||
<% content_for :title, @integration.name %>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 class="text-2xl font-bold"><%= @integration.name %> <% if @integration.revoked? %><span class="badge-red align-middle text-sm"><%= t(".revoked") %></span><% end %></h1>
|
||||
<% unless @integration.revoked? %>
|
||||
<div class="flex gap-2">
|
||||
<%= link_to t(".edit"), edit_admin_integration_path(@integration), class: "btn-secondary" %>
|
||||
<%= button_to t(".revoke"), admin_integration_path(@integration), method: :delete, class: "btn-danger",
|
||||
form: { data: { turbo_confirm: t(".revoke_confirm", name: @integration.name) } } %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
<div class="grid max-w-5xl items-start gap-5 lg:grid-cols-2">
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".token") %></h2>
|
||||
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||
<div class="detail-row"><dt><%= t(".hint") %></dt><dd><code><%= @integration.token_hint %>…</code></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".scopes") %></dt><dd><%= @integration.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".aircraft") %></dt><dd><%= Aircraft.where(id: Array(@integration.aircraft_ids)).order(:tail_number).pluck(:tail_number).join(", ").presence || "—" %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".created") %></dt><dd><%= fmt_time(@integration.created_at) %> · <%= @integration.user.display_name %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".last_used") %></dt><dd><%= @integration.last_used_at ? "#{fmt_time(@integration.last_used_at)} · #{@integration.last_used_ip}" : t(".never") %></dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".webhook") %></h2>
|
||||
<% if @endpoint %>
|
||||
<dl class="mt-2 grid gap-y-2 text-sm">
|
||||
<div class="detail-row"><dt><%= t(".url") %></dt><dd class="break-all"><%= @endpoint.url %> <% unless @endpoint.enabled %><span class="badge-gray"><%= t(".paused") %></span><% end %></dd></div>
|
||||
<div class="detail-row"><dt><%= t(".events") %></dt><dd><%= @endpoint.events.map { WebhookEndpoint::EVENTS[_1] }.to_sentence %></dd></div>
|
||||
</dl>
|
||||
<% unless @integration.revoked? %>
|
||||
<div class="mt-3"><%= button_to t(".new_secret"), new_secret_admin_integration_path(@integration), class: "btn-secondary btn-sm",
|
||||
form: { data: { turbo: false, turbo_confirm: t(".new_secret_confirm") } } %></div>
|
||||
<% end %>
|
||||
<% else %>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".no_webhook") %></p>
|
||||
<% end %>
|
||||
</section>
|
||||
</div>
|
||||
<% if @deliveries.any? %>
|
||||
<section class="card mt-5 max-w-5xl">
|
||||
<div class="card-header"><h2 class="card-title"><%= t(".recent_deliveries") %></h2></div>
|
||||
<table class="table"><thead><tr><th><%= t(".when") %></th><th><%= t(".event") %></th><th><%= t(".result") %></th></tr></thead>
|
||||
<tbody><% @deliveries.each do |d| %><tr>
|
||||
<td class="text-xs"><%= fmt_time(d.created_at) %></td><td><code class="text-xs"><%= d.event %></code></td>
|
||||
<td class="text-xs"><span class="<%= { "delivered" => "badge-green", "failed" => "badge-red" }.fetch(d.status, "badge-gray") %>"><%= t(".status.#{d.status}") %></span>
|
||||
<%= d.response_status %> <%= d.last_error %> <% if d.attempts > 1 %>· <%= t(".attempts", count: d.attempts) %><% end %></td>
|
||||
</tr><% end %></tbody></table>
|
||||
</section>
|
||||
<% end %>
|
||||
@@ -0,0 +1,8 @@
|
||||
<% content_for :title, t(".title") %>
|
||||
<section class="card card-body max-w-xl space-y-3">
|
||||
<h1 class="card-title"><%= t(".title") %></h1>
|
||||
<p class="text-sm text-slate-600"><%= t(".copy_now", name: @token.name) %></p>
|
||||
<input class="input font-mono text-sm" value="<%= @token.token %>" readonly aria-label="<%= t(".token") %>">
|
||||
<p class="hint"><%= t(".how_to_use_html") %></p>
|
||||
<p><%= link_to t(".done"), edit_profile_path(anchor: "api"), class: "btn-primary" %></p>
|
||||
</section>
|
||||
@@ -13,7 +13,14 @@
|
||||
<% if current.image? %>
|
||||
<%= image_tag rails_blob_path(current, disposition: :inline), alt: current.filename.to_s, class: "max-h-[80vh] max-w-full" %>
|
||||
<% elsif current.content_type == "application/pdf" %>
|
||||
<iframe src="<%= rails_blob_path(current, disposition: :inline) %>" class="h-[80vh] w-full"></iframe>
|
||||
<% pdf_url = rails_blob_path(current, disposition: :inline) %>
|
||||
<%# Phones get the pages drawn by PDF.js; browsers with a PDF viewer of their own get it in the frame. %>
|
||||
<div class="w-full space-y-2" data-controller="pdf-viewer" data-pdf-viewer-url-value="<%= pdf_url %>" data-pdf-viewer-pdfjs-value="<%= Rails.application.config.x.pdfjs_path %>">
|
||||
<template data-pdf-viewer-target="frame"><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></template>
|
||||
<p class="p-6 text-center text-sm text-slate-500" role="status" data-pdf-viewer-target="status"><%= t("js.pdf.loading") %></p>
|
||||
<div class="space-y-2" data-pdf-viewer-target="pages"></div>
|
||||
<noscript><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></noscript>
|
||||
</div>
|
||||
<% else %>
|
||||
<p class="p-6 text-sm"><%= link_to t(".download", filename: current.filename), rails_blob_path(current, disposition: :attachment), class: "link" %></p>
|
||||
<% end %>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<div class="card-body space-y-4">
|
||||
<p class="text-sm text-slate-600"><%= t(".review_the_entry_your_signature_html", link: (link_to t(".how_signing_works"), records_help_path, class: "link", target: "_blank")) %></p>
|
||||
<%= render "logbook_entries/content", entry: entry %>
|
||||
<%= render "logbook_entries/draft_batch", entry: entry %>
|
||||
<% if @signing_error %>
|
||||
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200" role="alert"><%= @signing_error %></div>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<%# One page of the activity log, in its own frame; a lazy frame after it
|
||||
loads the next page when it scrolls into view. Links open in the whole page. %>
|
||||
<%= turbo_frame_tag "events-#{page}", target: "_top", class: ["block", ("border-t border-slate-100" if page > 1)] do %>
|
||||
<%= render "events/list", events: events, full: true %>
|
||||
<% if more %>
|
||||
<% next_page = aircraft_events_path(@aircraft, category: category, page: page + 1) %>
|
||||
<%= turbo_frame_tag "events-#{page + 1}", src: next_page, loading: :lazy, target: "_top", class: "block border-t border-slate-100" do %>
|
||||
<p class="px-4 py-4 text-center text-sm text-slate-500">
|
||||
<%= t(".loading_earlier_activity_html", link: (link_to t(".load_more"), next_page, class: "link", data: { turbo_frame: "events-#{page + 1}" })) %>
|
||||
</p>
|
||||
<% end %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -10,5 +10,5 @@
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
<%= render "events/list", events: @events, full: true %>
|
||||
<%= render "events/page", events: @events, page: @page, more: @more, category: @category %>
|
||||
</section>
|
||||
@@ -2,7 +2,7 @@
|
||||
<%= 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-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| %>
|
||||
action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit 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 %>
|
||||
@@ -40,8 +40,8 @@
|
||||
</div>
|
||||
<p class="hint"><%= t(".saving_adds_the_tach_time") %></p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<%= f.submit t(".log_flight") %>
|
||||
<%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title") %>
|
||||
<%= f.submit t(".log_flight"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= f.submit t(".log_and_next_leg"), name: "next_leg", class: "btn-secondary", title: t(".log_and_next_leg_title"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= link_to t(".cancel"), aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -0,0 +1,20 @@
|
||||
<%# The release notes (CHANGELOG.md, see Changelog): the running version and
|
||||
any newer open, older releases folded to one line each, by month. %>
|
||||
<h1 class="mb-3 text-2xl font-bold"><%= changelog.title %></h1>
|
||||
<%= guide_markdown(changelog.intro, class: "mb-2") if changelog.intro.present? %>
|
||||
<% changelog.releases.group_by(&:month_start).each do |month, releases| %>
|
||||
<h2 class="mt-6 mb-2 text-xs font-semibold uppercase tracking-wide text-slate-500"><%= l(month, format: "%B %Y") %></h2>
|
||||
<div class="divide-y divide-slate-200 rounded-md ring-1 ring-slate-200">
|
||||
<% releases.each do |release| %>
|
||||
<details id="<%= release.anchor %>" class="group release" <%= "open" if changelog.open?(release, running: running) %>>
|
||||
<summary class="flex cursor-pointer list-none flex-wrap items-baseline gap-x-3 gap-y-1 px-4 py-3 hover:bg-slate-50 [&::-webkit-details-marker]:hidden">
|
||||
<span aria-hidden="true" class="inline-block text-xs text-slate-400 transition-transform group-open:rotate-90">▶</span>
|
||||
<h3 class="font-mono text-base font-semibold"><%= release.version %></h3>
|
||||
<% if release.version == running %><span class="badge-blue"><%= t(".this_version") %></span><% end %>
|
||||
<span class="text-sm text-slate-500"><%= release_summary(release) %></span>
|
||||
</summary>
|
||||
<%= guide_markdown(release.markdown, class: "px-4 pb-4") %>
|
||||
</details>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -10,5 +10,7 @@
|
||||
aria: { current: (p == @page ? "page" : nil) } %></li><% end %>
|
||||
</ul>
|
||||
</nav>
|
||||
<article class="card card-body min-w-0 max-w-3xl"><%= guide_html(@page) %></article>
|
||||
<article class="card card-body min-w-0 max-w-3xl">
|
||||
<%= @page.slug == "changelog" ? render("help/changelog", changelog: Changelog.load, running: SystemInfo.new.version) : guide_html(@page) %>
|
||||
</article>
|
||||
</div>
|
||||
@@ -14,7 +14,8 @@
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<meta name="apple-mobile-web-app-title" content="SAM">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%= javascript_importmap_tags %>
|
||||
@@ -26,11 +27,15 @@
|
||||
<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") %>
|
||||
<%# Solid and stuck to the top: iOS 26 home-screen apps then extend its color under the status bar instead of blurring it. %>
|
||||
<header class="sticky top-0 z-40 bg-header text-white">
|
||||
<%# Red when the server can't be reached; the ring shows saving for offline and sending (connection_controller.js). %>
|
||||
<header class="sticky top-0 z-40 bg-header text-white" data-controller="connection">
|
||||
<div class="mx-auto flex max-w-7xl items-center justify-between gap-4 px-4 py-3">
|
||||
<%= link_to root_path, class: "flex items-center gap-2 font-semibold tracking-tight whitespace-nowrap" do %>
|
||||
<span class="text-xl">✈</span> <span class="hidden sm:inline"><%= t(".simple_aircraft_manager") %></span><span class="sm:hidden" aria-label="<%= t(".simple_aircraft_manager") %>"><%= t(".sam") %></span>
|
||||
<% end %>
|
||||
<div class="flex items-center gap-2 sm:gap-4">
|
||||
<span class="sync-ring" role="img" hidden data-connection-target="ring"><span data-connection-target="label"></span></span>
|
||||
<span class="sr-only" role="status" data-connection-target="announce"></span>
|
||||
<% if current_user %>
|
||||
<%# Phones: Fleet, theme and one menu for the rest. %>
|
||||
<nav class="flex items-center gap-1 text-sm sm:hidden" aria-label="<%= t(".main") %>">
|
||||
@@ -45,7 +50,7 @@
|
||||
<%= link_to t(".help"), help_path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
|
||||
<% if current_user.admin? %>
|
||||
<p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500"><%= t(".admin") %></p>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
|
||||
<% end %>
|
||||
<% end %>
|
||||
@@ -66,7 +71,7 @@
|
||||
<%= t(".admin") %> <span aria-hidden="true" class="text-xs">▾</span>
|
||||
</summary>
|
||||
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<% [ [ t(".users"), admin_users_path ], [ t(".integrations"), admin_integrations_path ], [ t(".component_types"), admin_component_types_path ], [ t(".airports"), admin_airports_path ], [ t(".logbook_templates"), admin_logbook_templates_path ], [ t(".settings"), edit_admin_settings_path ], [ t(".off_site_backup"), admin_offsite_backup_path ], [ t(".recordkeeping_procedures"), admin_procedures_path ], [ t(".records_audits"), admin_audits_path ], [ t(".about"), admin_about_path ] ].each do |label, path| %>
|
||||
<%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -78,6 +83,7 @@
|
||||
<%= 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>
|
||||
</div>
|
||||
</header>
|
||||
<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>
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
<meta name="theme-color" content="#0f172a">
|
||||
<meta name="apple-mobile-web-app-title" content="SAM">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black">
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%= javascript_importmap_tags %>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<%# Always a full page load: a Turbo visit would keep the app's dark theme
|
||||
on this white page, and leave this page's styles behind on Back. %>
|
||||
<meta name="turbo-visit-control" content="reload">
|
||||
<% unless @standalone %><link rel="icon" href="/favicon.svg" type="image/svg+xml"><% end %>
|
||||
<% unless @standalone %><link rel="icon" href="/favicon.ico" sizes="32x32"><link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml"><% end %>
|
||||
<%= stylesheet_link_tag :app, "data-turbo-track": "reload" %>
|
||||
<%# No Turbo here (Back is then an ordinary page load); just the Print button. %>
|
||||
<script nonce="<%= content_security_policy_nonce %>">
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<%# An entry sent through the API as a draft: where it came from and what
|
||||
signing will do (held until every entry of the draft is signed). Locals: entry. %>
|
||||
<% batch = entry.draft_batch %>
|
||||
<% if batch %>
|
||||
<% effects = batch.awaiting? ? batch.held_effects_for(entry) : { squawks: [], inspections: [] } %>
|
||||
<div class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200">
|
||||
<p><%= t(".from", name: batch.api_token&.name || t(".the_api"), person: batch.created_by&.display_name || "—", ref: batch.external_ref.presence || "—") %></p>
|
||||
<% if effects[:squawks].any? || effects[:inspections].any? %>
|
||||
<p class="mt-1 font-medium"><%= t(batch.entries.size > 1 ? ".when_all_signed" : ".when_signed", count: batch.entries.size) %></p>
|
||||
<ul class="mt-1 list-disc pl-5">
|
||||
<% effects[:squawks].each do |s| %><li><%= t(".resolves", issue: s.issue_reported.truncate(120)) %></li><% end %>
|
||||
<% effects[:inspections].each do |type| %><li><%= t(".completes", name: type.name) %></li><% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
@@ -19,6 +19,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body space-y-3">
|
||||
<%= render "logbook_entries/draft_batch", entry: @entry %>
|
||||
<% if @entry.signed? %><%= render "logbook_entries/signature", entry: @entry %>
|
||||
<% elsif LogbookEntry::RECORD_TYPES.include?(@entry.entry_type) %>
|
||||
<p class="rounded-md bg-slate-50 px-3 py-2 text-sm text-slate-600 ring-1 ring-slate-200"><%= t(".not_signed_electronically_sign_it_html", supersedes: (t(".pending_correction_of_the_entry", date: (fmt_date(@entry.supersedes.date))) if @entry.supersedes)) %></p>
|
||||
|
||||
@@ -5,7 +5,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">
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32">
|
||||
<link rel="icon" href="/favicon.svg?v=2" type="image/svg+xml">
|
||||
<style>
|
||||
:root { --page: #f1f5f9; --surface: #fff; --text: #1e293b; --muted: #64748b; --accent: #0369a1; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
|
||||
@@ -136,6 +136,34 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card card-body" id="api">
|
||||
<h2 class="card-title"><%= t(".api_tokens") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600"><%= t(".api_tokens_what_html", docs: link_to(t(".api_docs"), help_page_path("api"), class: "link")) %></p>
|
||||
<% tokens = @user.api_tokens.personal.active.order(:created_at) %>
|
||||
<% if tokens.any? %>
|
||||
<ul class="mt-3 divide-y divide-slate-100 rounded-md ring-1 ring-slate-200">
|
||||
<% tokens.each do |token| %>
|
||||
<li class="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-sm">
|
||||
<span><span class="font-medium"><%= token.name %></span> <code class="text-xs text-slate-500"><%= token.token_hint %>…</code>
|
||||
<span class="block text-xs text-slate-500"><%= token.scopes.map { ApiToken::SCOPES[_1] }.to_sentence %> ·
|
||||
<%= token.last_used_at ? t(".api_token_used", ago: time_ago_in_words(token.last_used_at)) : t(".api_token_unused") %></span></span>
|
||||
<%= button_to t(".revoke"), api_token_path(token), method: :delete, class: "btn-secondary btn-sm",
|
||||
form: { data: { turbo_confirm: t(".revoke_token", name: token.name) } } %>
|
||||
</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
<% end %>
|
||||
<%= form_with model: ApiToken.new, url: api_tokens_path, class: "mt-3 space-y-2", data: { turbo: false } do |f| %>
|
||||
<%= f.text_field :name, class: "input", placeholder: t(".api_token_name"), required: true, maxlength: 80, "aria-label": t(".api_token_name") %>
|
||||
<fieldset class="space-y-1 text-sm">
|
||||
<% ApiToken::SCOPES.each do |key, label| %>
|
||||
<label class="flex items-start gap-2"><%= check_box_tag "api_token[scopes][]", key, key == "read", id: "api_token_scope_#{key.parameterize}", class: "mt-1" %> <span><%= label %></span></label>
|
||||
<% end %>
|
||||
</fieldset>
|
||||
<%= f.submit t(".create_api_token"), class: "btn-secondary" %>
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card card-body">
|
||||
<h2 class="card-title"><%= t(".integrations") %></h2>
|
||||
<p class="mt-1 text-sm text-slate-600">
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
// - 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.
|
||||
// Any other page, when the server can't be reached (no signal, or one so
|
||||
// weak nothing comes back within NETWORK_TIMEOUT), gets the offline page.
|
||||
// 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}" %>"
|
||||
@@ -24,7 +26,20 @@ const SHORTCUTS = { "/go/log-flight": "flight_logs", "/go/report-squawk": "squaw
|
||||
// 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" ]
|
||||
// A weak signal can leave a request hanging for minutes: give up after this.
|
||||
const NETWORK_TIMEOUT = 10 * 1000
|
||||
// Downloads made while you wait (the .sam.zip, the records package, PDFs)
|
||||
// can take longer than that to start, so they get no time limit.
|
||||
const DOWNLOADS = /\.\w+$|^\/aircraft\/\d+\/(export|records)$/
|
||||
// After a request fails, pages go straight to the kept copy or the offline
|
||||
// page for a moment instead of trying again (Turbo follows a failed visit
|
||||
// with a full page load, which would otherwise wait all over again), then
|
||||
// for a while longer wait only briefly, so moving around offline is quick.
|
||||
const RECENTLY = 5 * 1000
|
||||
const STILL_OFFLINE = 60 * 1000
|
||||
const OFFLINE_TIMEOUT = 3 * 1000
|
||||
let failedAt = 0
|
||||
const SHELL = [ "/offline", "/offline.js", "/icon.svg", "/icon-192.png", "/favicon.svg" ]
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting()))
|
||||
@@ -53,11 +68,9 @@ self.addEventListener("fetch", (event) => {
|
||||
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 (wantsHtml) {
|
||||
// Any other page comes from the network; the offline page when it's unreachable.
|
||||
event.respondWith(page(request))
|
||||
} 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))
|
||||
@@ -74,6 +87,39 @@ self.addEventListener("fetch", (event) => {
|
||||
})
|
||||
|
||||
const offlinePage = () => caches.match("/offline")
|
||||
|
||||
// The network, within NETWORK_TIMEOUT. A proxy's "can't reach the app" counts
|
||||
// as no connection. Rejects when there isn't one (and remembers that).
|
||||
async function network(request) {
|
||||
const since = Date.now() - failedAt
|
||||
if (since < RECENTLY) throw new Error("offline")
|
||||
const wait = since < STILL_OFFLINE ? OFFLINE_TIMEOUT : NETWORK_TIMEOUT
|
||||
let timer
|
||||
try {
|
||||
const limit = DOWNLOADS.test(new URL(request.url).pathname) ? [] :
|
||||
[ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("timed out")), wait) }) ]
|
||||
const response = await Promise.race([ fetch(request), ...limit ])
|
||||
if (UNREACHABLE.includes(response.status)) throw new Error("unreachable")
|
||||
failedAt = 0
|
||||
return response
|
||||
} catch (error) {
|
||||
failedAt = Date.now()
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
// A page with no kept copy. A Turbo fetch gets the error instead, so Turbo
|
||||
// falls back to a full page load, which then gets the offline page.
|
||||
async function page(request) {
|
||||
try {
|
||||
return await network(request)
|
||||
} catch (error) {
|
||||
if (request.mode !== "navigate") throw error
|
||||
return offlinePage()
|
||||
}
|
||||
}
|
||||
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()
|
||||
@@ -114,12 +160,7 @@ 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 response = await network(request)
|
||||
const html = (response.headers.get("Content-Type") || "").includes("text/html")
|
||||
if (response.ok && !response.redirected && html) await cache.put(key, response.clone())
|
||||
return response
|
||||
@@ -136,8 +177,7 @@ async function keptPage(request, cacheName) {
|
||||
// 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
|
||||
return await network(request)
|
||||
} catch (_) { /* offline */ }
|
||||
const cache = await caches.open(FORM_CACHE)
|
||||
const forms = (await cache.keys()).filter((r) => new URL(r.url).pathname.includes(`/${kind}/new`))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<%= form_with model: [aircraft, squawk], multipart: true, class: "card card-body space-y-4 max-w-2xl",
|
||||
data: (squawk.new_record? ? { controller: "offline-form show-when", 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" } : { controller: "show-when" }) do |f| %>
|
||||
action: "submit->offline-form#submit turbo:before-fetch-request->offline-form#limit turbo:submit-start->offline-form#remember turbo:fetch-request-error->offline-form#networkFailed turbo:before-fetch-response->offline-form#gatewayFailed" } : { controller: "show-when" }) 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>
|
||||
@@ -25,7 +25,7 @@
|
||||
<% end %>
|
||||
<% if squawk.persisted? %><%= f.field :notes, as: :textarea, rows: 3 %><% end %>
|
||||
<div class="flex gap-2">
|
||||
<%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save") %>
|
||||
<%= f.submit squawk.new_record? ? t(".report_squawk") : t(".save"), data: { turbo_submits_with: t(".sending") } %>
|
||||
<%= link_to t(".cancel"), aircraft_squawks_path(aircraft), class: "btn-secondary" %>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# Uploaded files already answer Range requests (206), but don't say so. The
|
||||
# PDF viewer on phones (PDF.js) needs "Accept-Ranges: bytes" to fetch only
|
||||
# the parts of a PDF for the pages being looked at, instead of all of it.
|
||||
Rails.application.config.to_prepare do
|
||||
ActiveStorage::DiskController.after_action(only: :show) do
|
||||
response.headers["Accept-Ranges"] = "bytes" if response.successful?
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,7 @@
|
||||
# PDF.js (pdfjs-dist from npm, Apache-2.0) draws PDFs in the document viewer
|
||||
# on phones, which can't show them in a frame. Its files live in
|
||||
# public/pdfjs/<version>/ undigested, because it loads its decoders and fonts
|
||||
# by name; the version in the path keeps the year-long cache safe.
|
||||
# To update: copy build/pdf.min.mjs, build/pdf.worker.min.mjs, LICENSE, iccs/,
|
||||
# standard_fonts/ and wasm/ (minus quickjs) into a new folder and change this.
|
||||
Rails.application.config.x.pdfjs_path = "/pdfjs/6.5.438/"
|
||||
@@ -4,7 +4,34 @@
|
||||
# a controller name are its views (t(".key") in the view).
|
||||
|
||||
en:
|
||||
api:
|
||||
draft_batches:
|
||||
sent:
|
||||
one: "Draft logbook entry sent by %{name} for signing"
|
||||
other: "%{count} draft logbook entries sent by %{name} for signing"
|
||||
api_tokens:
|
||||
created:
|
||||
title: Your new API token
|
||||
copy_now: "Copy the token for %{name} now: it isn't shown again (only its first characters are kept, to tell tokens apart)."
|
||||
token: API token
|
||||
how_to_use_html: 'Send it with each request: <code>Authorization: Bearer <token></code>. See the API reference in Help.'
|
||||
done: Done
|
||||
labels:
|
||||
api_token:
|
||||
scopes:
|
||||
read: Read aircraft, parts, due items, squawks and logbook entries
|
||||
'squawks:write': Report and update squawks
|
||||
'drafts:write': Send draft logbook entries for signing (acting for an owner of the aircraft)
|
||||
webhook_endpoint:
|
||||
events:
|
||||
squawk:
|
||||
created: A squawk is reported
|
||||
updated: A squawk is changed
|
||||
resolved: A squawk is resolved
|
||||
entry:
|
||||
signed: A logbook entry is signed
|
||||
draft_batch:
|
||||
completed: All the entries of a draft are signed (and what it resolves is done)
|
||||
aircraft:
|
||||
statuses:
|
||||
AVAILABLE: Available
|
||||
@@ -286,6 +313,10 @@ en:
|
||||
signed_locked: This entry is signed, so it can't be changed. Make a correction entry instead
|
||||
squawk:
|
||||
confirm: 'Confirm: %{check}'
|
||||
api_token:
|
||||
attributes:
|
||||
kind:
|
||||
admins_only: "integration tokens can only be made by an administrator"
|
||||
ad_compliance:
|
||||
needs_owner: Must belong to an aircraft or component
|
||||
attributes:
|
||||
@@ -705,6 +736,11 @@ en:
|
||||
envelope_weights: Envelope weights must be more than 0
|
||||
fuel_weight: Fuel weight per gallon must be between 4 and 9 lb
|
||||
flash:
|
||||
admin_integrations:
|
||||
saved: Integration saved.
|
||||
revoked: "%{name} revoked: its token no longer works and its webhook is stopped."
|
||||
api_tokens:
|
||||
revoked: Token revoked. Programs using it can no longer connect.
|
||||
push_subscriptions:
|
||||
not_saved: "This browser's push service (%{host}) isn't one the app sends to."
|
||||
unknown_device: Unknown browser
|
||||
@@ -1180,6 +1216,69 @@ en:
|
||||
matches: Matches
|
||||
update: Update
|
||||
admin:
|
||||
integrations:
|
||||
show:
|
||||
revoked: Revoked
|
||||
edit: Edit
|
||||
revoke: Revoke
|
||||
revoke_confirm: "Revoke %{name}? Its token stops working at once and its webhook stops. This can't be undone; make a new integration to reconnect."
|
||||
token: Token
|
||||
hint: Starts with
|
||||
scopes: May
|
||||
aircraft: Aircraft
|
||||
created: Created
|
||||
last_used: Last used
|
||||
never: never
|
||||
webhook: Webhook
|
||||
url: Address
|
||||
paused: Paused
|
||||
events: Events
|
||||
new_secret: New secret
|
||||
new_secret_confirm: "Make a new webhook secret? The other system needs the new one; webhooks signed with the old one will fail its check."
|
||||
no_webhook: "None: the system only calls the API."
|
||||
recent_deliveries: Recent webhooks
|
||||
when: When
|
||||
event: Event
|
||||
result: Result
|
||||
attempts:
|
||||
one: "%{count} attempt"
|
||||
other: "%{count} attempts"
|
||||
status:
|
||||
pending: Pending
|
||||
delivered: Delivered
|
||||
failed: Failed
|
||||
created:
|
||||
copy_now: "Copy these now: they aren't shown again."
|
||||
token: API token
|
||||
webhook_secret: Webhook secret
|
||||
secret_hint: The other system checks each webhook with it (see the API reference).
|
||||
done: Done
|
||||
new:
|
||||
new_integration: New integration
|
||||
form:
|
||||
name_hint: The system it's for, e.g. Redmine.
|
||||
scopes: What it may do
|
||||
aircraft: Aircraft it may reach
|
||||
aircraft_hint: When it acts for a person, only those of these aircraft that person can see.
|
||||
webhook: Webhook (optional)
|
||||
webhook_hint: "Where to post changes. Each post is signed with a secret shown once after saving (header SAM-Signature)."
|
||||
webhook_url: Webhook address
|
||||
webhook_enabled: Send webhooks
|
||||
save: Save
|
||||
create: Create integration
|
||||
index:
|
||||
integrations: Integrations
|
||||
new_integration: New integration
|
||||
what_html: "Let another system, such as Redmine, work with the aircraft through the REST API (%{docs}). Each integration has its own token, limited to the aircraft and actions you choose; its changes name the person they're for, so the record history shows who. It can be told about changes by webhook."
|
||||
api_docs: API reference
|
||||
name: Name
|
||||
aircraft: Aircraft
|
||||
webhook: Webhook
|
||||
last_used: Last used
|
||||
revoked: Revoked
|
||||
ago: "%{ago} ago"
|
||||
never: never
|
||||
none_yet: No integrations yet.
|
||||
about:
|
||||
show:
|
||||
about: About
|
||||
@@ -1188,6 +1287,8 @@ en:
|
||||
this_commit_on_github: This commit on GitHub
|
||||
build_html: Build %{build}
|
||||
what_s_new: What's new
|
||||
whats_new_in: What's new in %{version}
|
||||
all_releases: All releases
|
||||
disclaimer: Disclaimer
|
||||
source_code: Source code
|
||||
built: Built
|
||||
@@ -2172,6 +2273,9 @@ en:
|
||||
ago_html: "%{who} · %{created_at} ago"
|
||||
no_activity_yet: No activity yet.
|
||||
system: System
|
||||
page:
|
||||
load_more: Load more
|
||||
loading_earlier_activity_html: Loading earlier activity… %{link}
|
||||
flight_imports:
|
||||
new:
|
||||
import_flights: Import Flights
|
||||
@@ -2299,6 +2403,7 @@ en:
|
||||
oil_qt: Oil (qt)
|
||||
no_flights_logged_yet: No flights logged yet.
|
||||
new:
|
||||
sending: Sending…
|
||||
log_flight: Log Flight
|
||||
from: From
|
||||
koqu: KOQU
|
||||
@@ -2382,6 +2487,21 @@ en:
|
||||
past_30_days: Past 30 days
|
||||
this_year: This year
|
||||
help:
|
||||
changelog:
|
||||
this_version: This version
|
||||
counts:
|
||||
changes:
|
||||
one: 1 change
|
||||
other: "%{count} changes"
|
||||
fixes:
|
||||
one: 1 fix
|
||||
other: "%{count} fixes"
|
||||
administrators:
|
||||
one: 1 for administrators
|
||||
other: "%{count} for administrators"
|
||||
notes:
|
||||
one: 1 note
|
||||
other: "%{count} notes"
|
||||
show:
|
||||
help: 'Help: %{title}'
|
||||
help_pages: Help pages
|
||||
@@ -2471,6 +2591,7 @@ en:
|
||||
sign_out: Sign out
|
||||
layouts:
|
||||
application:
|
||||
integrations: Integrations
|
||||
skip_to_content_html: <a href="#main" class="skip-link">Skip to content</a>
|
||||
simple_aircraft_manager: Simple Aircraft Manager
|
||||
sam: SAM
|
||||
@@ -2531,6 +2652,13 @@ en:
|
||||
cg_in: "= CG (in)"
|
||||
cg_in_2: CG (in)
|
||||
logbook_entries:
|
||||
draft_batch:
|
||||
from: "Draft sent through %{name} for %{person} (their reference: %{ref})."
|
||||
the_api: the API
|
||||
when_signed: "When you sign it, this also:"
|
||||
when_all_signed: "When all %{count} entries of this draft are signed, this also:"
|
||||
resolves: "Resolves the squawk: %{issue}"
|
||||
completes: "Records the %{name} as completed"
|
||||
component_fields:
|
||||
component: Component
|
||||
for_engine_and_propeller_logs: 'For engine and propeller logs: printed with its serial number and times.'
|
||||
@@ -2946,6 +3074,15 @@ en:
|
||||
subject: Reset your password
|
||||
profiles:
|
||||
edit:
|
||||
revoke: Revoke
|
||||
api_tokens: API tokens
|
||||
api_tokens_what_html: "Keys for scripts and other programs to read your aircraft and report squawks through the REST API, acting as you (%{docs}). Treat a token like a password: anyone who has it can do what it allows."
|
||||
api_docs: API reference
|
||||
api_token_used: used %{ago} ago
|
||||
api_token_unused: never used
|
||||
revoke_token: "Revoke %{name}? Programs using it stop working."
|
||||
api_token_name: Name (what it's for)
|
||||
create_api_token: Create token
|
||||
your_profile: Your Profile
|
||||
account: Account
|
||||
email: Email
|
||||
@@ -3263,6 +3400,7 @@ en:
|
||||
edit:
|
||||
edit_squawk: Edit Squawk
|
||||
form:
|
||||
sending: Sending…
|
||||
ground_aircraft_makes_the_aircraft: "“Ground Aircraft” makes the aircraft not airworthy until resolved."
|
||||
issue: Issue
|
||||
component_optional: Component (optional)
|
||||
@@ -3506,6 +3644,9 @@ en:
|
||||
aircraft_grounded_error:
|
||||
message: Aircraft is grounded and airworthiness enforcement is enabled
|
||||
procedures_templates:
|
||||
api: "**Programs that use the records (API).** %{integrations} Each has its own key, limited to chosen aircraft and actions, which the administrator can revoke at any time; the system records when each key was last used and from where, and every change made through it is in the record history with the key and the person it was for. Through the API, another program can read records, report squawks and send draft logbook entries; it cannot sign an entry, change or delete a signed one, or change users, roles or the record history. Draft entries are reviewed and signed in the system by the person certifying the work, and the squawks or inspections they resolve take effect only once signed. [Describe what each program is used for and who looks after it.]"
|
||||
api_integrations: "The following programs are connected: %{names}."
|
||||
api_no_integrations: "No other systems are connected; users may make personal keys for their own scripts, which act with their own access."
|
||||
server: "**Server.** The system runs %{location} at [location, e.g. the owner's home or a hosting provider]. Its data (the database, the uploaded files and the nightly verified database copies) is on that server's storage volume. Only [the owner] has administrative access to the server."
|
||||
server_docker: as a Docker container on a server
|
||||
server_plain: on a server
|
||||
@@ -3802,6 +3943,20 @@ en:
|
||||
not_entries: 'Not logbook entries (forms, tags…), so nothing was transcribed from: %{pages}.'
|
||||
unreadable: 'Too hard to read: %{pages}.'
|
||||
js:
|
||||
connection:
|
||||
offline: "Offline: can't reach the server. Pages saved for offline use still work."
|
||||
back_online: Back online.
|
||||
saving: "Saving for offline use: %{percent}%"
|
||||
sending: "Sending what was logged offline: %{percent}%"
|
||||
waiting:
|
||||
one: "%{count} logged offline, waiting to send"
|
||||
other: "%{count} logged offline, waiting to send"
|
||||
pdf:
|
||||
loading: Loading the PDF…
|
||||
page: Page %{page} of %{pages}
|
||||
page_failed: This page couldn't be shown.
|
||||
failed: This PDF can't be shown here.
|
||||
open: Open it
|
||||
airports:
|
||||
not_found: Not in the airport database
|
||||
wb:
|
||||
|
||||
@@ -18,6 +18,9 @@ production:
|
||||
purge_abandoned_uploads:
|
||||
command: "ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)"
|
||||
schedule: every day at 4am <%= zone %>
|
||||
purge_api_records:
|
||||
command: "ApiIdempotencyKey.purge_old; WebhookDelivery.purge_old"
|
||||
schedule: every day at 4:15am <%= zone %>
|
||||
dedupe_storage:
|
||||
command: "ActiveStorage::Blob.service.try(:sweep)"
|
||||
schedule: every day at 4:30am <%= zone %>
|
||||
|
||||
@@ -27,6 +27,7 @@ Rails.application.routes.draw do
|
||||
# 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 :api_tokens, path: "profile/api_tokens", only: %i[create destroy]
|
||||
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
|
||||
@@ -171,12 +172,37 @@ Rails.application.routes.draw do
|
||||
post "about/test_reminder", to: "about#test_reminder", as: :test_reminder
|
||||
post "about/check_records", to: "about#check_records", as: :check_records
|
||||
resources :users, except: :show
|
||||
resources :integrations do
|
||||
post :new_secret, on: :member
|
||||
end
|
||||
resources :component_types, except: :show
|
||||
resources :airports, except: :show do
|
||||
collection { post :refresh }
|
||||
end
|
||||
end
|
||||
|
||||
# REST API (docs/api.md): bearer tokens, JSON.
|
||||
namespace :api, defaults: { format: :json } do
|
||||
namespace :v1 do
|
||||
get "me", to: "me#show"
|
||||
resources :aircraft, only: %i[index show] do
|
||||
member do
|
||||
get :components
|
||||
get :due
|
||||
get :inspections
|
||||
get :ads
|
||||
get :logbook_entries
|
||||
end
|
||||
resources :squawks, only: %i[index create]
|
||||
resources :draft_batches, only: %i[index create]
|
||||
end
|
||||
get "squawks", to: "squawks#lookup"
|
||||
resources :squawks, only: %i[show update]
|
||||
get "draft_batches", to: "draft_batches#lookup"
|
||||
resources :draft_batches, only: %i[show destroy]
|
||||
end
|
||||
end
|
||||
|
||||
get "up" => "rails/health#show", as: :rails_health_check
|
||||
get "manifest" => "rails/pwa#manifest", as: :pwa_manifest
|
||||
get "offline" => "offline#show", as: :offline
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# The REST API (docs/api.md): tokens, webhooks, idempotent writes, and links
|
||||
# from SAM records to the other system's ids ("redmine:issue:4512").
|
||||
class CreateApi < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
create_table :api_tokens do |t|
|
||||
t.string :name, null: false
|
||||
t.string :kind, null: false, default: "personal" # personal | integration
|
||||
t.references :user, null: false, foreign_key: true # the owner (personal) or the admin who made it (integration)
|
||||
t.string :token_digest, null: false
|
||||
t.string :token_hint, null: false # the first characters, to tell tokens apart
|
||||
t.json :scopes, null: false, default: []
|
||||
t.json :aircraft_ids # integration: the aircraft it may reach
|
||||
t.datetime :last_used_at
|
||||
t.string :last_used_ip
|
||||
t.datetime :revoked_at
|
||||
t.timestamps
|
||||
t.index :token_digest, unique: true
|
||||
end
|
||||
|
||||
create_table :webhook_endpoints do |t|
|
||||
t.references :api_token, null: false, foreign_key: true
|
||||
t.string :url, null: false
|
||||
t.text :secret, null: false
|
||||
t.json :events, null: false, default: []
|
||||
t.boolean :enabled, null: false, default: true
|
||||
t.timestamps
|
||||
end
|
||||
|
||||
create_table :webhook_deliveries do |t|
|
||||
t.references :webhook_endpoint, null: false, foreign_key: true
|
||||
t.string :event, null: false
|
||||
t.text :payload, null: false
|
||||
t.string :status, null: false, default: "pending" # pending | delivered | failed
|
||||
t.integer :attempts, null: false, default: 0
|
||||
t.integer :response_status
|
||||
t.string :last_error
|
||||
t.datetime :delivered_at
|
||||
t.timestamps
|
||||
t.index [ :webhook_endpoint_id, :created_at ]
|
||||
end
|
||||
|
||||
create_table :api_idempotency_keys do |t|
|
||||
t.references :api_token, null: false, foreign_key: true
|
||||
t.string :key, null: false
|
||||
t.string :request_digest, null: false
|
||||
t.integer :response_status, null: false
|
||||
t.text :response_body, null: false
|
||||
t.datetime :created_at, null: false
|
||||
t.index [ :api_token_id, :key ], unique: true
|
||||
end
|
||||
|
||||
add_column :squawks, :external_ref, :string
|
||||
add_index :squawks, :external_ref
|
||||
add_column :record_versions, :api_token_id, :integer
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,21 @@
|
||||
# Draft logbook entries from the API (docs/api.md, "Draft entries"): one
|
||||
# batch per visit, one unsigned entry per logbook; what the work resolves
|
||||
# (squawks, inspections) is held until every entry is signed.
|
||||
class CreateDraftBatches < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
create_table :draft_batches do |t|
|
||||
t.references :aircraft, null: false, foreign_key: true
|
||||
t.references :api_token, foreign_key: true
|
||||
t.references :created_by, foreign_key: { to_table: :users }
|
||||
t.string :external_ref
|
||||
t.string :status, null: false, default: "awaiting_signature" # awaiting_signature | completed | withdrawn
|
||||
t.string :signer_email
|
||||
t.json :held, null: false, default: {} # { "squawks" => [{ "id", "log" }], "inspections" => [{ "id", "log" }] }
|
||||
t.datetime :completed_at
|
||||
t.timestamps
|
||||
t.index :external_ref
|
||||
end
|
||||
add_reference :logbook_entries, :draft_batch, foreign_key: true
|
||||
add_column :logbook_entries, :external_ref, :string
|
||||
end
|
||||
end
|
||||
Generated
+87
-2
@@ -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_14_010000) do
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_15_020000) do
|
||||
create_table "active_storage_attachments", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -289,6 +289,34 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.index ["component_id", "airworthiness_directive_id"], name: "idx_component_ads", unique: true
|
||||
end
|
||||
|
||||
create_table "api_idempotency_keys", force: :cascade do |t|
|
||||
t.integer "api_token_id", null: false
|
||||
t.string "key", null: false
|
||||
t.string "request_digest", null: false
|
||||
t.integer "response_status", null: false
|
||||
t.text "response_body", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.index ["api_token_id", "key"], name: "index_api_idempotency_keys_on_api_token_id_and_key", unique: true
|
||||
t.index ["api_token_id"], name: "index_api_idempotency_keys_on_api_token_id"
|
||||
end
|
||||
|
||||
create_table "api_tokens", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "kind", default: "personal", null: false
|
||||
t.integer "user_id", null: false
|
||||
t.string "token_digest", null: false
|
||||
t.string "token_hint", null: false
|
||||
t.json "scopes", default: [], null: false
|
||||
t.json "aircraft_ids"
|
||||
t.datetime "last_used_at"
|
||||
t.string "last_used_ip"
|
||||
t.datetime "revoked_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["token_digest"], name: "index_api_tokens_on_token_digest", unique: true
|
||||
t.index ["user_id"], name: "index_api_tokens_on_user_id"
|
||||
end
|
||||
|
||||
create_table "app_revisions", force: :cascade do |t|
|
||||
t.string "revision", null: false
|
||||
t.datetime "built_at"
|
||||
@@ -347,13 +375,13 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.boolean "tbo_critical", default: true, null: false
|
||||
t.boolean "on_condition", default: false, null: false
|
||||
t.boolean "replacement_critical", default: false, null: false
|
||||
t.boolean "replacement_from_install", default: false, null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.date "expires_on"
|
||||
t.string "overhaul_kind"
|
||||
t.integer "replacement_months"
|
||||
t.integer "tbo_months"
|
||||
t.boolean "replacement_from_install", default: false, null: false
|
||||
t.index ["aircraft_id"], name: "index_components_on_aircraft_id"
|
||||
t.index ["component_type_id"], name: "index_components_on_component_type_id"
|
||||
t.index ["parent_component_id"], name: "index_components_on_parent_component_id"
|
||||
@@ -413,6 +441,23 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.index ["document_collection_id"], name: "index_documents_on_document_collection_id"
|
||||
end
|
||||
|
||||
create_table "draft_batches", force: :cascade do |t|
|
||||
t.integer "aircraft_id", null: false
|
||||
t.integer "api_token_id"
|
||||
t.integer "created_by_id"
|
||||
t.string "external_ref"
|
||||
t.string "status", default: "awaiting_signature", null: false
|
||||
t.string "signer_email"
|
||||
t.json "held", default: {}, null: false
|
||||
t.datetime "completed_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["aircraft_id"], name: "index_draft_batches_on_aircraft_id"
|
||||
t.index ["api_token_id"], name: "index_draft_batches_on_api_token_id"
|
||||
t.index ["created_by_id"], name: "index_draft_batches_on_created_by_id"
|
||||
t.index ["external_ref"], name: "index_draft_batches_on_external_ref"
|
||||
end
|
||||
|
||||
create_table "drs_imports", force: :cascade do |t|
|
||||
t.integer "aircraft_id", null: false
|
||||
t.integer "user_id"
|
||||
@@ -541,9 +586,12 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.decimal "component_since_overhaul_at_entry", precision: 8, scale: 1
|
||||
t.integer "supersedes_id"
|
||||
t.datetime "superseded_at"
|
||||
t.integer "draft_batch_id"
|
||||
t.string "external_ref"
|
||||
t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id"
|
||||
t.index ["component_id"], name: "index_logbook_entries_on_component_id"
|
||||
t.index ["document_id"], name: "index_logbook_entries_on_document_id"
|
||||
t.index ["draft_batch_id"], name: "index_logbook_entries_on_draft_batch_id"
|
||||
t.index ["supersedes_id"], name: "index_logbook_entries_on_supersedes_id"
|
||||
end
|
||||
|
||||
@@ -719,6 +767,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.string "prev_hash"
|
||||
t.string "chain_hash", null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.integer "api_token_id"
|
||||
t.index ["aircraft_id"], name: "index_record_versions_on_aircraft_id"
|
||||
t.index ["item_type", "item_id"], name: "index_record_versions_on_item_type_and_item_id"
|
||||
end
|
||||
@@ -802,9 +851,11 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.text "deferral_notes"
|
||||
t.integer "logbook_entry_id"
|
||||
t.string "client_key"
|
||||
t.string "external_ref"
|
||||
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 ["external_ref"], name: "index_squawks_on_external_ref"
|
||||
t.index ["logbook_entry_id"], name: "index_squawks_on_logbook_entry_id"
|
||||
t.index ["reported_by_id"], name: "index_squawks_on_reported_by_id"
|
||||
end
|
||||
@@ -843,6 +894,32 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true
|
||||
end
|
||||
|
||||
create_table "webhook_deliveries", force: :cascade do |t|
|
||||
t.integer "webhook_endpoint_id", null: false
|
||||
t.string "event", null: false
|
||||
t.text "payload", null: false
|
||||
t.string "status", default: "pending", null: false
|
||||
t.integer "attempts", default: 0, null: false
|
||||
t.integer "response_status"
|
||||
t.string "last_error"
|
||||
t.datetime "delivered_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["webhook_endpoint_id", "created_at"], name: "index_webhook_deliveries_on_webhook_endpoint_id_and_created_at"
|
||||
t.index ["webhook_endpoint_id"], name: "index_webhook_deliveries_on_webhook_endpoint_id"
|
||||
end
|
||||
|
||||
create_table "webhook_endpoints", force: :cascade do |t|
|
||||
t.integer "api_token_id", null: false
|
||||
t.string "url", null: false
|
||||
t.text "secret", null: false
|
||||
t.json "events", default: [], null: false
|
||||
t.boolean "enabled", default: true, null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["api_token_id"], name: "index_webhook_endpoints_on_api_token_id"
|
||||
end
|
||||
|
||||
create_table "weight_balance_records", force: :cascade do |t|
|
||||
t.integer "aircraft_id", null: false
|
||||
t.date "date", null: false
|
||||
@@ -884,6 +961,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
add_foreign_key "aircraft_roles", "users"
|
||||
add_foreign_key "airport_updates", "users", column: "requested_by_id", on_delete: :nullify
|
||||
add_foreign_key "airworthiness_directives", "documents", on_delete: :nullify
|
||||
add_foreign_key "api_idempotency_keys", "api_tokens"
|
||||
add_foreign_key "api_tokens", "users"
|
||||
add_foreign_key "audit_runs", "users", column: "performed_by_id", on_delete: :nullify
|
||||
add_foreign_key "components", "aircraft"
|
||||
add_foreign_key "components", "component_types"
|
||||
@@ -893,6 +972,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
add_foreign_key "document_collections", "aircraft"
|
||||
add_foreign_key "documents", "aircraft"
|
||||
add_foreign_key "documents", "document_collections"
|
||||
add_foreign_key "draft_batches", "aircraft"
|
||||
add_foreign_key "draft_batches", "api_tokens"
|
||||
add_foreign_key "draft_batches", "users", column: "created_by_id"
|
||||
add_foreign_key "drs_imports", "aircraft", on_delete: :cascade
|
||||
add_foreign_key "drs_imports", "users", on_delete: :nullify
|
||||
add_foreign_key "entry_signatures", "logbook_entries"
|
||||
@@ -907,6 +989,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
add_foreign_key "logbook_entries", "aircraft"
|
||||
add_foreign_key "logbook_entries", "components", on_delete: :nullify
|
||||
add_foreign_key "logbook_entries", "documents", on_delete: :nullify
|
||||
add_foreign_key "logbook_entries", "draft_batches"
|
||||
add_foreign_key "logbook_entries", "logbook_entries", column: "supersedes_id", on_delete: :nullify
|
||||
add_foreign_key "logbook_entry_parts", "components", on_delete: :cascade
|
||||
add_foreign_key "logbook_entry_parts", "logbook_entries", on_delete: :cascade
|
||||
@@ -935,6 +1018,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do
|
||||
add_foreign_key "squawks", "logbook_entries", on_delete: :nullify
|
||||
add_foreign_key "squawks", "users", column: "reported_by_id", on_delete: :nullify
|
||||
add_foreign_key "user_certificates", "users"
|
||||
add_foreign_key "webhook_deliveries", "webhook_endpoints"
|
||||
add_foreign_key "webhook_endpoints", "api_tokens"
|
||||
add_foreign_key "weight_balance_records", "aircraft"
|
||||
add_foreign_key "weight_balance_records", "documents", on_delete: :nullify
|
||||
add_foreign_key "weight_balance_records", "major_records", on_delete: :nullify
|
||||
|
||||
@@ -29,6 +29,7 @@ The same pages are in the app under **Help** in the menu.
|
||||
## Administrators
|
||||
|
||||
- [Administration](administration.md): users, settings, templates, backups and off-site backup to Google Drive, recordkeeping procedures and audits
|
||||
- [REST API](api.md): tokens, endpoints and webhooks, for scripts and other systems such as Redmine
|
||||
|
||||
## Legal
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
# REST API
|
||||
|
||||
Other programs can work with the aircraft through the API: a script that pulls what's coming due, or another system such as Redmine that tracks work orders. The API reads the same records you see in the app and goes through the same rules. Anything it changes is in the record history, with the person it was for.
|
||||
|
||||
The API never signs a logbook entry, never changes or deletes a signed one, and never changes users, roles or the record history. Signing always happens in the app, by the person certifying the work ([Electronic records and signing](records.md)).
|
||||
|
||||
## Tokens
|
||||
|
||||
Each request carries a token:
|
||||
|
||||
```
|
||||
Authorization: Bearer sam_…
|
||||
```
|
||||
|
||||
There are two kinds:
|
||||
|
||||
| Kind | Made in | Acts as | Reaches |
|
||||
|---|---|---|---|
|
||||
| **Personal** | Profile → API tokens | you | your aircraft, with your role |
|
||||
| **Integration** | Admin → Integrations (administrators) | the person named in `SAM-On-Behalf-Of` | the aircraft chosen for it, and only those that person can also see |
|
||||
|
||||
A token is shown once, when it's made; only its first characters are kept, to tell tokens apart. Revoke a token you no longer need, or one that may have been seen by someone else. Profile and Admin → Integrations show when each token was last used, and from where.
|
||||
|
||||
An integration acting for someone names them by email in each request:
|
||||
|
||||
```
|
||||
SAM-On-Behalf-Of: mechanic@example.com
|
||||
```
|
||||
|
||||
Reading works without it (limited to the integration's aircraft). Every write needs it, so each change names a person.
|
||||
|
||||
### Scopes
|
||||
|
||||
| Scope | Allows |
|
||||
|---|---|
|
||||
| `read` | Aircraft, parts, due items, inspections, ADs, squawks and logbook entries |
|
||||
| `squawks:write` | Reporting squawks and updating them |
|
||||
| `drafts:write` | Sending draft logbook entries for signing, and withdrawing them (acting for an owner of the aircraft) |
|
||||
|
||||
## Requests and answers
|
||||
|
||||
- Base address: `https://<your server>/api/v1`
|
||||
- JSON in and out. Times are ISO 8601 in UTC, hours are decimals, and values are codes (`ENG`, `IN-USE`) rather than translated labels.
|
||||
- Lists answer `{ "data": [ … ], "next_after": 123 }`. Ask for more with `?after=123`; `?limit=` sets the page size (up to 200, default 50); `?updated_since=2026-11-01T00:00:00Z` lists only what changed since then.
|
||||
- Errors answer `{ "error": { "code": "invalid", "message": "…", "fields": { "issue_reported": ["can't be blank"] } } }` with the matching HTTP status: 400 bad request, 401 no or wrong token, 403 not allowed (`missing_scope`, `owners_only`), 404 not found or not reachable with this token, 409 `idempotency_conflict`, 422 invalid, 429 too many requests (600 a minute per token).
|
||||
|
||||
### Safe retries
|
||||
|
||||
Send an `Idempotency-Key` header (any unique string up to 100 characters) with each write. If the answer is lost and you send the same request with the same key again, you get the first answer back (with `Idempotent-Replay: true`) instead of a second record. Keys are kept for 24 hours. The same key with a different request is refused (409).
|
||||
|
||||
### Linking to the other system
|
||||
|
||||
Squawks have an `external_ref`: your own id for them, such as `redmine:issue:4512`. Set it when reporting or later, and find squawks by it with `GET /squawks?external_ref=…`. The other system then doesn't need to store SAM's ids.
|
||||
|
||||
## Endpoints
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /me` | The token, who it acts as, and the aircraft it reaches |
|
||||
| `GET /aircraft` | The aircraft: tail number, make and model, status, airworthiness, hours |
|
||||
| `GET /aircraft/:id` | One aircraft |
|
||||
| `GET /aircraft/:id/components` | Its parts: type, serial, hours, since overhaul, TBO and replacement limits, parent part (`?all=1` includes disposed parts) |
|
||||
| `GET /aircraft/:id/due` | Everything coming due, soonest first; items due by hours get a projected date |
|
||||
| `GET /aircraft/:id/inspections` | Each inspection's status and next due date and hours |
|
||||
| `GET /aircraft/:id/ads` | Each AD's status and next due date and hours |
|
||||
| `GET /aircraft/:id/logbook_entries` | Logbook entries, with their signatures (`?log=AC`, `ENG`, `PROP` or `OTHER`; `?signed=true` or `false`) |
|
||||
| `GET /aircraft/:id/squawks` | Squawks (`?status=open`, the default, or `resolved` or `all`) |
|
||||
| `POST /aircraft/:id/squawks` | Report a squawk |
|
||||
| `GET /squawks?external_ref=…` | Find squawks by your id for them |
|
||||
| `GET /squawks/:id` | One squawk |
|
||||
| `PATCH /squawks/:id` | Update a squawk |
|
||||
| `POST /aircraft/:id/draft_batches` | Send a visit's work as draft logbook entries for signing |
|
||||
| `GET /aircraft/:id/draft_batches` | Its drafts (`?status=awaiting_signature`, `completed` or `withdrawn`) |
|
||||
| `GET /draft_batches?external_ref=…` | Find drafts by your id for them |
|
||||
| `GET /draft_batches/:id` | One draft, with its entries and whether they're signed |
|
||||
| `DELETE /draft_batches/:id` | Withdraw a draft nothing in which is signed yet |
|
||||
|
||||
### Reporting a squawk
|
||||
|
||||
```
|
||||
POST /api/v1/aircraft/12/squawks
|
||||
Authorization: Bearer sam_…
|
||||
SAM-On-Behalf-Of: pilot@example.com
|
||||
Idempotency-Key: 7f9c1e2a-…
|
||||
Content-Type: application/json
|
||||
|
||||
{ "squawk": { "issue_reported": "Left mag drop 200 rpm", "priority": 0, "component_id": 41, "external_ref": "redmine:issue:4512" } }
|
||||
```
|
||||
|
||||
`priority` is 0 (ground the aircraft), 1 (fix soon), 2 (fix at the next inspection, the default) or 3 (fix eventually). Like a squawk reported in the app, a grounding squawk notifies the aircraft's other people. Anyone who may report squawks on the aircraft can report one.
|
||||
|
||||
The answer is `201` with the squawk:
|
||||
|
||||
```json
|
||||
{ "data": { "id": 88, "aircraft_id": 12, "component_id": 41, "issue_reported": "Left mag drop 200 rpm", "priority": 0,
|
||||
"grounding": true, "deferred": false, "resolved": false, "external_ref": "redmine:issue:4512", … } }
|
||||
```
|
||||
|
||||
### Updating a squawk
|
||||
|
||||
`PATCH /squawks/:id` with `{ "squawk": { … } }`. Anyone who may write can set `external_ref`; changing `issue_reported`, `priority`, `component_id` or `notes` needs an owner of the aircraft, as in the app. A resolved squawk can't be changed. Squawks are resolved by a signed logbook entry, in the app.
|
||||
|
||||
## Draft entries
|
||||
|
||||
Another system that tracks the work, such as Redmine's issues, can send a finished visit to SAM as **draft logbook entries**: the person certifying the work then reviews and signs them in the app. Like writing entries in the app, sending drafts is for the aircraft's owners: an integration acts for an owner (`SAM-On-Behalf-Of`), such as the director of maintenance.
|
||||
|
||||
```
|
||||
POST /api/v1/aircraft/12/draft_batches
|
||||
{ "draft_batch": {
|
||||
"date": "2026-11-20",
|
||||
"aircraft_hours": 4321.4,
|
||||
"external_ref": "redmine:visit:77",
|
||||
"items": [
|
||||
{ "log": "ENG", "text": "Changed oil and filter, 7 qt Aeroshell W100.", "external_ref": "redmine:issue:4512" },
|
||||
{ "log": "AC", "text": "Replaced left brake linings.", "resolves_squawks": [88], "external_ref": "redmine:issue:4513" },
|
||||
{ "log": "AC", "text": "Annual inspection completed IAW Part 43 Appendix D.", "external_ref": "redmine:issue:4519" }
|
||||
],
|
||||
"completes_inspections": [ { "inspection_type_id": 3, "result": "approved" } ],
|
||||
"signer": { "email": "mechanic@example.com", "send_email": false }
|
||||
} }
|
||||
```
|
||||
|
||||
- **One entry per logbook.** Items are grouped by `log` (`AC`, `ENG`, `PROP` or `OTHER`) into one unsigned entry each, their texts in order, so a visit that touched the engine and the airframe makes two entries, signed one after the other.
|
||||
- **Inspections** (`completes_inspections`): each needs its `result`, `approved` (airworthy) or `discrepancies` (a list was given to the owner), and the draft needs `aircraft_hours`. The entry recording it is an inspection entry, in the logbook named by `log`, else the airframe log if an item is for it.
|
||||
- **Nothing is resolved until it's signed.** The squawks the items resolve and the inspections they complete are held until **every** entry of the draft is signed; then they're resolved and recorded, attributed to the person who signed last, and linked to the entry that described the work. A draft never clears a squawk on its own. The signer sees what signing will do before they sign.
|
||||
- **The signer.** Anyone with access to the aircraft and a certificate in their profile can sign, from each entry's `sign_url`. Give `signer.email` for someone else (a mechanic without an account): each entry then gets an `invitation_url`, a link that lets that person create an account for that address and sign that entry, for 14 days. Pass the link on yourself (for example inside Redmine), or set `send_email: true` to have SAM email it.
|
||||
|
||||
The answer (`201`):
|
||||
|
||||
```json
|
||||
{ "data": { "id": 301, "status": "awaiting_signature", "external_ref": "redmine:visit:77",
|
||||
"held": { "resolves_squawks": [88], "completes_inspections": [3] },
|
||||
"entries": [
|
||||
{ "id": 9001, "log": "AC", "entry_type": "INSPECTION", "text": "Replaced left brake linings.\n\nAnnual inspection…", "signed": false,
|
||||
"sign_url": "https://sam.example.com/aircraft/12/logbook_entries/9001/signature/new", "invitation_url": "https://sam.example.com/sign/…" },
|
||||
{ "id": 9002, "log": "ENG", "entry_type": "MAINTENANCE", "text": "Changed oil and filter…", "signed": false, … } ] } }
|
||||
```
|
||||
|
||||
When every entry is signed, the draft's `status` becomes `completed` and the `draft_batch.completed` webhook is sent: the moment to close the work order.
|
||||
|
||||
A draft can be withdrawn (`DELETE /draft_batches/:id`) while nothing in it is signed; its entries are removed, and the record history keeps them. Once an entry is signed it's a record: mistakes are fixed with a correction entry in the app, never through the API.
|
||||
|
||||
## Webhooks
|
||||
|
||||
An integration can be told about changes. In Admin → Integrations, give it a webhook address and choose the events. SAM then posts JSON there after each change:
|
||||
|
||||
| Event | When |
|
||||
|---|---|
|
||||
| `squawk.created` | A squawk is reported |
|
||||
| `squawk.updated` | A squawk is changed |
|
||||
| `squawk.resolved` | A squawk is resolved |
|
||||
| `entry.signed` | A logbook entry is signed |
|
||||
| `draft_batch.completed` | Every entry of a draft is signed, and what it resolves is done |
|
||||
|
||||
Only events on the integration's aircraft are sent. The body:
|
||||
|
||||
```json
|
||||
{ "event": "squawk.created", "id": "6c1f…", "created_at": "2026-11-20T15:04:05Z", "aircraft_id": 12,
|
||||
"data": { …the squawk, as the API returns it… } }
|
||||
```
|
||||
|
||||
With the headers `SAM-Event`, `SAM-Delivery` (a number, the same on every retry) and `SAM-Signature: t=<unix time>,v1=<signature>`. Check each post before trusting it: compute the HMAC-SHA256 of `<t>.<body>` with the webhook secret (shown once when the webhook is set up; Admin → Integrations → New secret makes another) and compare it with `v1`. Reject posts whose `t` is more than a few minutes old.
|
||||
|
||||
```ruby
|
||||
t, v1 = request.headers["SAM-Signature"].scan(/t=(\d+),v1=(\h+)/).first
|
||||
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{request.raw_post}")
|
||||
valid = ActiveSupport::SecurityUtils.secure_compare(expected, v1.to_s) && (Time.now.to_i - t.to_i).abs < 300
|
||||
```
|
||||
|
||||
Answer any 2xx status to accept it. Anything else, or no answer within 10 seconds, is retried with growing waits (8 tries over about a day), then marked failed. Admin → Integrations lists recent webhooks and what the other system answered. The same event may arrive more than once; use `SAM-Delivery` or the event's `id` to ignore repeats.
|
||||
|
||||
A webhook address may be on your private network (where Redmine often runs), but never the server itself or a link-local address.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.1 KiB |
+5
-1
@@ -1 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50" y="50" font-size="88" text-anchor="middle" dominant-baseline="central">✈️</text></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#0f172a"/>
|
||||
<circle cx="256" cy="256" r="200" fill="none" stroke="#0369a1" stroke-width="30"/>
|
||||
<path fill="#fff" transform="translate(256 256) scale(1.08) translate(-256 -256)" d="M256 92C270 92 278 108 278 128L278 214L408 270L408 300L278 280L276 370L326 400L326 424L256 410L186 424L186 400L236 370L234 280L104 300L104 270L234 214L234 128C234 108 242 92 256 92Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 166 B After Width: | Height: | Size: 486 B |
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Binary file not shown.
@@ -0,0 +1,116 @@
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* @licstart The following is the entire license notice for the
|
||||
* JavaScript code in this page
|
||||
*
|
||||
* Copyright 2024 Mozilla Foundation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* @licend The above is the entire license notice for the
|
||||
* JavaScript code in this page
|
||||
*/
|
||||
/**
|
||||
* pdfjsVersion = 6.5.438
|
||||
* pdfjsBuild = 0a4153349
|
||||
*/
|
||||
const t=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),e=[1/0,1/0,-1/0,-1/0],i=new Float32Array(e),n=[.001,0,0,.001,0,0],s="http://www.w3.org/2000/svg",r=1,a=2,o=4,l=16,h=32,c=64,d=128,u=256,p={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},g="pdfjs_internal_id_",m="pdfjs_internal_editor_",f={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},b={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},w=0,v=1,A=2,x=3,C=3,E=4,S={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},T={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},k=1,_=2,P=3,M=4,D=5,I={ERRORS:0,WARNINGS:1,INFOS:5},F={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},B=0,L=1,O=2,R=3,N=4,U={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let H=I.WARNINGS;function setVerbosityLevel(t){Number.isInteger(t)&&(H=t)}function getVerbosityLevel(){return H}function info(t){H>=I.INFOS&&console.info(`Info: ${t}`)}function warn(t){H>=I.WARNINGS&&console.warn(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function assert(t,e){t||unreachable(e)}function createValidAbsoluteUrl(t,e=null,i=null){if(!t)return null;if(i&&"string"==typeof t){if(i.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e?.length>=2&&(t=`http://${t}`)}if(i.tryConvertEncoding)try{t=function stringToUTF8String(t){return decodeURIComponent(escape(t))}(t)}catch{}}const n=e?URL.parse(t,e):URL.parse(t);return function _isValidProtocol(t){switch(t?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function updateUrlHash(t,e,i=!1){const n=URL.parse(t);if(n){n.hash=e;return n.href}return i&&createValidAbsoluteUrl(t,"http://example.com")?t.split("#",1)[0]+""+(e?`#${e}`:""):""}function stripPath(t){return t.substring(t.lastIndexOf("/")+1)}function shadow(t,e,i,n=!1){Object.defineProperty(t,e,{value:i,enumerable:!n,configurable:!0,writable:!1});return i}const G=function BaseExceptionClosure(){function BaseException(t,e){this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends G{constructor(t,e){super(t,"PasswordException");this.code=e}}class UnknownErrorException extends G{constructor(t,e){super(t,"UnknownErrorException");this.details=e}}class InvalidPDFException extends G{constructor(t){super(t,"InvalidPDFException")}}class ResponseException extends G{constructor(t,e,i){super(t,"ResponseException");this.status=e;this.missing=i}}class FormatError extends G{constructor(t){super(t,"FormatError")}}class AbortException extends G{constructor(t){super(t,"AbortException")}}function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,i=new Uint8Array(e);for(let n=0;n<e;++n)i[n]=255&t.charCodeAt(n);return i}clLine truncated
|
||||
/*webpackIgnore: true*/
|
||||
/*@vite-ignore*/
|
||||
this.workerSrc))).WorkerMessageHandler})())}}class WorkerTransport{downloadInfoCapability=Promise.withResolvers();#Ga=null;#za=!1;#Wa=new Map;#ja=null;#Va=new Map;#$a=new Map;#Xa=new Map;#Ka=null;#qa=null;constructor(t,e,i,n,s,r){this.messageHandler=t;this.loadingTask=e;this.#ja=i;this.commonObjs=new PDFObjects;this.fontLoader=new FontLoader({ownerDocument:n.ownerDocument,styleElement:n.styleElement});this.rendererWorker=n.rendererWorker;this.loadingParams=n.loadingParams;this._params=n;this.canvasFactory=s.canvasFactory;this.filterFactory=s.filterFactory;this.binaryDataFactory=s.binaryDataFactory;this.pagesMapper=r;this.destroyed=!1;this.destroyCapability=null;this.setupMessageHandler()}updatePage(t){this.#Va.set(t._id,t);this.#$a.set(t._pageIndex,Promise.resolve(t))}#Ya(t,e=null){return this.#Wa.getOrInsertComputed(t,()=>this.messageHandler.sendWithPromise(t,e))}#Hs({loaded:t,total:e}){this.loadingTask.onProgress?.({loaded:t,total:e,percent:e?MathClamp(Math.round(t/e*100),0,100):NaN})}get annotationStorage(){return shadow(this,"annotationStorage",new AnnotationStorage)}getRenderingIntent(t,e=p.ENABLE,i=null,n=!1,s=!1){let g=a,m=Z;switch(t){case"any":g=r;break;case"display":break;case"print":g=o;break;default:warn(`getRenderingIntent - invalid intent: ${t}`)}const f=g&o&&i instanceof PrintAnnotationStorage?i:this.annotationStorage;switch(e){case p.DISABLE:g+=c;break;case p.ENABLE:break;case p.ENABLE_FORMS:g+=l;break;case p.ENABLE_STORAGE:g+=h;m=f.serializable;break;default:warn(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(g+=d);s&&(g+=u);const{ids:b,hash:y}=f.modifiedIds;return{renderingIntent:g,cacheKey:[g,m.hash,y].join("_"),annotationStorageSerializable:m,modifiedIds:b}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=Promise.withResolvers();this.#Ka?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#Va.values())t.push(e._destroy());this.#Va.clear();this.#$a.clear();this.#Xa.clear();Object.hasOwn(this,"annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then(()=>{this.commonObjs.clear();this.fontLoader.clear();this.#Wa.clear();this.filterFactory.destroy();TextLayer.cleanup();this.#ja?.cancelAllRequests(new AbortException("Worker was terminated."));this.messageHandler?.destroy();this.messageHandler=null;this.rendererWorker=null;this.destroyCapability.resolve()},this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(t,e)=>{assert(this.#ja,"GetReader - no `BasePDFStream` instance available.");this.#Ga=this.#ja.getFullReader();this.#Ga.onProgress=t=>this.#Hs(t);e.onPull=()=>{this.#Ga.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{this.#Ga.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}});t.on("ReaderHeadersReady",async t=>{await this.#Ga.headersReady;const{isStreamingSupported:e,isRangeSupported:i,contentLength:n}=this.#Ga;e&&i&&(this.#Ga.onProgress=null);return{isStreamingSupported:e,isRangeSupported:i,contentLength:n}});t.on("GetRangeReader",(t,e)=>{assert(this.#ja,"GetRangeReader - no `BasePDFStream` instance available.");const i=this.#ja.getRangeReader(t.begin,t.end);if(i){e.onPull=()=>{i.read().then(function({value:t,done:i}){if(i)e.close();else{assert(t instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}}).catch(t=>{e.error(t)})};e.onCancel=t=>{i.cancel(t);e.ready.catch(t=>{if(!this.destroyed)throw t})}}else e.close()});t.on("GetDoc",({pdfInfo:t})=>{this.pagesMapper.pagesNumber=t.numPages;this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))});t.on("DocException",t=>{e._capability.reject(wrapReason(t))});t.on("PasswordRequest",t=>{this.#Ka=Promise.withResolvers();try{if(!e.onPassword)throw wrapReason(t);const updatePassword=t=>{t instanceof Error?this.#Ka.reject(t):this.#Ka.resolve({password:t})};e.onPassword(updatePassword,t.code)}catch(t){this.#Ka.reject(t)}return this.#Ka.promise});t.on("DataLoaded",t=>{this.#Hs({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)});t.on("StartRenderPage",t=>{if(this.destroyed)return;this.#Va.get(t.pageProxyId)._startRenderPage(t.transparency,t.cacheKey)});const i=new ObjectHandler({messageHandler:t,commonObjs:this.commonObjs,fontLoader:this.fontLoader,pageCache:this.#Va,pdfBug:this._params.pdfBug});this.rendererWorker?.promise.then(()=>{this.rendererWorker?.messageHandler?.on("FontFallback",e=>this.destroyed?null:t.sendWithPromise("FontFallback",e))},()=>{});t.on("commonobj",([t,e,n])=>{if(this.destroyed)return null;const{rendererWorker:Line truncated
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* @licstart The following is the entire license notice for the
|
||||
* JavaScript code in this page
|
||||
*
|
||||
* Copyright 2024 Mozilla Foundation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
* @licend The above is the entire license notice for the
|
||||
* JavaScript code in this page
|
||||
*/
|
||||
/**
|
||||
* pdfjsVersion = 6.5.438
|
||||
* pdfjsBuild = 0a4153349
|
||||
*/
|
||||
const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),t=[1/0,1/0,-1/0,-1/0],a=new Float32Array(t),n=[.001,0,0,.001,0,0],s=.35/1.35,r="http://www.w3.org/2000/svg",i=1,o=2,l=4,f=8,c=16,h=64,u=128,m=256,d="pdfjs_internal_editor_",g=3,b=9,w=13,j=15,k=101,y={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},q=1,v=2,S=3,x=0,C=4,F=1,T=2,R=3,D={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},O="Group",M="R",H=0,N=4,E=1,z=2,_=4,L=16,U=32,W=128,X=512,K=1,G=2,V=4096,$=8192,Y=32768,J=65536,Q=131072,Z=1048576,ee=2097152,te=8388608,ae=16777216,ne=1,se=2,re=3,ie=4,oe=5,le={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},fe={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},ce={O:"PageOpen",C:"PageClose"},he=1,ue=5,me=1,pe=2,de=3,ge=4,be=5,we=6,je=7,ke=8,ye=9,qe=10,ve=11,Se=12,Ae=13,xe=14,Ce=15,Ie=16,Fe=17,Te=18,Re=19,De=20,Oe=21,Me=22,Be=23,He=24,Pe=25,Ne=26,Ee=27,ze=28,_e=29,Le=30,Ue=31,We=32,Xe=33,Ke=34,Ge=35,Ve=36,$e=37,Ye=38,Je=39,Qe=40,Ze=41,et=42,tt=43,at=44,nt=45,st=46,rt=47,it=48,ot=49,lt=50,ft=51,ct=52,ht=53,ut=54,mt=55,pt=56,dt=57,gt=58,bt=59,wt=60,jt=61,kt=62,yt=63,qt=64,vt=65,St=66,At=67,xt=68,Ct=69,It=70,Ft=71,Tt=72,Rt=73,Dt=74,Ot=75,Mt=76,Bt=77,Ht=80,Pt=81,Nt=83,Et=84,zt=85,_t=86,Lt=87,Ut=88,Wt=89,Xt=90,Kt=91,Gt=92,Vt=93,$t=94,Yt=0,Jt=1,Qt=2,Zt=3,ea=4,ta=1,aa=2;let na=he;function info(e){na>=ue&&console.info(`Info: ${e}`)}function warn(e){na>=he&&console.warn(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,a=null){if(!e)return null;if(a&&"string"==typeof e){if(a.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(a.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const n=t?URL.parse(e,t):URL.parse(e);return function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n)?n:null}function shadow(e,t,a,n=!1){Object.defineProperty(e,t,{value:a,enumerable:!n,configurable:!0,writable:!1});return a}const sa=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends sa{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends sa{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends sa{constructor(e){super(e,"InvalidPDFException")}}class ResponseException extends sa{constructor(e,t,a){super(e,"ResponseException");this.status=t;this.missing=a}}class FormatError extends sa{constructor(e){super(e,"FormatError")}}class AbortException extends sa{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,a=8192;if(t<a)return String.fromCharCode.apply(null,e);const n=[];for(let s=0;s<t;s+=a){const r=Math.min(s+a,t),i=e.subarray(s,r);n.push(String.fromCharCode.apply(null,i))}return n.join("")}function stringToBytes(e){"string"!=typeof e&&unreachable("Invalid argument for stringToBytes");const t=e.length,a=new Uint8Array(t);for(let n=0;n<t;++n)a[n]=255&e.charCodeAt(n);return a}class FeatureTest{static get isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return shadow(this,"isLittleEndian",1===new Uint32Array(e.buffer,0,1)[0])}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isVideoFrameSupported(){return shadow(this,"isVideoFrameSupported","undefined"!=typeof VideoFrame)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:e,userAgent:t}=navigator;return shadow(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCanvasFilterSupported(){let e;this.isOffscreenCanvasSupported&&(e=new OffscreenCanvas(1,1).getContext("2d"));return shadow(thLine truncated
|
||||
/*webpackIgnore: true*/
|
||||
/*@vite-ignore*/
|
||||
`${WasmImage.#R}${this._noWasmFilename}`));return{exports:t(e)}}async#se(e){this.#te||(WasmImage.#ee?this.#te=await fetchBinaryData(`${WasmImage.#R}${this._filename}`):this.#te=await WasmImage.#Q().sendWithPromise("FetchBinaryData",{kind:"wasmUrl",filename:this._filename}));return(await WebAssembly.instantiate(this.#te,e)).instance}async#re(e,t,a){if(WasmImage.#T)try{return a(await this.#se(t))}catch(e){warn(`#getWasmInstance: ${e}`)}try{return a(await this.#ne(t))}catch(e){warn(`#getJsInstance: ${e}`)}e(null);return null}_getModule(e){if(!this.#ae){const{promise:t,resolve:a}=Promise.withResolvers();this.#ae=Promise.race([t,e({warn,instantiateWasm:this.#re.bind(this,a)})])}return this.#ae}async decode(e,t){unreachable("Abstract method `decode` called")}}class Jbig2Error extends sa{constructor(e){super(e,"Jbig2Error")}}class JBig2CCITTFaxImage extends WasmImage{_filename="jbig2.wasm";_noWasmFilename="jbig2_nowasm_fallback.js";static get instance(){return shadow(this,"instance",new JBig2CCITTFaxImage(!0))}async decode(e,t,a,n,s){const r=await this._getModule(Ga);if(!r)throw new Jbig2Error("JBig2 failed to initialize");let i,o;try{const l=e.length;i=r._malloc(l);r.writeArrayToMemory(e,i);if(s)r._ccitt_decode(i,l,t,a,s.K,s.EndOfLine?1:0,s.EncodedByteAlign?1:0,s.BlackIs1?1:0,s.Columns,s.Rows);else{const e=n?n.length:0;if(e>0){o=r._malloc(e);r.writeArrayToMemory(n,o)}r._jbig2_decode(i,l,t,a,o,e)}if(!r.imageData)throw new Jbig2Error("Unknown error");const{imageData:f}=r;r.imageData=null;return f}finally{i&&r._free(i);o&&r._free(o)}}}class CCITTFaxStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.maybeLength=t;this.dict=e.dict;a instanceof Dict||(a=Dict.empty);this.params={K:a.get("K")||0,EndOfLine:!!a.get("EndOfLine"),EncodedByteAlign:!!a.get("EncodedByteAlign"),Columns:a.get("Columns")||1728,Rows:a.get("Rows")||0,EndOfBlock:!!(a.get("EndOfBlock")??!0),BlackIs1:!!a.get("BlackIs1")}}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}get isImageStream(){return!0}get isAsyncDecoder(){return!0}async decodeImage(e,t,a){if(this.eof)return this.buffer;e??=this.stream.isAsync&&await this.stream.asyncGetBytes()||this.bytes;this.buffer=await JBig2CCITTFaxImage.instance.decode(e,this.dict.get("W","Width"),this.dict.get("H","Height"),null,this.params);this.bufferLength=this.buffer.length;this.eof=!0;return this.buffer}}const Va=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$a=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),Ya=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),Ja=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524Line truncated
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
// Copyright 2014 PDFium Authors. All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,363 @@
|
||||
LICENSE AGREEMENT AND LIMITED PRODUCT WARRANTY
|
||||
LIBERATION FONT SOFTWARE
|
||||
|
||||
This agreement governs the use of the Software and any updates to the Software, regardless of the delivery mechanism. Subject to the following terms, Red Hat, Inc. ("Red Hat") grants to the user ("Client") a license to this work pursuant to the GNU General Public License v.2 with the exceptions set forth below and such other terms as are set forth in this End User License Agreement.
|
||||
|
||||
1. The Software and License Exception. LIBERATION font software (the "Software") consists of TrueType-OpenType formatted font software for rendering LIBERATION typefaces in sans-serif, serif, and monospaced character styles. You are licensed to use, modify, copy, and distribute the Software pursuant to the GNU General Public License v.2 with the following exceptions:
|
||||
|
||||
(a) As a special exception, if you create a document which uses this font, and embed this font or unaltered portions of this font into the document, this font does not by itself cause the resulting document to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the document might be covered by the GNU General Public License. If you modify this font, you may extend this exception to your version of the font, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.
|
||||
|
||||
(b) As a further exception, any distribution of the object code of the Software in a physical product must provide you the right to access and modify the source code for the Software and to reinstall that modified version of the Software in object code form on the same physical product on which you received it.
|
||||
|
||||
2. Intellectual Property Rights. The Software and each of its components, including the source code, documentation, appearance, structure and organization are owned by Red Hat and others and are protected under copyright and other laws. Title to the Software and any component, or to any copy, modification, or merged portion shall remain with the aforementioned, subject to the applicable license. The "LIBERATION" trademark is a trademark of Red Hat, Inc. in the U.S. and other countries. This agreement does not permit Client to distribute modified versions of the Software using Red Hat's trademarks. If Client makes a redistribution of a modified version of the Software, then Client must modify the files names to remove any reference to the Red Hat trademarks and must not use the Red Hat trademarks in any way to reference or promote the modified Software.
|
||||
|
||||
3. Limited Warranty. To the maximum extent permitted under applicable law, the Software is provided and licensed "as is" without warranty of any kind, expressed or implied, including the implied warranties of merchantability, non-infringement or fitness for a particular purpose. Red Hat does not warrant that the functions contained in the Software will meet Client's requirements or that the operation of the Software will be entirely error free or appear precisely as described in the accompanying documentation.
|
||||
|
||||
4. Limitation of Remedies and Liability. To the maximum extent permitted by applicable law, Red Hat or any Red Hat authorized dealer will not be liable to Client for any incidental or consequential damages, including lost profits or lost savings arising out of the use or inability to use the Software, even if Red Hat or such dealer has been advised of the possibility of such damages.
|
||||
|
||||
5. General. If any provision of this agreement is held to be unenforceable, that shall not affect the enforceability of the remaining provisions. This agreement shall be governed by the laws of the State of North Carolina and of the United States, without regard to any conflict of laws provisions, except that the United Nations Convention on the International Sale of Goods shall not apply.
|
||||
Copyright © 2007-2011 Red Hat, Inc. All rights reserved. LIBERATION is a trademark of Red Hat, Inc.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
The text of the GNU General Public License, version 2, referenced above:
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,196 @@
|
||||
// Copyright 2014 The PDFium Authors
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
https://www.apache.org/licenses/
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
1. Definitions.
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
END OF TERMS AND CONDITIONS
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* The copyright in this software is being made available under the 2-clauses
|
||||
* BSD License, included below. This software may be subject to other third
|
||||
* party and contributor rights, including patent rights, and no such rights
|
||||
* are granted under this license.
|
||||
*
|
||||
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
|
||||
* Copyright (c) 2002-2014, Professor Benoit Macq
|
||||
* Copyright (c) 2003-2014, Antonin Descampe
|
||||
* Copyright (c) 2003-2009, Francois-Olivier Devaux
|
||||
* Copyright (c) 2005, Herve Drolon, FreeImage Team
|
||||
* Copyright (c) 2002-2003, Yannick Verschueren
|
||||
* Copyright (c) 2001-2003, David Janssens
|
||||
* Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
|
||||
* Copyright (c) 2012, CS Systemes d'Information, France
|
||||
*
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user