@robono/messaging-react-native 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +157 -4
- package/RobonoMessagingRuntime.podspec +16 -0
- package/SBOM.spdx.json +2709 -813
- package/android/build.gradle +10 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/robono/messaging/RobonoBackupCrypto.java +27 -0
- package/android/src/main/java/com/robono/messaging/RobonoBackupGoogle.java +76 -0
- package/android/src/main/java/com/robono/messaging/RobonoHistoryStore.java +173 -0
- package/android/src/main/java/com/robono/messaging/RobonoMessagingPackage.java +11 -0
- package/app.plugin.cjs +22 -3
- package/cloudkit/backup-schema.ckdb +13 -0
- package/dist/account-pages.d.ts +51 -0
- package/dist/account-pages.js +65 -0
- package/dist/account.d.ts +6 -2
- package/dist/account.js +37 -11
- package/dist/attachment-preview.d.ts +11 -10
- package/dist/attachment-preview.js +15 -12
- package/dist/backup-background.d.ts +25 -0
- package/dist/backup-background.js +71 -0
- package/dist/backup-base64.d.ts +3 -0
- package/dist/backup-base64.js +41 -0
- package/dist/backup-google-authorization.d.ts +23 -0
- package/dist/backup-google-authorization.js +95 -0
- package/dist/backup.d.ts +24 -0
- package/dist/backup.js +202 -0
- package/dist/brand.js +4 -4
- package/dist/bubble-design.d.ts +1 -1
- package/dist/bubble-design.js +5 -3
- package/dist/cloudkit-backup.d.ts +14 -0
- package/dist/cloudkit-backup.js +193 -0
- package/dist/contact-directory.d.ts +3 -1
- package/dist/contact-directory.js +3 -3
- package/dist/conversation-details.js +2 -2
- package/dist/customization.d.ts +1 -0
- package/dist/delivery-bar.d.ts +3 -2
- package/dist/delivery-bar.js +7 -4
- package/dist/delivery-notice.d.ts +9 -0
- package/dist/delivery-notice.js +15 -0
- package/dist/directory-navigation.d.ts +25 -0
- package/dist/directory-navigation.js +69 -0
- package/dist/expo-backup-background.d.ts +17 -0
- package/dist/expo-backup-background.js +57 -0
- package/dist/expo-backup-cloudkit.d.ts +6 -0
- package/dist/expo-backup-cloudkit.js +11 -0
- package/dist/expo-backup-crypto.d.ts +3 -0
- package/dist/expo-backup-crypto.js +17 -0
- package/dist/expo-backup-google.d.ts +7 -0
- package/dist/expo-backup-google.js +16 -0
- package/dist/expo-backup-network.d.ts +8 -0
- package/dist/expo-backup-network.js +18 -0
- package/dist/expo-backup-passkeys.d.ts +14 -0
- package/dist/expo-backup-passkeys.js +46 -0
- package/dist/expo-backup-settings.d.ts +4 -0
- package/dist/expo-backup-settings.js +59 -0
- package/dist/expo-backup.d.ts +14 -0
- package/dist/expo-backup.js +22 -0
- package/dist/expo-bridge.d.ts +2 -0
- package/dist/expo-bridge.js +3 -1
- package/dist/expo-cache.js +20 -1
- package/dist/expo-device-history.d.ts +24 -0
- package/dist/expo-device-history.js +88 -0
- package/dist/expo-durable-history.d.ts +26 -0
- package/dist/expo-durable-history.js +56 -0
- package/dist/expo-history-backup.d.ts +3 -0
- package/dist/expo-history-backup.js +79 -0
- package/dist/expo-history-maintenance.d.ts +4 -0
- package/dist/expo-history-maintenance.js +23 -0
- package/dist/expo-history-previews.d.ts +5 -0
- package/dist/expo-history-previews.js +57 -0
- package/dist/expo-history.d.ts +1 -1
- package/dist/expo-history.js +2 -2
- package/dist/expo-inbox-preferences.d.ts +3 -0
- package/dist/expo-inbox-preferences.js +9 -0
- package/dist/expo-media.d.ts +2 -0
- package/dist/expo-media.js +18 -24
- package/dist/expo-messenger.d.ts +8 -0
- package/dist/expo-messenger.js +27 -11
- package/dist/expo-notifications.d.ts +17 -1
- package/dist/expo-notifications.js +36 -16
- package/dist/expo-outbox.d.ts +2 -0
- package/dist/expo-outbox.js +1 -1
- package/dist/expo-oversight.d.ts +15 -0
- package/dist/expo-oversight.js +15 -0
- package/dist/expo-reviews.d.ts +6 -0
- package/dist/expo-reviews.js +145 -0
- package/dist/expo-screen.js +62 -28
- package/dist/expo-thumbnails.d.ts +6 -2
- package/dist/expo-thumbnails.js +73 -8
- package/dist/expo.d.ts +14 -0
- package/dist/expo.js +12 -0
- package/dist/forward.js +2 -2
- package/dist/header-calls.js +1 -1
- package/dist/header-colors.d.ts +5 -0
- package/dist/header-colors.js +7 -0
- package/dist/inbox-search.d.ts +1 -1
- package/dist/inbox-search.js +7 -3
- package/dist/inbox.d.ts +6 -2
- package/dist/inbox.js +27 -55
- package/dist/index.d.ts +14 -6
- package/dist/index.js +195 -78
- package/dist/linked-apps.d.ts +45 -0
- package/dist/linked-apps.js +40 -0
- package/dist/loading-messages.d.ts +5 -0
- package/dist/loading-messages.js +10 -0
- package/dist/media-access.d.ts +8 -0
- package/dist/media-access.js +6 -1
- package/dist/media-controller.d.ts +2 -0
- package/dist/native-history-authorization.d.ts +4 -0
- package/dist/native-history-authorization.js +69 -0
- package/dist/native-history-backup.d.ts +16 -0
- package/dist/native-history-backup.js +144 -0
- package/dist/native-history.d.ts +14 -0
- package/dist/native-history.js +186 -0
- package/dist/native-outbox.d.ts +2 -0
- package/dist/oversight-session.d.ts +4 -0
- package/dist/oversight-session.js +14 -0
- package/dist/popup.d.ts +6 -3
- package/dist/popup.js +6 -6
- package/dist/preview-layout.d.ts +12 -0
- package/dist/preview-layout.js +102 -0
- package/dist/recent-media.js +2 -1
- package/dist/reviews.d.ts +19 -0
- package/dist/reviews.js +231 -0
- package/dist/scheduled.js +6 -6
- package/dist/search.js +18 -8
- package/ios/RobonoBackupCloudKit.m +96 -0
- package/ios/RobonoBackupCrypto.m +30 -0
- package/ios/RobonoHistoryStore.m +170 -0
- package/package.json +34 -7
- package/plugin/backup-expiration.cjs +23 -0
- package/plugin/prepare-native.cjs +12 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import * as Network from 'expo-network';
|
|
2
|
+
function classify(state) {
|
|
3
|
+
if (state.isConnected === false || state.isInternetReachable === false)
|
|
4
|
+
return 'offline';
|
|
5
|
+
if (state.type === Network.NetworkStateType.WIFI)
|
|
6
|
+
return 'wifi';
|
|
7
|
+
if (state.type === Network.NetworkStateType.CELLULAR)
|
|
8
|
+
return 'cellular';
|
|
9
|
+
// Unknown/VPN/wired interfaces cannot silently override Wi-Fi-only consent.
|
|
10
|
+
return 'unknown';
|
|
11
|
+
}
|
|
12
|
+
/** Network events cancel transfers when the user's current policy forbids them. */
|
|
13
|
+
export function createExpoMessagingBackupNetwork() {
|
|
14
|
+
return {
|
|
15
|
+
network: async () => classify(await Network.getNetworkStateAsync()),
|
|
16
|
+
subscribeNetwork(listener) { const subscription = Network.addNetworkStateListener(state => listener(classify(state))); return () => subscription.remove(); },
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type MessagingBackupPasskeys } from '@robono/messaging';
|
|
2
|
+
/** Requires react-native-passkey, iOS associated domains and Android Digital Asset
|
|
3
|
+
* Links for the same RP ID. Unsupported providers never fall back to weaker keys. */
|
|
4
|
+
export interface MessagingNativePasskeyDiagnostic {
|
|
5
|
+
operation: 'create' | 'get';
|
|
6
|
+
code: string;
|
|
7
|
+
nativeCode: number | null;
|
|
8
|
+
reason: 'domain-association' | 'request-format' | 'provider-unavailable' | 'cancelled' | 'other';
|
|
9
|
+
}
|
|
10
|
+
export declare function createExpoMessagingBackupPasskeys(options: {
|
|
11
|
+
rpId: string;
|
|
12
|
+
name: string;
|
|
13
|
+
onDiagnostic?: (diagnostic: MessagingNativePasskeyDiagnostic) => void;
|
|
14
|
+
}): MessagingBackupPasskeys;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { NativeModules, Platform } from 'react-native';
|
|
2
|
+
import { getRandomBytes } from 'expo-crypto';
|
|
3
|
+
import { backupUnbase64, createMessagingBackupPasskeys } from '@robono/messaging';
|
|
4
|
+
// react-native-passkey's iOS bridge decodes PRF inputs as byte dictionaries;
|
|
5
|
+
// Android accepts their base64url JSON representation. Keep the shared/web
|
|
6
|
+
// protocol unchanged and translate only at this native transport boundary.
|
|
7
|
+
function nativeRequest(request) {
|
|
8
|
+
return { ...request, extensions: { ...request.extensions, prf: { eval: { first: Platform.OS === 'ios' ? backupUnbase64(request.extensions.prf.eval.first) : request.extensions.prf.eval.first } } } };
|
|
9
|
+
}
|
|
10
|
+
export function createExpoMessagingBackupPasskeys(options) {
|
|
11
|
+
const load = async () => { try {
|
|
12
|
+
return (await import('react-native-passkey')).Passkey;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
} };
|
|
17
|
+
const invoke = async (operation, request) => {
|
|
18
|
+
try {
|
|
19
|
+
const passkey = await load();
|
|
20
|
+
if (!passkey)
|
|
21
|
+
throw { error: 'ModuleUnavailable' };
|
|
22
|
+
return operation === 'create' ? await passkey.create(nativeRequest(request)) : await passkey.get(nativeRequest(request));
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
const e = error;
|
|
26
|
+
const value = String(e?.error ?? e?.code ?? 'UnknownError'), message = String(e?.message ?? '');
|
|
27
|
+
const code = /^[A-Za-z ]{1,40}$/.test(value) ? value : 'UnknownError';
|
|
28
|
+
const number = message.match(/(?:error|code)\s*[:=]?\s*(-?\d{1,8})\b/i);
|
|
29
|
+
const reason = /associat|domain|rp id|relying party/i.test(message) ? 'domain-association' : /decod|format|data couldn.t be read|missing/i.test(message) ? 'request-format' : /provider|keychain|no credentials/i.test(message) ? 'provider-unavailable' : code === 'UserCancelled' ? 'cancelled' : 'other';
|
|
30
|
+
// Only bounded categorical metadata reaches host diagnostics, never the
|
|
31
|
+
// request, credential, salts, PRF result, account name or native message.
|
|
32
|
+
try {
|
|
33
|
+
options.onDiagnostic?.({ operation, code, nativeCode: number ? Number(number[1]) : null, reason });
|
|
34
|
+
}
|
|
35
|
+
catch { }
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
return createMessagingBackupPasskeys({ ...options, random: getRandomBytes, transport: {
|
|
40
|
+
async available() { if (!NativeModules.Passkey)
|
|
41
|
+
return false; if (Platform.OS === 'ios' && Number.parseInt(String(Platform.Version), 10) < 18)
|
|
42
|
+
return false; const passkey = await load(); return !!passkey?.isSupported(); },
|
|
43
|
+
create: request => invoke('create', request),
|
|
44
|
+
get: request => invoke('get', request),
|
|
45
|
+
} });
|
|
46
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { MessagingBackupLocalSettings } from '@robono/messaging';
|
|
2
|
+
/** Recovery keys stay in Keychain/Keystore. Preferences contain no credentials.
|
|
3
|
+
* The scope must be identical to the durable history's endpoint/tenant/account scope. */
|
|
4
|
+
export declare function createExpoMessagingBackupSettings(endpoint: string, userId: string, namespace?: string): MessagingBackupLocalSettings;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import * as FS from 'expo-file-system/legacy';
|
|
2
|
+
import * as SecureStore from 'expo-secure-store';
|
|
3
|
+
import { randomUUID } from 'expo-crypto';
|
|
4
|
+
import { storageDigest } from './expo-storage-digest.js';
|
|
5
|
+
/** Recovery keys stay in Keychain/Keystore. Preferences contain no credentials.
|
|
6
|
+
* The scope must be identical to the durable history's endpoint/tenant/account scope. */
|
|
7
|
+
export function createExpoMessagingBackupSettings(endpoint, userId, namespace = 'default') {
|
|
8
|
+
const scope = storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
|
|
9
|
+
// Preserve protection configured by earlier SDKs that hashed the raw URL.
|
|
10
|
+
const legacyScope = storageDigest(JSON.stringify([endpoint, namespace, userId]));
|
|
11
|
+
const scopes = async () => [...new Set(await Promise.all([scope, legacyScope]))];
|
|
12
|
+
const directory = async (value) => {
|
|
13
|
+
if (!FS.documentDirectory)
|
|
14
|
+
throw Error('Private backup settings are unavailable.');
|
|
15
|
+
return FS.documentDirectory + 'robono-backup-settings/' + (value ?? await scope) + '/';
|
|
16
|
+
};
|
|
17
|
+
const keyOptions = { keychainService: 'robono-messaging-backup', keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY };
|
|
18
|
+
const secret = async (prefix) => { for (const value of await scopes()) {
|
|
19
|
+
const raw = await SecureStore.getItemAsync(prefix + value, keyOptions);
|
|
20
|
+
if (raw !== null)
|
|
21
|
+
return raw;
|
|
22
|
+
} return null; };
|
|
23
|
+
const readEncryption = async () => { const raw = await secret('encryption-'); return raw ? JSON.parse(raw) : null; };
|
|
24
|
+
let pending = Promise.resolve();
|
|
25
|
+
return {
|
|
26
|
+
async readPreferences() { await pending.catch(() => { }); for (const value of await scopes()) {
|
|
27
|
+
const file = await directory(value) + 'preferences.json';
|
|
28
|
+
const info = await FS.getInfoAsync(file);
|
|
29
|
+
if (!info.exists)
|
|
30
|
+
continue;
|
|
31
|
+
if (info.isDirectory || info.size > 4096)
|
|
32
|
+
throw Error('Backup settings could not be read.');
|
|
33
|
+
return JSON.parse(await FS.readAsStringAsync(file));
|
|
34
|
+
} return null; },
|
|
35
|
+
writePreferences(value) {
|
|
36
|
+
const work = pending.catch(() => { }).then(async () => {
|
|
37
|
+
const dir = await directory(), temp = dir + randomUUID() + '.tmp';
|
|
38
|
+
await FS.makeDirectoryAsync(dir, { intermediates: true });
|
|
39
|
+
try {
|
|
40
|
+
await FS.writeAsStringAsync(temp, JSON.stringify(value));
|
|
41
|
+
await FS.moveAsync({ from: temp, to: dir + 'preferences.json' });
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await FS.deleteAsync(temp, { idempotent: true }).catch(() => { });
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
pending = work;
|
|
48
|
+
return work;
|
|
49
|
+
},
|
|
50
|
+
readEncryption,
|
|
51
|
+
async readCloudAccount() { const raw = await secret('cloud-account-'); if (!raw)
|
|
52
|
+
return null; const value = JSON.parse(raw); if (typeof value?.id !== 'string' || !value.id || value.id.length > 1024 || !['google', 'icloud', 'custom'].includes(value.provider))
|
|
53
|
+
throw Error('Backup account settings could not be read.'); return { id: value.id, provider: value.provider }; },
|
|
54
|
+
async writeCloudAccount(value) { await SecureStore.setItemAsync('cloud-account-' + await scope, JSON.stringify({ id: value.id, provider: value.provider }), keyOptions); },
|
|
55
|
+
async writeEncryption(value) { await SecureStore.setItemAsync('encryption-' + await scope, JSON.stringify(value), keyOptions); },
|
|
56
|
+
async readRecoveryKey() { return (await readEncryption())?.key ?? secret('recovery-'); },
|
|
57
|
+
async writeRecoveryKey(value) { await SecureStore.setItemAsync('recovery-' + await scope, value, keyOptions); },
|
|
58
|
+
};
|
|
59
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { MessagingBackupClient, type MessagingBackupCloud, type MessagingBackupDriver, type MessagingBackupPasskeys } from '@robono/messaging';
|
|
2
|
+
/** Complete local backup plumbing for the shared Account → Chat backup screen.
|
|
3
|
+
* The host supplies its user's cloud authorization and OS scheduling. This must
|
|
4
|
+
* use the same identity as the durable received-history connection. */
|
|
5
|
+
export declare function createExpoMessagingBackup(options: {
|
|
6
|
+
endpoint: string;
|
|
7
|
+
userId: string;
|
|
8
|
+
namespace?: string;
|
|
9
|
+
cloud: MessagingBackupCloud | (() => MessagingBackupCloud);
|
|
10
|
+
network: MessagingBackupDriver['network'];
|
|
11
|
+
schedule: MessagingBackupDriver['schedule'];
|
|
12
|
+
subscribeNetwork?: MessagingBackupDriver['subscribeNetwork'];
|
|
13
|
+
passkeys?: MessagingBackupPasskeys;
|
|
14
|
+
}): Promise<MessagingBackupClient>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { MessagingBackupClient, createMessagingBackupDriver } from '@robono/messaging';
|
|
2
|
+
import { createExpoDurableHistoryBackupSource } from './expo-history-backup.js';
|
|
3
|
+
import { createExpoMessagingBackupCrypto } from './expo-backup-crypto.js';
|
|
4
|
+
import { createExpoMessagingBackupSettings } from './expo-backup-settings.js';
|
|
5
|
+
import { storageDigest } from './expo-storage-digest.js';
|
|
6
|
+
/** Complete local backup plumbing for the shared Account → Chat backup screen.
|
|
7
|
+
* The host supplies its user's cloud authorization and OS scheduling. This must
|
|
8
|
+
* use the same identity as the durable received-history connection. */
|
|
9
|
+
export async function createExpoMessagingBackup(options) {
|
|
10
|
+
const endpoint = new URL(options.endpoint).href, namespace = options.namespace ?? 'default';
|
|
11
|
+
if (!options.userId.trim() || options.userId.length > 200 || !namespace || namespace.length > 200)
|
|
12
|
+
throw Error('Choose a signed-in history account.');
|
|
13
|
+
const scope = await storageDigest(JSON.stringify([endpoint, namespace, options.userId]));
|
|
14
|
+
const source = await createExpoDurableHistoryBackupSource(endpoint, options.userId, namespace);
|
|
15
|
+
// Defer provider setup until the screen refreshes. A missing native module or
|
|
16
|
+
// account configuration becomes the shared screen's normal recoverable error,
|
|
17
|
+
// rather than removing Account → Chat backup or breaking Messenger startup.
|
|
18
|
+
let provider;
|
|
19
|
+
const get = () => provider ??= (typeof options.cloud === 'function' ? options.cloud() : options.cloud);
|
|
20
|
+
const cloud = { account: async (signal) => get().account(signal), connect: async (signal) => get().connect(signal), manageStorage: async () => get().manageStorage(), latest: async (...args) => get().latest(...args), read: async (...args) => get().read(...args), write: async (...args) => get().write(...args), commit: async (...args) => get().commit(...args), discard: async (...args) => get().discard(...args), maintain: async (...args) => { await get().maintain?.(...args); } };
|
|
21
|
+
return new MessagingBackupClient(createMessagingBackupDriver({ scope, source, cloud, crypto: createExpoMessagingBackupCrypto(), local: createExpoMessagingBackupSettings(endpoint, options.userId, namespace), network: options.network, subscribeNetwork: options.subscribeNetwork, schedule: options.schedule, passkeys: options.passkeys }));
|
|
22
|
+
}
|
package/dist/expo-bridge.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ export declare function createExpoBridgeMessenger(options: {
|
|
|
5
5
|
userId: string;
|
|
6
6
|
connectionId: string;
|
|
7
7
|
getAccessToken: () => Promise<string>;
|
|
8
|
+
deviceHistory?: import('@robono/messaging').MessagingDeviceHistory;
|
|
9
|
+
historyAccess?: 'authorized-cache' | 'online';
|
|
8
10
|
foregroundPresence?: boolean;
|
|
9
11
|
fetch?: typeof fetch;
|
|
10
12
|
namespace?: string;
|
package/dist/expo-bridge.js
CHANGED
|
@@ -4,11 +4,13 @@ import { createBridgePresenceSession } from '@robono/messaging';
|
|
|
4
4
|
import { bridgeMessengerFetch, bridgeLanguageRequest, createMessagingTransport, refreshBridgeMessengerFromPush } from '@robono/messaging';
|
|
5
5
|
import { createExpoMessagingClient, expoOutbox } from './expo-outbox.js';
|
|
6
6
|
import { createExpoMessagingStorage, createExpoMessagingAudioSession } from './expo-media.js';
|
|
7
|
+
import { withExpoDeviceHistoryStorage } from './expo-device-history.js';
|
|
7
8
|
/** Standard ExpoMessagingScreen connection for an already accepted Bridge friend. */
|
|
8
9
|
export function createExpoBridgeMessenger(options) {
|
|
9
10
|
const transportFetch = bridgeMessengerFetch(options.connectionId, options.fetch);
|
|
10
11
|
const client = createExpoMessagingClient({ ...options, fetch: transportFetch, transformRequest: bridgeLanguageRequest(createMessagingTransport({ ...options, fetch: transportFetch })), namespace: (options.namespace ?? '') + ':bridge:' + options.connectionId });
|
|
11
|
-
const
|
|
12
|
+
const remoteStorage = createExpoMessagingStorage({ url: options.url, getAccessToken: options.getAccessToken, fetch: transportFetch });
|
|
13
|
+
const storage = options.deviceHistory ? withExpoDeviceHistoryStorage(remoteStorage, client, { endpoint: options.url, userId: options.userId, namespace: options.namespace }) : remoteStorage;
|
|
12
14
|
const outgoing = expoOutbox(client);
|
|
13
15
|
if (outgoing)
|
|
14
16
|
client.setRecoveryAdapter(worker => {
|
package/dist/expo-cache.js
CHANGED
|
@@ -6,6 +6,19 @@ let limits = { ...defaultMessagingDiskCacheLimits };
|
|
|
6
6
|
// selected attachments stay protected until their existing remove() lifecycle.
|
|
7
7
|
const active = new Set();
|
|
8
8
|
let maintenance, started = false, lastMaintenance = 0;
|
|
9
|
+
let scheduled = false;
|
|
10
|
+
function scheduleMaintenance() {
|
|
11
|
+
if (scheduled)
|
|
12
|
+
return;
|
|
13
|
+
scheduled = true;
|
|
14
|
+
const run = () => { scheduled = false; if (maintenance || Date.now() - lastMaintenance < 60000)
|
|
15
|
+
return; void maintainExpoMessagingCache().catch(() => { started = false; }); };
|
|
16
|
+
const idle = globalThis.requestIdleCallback;
|
|
17
|
+
if (idle)
|
|
18
|
+
idle(run, { timeout: 5000 });
|
|
19
|
+
else
|
|
20
|
+
setTimeout(run, 1000);
|
|
21
|
+
}
|
|
9
22
|
export function configureExpoMessagingCache(options) {
|
|
10
23
|
for (const [key, value] of Object.entries(options))
|
|
11
24
|
if (!Object.prototype.hasOwnProperty.call(limits, key) || !Number.isSafeInteger(value) || value < 0)
|
|
@@ -81,10 +94,16 @@ export async function maintainExpoMessagingCache(options = {}) {
|
|
|
81
94
|
}
|
|
82
95
|
export async function allocateMessagingCache(requiredBytes = 0, draft = false) {
|
|
83
96
|
const low = requiredBytes > 0 && (await FS.getFreeDiskStorageAsync()) < limits.minFreeBytes + requiredBytes;
|
|
84
|
-
|
|
97
|
+
// Low space must be resolved before writing. Routine age/size housekeeping
|
|
98
|
+
// waits for idle time, so opening a chat never waits for a scan of old files.
|
|
99
|
+
if (low) {
|
|
85
100
|
await maintainExpoMessagingCache({ requiredBytes });
|
|
86
101
|
started = true;
|
|
87
102
|
}
|
|
103
|
+
else if (!started || Date.now() - lastMaintenance > 60000) {
|
|
104
|
+
started = true;
|
|
105
|
+
scheduleMaintenance();
|
|
106
|
+
}
|
|
88
107
|
const dir = messagingCacheRoot() + Crypto.randomUUID() + '/';
|
|
89
108
|
active.add(dir);
|
|
90
109
|
try {
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { MessagingDeviceHistory, type MessagingClient } from '@robono/messaging';
|
|
2
|
+
import type { MessagingMediaStorage } from './media-controller.js';
|
|
3
|
+
type Account = {
|
|
4
|
+
endpoint: string;
|
|
5
|
+
userId: string;
|
|
6
|
+
namespace?: string;
|
|
7
|
+
};
|
|
8
|
+
/** Explicit opt-in for the authenticated device-history route. This does not
|
|
9
|
+
* change the server's retention policy or enroll any other integration. */
|
|
10
|
+
export declare function createExpoDeviceHistory(options: Account & {
|
|
11
|
+
getAccessToken: () => Promise<string>;
|
|
12
|
+
fetch?: typeof fetch;
|
|
13
|
+
onError?: (error: unknown) => void;
|
|
14
|
+
historyRequest?: import('@robono/messaging').MessagingRequest;
|
|
15
|
+
localAccess?: import('@robono/messaging').MessagingRequest;
|
|
16
|
+
download?: (change: import('@robono/messaging').DurableHistoryChange, signal: AbortSignal) => Promise<{
|
|
17
|
+
uri: string;
|
|
18
|
+
release(): Promise<void>;
|
|
19
|
+
}>;
|
|
20
|
+
}): Promise<MessagingDeviceHistory>;
|
|
21
|
+
/** Viewer/forward/export copies use the established bounded private cache. The
|
|
22
|
+
* durable source is never passed to cleanup code or copied through JS base64. */
|
|
23
|
+
export declare function withExpoDeviceHistoryStorage(storage: MessagingMediaStorage, client: MessagingClient, account: Account): MessagingMediaStorage;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native';
|
|
2
|
+
import { MessagingDeviceHistory, MessagingHistorySync, createMessagingTransport } from '@robono/messaging';
|
|
3
|
+
import { createExpoDurableHistoryStore, createExpoDurableHistoryMedia } from './expo-durable-history.js';
|
|
4
|
+
import { createExpoMessagingStorage, createExpoMessagingDevice, createExpoMessagingAudioSession } from './expo-media.js';
|
|
5
|
+
import { storageDigest } from './expo-storage-digest.js';
|
|
6
|
+
import { allocateMessagingCache, removeMessagingCacheUri } from './expo-cache.js';
|
|
7
|
+
import { readExpoHistoryPreview, saveExpoHistoryPreview } from './expo-history-previews.js';
|
|
8
|
+
/** Explicit opt-in for the authenticated device-history route. This does not
|
|
9
|
+
* change the server's retention policy or enroll any other integration. */
|
|
10
|
+
export async function createExpoDeviceHistory(options) {
|
|
11
|
+
if (!NativeModules.RobonoHistoryStore?.copyOriginal)
|
|
12
|
+
throw Error('Update this app to open saved device history.');
|
|
13
|
+
const historyUrl = new URL(options.endpoint);
|
|
14
|
+
historyUrl.searchParams.set('service', 'history');
|
|
15
|
+
const mediaUrl = new URL(options.endpoint);
|
|
16
|
+
mediaUrl.searchParams.set('service', 'media');
|
|
17
|
+
const storage = createExpoMessagingStorage({ ...options, url: mediaUrl.href });
|
|
18
|
+
const device = createExpoMessagingDevice(createExpoMessagingAudioSession());
|
|
19
|
+
const store = await createExpoDurableHistoryStore(options.endpoint, options.userId, options.namespace);
|
|
20
|
+
const media = await createExpoDurableHistoryMedia({ ...options, download: options.download ?? (async (change, signal) => {
|
|
21
|
+
const file = await storage.download(change.message, { signal, onProgress: () => { } });
|
|
22
|
+
return { uri: file.uri, release: () => device.remove(file) };
|
|
23
|
+
}) });
|
|
24
|
+
const sync = new MessagingHistorySync({ store, media, request: options.historyRequest ?? createMessagingTransport({ ...options, url: historyUrl.href }) });
|
|
25
|
+
return new MessagingDeviceHistory({ store, sync, localAccess: options.localAccess, onError: options.onError });
|
|
26
|
+
}
|
|
27
|
+
/** Viewer/forward/export copies use the established bounded private cache. The
|
|
28
|
+
* durable source is never passed to cleanup code or copied through JS base64. */
|
|
29
|
+
export function withExpoDeviceHistoryStorage(storage, client, account) {
|
|
30
|
+
const scope = storageDigest(JSON.stringify([new URL(account.endpoint).href, account.namespace ?? 'default', account.userId]));
|
|
31
|
+
const local = async (message, context) => {
|
|
32
|
+
if (!message.media)
|
|
33
|
+
return null;
|
|
34
|
+
const original = await client.deviceHistoryOriginal(message, context.signal);
|
|
35
|
+
if (!original)
|
|
36
|
+
return null;
|
|
37
|
+
if (!NativeModules.RobonoHistoryStore?.copyOriginal)
|
|
38
|
+
throw Error('Update this app to open saved device history.');
|
|
39
|
+
if (original.byteSize !== message.media.byteSize)
|
|
40
|
+
throw Error('This attachment changed. Refresh the conversation.');
|
|
41
|
+
const directory = await allocateMessagingCache(original.byteSize), name = message.media.fileName.replace(/[^a-zA-Z0-9._-]/g, '_').slice(-90) || 'Attachment';
|
|
42
|
+
const destination = directory + (['__draft__', '.', '..'].includes(name) ? 'Attachment' : name);
|
|
43
|
+
try {
|
|
44
|
+
// copyOriginal checks the account epoch on its serialized native queue.
|
|
45
|
+
// The exact revision is checked after copying and before exposing the URI.
|
|
46
|
+
if (context.signal.aborted)
|
|
47
|
+
throw Error('The history account changed.');
|
|
48
|
+
await NativeModules.RobonoHistoryStore.copyOriginal(await scope, original.sha256, original.byteSize, original.generation, destination);
|
|
49
|
+
if (context.signal.aborted || !await client.deviceHistoryOriginalCurrent(message, original))
|
|
50
|
+
throw Error('The history account changed.');
|
|
51
|
+
// Keep the cache allocator's URI spelling. Android canonicalizes /data/user
|
|
52
|
+
// to /data/data; returning that alias bypasses the cache ownership matcher.
|
|
53
|
+
const { assetId, ...metadata } = message.media;
|
|
54
|
+
context.onProgress(1);
|
|
55
|
+
return { ...metadata, uri: destination };
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
await removeMessagingCacheUri(destination).catch(() => { });
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
return { ...storage,
|
|
63
|
+
download: async (message, context) => await local(message, context) ?? storage.download(message, context),
|
|
64
|
+
stream: async (message, context) => await local(message, context) ?? storage.stream?.(message, context) ?? null,
|
|
65
|
+
// Let the standard preview generator handle a local image/video. Returning
|
|
66
|
+
// a full image as a dedicated thumbnail would misreport its dimensions/size.
|
|
67
|
+
thumbnail: async (message, context) => {
|
|
68
|
+
const original = await client.deviceHistoryOriginal(message, context.signal);
|
|
69
|
+
if (!original)
|
|
70
|
+
return storage.thumbnail?.(message, context) ?? null;
|
|
71
|
+
let preview = await readExpoHistoryPreview(await scope, original.sha256);
|
|
72
|
+
if (!preview && ['image', 'video'].includes(message.kind)) {
|
|
73
|
+
const copy = await local(message, context);
|
|
74
|
+
if (copy)
|
|
75
|
+
try {
|
|
76
|
+
await saveExpoHistoryPreview(await scope, original.sha256, original.generation, message.kind, copy.uri, context.signal);
|
|
77
|
+
preview = await readExpoHistoryPreview(await scope, original.sha256);
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
await removeMessagingCacheUri(copy.uri).catch(() => { });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (context.signal.aborted || !await client.deviceHistoryOriginalCurrent(message, original))
|
|
84
|
+
throw Error('The history account changed.');
|
|
85
|
+
return preview;
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { MessagingDurableHistoryStore, MessagingDurableMedia, DurableHistoryChange } from '@robono/messaging';
|
|
2
|
+
/** Separate private SQLite database per endpoint, tenant and authenticated user.
|
|
3
|
+
* A native rebuild is required. Missing durable support must never silently
|
|
4
|
+
* fall back to an expiring cache and acknowledge delivery. */
|
|
5
|
+
export declare function createExpoDurableHistoryStore(endpoint: string, userId: string, namespace?: string): Promise<MessagingDurableHistoryStore>;
|
|
6
|
+
/** Bounded original-file reads for backup/export; never route private bytes
|
|
7
|
+
* through a network URL or depend on Expo access to Android no_backup files. */
|
|
8
|
+
export declare function readExpoDurableHistoryOriginal(options: {
|
|
9
|
+
endpoint: string;
|
|
10
|
+
userId: string;
|
|
11
|
+
namespace?: string;
|
|
12
|
+
sha256: string;
|
|
13
|
+
offset: number;
|
|
14
|
+
length: number;
|
|
15
|
+
}): Promise<string>;
|
|
16
|
+
/** Download uses the normal authenticated media adapter. Native copying streams,
|
|
17
|
+
* hashes and syncs the original before the history transaction can acknowledge it. */
|
|
18
|
+
export declare function createExpoDurableHistoryMedia(options: {
|
|
19
|
+
endpoint: string;
|
|
20
|
+
userId: string;
|
|
21
|
+
namespace?: string;
|
|
22
|
+
download: (change: DurableHistoryChange, signal: AbortSignal) => Promise<{
|
|
23
|
+
uri: string;
|
|
24
|
+
release(): Promise<void>;
|
|
25
|
+
}>;
|
|
26
|
+
}): Promise<MessagingDurableMedia>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native';
|
|
2
|
+
import { storageDigest } from './expo-storage-digest.js';
|
|
3
|
+
import { saveExpoHistoryPreview } from './expo-history-previews.js';
|
|
4
|
+
import { createNativeHistoryStore } from './native-history.js';
|
|
5
|
+
import { cleanExpoHistoryRestoreSessions } from './expo-history-maintenance.js';
|
|
6
|
+
/** Separate private SQLite database per endpoint, tenant and authenticated user.
|
|
7
|
+
* A native rebuild is required. Missing durable support must never silently
|
|
8
|
+
* fall back to an expiring cache and acknowledge delivery. */
|
|
9
|
+
export async function createExpoDurableHistoryStore(endpoint, userId, namespace = 'default') {
|
|
10
|
+
if (!NativeModules.RobonoHistoryStore?.executeAndPruneOriginals)
|
|
11
|
+
throw Error('Update this app to enable device history.');
|
|
12
|
+
const scope = await storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
|
|
13
|
+
const database = commands => NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify(commands));
|
|
14
|
+
return createNativeHistoryStore(database, {
|
|
15
|
+
clearAll: async (commands) => { const result = await NativeModules.RobonoHistoryStore.executeAndClearOriginals(scope, JSON.stringify(commands)); await cleanExpoHistoryRestoreSessions(scope, database, true); return result; },
|
|
16
|
+
clearConversation: async (commands) => { const result = await NativeModules.RobonoHistoryStore.executeAndPruneOriginals(scope, JSON.stringify(commands)); await cleanExpoHistoryRestoreSessions(scope, database); return result; },
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/** Bounded original-file reads for backup/export; never route private bytes
|
|
20
|
+
* through a network URL or depend on Expo access to Android no_backup files. */
|
|
21
|
+
export async function readExpoDurableHistoryOriginal(options) {
|
|
22
|
+
const scope = await storageDigest(JSON.stringify([new URL(options.endpoint).href, options.namespace ?? 'default', options.userId]));
|
|
23
|
+
return NativeModules.RobonoHistoryStore.readOriginal(scope, options.sha256, options.offset, options.length);
|
|
24
|
+
}
|
|
25
|
+
/** Download uses the normal authenticated media adapter. Native copying streams,
|
|
26
|
+
* hashes and syncs the original before the history transaction can acknowledge it. */
|
|
27
|
+
export async function createExpoDurableHistoryMedia(options) {
|
|
28
|
+
if (!NativeModules.RobonoHistoryStore?.saveOriginalGuarded)
|
|
29
|
+
throw Error('Update this app to save device history.');
|
|
30
|
+
const scope = await storageDigest(JSON.stringify([new URL(options.endpoint).href, options.namespace ?? 'default', options.userId]));
|
|
31
|
+
const account = createNativeHistoryStore(commands => NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify(commands)));
|
|
32
|
+
return {
|
|
33
|
+
async verify(original, signal) { if (signal.aborted || !NativeModules.RobonoHistoryStore?.verifyOriginal)
|
|
34
|
+
return false; const valid = await NativeModules.RobonoHistoryStore.verifyOriginal(scope, original.sha256, original.byteSize); return !signal.aborted && (valid === true || valid === 1); },
|
|
35
|
+
async save(change, signal, expectedGeneration) {
|
|
36
|
+
if (signal.aborted || !change.message.media || !change.mediaSha256)
|
|
37
|
+
throw Error('This attachment is unavailable.');
|
|
38
|
+
const epoch = expectedGeneration ?? await account.generation();
|
|
39
|
+
if (await account.generation() !== epoch)
|
|
40
|
+
throw Error('The account changed.');
|
|
41
|
+
const source = await options.download(change, signal);
|
|
42
|
+
try {
|
|
43
|
+
if (signal.aborted || await account.generation() !== epoch)
|
|
44
|
+
throw Error('The account changed.');
|
|
45
|
+
const original = await NativeModules.RobonoHistoryStore.saveOriginalGuarded(scope, source.uri, change.mediaSha256, change.message.media.byteSize, epoch);
|
|
46
|
+
await saveExpoHistoryPreview(scope, change.mediaSha256, epoch, change.message.kind, source.uri, signal);
|
|
47
|
+
if (signal.aborted || await account.generation() !== epoch)
|
|
48
|
+
throw Error('The account changed.');
|
|
49
|
+
return original;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
await source.release();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Real durable history, not the expiring UI cache. Only the encrypted archive
|
|
2
|
+
* leaves the device; temporary restore files stay in the app's private cache. */
|
|
3
|
+
export declare function createExpoDurableHistoryBackupSource(endpoint: string, userId: string, namespace?: string): Promise<import("@robono/messaging").MessagingBackupSource>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { NativeModules } from 'react-native';
|
|
2
|
+
import { Directory, File, Paths } from 'expo-file-system';
|
|
3
|
+
import { randomUUID } from 'expo-crypto';
|
|
4
|
+
import { storageDigest } from './expo-storage-digest.js';
|
|
5
|
+
import { createNativeHistoryBackupSource } from './native-history-backup.js';
|
|
6
|
+
/** Real durable history, not the expiring UI cache. Only the encrypted archive
|
|
7
|
+
* leaves the device; temporary restore files stay in the app's private cache. */
|
|
8
|
+
export async function createExpoDurableHistoryBackupSource(endpoint, userId, namespace = 'default') {
|
|
9
|
+
const native = NativeModules.RobonoHistoryStore;
|
|
10
|
+
if (!native?.executeAndClearOriginals || !native?.readOriginal || !native?.saveOriginalGuarded)
|
|
11
|
+
throw Error('Update this app to enable history backups.');
|
|
12
|
+
const scope = await storageDigest(JSON.stringify([new URL(endpoint).href, namespace, userId]));
|
|
13
|
+
return createNativeHistoryBackupSource(commands => native.execute(scope, JSON.stringify(commands)), {
|
|
14
|
+
async read(sha, offset, length) { const encoded = await native.readOriginal(scope, sha, offset, length); return decodeOriginal(encoded); },
|
|
15
|
+
async stage(session) {
|
|
16
|
+
const directory = new Directory(Paths.cache, 'robono-history-restore', scope, session);
|
|
17
|
+
directory.create({ intermediates: true });
|
|
18
|
+
const files = new Map();
|
|
19
|
+
let closed = false;
|
|
20
|
+
return {
|
|
21
|
+
async write(sha, size, offset, bytes) {
|
|
22
|
+
if (closed || !/^[a-f0-9]{64}$/.test(sha) || bytes.length > 1024 * 1024)
|
|
23
|
+
throw Error('Invalid backup original.');
|
|
24
|
+
let row = files.get(sha);
|
|
25
|
+
if (!row) {
|
|
26
|
+
if (offset !== 0)
|
|
27
|
+
throw Error('Missing backup original part.');
|
|
28
|
+
const file = new File(directory, sha);
|
|
29
|
+
file.create();
|
|
30
|
+
row = { file, received: 0, size };
|
|
31
|
+
files.set(sha, row);
|
|
32
|
+
}
|
|
33
|
+
if (row.received !== offset || row.size !== size || offset + bytes.length > size)
|
|
34
|
+
throw Error('Invalid backup original order.');
|
|
35
|
+
const handle = row.file.open();
|
|
36
|
+
try {
|
|
37
|
+
handle.offset = offset;
|
|
38
|
+
handle.writeBytes(bytes);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
handle.close();
|
|
42
|
+
}
|
|
43
|
+
row.received += bytes.length;
|
|
44
|
+
},
|
|
45
|
+
async promote(sha, size, epoch) {
|
|
46
|
+
const row = files.get(sha);
|
|
47
|
+
if (closed || !row || row.received !== size || row.size !== size)
|
|
48
|
+
throw Error('The backup original is incomplete.');
|
|
49
|
+
if (!native.saveOriginalGuarded)
|
|
50
|
+
throw Error('Update this app to restore message history.');
|
|
51
|
+
return native.saveOriginalGuarded(scope, row.file.uri, sha, size, epoch);
|
|
52
|
+
},
|
|
53
|
+
async discard() { closed = true; if (directory.exists)
|
|
54
|
+
directory.delete(); files.clear(); },
|
|
55
|
+
};
|
|
56
|
+
},
|
|
57
|
+
}, randomUUID);
|
|
58
|
+
}
|
|
59
|
+
// Hermes does not consistently expose atob. Decode at most one native 1 MiB
|
|
60
|
+
// chunk without allocating a JavaScript string/array for every decoded byte.
|
|
61
|
+
function decodeOriginal(input) {
|
|
62
|
+
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', length = input.length;
|
|
63
|
+
if (length > 1398104 || length % 4 !== 0)
|
|
64
|
+
throw Error('Invalid saved original.');
|
|
65
|
+
const padding = input.endsWith('==') ? 2 : input.endsWith('=') ? 1 : 0, out = new Uint8Array(length / 4 * 3 - padding);
|
|
66
|
+
let position = 0;
|
|
67
|
+
for (let i = 0; i < length; i += 4) {
|
|
68
|
+
let value = 0;
|
|
69
|
+
for (let j = 0; j < 4; j++) {
|
|
70
|
+
const char = input[i + j], digit = char === '=' && i + j >= length - padding ? 0 : alphabet.indexOf(char);
|
|
71
|
+
if (digit < 0)
|
|
72
|
+
throw Error('Invalid saved original.');
|
|
73
|
+
value = (value << 6) | digit;
|
|
74
|
+
}
|
|
75
|
+
for (let shift = 16; shift >= 0 && position < out.length; shift -= 8)
|
|
76
|
+
out[position++] = (value >> shift) & 255;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { NativeHistoryDatabase } from './native-history.js';
|
|
2
|
+
/** Only this account's SDK-owned restore scratch files. A fresh or active
|
|
3
|
+
* session is protected; session UUIDs are never reused by another restore. */
|
|
4
|
+
export declare function cleanExpoHistoryRestoreSessions(scope: string, database: NativeHistoryDatabase, cleared?: boolean): Promise<void>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import * as FS from 'expo-file-system/legacy';
|
|
2
|
+
/** Only this account's SDK-owned restore scratch files. A fresh or active
|
|
3
|
+
* session is protected; session UUIDs are never reused by another restore. */
|
|
4
|
+
export async function cleanExpoHistoryRestoreSessions(scope, database, cleared = false) {
|
|
5
|
+
if (!/^[a-f0-9]{64}$/.test(scope) || !FS.cacheDirectory)
|
|
6
|
+
return;
|
|
7
|
+
const root = FS.cacheDirectory + 'robono-history-restore/' + scope + '/';
|
|
8
|
+
if (!(await FS.getInfoAsync(root)).exists)
|
|
9
|
+
return;
|
|
10
|
+
const names = (await FS.readDirectoryAsync(root)).filter(name => /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(name)).slice(0, 100);
|
|
11
|
+
if (!names.length)
|
|
12
|
+
return;
|
|
13
|
+
const rows = await database([{ sql: `SELECT session FROM backup_sessions WHERE session IN(${names.map(() => '?').join(',')})`, args: names }]);
|
|
14
|
+
const active = new Set(rows[0].map(row => row.session));
|
|
15
|
+
for (const name of names) {
|
|
16
|
+
if (active.has(name))
|
|
17
|
+
continue;
|
|
18
|
+
const path = root + name + '/', info = await FS.getInfoAsync(path);
|
|
19
|
+
if (!info.exists || !info.isDirectory || !cleared && (!Number.isFinite(info.modificationTime) || info.modificationTime * 1000 > Date.now() - 86400000))
|
|
20
|
+
continue;
|
|
21
|
+
await FS.deleteAsync(path, { idempotent: true });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { LocalMessagingMedia } from './media-controller.js';
|
|
2
|
+
/** Disposable derived previews, scoped with private history. Generated only
|
|
3
|
+
* while receiving a sent original, never while browsing a media picker. */
|
|
4
|
+
export declare function saveExpoHistoryPreview(scope: string, sha256: string, epoch: number, kind: string, source: string, parent: AbortSignal): Promise<void>;
|
|
5
|
+
export declare function readExpoHistoryPreview(scope: string, sha256: string): Promise<LocalMessagingMedia | null>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Image, NativeModules } from 'react-native';
|
|
2
|
+
import * as FS from 'expo-file-system/legacy';
|
|
3
|
+
import * as Images from 'expo-image-manipulator';
|
|
4
|
+
import * as Videos from 'expo-video-thumbnails';
|
|
5
|
+
import { withMessagingDeadline } from '@robono/messaging';
|
|
6
|
+
import { nativeHistoryPreviewTable } from './native-history.js';
|
|
7
|
+
/** Disposable derived previews, scoped with private history. Generated only
|
|
8
|
+
* while receiving a sent original, never while browsing a media picker. */
|
|
9
|
+
export async function saveExpoHistoryPreview(scope, sha256, epoch, kind, source, parent) {
|
|
10
|
+
if (!['image', 'video'].includes(kind))
|
|
11
|
+
return;
|
|
12
|
+
await withMessagingDeadline(async (signal) => {
|
|
13
|
+
let poster, output;
|
|
14
|
+
try {
|
|
15
|
+
if (signal.aborted)
|
|
16
|
+
return;
|
|
17
|
+
if (kind === 'video')
|
|
18
|
+
poster = (await Videos.getThumbnailAsync(source, { time: 0, quality: .6 })).uri;
|
|
19
|
+
if (signal.aborted)
|
|
20
|
+
return;
|
|
21
|
+
const dimensions = await new Promise((resolve, reject) => Image.getSize(poster ?? source, (width, height) => resolve({ width, height }), reject));
|
|
22
|
+
if (!Number.isFinite(dimensions.width) || !Number.isFinite(dimensions.height) || dimensions.width < 1 || dimensions.height < 1 || signal.aborted)
|
|
23
|
+
return;
|
|
24
|
+
const scale = Math.min(1, 320 / dimensions.width, 320 / dimensions.height);
|
|
25
|
+
const image = await Images.manipulateAsync(poster ?? source, [{ resize: { width: Math.max(1, Math.round(dimensions.width * scale)), height: Math.max(1, Math.round(dimensions.height * scale)) } }], { compress: .6, format: Images.SaveFormat.JPEG, base64: true });
|
|
26
|
+
output = image.uri;
|
|
27
|
+
if (signal.aborted || !image.base64 || image.base64.length > 65536)
|
|
28
|
+
return;
|
|
29
|
+
const preview = { uri: 'data:image/jpeg;base64,' + image.base64, mimeType: 'image/jpeg', fileName: 'Preview.jpg', byteSize: image.base64.length * 3 / 4 - (image.base64.endsWith('==') ? 2 : image.base64.endsWith('=') ? 1 : 0) };
|
|
30
|
+
await NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify([
|
|
31
|
+
nativeHistoryPreviewTable,
|
|
32
|
+
{ sql: 'UPDATE history_control SET epoch=CASE WHEN epoch=? THEN epoch ELSE NULL END WHERE id=1', args: [epoch] },
|
|
33
|
+
{ sql: 'INSERT OR REPLACE INTO history_previews(sha,preview) VALUES(?,?)', args: [sha256, JSON.stringify(preview)] },
|
|
34
|
+
]));
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
for (const uri of [poster, output])
|
|
38
|
+
if (uri && FS.cacheDirectory && uri.startsWith(FS.cacheDirectory))
|
|
39
|
+
await FS.deleteAsync(uri, { idempotent: true }).catch(() => { });
|
|
40
|
+
}
|
|
41
|
+
}, { signal: parent, timeoutMs: 3000 }).catch(() => { }); // A preview failure never invalidates a verified original.
|
|
42
|
+
}
|
|
43
|
+
export async function readExpoHistoryPreview(scope, sha256) {
|
|
44
|
+
const results = await NativeModules.RobonoHistoryStore.execute(scope, JSON.stringify([nativeHistoryPreviewTable, { sql: 'SELECT preview FROM history_previews WHERE sha=?', args: [sha256] }]));
|
|
45
|
+
const raw = results[1]?.[0]?.preview;
|
|
46
|
+
if (typeof raw !== 'string' || raw.length > 66000)
|
|
47
|
+
return null;
|
|
48
|
+
try {
|
|
49
|
+
const preview = JSON.parse(raw);
|
|
50
|
+
if (preview.mimeType !== 'image/jpeg' || typeof preview.uri !== 'string' || !/^data:image\/jpeg;base64,[a-zA-Z0-9+/]+={0,2}$/.test(preview.uri) || !Number.isSafeInteger(preview.byteSize) || preview.byteSize < 1 || preview.byteSize > 49152)
|
|
51
|
+
return null;
|
|
52
|
+
return preview;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|