forked from Blendman974/faceclaw
EvenHub compatibility for iOS
This commit is contained in:
1 parent
617cdc39eb
commit
7e58c7c05f
40 files changed
+629
-176
No files matched your search
@@ -108,8 +108,6 @@ export function createDeveloperAppWindow(appContext: AppContext, options: InProc
|
||||
[
|
||||
{
|
||||
label: "Load app from URL",
|
||||
disabled: global.isIOS,
|
||||
description: global.isIOS ? "Not available on iOS yet." : undefined,
|
||||
onSelect: (ctx) => {
|
||||
const layer = new LoadAppFromUrlLayer(appContext);
|
||||
ctx.stack.push(layer);
|
||||
|
||||
@@ -80,7 +80,7 @@ class EvenHubCompassRouter {
|
||||
});
|
||||
}
|
||||
if (!this.enabled) {
|
||||
setCompassEnabled(true);
|
||||
setCompassEnabled(true, "evenhub");
|
||||
this.enabled = true;
|
||||
// Uses location only if the wearer already granted it; an app turning
|
||||
// on the compass is not a reason to raise a system permission prompt.
|
||||
@@ -88,7 +88,7 @@ class EvenHubCompassRouter {
|
||||
}
|
||||
} else {
|
||||
if (this.enabled) {
|
||||
setCompassEnabled(false);
|
||||
setCompassEnabled(false, "evenhub");
|
||||
this.enabled = false;
|
||||
}
|
||||
this.unsubscribe?.();
|
||||
|
||||
+38
-25
@@ -76,42 +76,55 @@ export function utf8Decode(bytes: Uint8Array): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
export function parseEhpk(data: Uint8Array): EhpkArchive {
|
||||
if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b) {
|
||||
/** Index compressed records without expanding assets merely to read app.json. */
|
||||
export function openEhpk(data: Uint8Array) {
|
||||
if (data.length < 20 || data[0] !== 0x45 || data[1] !== 0x48 || data[2] !== 0x50 || data[3] !== 0x4b)
|
||||
throw new Error("not an EHPK file");
|
||||
}
|
||||
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
||||
const firstRecord = view.getUint32(8, true);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
|
||||
let p = firstRecord;
|
||||
const records = new Map<string, { offset: number; compressed: number; size: number }>();
|
||||
const requireBytes = (offset: number, length: number) => {
|
||||
if (offset < 20 || length < 0 || offset + length > data.length) throw new Error("ehpk: truncated record");
|
||||
};
|
||||
let p = view.getUint32(8, true);
|
||||
requireBytes(p, 0);
|
||||
while (p < data.length) {
|
||||
requireBytes(p, 4);
|
||||
const type = data[p]!;
|
||||
if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba) {
|
||||
if (data[p + 1] !== 0xba || data[p + 2] !== 0xa9 || data[p + 3] !== 0xba)
|
||||
throw new Error(`ehpk: bad record magic at ${p}`);
|
||||
}
|
||||
if (type === RECORD_FILE) {
|
||||
const compressedLength = view.getUint32(p + 4, true);
|
||||
const uncompressedLength = view.getUint32(p + 8, true);
|
||||
requireBytes(p, 16);
|
||||
const compressed = view.getUint32(p + 4, true), size = view.getUint32(p + 8, true);
|
||||
const nameLength = view.getUint16(p + 14, true);
|
||||
requireBytes(p + 16, nameLength + compressed);
|
||||
const name = utf8Decode(unxor(data, p + 16, nameLength));
|
||||
if (!safeEhpkPath(name)) throw new Error(`ehpk: invalid file path ${name}`);
|
||||
const blob = unxor(data, p + 16 + nameLength, compressedLength);
|
||||
const content = decompress(blob, new Uint8Array(uncompressedLength));
|
||||
if (content.length !== uncompressedLength) {
|
||||
throw new Error(`ehpk: ${name}: expected ${uncompressedLength} bytes, got ${content.length}`);
|
||||
}
|
||||
files.set(name, content);
|
||||
p += 16 + nameLength + compressedLength;
|
||||
records.set(name, { offset: p + 16 + nameLength, compressed, size });
|
||||
p += 16 + nameLength + compressed;
|
||||
} else if (type === RECORD_DIR) {
|
||||
const nameLength = view.getUint16(p + 6, true);
|
||||
p += 8 + nameLength;
|
||||
} else if (type === RECORD_FOOTER) {
|
||||
break;
|
||||
} else {
|
||||
throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`);
|
||||
}
|
||||
requireBytes(p, 8);
|
||||
const length = view.getUint16(p + 6, true);
|
||||
requireBytes(p + 8, length); p += 8 + length;
|
||||
} else if (type === RECORD_FOOTER) break;
|
||||
else throw new Error(`ehpk: unknown record type 0x${type.toString(16)} at ${p}`);
|
||||
}
|
||||
return { files: {
|
||||
keys: () => records.keys(),
|
||||
has: (name: string) => records.has(name),
|
||||
get: (name: string): Uint8Array | undefined => {
|
||||
const record = records.get(name);
|
||||
if (!record) return undefined;
|
||||
const content = decompress(unxor(data, record.offset, record.compressed), new Uint8Array(record.size));
|
||||
if (content.length !== record.size) throw new Error(`ehpk: ${name}: expected ${record.size} bytes, got ${content.length}`);
|
||||
return content;
|
||||
},
|
||||
} };
|
||||
}
|
||||
export type EhpkIndex = ReturnType<typeof openEhpk>;
|
||||
|
||||
export function parseEhpk(data: Uint8Array): EhpkArchive {
|
||||
const index = openEhpk(data), files = new Map<string, Uint8Array>();
|
||||
for (const name of index.files.keys()) files.set(name, index.files.get(name)!);
|
||||
return { files };
|
||||
}
|
||||
|
||||
|
||||
@@ -5,16 +5,17 @@
|
||||
* it only discovers and downloads public .ehpk packages. Authentication is
|
||||
* the same signed-header scheme used by the firmware API.
|
||||
*/
|
||||
import { Application } from "@nativescript/core";
|
||||
import { hmacSha256Base64, getPhoneOpenUdid } from "./even-platform";
|
||||
export { getPhoneOpenUdid } from "./even-platform";
|
||||
import {
|
||||
getEvenHubToken,
|
||||
hasEvenHubCredentials,
|
||||
invalidateEvenHubToken,
|
||||
saveEvenHubSession,
|
||||
} from "./credentials";
|
||||
import { downloadBinary } from "../../native/binary-http";
|
||||
import { fetchWithUserAgent } from "../../util/http";
|
||||
|
||||
declare const android: any;
|
||||
|
||||
const API_HOST = "https://api.evenrealities.com";
|
||||
const PUBLIC_CDN_HOST = "https://cdn-pub.evenhub.evenrealities.com";
|
||||
@@ -128,9 +129,9 @@ export class EvenHubApiClient {
|
||||
const url = typeof metadata.url === "string" ? metadata.url : "";
|
||||
if (!url.startsWith("https://")) throw new Error("EvenHub returned no package download URL.");
|
||||
|
||||
const response = await fetchWithTimeout(url, {}, 60_000);
|
||||
if (!response.ok) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
const response = await downloadBinary(url, 60_000);
|
||||
if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub package download failed (HTTP ${response.status}).`);
|
||||
const bytes = response.bytes;
|
||||
const expectedSize = finiteNumber(metadata.size);
|
||||
if (expectedSize > 0 && bytes.length !== expectedSize) {
|
||||
throw new Error(`EvenHub package was truncated (${bytes.length} of ${expectedSize} bytes).`);
|
||||
@@ -156,11 +157,11 @@ export class EvenHubApiClient {
|
||||
if (!/^prod\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+\.(?:svg|png|webp|jpe?g)$/i.test(cleanPath) || cleanPath.includes("..")) {
|
||||
throw new Error("EvenHub returned an invalid public asset path.");
|
||||
}
|
||||
const response = await fetchWithTimeout(`${PUBLIC_CDN_HOST}/${cleanPath}`, {}, 30_000);
|
||||
if (!response.ok) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`);
|
||||
const contentLength = Number(response.headers.get("Content-Length") ?? 0);
|
||||
const response = await downloadBinary(`${PUBLIC_CDN_HOST}/${cleanPath}`, 30_000);
|
||||
if (response.status < 200 || response.status >= 300) throw new Error(`EvenHub icon download failed (HTTP ${response.status}).`);
|
||||
const contentLength = response.contentLength;
|
||||
if (contentLength > 1_000_000) throw new Error("EvenHub icon is unexpectedly large.");
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
const bytes = response.bytes;
|
||||
if (bytes.length === 0 || bytes.length > 1_000_000) throw new Error("EvenHub icon is empty or too large.");
|
||||
const extension = cleanPath.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? "";
|
||||
return { bytes, extension: extension === "jpeg" ? "jpg" : extension };
|
||||
@@ -287,9 +288,9 @@ function buildCommon(version: 1 | 3): string {
|
||||
buildTime: "26060821",
|
||||
appId: "1001",
|
||||
v: version,
|
||||
// This is Android's app-scoped SSAID. Even's login endpoint registers a
|
||||
// previously unseen value as a terminal, so Faceclaw does not need the
|
||||
// official Even app's differently-scoped ID.
|
||||
// Keep the established wire profile on both platforms. Even registers
|
||||
// this installation-scoped terminal ID at login (SSAID on Android,
|
||||
// a persisted random ID on iOS).
|
||||
openUdid: getPhoneOpenUdid(),
|
||||
os: "1",
|
||||
sn: "",
|
||||
@@ -333,13 +334,7 @@ function formEncode(value: string): string {
|
||||
}
|
||||
|
||||
function hmacSign(message: string): string {
|
||||
if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android.");
|
||||
const charset = java.nio.charset.StandardCharsets.UTF_8;
|
||||
const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(SIGN_KEY).getBytes(charset), "HmacSHA256");
|
||||
const mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(key);
|
||||
const digest = mac.doFinal(new java.lang.String(message).getBytes(charset));
|
||||
return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP));
|
||||
return hmacSha256Base64(SIGN_KEY, message);
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQUEST_TIMEOUT_MS): Promise<Response> {
|
||||
@@ -368,17 +363,6 @@ function unwrap(envelope: ApiEnvelope, httpStatus: number, path: string): unknow
|
||||
return envelope.data;
|
||||
}
|
||||
|
||||
/** Return this installation's Android ID, which Even calls `openUdid`. */
|
||||
export function getPhoneOpenUdid(): string {
|
||||
if (!global.isAndroid) throw new Error("The EvenHub storefront is currently available only on Android.");
|
||||
const resolver = Application.android.context?.getContentResolver();
|
||||
const openUdid = resolver
|
||||
? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "")
|
||||
: "";
|
||||
if (!openUdid) throw new Error("Android did not provide a device ID for EvenHub authentication.");
|
||||
return openUdid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a list response. The leaderboard returns `{list, total, page,
|
||||
* page_size}`; the ranking/search endpoints were only recovered from the
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
declare const FaceclawCrypto: any;
|
||||
|
||||
export function hmacSha256Base64(secret: string, message: string): string {
|
||||
return FaceclawCrypto.hmacSha256Message(secret, message);
|
||||
}
|
||||
|
||||
/** A stable random terminal ID, independent of phone hardware identifiers. */
|
||||
export function getPhoneOpenUdid(): string {
|
||||
const key = "integrations.evenhub.terminalId";
|
||||
let id = getStringSetting(key, "");
|
||||
if (!id) {
|
||||
id = NSUUID.UUID().UUIDString.replace(/-/g, "").slice(0, 16).toLowerCase();
|
||||
setStringSetting(key, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Application } from "@nativescript/core";
|
||||
|
||||
export function hmacSha256Base64(secret: string, message: string): string {
|
||||
const charset = java.nio.charset.StandardCharsets.UTF_8;
|
||||
const key = new javax.crypto.spec.SecretKeySpec(new java.lang.String(secret).getBytes(charset), "HmacSHA256");
|
||||
const mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(key);
|
||||
const digest = mac.doFinal(new java.lang.String(message).getBytes(charset));
|
||||
return String(android.util.Base64.encodeToString(digest, android.util.Base64.NO_WRAP));
|
||||
}
|
||||
|
||||
export function getPhoneOpenUdid(): string {
|
||||
const resolver = Application.android.context?.getContentResolver();
|
||||
const id = resolver ? String(android.provider.Settings.Secure.getString(resolver, android.provider.Settings.Secure.ANDROID_ID) ?? "") : "";
|
||||
if (!id) throw new Error("Android did not provide a device ID for EvenHub authentication.");
|
||||
return id;
|
||||
}
|
||||
@@ -13,10 +13,10 @@ import {
|
||||
writeBinaryFile,
|
||||
} from "../../native/file-access";
|
||||
import { getStringSetting, setStringSetting } from "../../native/settings-store";
|
||||
import { loadImageFileAsGray } from "../../native/image-files";
|
||||
import { loadIconImage } from "../../native/icon-image";
|
||||
import { renderSvgIcon } from "../../graphics/icons";
|
||||
import { type GrayImage } from "../../graphics/image";
|
||||
import { parseEhpk, parseManifest, utf8Decode, type EhpkArchive, type EvenHubManifest } from "./ehpk";
|
||||
import { openEhpk, parseManifest, utf8Decode, type EhpkIndex, type EvenHubManifest } from "./ehpk";
|
||||
|
||||
const STORAGE_KEY = "evenhub.installedApps.v1";
|
||||
const APP_ID_PREFIX = "evenhub-installed:";
|
||||
@@ -209,7 +209,7 @@ export function renderInstalledEvenHubIcon(
|
||||
const svg = readTextFile(path);
|
||||
if (svg) image = renderSvgIcon(cacheKey, svg, size);
|
||||
} else {
|
||||
image = loadImageFileAsGray(path, size, size);
|
||||
image = loadIconImage(path, size, size);
|
||||
}
|
||||
renderedIconCache.set(cacheKey, image);
|
||||
return image;
|
||||
@@ -220,8 +220,8 @@ export function getInstalledEvenHubFingerprint(): string {
|
||||
return getStringSetting(STORAGE_KEY, "");
|
||||
}
|
||||
|
||||
function inspectEhpk(bytes: Uint8Array): { archive: EhpkArchive; manifest: EvenHubManifest } {
|
||||
const archive = parseEhpk(bytes);
|
||||
function inspectEhpk(bytes: Uint8Array): { archive: EhpkIndex; manifest: EvenHubManifest } {
|
||||
const archive = openEhpk(bytes);
|
||||
const appJson = archive.files.get("app.json");
|
||||
if (!appJson) throw new Error("The EHPK package has no app.json manifest.");
|
||||
return { archive, manifest: parseManifest(utf8Decode(appJson)) };
|
||||
@@ -242,7 +242,7 @@ function saveInstalledApps(apps: InstalledEvenHubApp[]): void {
|
||||
);
|
||||
}
|
||||
|
||||
function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): EvenHubInstallIcon | null {
|
||||
function findEmbeddedIcon(archive: EhpkIndex, manifest: EvenHubManifest): EvenHubInstallIcon | null {
|
||||
const candidates: string[] = [];
|
||||
for (const key of ["icon", "icon_path", "iconPath", "app_icon", "appIcon"]) {
|
||||
const value = manifest.raw[key];
|
||||
@@ -270,11 +270,11 @@ function findEmbeddedIcon(archive: EhpkArchive, manifest: EvenHubManifest): Even
|
||||
if (content && extension) return { bytes: content, extension };
|
||||
}
|
||||
}
|
||||
const fallback = Array.from(archive.files.entries()).find(([path]) =>
|
||||
const fallback = Array.from(archive.files.keys()).find((path) =>
|
||||
/(?:^|\/)(?:app-?)?(?:icon|favicon)\.(?:svg|png|webp|jpe?g)$/i.test(path),
|
||||
);
|
||||
const extension = fallback ? iconExtension(fallback[0]) : null;
|
||||
return fallback && extension ? { bytes: fallback[1], extension } : null;
|
||||
const extension = fallback ? iconExtension(fallback) : null;
|
||||
return fallback && extension ? { bytes: archive.files.get(fallback)!, extension } : null;
|
||||
}
|
||||
|
||||
function normalizeInstallIcon(icon: EvenHubInstallIcon | undefined): EvenHubInstallIcon | null {
|
||||
|
||||
+14
-26
@@ -15,16 +15,16 @@ import { type AppContext } from "../app-definition";
|
||||
import {
|
||||
appFilesDirPath,
|
||||
deletePathRecursively,
|
||||
readBinaryFile,
|
||||
writeBinaryFile,
|
||||
} from "../../native/file-access";
|
||||
import { parseEhpk, parseManifest, utf8Decode, type EvenHubManifest } from "./ehpk";
|
||||
import { type EvenHubManifest } from "./ehpk";
|
||||
import { unpackRuntime } from "./unpack-runtime";
|
||||
import { type EvenHubPermission } from "./permissions";
|
||||
import { EvenHubSession } from "./session";
|
||||
import { createEvenHubWindow } from "./evenhub-window";
|
||||
import { createEvenHubWebView, type EvenHubWebView } from "./webview";
|
||||
import { shell } from "../../ui/shell/shell";
|
||||
import {
|
||||
readEvenHubPackageManifest,
|
||||
installedEvenHubAppId,
|
||||
installedEvenHubPackagePath,
|
||||
type InstalledEvenHubApp,
|
||||
@@ -64,17 +64,6 @@ export async function launchPackage(
|
||||
ehpkPath: string,
|
||||
options: { appId?: string; singleton?: boolean } = {},
|
||||
): Promise<void> {
|
||||
const data = readBinaryFile(ehpkPath);
|
||||
if (!data) {
|
||||
throw new Error('Could not read the EHPK file.');
|
||||
}
|
||||
const archive = parseEhpk(data);
|
||||
const appJson = archive.files.get("app.json");
|
||||
if (!appJson) {
|
||||
throw new Error('The EHPK package has no app.json.');
|
||||
}
|
||||
const manifest = parseManifest(utf8Decode(appJson));
|
||||
if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.');
|
||||
const appId = options.appId ?? "evenhub";
|
||||
if (options.singleton) {
|
||||
const existing = Array.from(running.values()).find((app) => app.appId === appId);
|
||||
@@ -85,20 +74,19 @@ export async function launchPackage(
|
||||
}
|
||||
}
|
||||
|
||||
// Unpack fresh into app-private storage, keyed by package id.
|
||||
const manifest = readEvenHubPackageManifest(ehpkPath);
|
||||
if (!manifest) throw new Error('Could not read the EHPK manifest.');
|
||||
// Unpack off the iOS UI thread; reserve a unique directory before awaiting.
|
||||
const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_");
|
||||
if (!safeId || safeId === '.' || safeId === '..') throw new Error('Invalid EHPK package ID');
|
||||
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial}` : ''}`;
|
||||
deletePathRecursively(baseDir);
|
||||
for (const [name, content] of Array.from(archive.files)) {
|
||||
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
|
||||
deletePathRecursively(baseDir);
|
||||
throw new Error(`Could not unpack ${name}.`);
|
||||
}
|
||||
}
|
||||
|
||||
try { await startApp(ctx, manifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined); }
|
||||
catch (error) { deletePathRecursively(baseDir); throw error; }
|
||||
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial++}` : ''}`;
|
||||
const started = Date.now();
|
||||
ctx.appendLog(`evenhub: unpacking ${manifest.name}`);
|
||||
try {
|
||||
const loadedManifest = await unpackRuntime(ehpkPath, baseDir);
|
||||
ctx.appendLog(`evenhub: unpacked ${loadedManifest.name} in ${Date.now() - started} ms`);
|
||||
await startApp(ctx, loadedManifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined);
|
||||
} catch (error) { deletePathRecursively(baseDir); throw error; }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { deletePathRecursively, readBinaryFile, writeBinaryFile } from '../../native/file-access';
|
||||
import { openEhpk, parseManifest, utf8Decode, type EvenHubManifest } from './ehpk';
|
||||
|
||||
/** Called on a worker on iOS. Hold only one expanded asset at a time. */
|
||||
export function extractPackage(path: string, directory: string): EvenHubManifest {
|
||||
try {
|
||||
const bytes = readBinaryFile(path);
|
||||
if (!bytes) throw new Error('Could not read the EHPK file.');
|
||||
const archive = openEhpk(bytes);
|
||||
const json = archive.files.get('app.json');
|
||||
if (!json) throw new Error('The EHPK package has no app.json.');
|
||||
const manifest = parseManifest(utf8Decode(json));
|
||||
if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.');
|
||||
deletePathRecursively(directory);
|
||||
for (const name of archive.files.keys()) {
|
||||
if (!writeBinaryFile(`${directory}/${name}`, archive.files.get(name)!)) throw new Error(`Could not unpack ${name}.`);
|
||||
}
|
||||
return manifest;
|
||||
} catch (error) { deletePathRecursively(directory); throw error; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import '@nativescript/core/globals';
|
||||
import { extractPackage } from './package-extraction';
|
||||
|
||||
global.onmessage = (event: { data: { path: string; directory: string } }) => {
|
||||
try {
|
||||
const manifest = extractPackage(event.data.path, event.data.directory);
|
||||
global.postMessage({ manifest });
|
||||
} catch (error) { global.postMessage({ error: String((error as Error)?.message ?? error) }); }
|
||||
};
|
||||
@@ -61,7 +61,7 @@ import { type ImuReading } from "../../native/imu";
|
||||
import { toolRegistry, type ToolResult, type ToolSpec } from "../../assistant/tool-registry";
|
||||
import { getCurrentLocation } from "../../native/location";
|
||||
import { LocationTracker, type TrackedLocation } from "../../native/location-tracker";
|
||||
import { ensureFineLocationPermission } from "../../g2/android-permissions";
|
||||
import { ensureFineLocationPermission } from "../../native/location-permissions";
|
||||
|
||||
const UPNG = require("upng-js");
|
||||
|
||||
@@ -642,7 +642,6 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
|
||||
/** getAppLocation(): one-shot fix, or null on denial/error (SDK contract). */
|
||||
private async getAppLocation(): Promise<AppLocation | null> {
|
||||
if (global.isIOS) return null;
|
||||
if (!this.declaresLocation()) return null;
|
||||
if (!(await ensureFineLocationPermission())) return null;
|
||||
try {
|
||||
@@ -666,7 +665,6 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
|
||||
* Navigate app's foreground-service-backed tracking.
|
||||
*/
|
||||
private async startLocationUpdates(data: Record<string, unknown>): Promise<boolean> {
|
||||
if (global.isIOS) return false;
|
||||
if (!this.declaresLocation()) return false;
|
||||
if (!(await ensureFineLocationPermission())) return false;
|
||||
if (this.closed) return false;
|
||||
|
||||
@@ -133,24 +133,36 @@ export class EvenHubStoreDetailLayer implements Layer {
|
||||
}
|
||||
if (event.type !== "click") return;
|
||||
|
||||
await this.ensureDetail(ctx);
|
||||
// Never hold the serialized input queue across network work or a dialog
|
||||
// that needs a subsequent input to resolve.
|
||||
void this.activate(ctx);
|
||||
}
|
||||
|
||||
if (this.selectedIndex === 0) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About"));
|
||||
return;
|
||||
}
|
||||
if (this.selectedIndex === 1) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New"));
|
||||
return;
|
||||
}
|
||||
private async activate(ctx: LayerContext): Promise<void> {
|
||||
this.working = true;
|
||||
try {
|
||||
await this.ensureDetail(ctx);
|
||||
|
||||
const installed = getInstalledEvenHubApp(this.app.packageId);
|
||||
if (installed && this.primaryActionLabel(installed) === "Launch") {
|
||||
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
|
||||
return;
|
||||
}
|
||||
if (this.selectedIndex === 0) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.description || "No description supplied.", "About"));
|
||||
return;
|
||||
}
|
||||
if (this.selectedIndex === 1) {
|
||||
ctx.stack.push(new TextViewerLayer(this.app.changelog || "No release notes supplied.", "What's New"));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.install(ctx);
|
||||
const installed = getInstalledEvenHubApp(this.app.packageId);
|
||||
if (installed && this.primaryActionLabel(installed) === "Launch") {
|
||||
await this.options.launchApp(installedEvenHubAppId(installed.packageId));
|
||||
return;
|
||||
}
|
||||
|
||||
await this.install(ctx);
|
||||
} catch (error) {
|
||||
this.status = cleanError(error);
|
||||
this.options.appendLog(`evenhub store: ${this.status}`);
|
||||
} finally { this.working = false; ctx.actions.requestRender(); }
|
||||
}
|
||||
|
||||
/** Install for a new app; Update / Reinstall when the installed copy is stale or gone. */
|
||||
|
||||
@@ -674,6 +674,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
void this.submitCredentials(ctx);
|
||||
},
|
||||
{ setting: evenHubRememberMeSetting, label: "Remember me" },
|
||||
() => { this.phoneEditor = "none"; clearEvenHubLoginForm(); },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -684,7 +685,7 @@ export class EvenHubStoreLayer implements Layer {
|
||||
this.phoneEditor = "none";
|
||||
if (this.closed) return;
|
||||
void this.runSearch(ctx, evenHubSearchQuerySetting.get());
|
||||
});
|
||||
}, undefined, () => { this.phoneEditor = "none"; });
|
||||
}
|
||||
|
||||
/** Close the phone editor if one is open (optionally only a given kind). */
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { EvenHubManifest } from './ehpk';
|
||||
|
||||
/** Paths and a small manifest cross isolates; package bytes never become JSON. */
|
||||
export function unpackRuntime(path: string, directory: string): Promise<EvenHubManifest> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker('./package-extraction.worker');
|
||||
let settled = false;
|
||||
const finish = (error?: string, manifest?: EvenHubManifest) => {
|
||||
if (settled) return;
|
||||
settled = true; clearTimeout(timeout); worker.terminate();
|
||||
if (error) reject(new Error(error));
|
||||
else if (manifest) resolve(manifest);
|
||||
else reject(new Error('The package worker returned no manifest.'));
|
||||
};
|
||||
const timeout = setTimeout(() => finish('Unpacking the EvenHub app timed out.'), 180_000);
|
||||
worker.onmessage = (event: MessageEvent) => finish(event.data.error, event.data.manifest);
|
||||
worker.onerror = event => { finish(String(event.message ?? event)); return true; };
|
||||
try { worker.postMessage({ path, directory }); }
|
||||
catch (error) { finish(String(error)); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { extractPackage } from './package-extraction';
|
||||
import type { EvenHubManifest } from './ehpk';
|
||||
export async function unpackRuntime(path: string, directory: string): Promise<EvenHubManifest> {
|
||||
return extractPackage(path, directory);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ window.__faceclawEvenHub = { postMessage: function(name, args, id) {
|
||||
`
|
||||
|
||||
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
|
||||
if (session.remoteUrl) throw new Error('On iOS, open a local .ehpk package from Files.')
|
||||
const host = FaceclawEvenHubWebView.new()
|
||||
host.packageIdentifier = session.manifest.packageId
|
||||
host.eventHandler = (json: string) => {
|
||||
@@ -35,8 +34,11 @@ export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
|
||||
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
|
||||
}
|
||||
// Defer loading until manager.ts has attached the session/window handles.
|
||||
const loading = setTimeout(() => host.startEntrypointScript(session.distDir, session.manifest.entrypoint,
|
||||
IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)), 0)
|
||||
const script = IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)
|
||||
const loading = setTimeout(() => {
|
||||
if (session.remoteUrl) host.startURLScript(session.remoteUrl, script)
|
||||
else host.startEntrypointScript(session.distDir, session.manifest.entrypoint, script)
|
||||
}, 0)
|
||||
return { native: host, evaluateJs: js => host.evaluate(js),
|
||||
destroy: () => { clearTimeout(loading); host.destroy() },
|
||||
showOnPhone: () => host.showOnPhone(), hideOnPhone: () => host.hideOnPhone() }
|
||||
|
||||
@@ -210,7 +210,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
|
||||
},
|
||||
},
|
||||
];
|
||||
return global.isIOS ? actions.slice(0, 1) : actions;
|
||||
return actions;
|
||||
}
|
||||
if (isDecodableImageFile(entry.name)) {
|
||||
return [
|
||||
|
||||
@@ -5,7 +5,6 @@ const unavailable: Record<string, string> = {
|
||||
transcribe: 'Voice capture and transcription are not available on iOS yet.',
|
||||
microphones: 'Glasses microphone capture is not available on iOS yet.',
|
||||
calendar: 'Calendar access is not available on iOS yet.',
|
||||
evenhub: 'Open a local .ehpk file in Files to run an EvenHub app. The EvenHub store is not available on iOS yet.',
|
||||
}
|
||||
export function iosAppUnavailableReason(appId: string): string | null {
|
||||
return unavailable[appId] ?? null
|
||||
|
||||
+23
-18
@@ -7,6 +7,28 @@ import {
|
||||
renderInstalledEvenHubIcon,
|
||||
} from "../evenhub/installed-apps";
|
||||
|
||||
/** Shared built-in and installed-app listing for both phone hosts. */
|
||||
export function launcherEntries(apps: readonly AppDefinition[]) {
|
||||
return [
|
||||
...apps
|
||||
.filter((app) => app.showInLauncher !== false)
|
||||
.map((app) => ({
|
||||
appId: app.appId,
|
||||
label: app.title,
|
||||
icon: app.icon,
|
||||
renderIcon: app.renderIcon,
|
||||
})),
|
||||
...getInstalledEvenHubApps().map((app) => ({
|
||||
appId: installedEvenHubAppId(app.packageId),
|
||||
label: app.name,
|
||||
icon: "package" as const,
|
||||
renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app),
|
||||
iconKey: `${app.installedAt}:${app.iconFile ?? ""}`,
|
||||
uninstallable: true,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
const launcherApp: AppDefinition = {
|
||||
appId: "launcher",
|
||||
title: "Apps",
|
||||
@@ -22,24 +44,7 @@ const launcherApp: AppDefinition = {
|
||||
...ctx.actions,
|
||||
requestRender: () => shell.foregroundWindow()?.requestRender(),
|
||||
},
|
||||
apps: () => [
|
||||
...ctx.apps
|
||||
.filter((app) => app.showInLauncher !== false)
|
||||
.map((app) => ({
|
||||
appId: app.appId,
|
||||
label: app.title,
|
||||
icon: app.icon,
|
||||
renderIcon: app.renderIcon,
|
||||
})),
|
||||
...getInstalledEvenHubApps().map((app) => ({
|
||||
appId: installedEvenHubAppId(app.packageId),
|
||||
label: app.name,
|
||||
icon: "package" as const,
|
||||
renderIcon: (size: number) => renderInstalledEvenHubIcon(app.packageId, size, app),
|
||||
iconKey: `${app.installedAt}:${app.iconFile ?? ""}`,
|
||||
uninstallable: true,
|
||||
})),
|
||||
],
|
||||
apps: () => launcherEntries(ctx.apps),
|
||||
launchApp: (appId) => ctx.launchApp(appId),
|
||||
uninstallApp: (appId) => ctx.uninstallApp(appId),
|
||||
submitFrame: (planes, paintMs, frameId) => ctx.submitWindowFrame(LAUNCHER_SURFACE_ID, planes, paintMs, frameId),
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import { launcherEntries } from '../apps/launcher'
|
||||
import { getInstalledEvenHubAppById, installedEvenHubPackageId, uninstallEvenHubPackage } from '../apps/evenhub/installed-apps'
|
||||
import { isInstalledPackagePresent } from '../apps/evenhub/updates'
|
||||
import { openEvenHubStoreForPackage } from '../apps/evenhub'
|
||||
import { launchInstalledPackage, closeRunningPackage } from '../apps/evenhub/manager'
|
||||
import { registerSystemTools } from '../assistant/system-tools'
|
||||
import { registerWindowTools } from '../assistant/window-tools'
|
||||
import { registerNavigateTools } from '../assistant/navigate-tools'
|
||||
@@ -91,9 +96,14 @@ export class IosPreviewController {
|
||||
startVoiceCapture: () => this.startVoiceCapture(),
|
||||
stopVoiceCapture: () => iosVoiceInput.stopPushToTalk(),
|
||||
startContinuousVoiceCapture: () => this.onError("Voice capture is not available on iOS yet."),
|
||||
startTextSettingEdit: setting => this.editSetting(setting),
|
||||
startTextSettingsEdit: async (settings, _title, finished) => {
|
||||
for (const setting of settings) await this.editSetting(setting)
|
||||
startTextSettingEdit: async setting => { await this.editSetting(setting) },
|
||||
startTextSettingsEdit: async (settings, title, finished, toggle, cancelled) => {
|
||||
for (const setting of settings) if (!await this.editSetting(setting)) { cancelled?.(); return }
|
||||
if (toggle) {
|
||||
const choice = await Dialogs.action({ title, cancelButtonText: 'Cancel', actions: [toggle.label, 'This session only'] })
|
||||
if (choice === 'Cancel') { cancelled?.(); return }
|
||||
toggle.setting.set(choice === toggle.label)
|
||||
}
|
||||
finished?.()
|
||||
},
|
||||
}
|
||||
@@ -116,11 +126,9 @@ export class IosPreviewController {
|
||||
})
|
||||
const launcher = createLauncherWindow({
|
||||
actions: this.actions,
|
||||
apps: () => ALL_APPS.filter(app => app.showInLauncher !== false).map(app => ({
|
||||
appId: app.appId, label: app.title, icon: app.icon, renderIcon: app.renderIcon,
|
||||
})),
|
||||
apps: () => launcherEntries(ALL_APPS),
|
||||
launchApp: id => this.launchApp(id),
|
||||
uninstallApp: () => {},
|
||||
uninstallApp: id => this.uninstallApp(id),
|
||||
submitFrame: planes => this.submit(LAUNCHER_SURFACE_ID, planes),
|
||||
setSurfaceVisible: visible => { this.compositor.setSurfaceVisible(LAUNCHER_SURFACE_ID, visible); this.scheduleFrame() },
|
||||
})
|
||||
@@ -293,7 +301,19 @@ export class IosPreviewController {
|
||||
}
|
||||
async launchApp(id: string, params?: AppLaunchParams): Promise<void> {
|
||||
const app = ALL_APPS.find(app => app.appId === id)
|
||||
if (!app) return
|
||||
if (!app) {
|
||||
const installed = getInstalledEvenHubAppById(id)
|
||||
const host = ALL_APPS.find(app => app.appId === 'evenhub')
|
||||
if (installed && host) {
|
||||
try {
|
||||
if (isInstalledPackagePresent(installed.packageId))
|
||||
await launchInstalledPackage(this.buildAppContext({ ...host, appId: id }), installed)
|
||||
else await openEvenHubStoreForPackage(this.buildAppContext(host), installed)
|
||||
}
|
||||
catch (error) { this.fail(error) }
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
const reason = iosAppUnavailableReason(id)
|
||||
if (reason) {
|
||||
@@ -306,10 +326,17 @@ export class IosPreviewController {
|
||||
console.log(`[ios-preview] Launched ${id}`)
|
||||
} catch (error) { this.fail(error) }
|
||||
}
|
||||
private async uninstallApp(id: string): Promise<void> {
|
||||
const packageId = installedEvenHubPackageId(id)
|
||||
if (!packageId) return
|
||||
closeRunningPackage(packageId)
|
||||
uninstallEvenHubPackage(packageId)
|
||||
this.requestShellRender()
|
||||
}
|
||||
private buildAppContext(app: AppDefinition): AppContext {
|
||||
return {
|
||||
appId: app.appId, apps: ALL_APPS, actions: this.actions,
|
||||
launchApp: (id, params) => this.launchApp(id, params), uninstallApp: async () => {},
|
||||
launchApp: (id, params) => this.launchApp(id, params), uninstallApp: id => this.uninstallApp(id),
|
||||
launchInProcessApp: (id, surface, create) => this.launchInProcessApp(id, surface, create),
|
||||
ensureWorkerHost: create => this.ensureWorkerHost(app.appId, create),
|
||||
submitWindowFrame: (id, planes) => this.submit(id, planes),
|
||||
@@ -441,12 +468,13 @@ export class IosPreviewController {
|
||||
} catch (error) { this.fail(error) }
|
||||
finally { this.prompting = false }
|
||||
}
|
||||
private async editSetting(setting: { editorTitle: string; get(): string; set(value: string): void }): Promise<void> {
|
||||
if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return }
|
||||
const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), okButtonText: 'Save', cancelButtonText: 'Cancel' })
|
||||
private async editSetting(setting: { editorTitle: string; inputKind?: string; get(): string; set(value: string): void }): Promise<boolean> {
|
||||
if (!this.active) { this.logBluetooth('Editing text settings requires opening Faceclaw on the phone'); return false }
|
||||
const result = await Dialogs.prompt({ title: setting.editorTitle, defaultText: setting.get(), inputType: setting.inputKind, okButtonText: 'Save', cancelButtonText: 'Cancel' })
|
||||
if (result.result) {
|
||||
setting.set(result.text)
|
||||
if (setting === nightscoutSiteUrlSetting || setting === nightscoutApiTokenSetting) await nightscoutBridge.refreshNow()
|
||||
}
|
||||
return result.result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Http } from '@nativescript/core';
|
||||
import { withUserAgent } from '../util/http';
|
||||
import type { BinaryResponse } from './binary-http';
|
||||
|
||||
/** Bulk NSData -> ArrayBuffer; bypass fetch's Blob/FileReader copies. */
|
||||
export async function downloadBinary(url: string, timeoutMs: number): Promise<BinaryResponse> {
|
||||
const response = await Http.request({ url, method: 'GET', headers: withUserAgent(), timeout: timeoutMs });
|
||||
const length = Object.entries(response.headers).find(([name]) => name.toLowerCase() === 'content-length')?.[1];
|
||||
return { status: response.statusCode, bytes: new Uint8Array(response.content.toArrayBuffer()), contentLength: Number(length ?? 0) };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { fetchWithUserAgent } from '../util/http';
|
||||
export type BinaryResponse = { status: number; bytes: Uint8Array; contentLength: number };
|
||||
export async function downloadBinary(url: string, timeoutMs: number): Promise<BinaryResponse> {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const request = async () => {
|
||||
const response = await fetchWithUserAgent(url);
|
||||
return { status: response.status, bytes: new Uint8Array(await response.arrayBuffer()),
|
||||
contentLength: Number(response.headers.get('Content-Length') ?? 0) };
|
||||
};
|
||||
try {
|
||||
return await Promise.race([request(), new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('Download timed out.')), timeoutMs);
|
||||
})]);
|
||||
} finally { clearTimeout(timer!); }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { grayImageFromPacket } from './image-files';
|
||||
import { fromData } from './kotlin-data';
|
||||
import type { GrayImage } from '../graphics/image';
|
||||
declare const FaceclawGraphics: any;
|
||||
|
||||
export function loadIconImage(path: string, maxWidth: number, maxHeight: number): GrayImage | null {
|
||||
const data = FaceclawGraphics.decodeImageFileMaxWidthMaxHeight(path, Math.round(maxWidth), Math.round(maxHeight));
|
||||
return data ? grayImageFromPacket(fromData(data)) : null;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { loadImageFileAsGray } from './image-files';
|
||||
/** UI artwork uses flat grayscale, preserving its source aspect ratio. */
|
||||
export const loadIconImage = loadImageFileAsGray;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Application, Button, Color, Dialogs, GridLayout, Image, Label, Page, StackLayout, type TouchGestureEventData } from '@nativescript/core'
|
||||
import { createConfigureDevicesPage } from './config-page.ios'
|
||||
import { launcherEntries } from '../apps/launcher'
|
||||
import { ALL_APPS } from '../apps/all-apps'
|
||||
import { IosPreviewController } from '../g2/ios-preview-controller'
|
||||
import { PhoneGestureRecognizer } from './phone-gestures'
|
||||
@@ -107,9 +108,9 @@ export function createMainPage(): Page {
|
||||
}
|
||||
const sizeButton = button(controller.displayModeLabel, () => controller.cycleDisplayMode())
|
||||
settings.addChild(button('Open app', () => { void (async () => {
|
||||
const apps = ALL_APPS.filter(app => app.showInLauncher !== false).slice().sort((a, b) => a.title.localeCompare(b.title))
|
||||
const title = await Dialogs.action({ title: 'Open app', cancelButtonText: 'Cancel', actions: apps.map(app => app.title) })
|
||||
const app = apps.find(app => app.title === title)
|
||||
const apps = launcherEntries(ALL_APPS).sort((a, b) => a.label.localeCompare(b.label))
|
||||
const title = await Dialogs.action({ title: 'Open app', cancelButtonText: 'Cancel', actions: apps.map(app => app.label) })
|
||||
const app = apps.find(app => app.label === title)
|
||||
if (app) { await controller.launchApp(app.appId); selectTab('watch') }
|
||||
})() }))
|
||||
settings.addChild(sizeButton)
|
||||
|
||||
@@ -20,6 +20,7 @@ export type LayerActions = {
|
||||
title: string,
|
||||
onFinish?: () => void,
|
||||
toggle?: TextSettingsEditToggle,
|
||||
onCancel?: () => void,
|
||||
) => Promise<void> | void;
|
||||
endTextSettingEdit: () => Promise<void> | void;
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user