From 794da3be7265d2595cb172496881d6d3b727126c Mon Sep 17 00:00:00 2001 From: Maurice Date: Sat, 7 Nov 2026 10:08:05 +0100 Subject: [PATCH] feat(native): booking passes go straight into Apple Wallet Opening a .pkpass in the iOS app brought up the generic share sheet. It now shows Wallet's own sheet with the pass and "Add", and a pass that is already in Wallet opens there instead of being offered twice (TrekShell.addToWallet, feature wallet). A broken pass or a device without Wallet falls back to the share sheet as before. Passes carry an "Apple Wallet" badge in the trip's files and a wallet icon where they hang on a booking, so it is clear what a tap does. --- client/ios/App/App/TrekShellPlugin.swift | 56 +++++++++++++++- .../screens/trip/sheets/PlFileAttach.tsx | 7 +- .../mobile/screens/trip/tabs/MFilesTab.tsx | 14 +++- client/src/native/blobBase64.ts | 9 +++ client/src/native/nativeFiles.ts | 13 ++-- client/src/native/trekShell.ts | 2 + client/src/native/wallet.test.ts | 64 +++++++++++++++++++ client/src/native/wallet.ts | 34 ++++++++++ 8 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 client/src/native/blobBase64.ts create mode 100644 client/src/native/wallet.test.ts create mode 100644 client/src/native/wallet.ts diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index 65ffe10c6..24bd7c98c 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -10,6 +10,7 @@ import WidgetKit import ActivityKit #endif import LocalAuthentication +import PassKit import UIKit import WebKit @@ -44,6 +45,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "storePurchase", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "storeFinish", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "storeRestore", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "addToWallet", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -51,7 +53,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation", "sharedFiles", "nativePush", "widgets", "liveActivity", "widgetTrips", "storeKit", "shareSheet", "wallet"] // MARK: - Shared booking documents @@ -381,6 +383,58 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// Positions and errors for the UI, shaped like the Geolocation API's, with the /// When-In-Use permission asked the first time. +// MARK: - Apple Wallet + +extension TrekShellPlugin { + /// Feature wallet: a booking's Wallet pass, straight into Apple Wallet. A pass + /// already there opens in Wallet instead of being offered twice. Resolves with + /// `result` added, opened or cancelled; rejects INVALID for bytes that are no + /// pass and UNAVAILABLE where Wallet cannot take one. + @objc func addToWallet(_ call: CAPPluginCall) { + guard let base64 = call.getString("data"), let data = Data(base64Encoded: base64), + let pass = try? PKPass(data: data) else { + call.reject("not a Wallet pass", "INVALID") + return + } + DispatchQueue.main.async { [weak self] in + let library = PKPassLibrary() + if library.containsPass(pass), let url = pass.passURL { + UIApplication.shared.open(url) + call.resolve(["result": "opened"]) + return + } + guard PKAddPassesViewController.canAddPasses(), + let sheet = PKAddPassesViewController(pass: pass), + let presenter = self?.bridge?.viewController else { + call.reject("Wallet is not available", "UNAVAILABLE") + return + } + let delegate = TrekWalletSheet { [weak sheet] in + sheet?.dismiss(animated: true) + call.resolve(["result": library.containsPass(pass) ? "added" : "cancelled"]) + } + sheet.delegate = delegate + TrekWalletSheet.current = delegate + presenter.present(sheet, animated: true) + } + } +} + +/// Answers the Wallet sheet closing; held while it is up, since the sheet only keeps a weak delegate. +final class TrekWalletSheet: NSObject, PKAddPassesViewControllerDelegate { + static var current: TrekWalletSheet? + private let done: () -> Void + + init(done: @escaping () -> Void) { + self.done = done + } + + func addPassesViewControllerDidFinish(_ controller: PKAddPassesViewController) { + done() + TrekWalletSheet.current = nil + } +} + // MARK: - In-app purchase extension TrekShellPlugin { diff --git a/client/src/mobile/screens/trip/sheets/PlFileAttach.tsx b/client/src/mobile/screens/trip/sheets/PlFileAttach.tsx index e3aa2097b..43d13b792 100644 --- a/client/src/mobile/screens/trip/sheets/PlFileAttach.tsx +++ b/client/src/mobile/screens/trip/sheets/PlFileAttach.tsx @@ -1,6 +1,7 @@ import { useRef, useState } from 'react' -import { ExternalLink, FileText, Link2, Paperclip, X } from 'lucide-react' +import { ExternalLink, FileText, Link2, Paperclip, Wallet, X } from 'lucide-react' import { openFile } from '../../../../utils/fileDownload' +import { isWalletPass } from '../../../../components/Files/FileManager.helpers' import type { TripFile } from '../../../../types' import type { TripPlanner } from '../MTripShell' @@ -95,7 +96,9 @@ export default function PlFileAttach({ planner, files, onAdd, onRemove, hideHint
{attached.map(file => ( diff --git a/client/src/mobile/screens/trip/tabs/MFilesTab.tsx b/client/src/mobile/screens/trip/tabs/MFilesTab.tsx index a10398851..e411fd10b 100644 --- a/client/src/mobile/screens/trip/tabs/MFilesTab.tsx +++ b/client/src/mobile/screens/trip/tabs/MFilesTab.tsx @@ -1,10 +1,10 @@ import { useEffect, useRef, useState, type ChangeEvent, type ClipboardEvent } from 'react' -import { Link, Loader2, MoreVertical, Star } from 'lucide-react' +import { Link, Loader2, MoreVertical, Star, Wallet } from 'lucide-react' import MDancingTrek from '../../../components/MDancingTrek' import { useTranslation, translateApiError } from '../../../../i18n' import { fileRepo } from '../../../../repo/fileRepo' import { openFile } from '../../../../utils/fileDownload' -import { isMedia, formatSize } from '../../../../components/Files/FileManager.helpers' +import { isMedia, isWalletPass, formatSize } from '../../../../components/Files/FileManager.helpers' import type { TripFile } from '../../../../types' import { TabScroller } from './tabChrome' import type { MTabScreenProps } from './tabModel' @@ -237,6 +237,9 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) { ) } +/** The product's name, the same in every language. */ +const APPLE_WALLET = 'Apple Wallet' + function FileRow({ file, planner, onOpen, onStar, onMenu }: { file: TripFile planner: MTabScreenProps['planner'] @@ -266,6 +269,13 @@ function FileRow({ file, planner, onOpen, onStar, onMenu }: {
{file.original_name}
+ {isWalletPass(file.mime_type, file.original_name) && ( + // A tap hands the pass to Apple Wallet (native/wallet.ts), or downloads it into Wallet on the web. + + + )} {!!file.file_size && ( {formatSize(file.file_size)} diff --git a/client/src/native/blobBase64.ts b/client/src/native/blobBase64.ts new file mode 100644 index 000000000..121bc9149 --- /dev/null +++ b/client/src/native/blobBase64.ts @@ -0,0 +1,9 @@ +/** A Blob as plain base64 (no data: prefix), the way the native bridge takes bytes. */ +export function toBase64(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1)); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); +} diff --git a/client/src/native/nativeFiles.ts b/client/src/native/nativeFiles.ts index a72b916ec..98639cfd3 100644 --- a/client/src/native/nativeFiles.ts +++ b/client/src/native/nativeFiles.ts @@ -1,14 +1,7 @@ import { Directory, Filesystem } from '@capacitor/filesystem'; import { Share } from '@capacitor/share'; - -function toBase64(blob: Blob): Promise { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => resolve(String(reader.result).slice(String(reader.result).indexOf(',') + 1)); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} +import { toBase64 } from './blobBase64'; +import { addToWallet, isWalletPassName } from './wallet'; /** Readable, but safe as a single path segment inside the cache directory. */ export function cacheFileName(filename: string): string { @@ -34,6 +27,8 @@ export function fileNameFromUrl(url: string): string { * saving it to Files, opening it in another app or sending it on. */ export async function shareFile(blob: Blob, filename: string): Promise { + // A Wallet pass goes to Apple Wallet's own sheet, not to the generic share sheet. + if (isWalletPassName(filename) && (await addToWallet(blob))) return; const { uri } = await Filesystem.writeFile({ path: cacheFileName(filename), data: await toBase64(blob), diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index 4bf1f93c2..704246e69 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -81,6 +81,8 @@ export interface TrekShellPlugin { }): Promise<{ kind: 'bought' | 'cancelled' | 'pending' | 'failed'; jws?: string; transactionId?: string }>; /** iOS, feature storeKit: marks a purchase delivered once its instance exists. */ storeFinish(options: { transactionId: string }): Promise; + /** iOS, feature wallet: adds a .pkpass (base64) to Apple Wallet, or opens it there when it is already in. */ + addToWallet(options: { data: string }): Promise<{ result: 'added' | 'opened' | 'cancelled' }>; /** iOS, feature storeKit: the newest active subscription under `prefix` on this Apple ID, if any. */ storeRestore(options: { prefix: string }): Promise<{ jws?: string; transactionId?: string }>; addListener( diff --git a/client/src/native/wallet.test.ts b/client/src/native/wallet.test.ts new file mode 100644 index 000000000..c08aff495 --- /dev/null +++ b/client/src/native/wallet.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const env = vi.hoisted(() => ({ ios: true, wallet: true })); +const shell = vi.hoisted(() => ({ addToWallet: vi.fn() })); +const report = vi.hoisted(() => vi.fn()); + +vi.mock('./platform', () => ({ isNativeIos: () => env.ios })); +vi.mock('./capabilities', () => ({ hasNativeFeature: (name: string) => name === 'wallet' && env.wallet })); +vi.mock('./trekShell', () => ({ TrekShell: shell })); +vi.mock('./reportFailure', () => ({ reportNativeFailure: report })); + +import { addToWallet, canAddToWallet, isWalletPassName } from './wallet'; + +const pass = new Blob(['PK\u0003\u0004pass'], { type: 'application/vnd.apple.pkpass' }); + +beforeEach(() => { + env.ios = true; + env.wallet = true; + shell.addToWallet.mockReset(); + report.mockReset(); +}); + +describe('Apple Wallet', () => { + it('knows a pass by its name', () => { + expect(isWalletPassName('Boarding Pass.pkpass')).toBe(true); + expect(isWalletPassName('TICKET.PKPASS ')).toBe(true); + expect(isWalletPassName('passes.pkpasses')).toBe(false); + expect(isWalletPassName('booking.pdf')).toBe(false); + }); + + it('is offered only on iOS with the wallet feature', () => { + expect(canAddToWallet()).toBe(true); + env.wallet = false; + expect(canAddToWallet()).toBe(false); + env.wallet = true; + env.ios = false; + expect(canAddToWallet()).toBe(false); + }); + + it('hands the pass to Wallet as base64', async () => { + shell.addToWallet.mockResolvedValue({ result: 'added' }); + expect(await addToWallet(pass)).toBe(true); + const { data } = shell.addToWallet.mock.calls[0][0] as { data: string }; + expect(atob(data)).toBe('PK\u0003\u0004pass'); + }); + + it('falls back quietly for a broken pass or no Wallet, and reports anything else', async () => { + shell.addToWallet.mockRejectedValue({ code: 'INVALID' }); + expect(await addToWallet(pass)).toBe(false); + shell.addToWallet.mockRejectedValue({ code: 'UNAVAILABLE' }); + expect(await addToWallet(pass)).toBe(false); + expect(report).not.toHaveBeenCalled(); + + shell.addToWallet.mockRejectedValue(new Error('bridge gone')); + expect(await addToWallet(pass)).toBe(false); + expect(report).toHaveBeenCalledTimes(1); + }); + + it('does not touch the bridge where it cannot add a pass', async () => { + env.ios = false; + expect(await addToWallet(pass)).toBe(false); + expect(shell.addToWallet).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/native/wallet.ts b/client/src/native/wallet.ts new file mode 100644 index 000000000..e53a25c04 --- /dev/null +++ b/client/src/native/wallet.ts @@ -0,0 +1,34 @@ +import { toBase64 } from './blobBase64'; +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell } from './trekShell'; + +/** A file that is a single Apple Wallet pass, by its name (the MIME type is often missing). */ +export function isWalletPassName(filename: string): boolean { + return /\.pkpass$/i.test(filename.trim()); +} + +/** Whether this app can hand a pass to Apple Wallet itself (iOS, feature wallet). */ +export function canAddToWallet(): boolean { + return isNativeIos() && hasNativeFeature('wallet'); +} + +/** + * Hands a booking's Wallet pass to Apple Wallet: the system sheet with the pass + * and "Add", or the pass opened in Wallet when it is already there. True when + * Wallet took it over (including the user closing the sheet); false when the app + * cannot, so the caller falls back to the share sheet. + */ +export async function addToWallet(blob: Blob): Promise { + if (!canAddToWallet()) return false; + try { + await TrekShell.addToWallet({ data: await toBase64(blob) }); + return true; + } catch (err) { + // INVALID (not really a pass) and UNAVAILABLE fall back to the share sheet quietly. + const code = (err as { code?: unknown })?.code; + if (code !== 'INVALID' && code !== 'UNAVAILABLE') reportNativeFailure(err); + return false; + } +}