@robono/messaging-react-native 0.20.3 → 0.22.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 +5 -1
- package/README.md +58 -0
- package/SBOM.spdx.json +478 -238
- package/app.plugin.cjs +9 -3
- package/dist/bubble-design.d.ts +12 -0
- package/dist/bubble-design.js +11 -0
- package/dist/call-message.js +39 -9
- package/dist/delivery-bar.d.ts +7 -0
- package/dist/delivery-bar.js +19 -0
- package/dist/disk-cache.d.ts +14 -0
- package/dist/disk-cache.js +15 -0
- package/dist/expo-cache.d.ts +20 -0
- package/dist/expo-cache.js +111 -0
- package/dist/expo-calling.d.ts +1 -1
- package/dist/expo-calling.js +1 -1
- package/dist/expo-media.js +7 -22
- package/dist/expo-messenger.js +12 -3
- package/dist/expo-notification-cleanup.d.ts +7 -0
- package/dist/expo-notification-cleanup.js +96 -0
- package/dist/expo-notifications.d.ts +1 -0
- package/dist/expo-notifications.js +38 -8
- package/dist/expo-screen.js +16 -8
- package/dist/expo-thumbnails.d.ts +4 -0
- package/dist/expo-thumbnails.js +3 -2
- package/dist/expo.d.ts +1 -0
- package/dist/expo.js +1 -0
- package/dist/inbox.d.ts +2 -1
- package/dist/inbox.js +4 -3
- package/dist/index.js +21 -20
- package/dist/media-controller.d.ts +2 -1
- package/dist/media-controller.js +8 -8
- package/dist/media-ui.d.ts +4 -2
- package/dist/media-ui.js +13 -13
- package/dist/message-order.d.ts +2 -2
- package/dist/message-order.js +2 -2
- package/dist/preview-cache.d.ts +1 -0
- package/dist/preview-cache.js +2 -0
- package/dist/voice-composer.js +2 -1
- package/dist/voice-waveform.d.ts +2 -0
- package/dist/voice-waveform.js +9 -0
- package/package.json +12 -6
package/app.plugin.cjs
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
-
const {withDangerousMod,createRunOncePlugin} = require('expo/config-plugins');
|
|
2
|
-
module.exports=createRunOncePlugin(config=>
|
|
1
|
+
const {withDangerousMod,withInfoPlist,createRunOncePlugin} = require('expo/config-plugins');
|
|
2
|
+
module.exports=createRunOncePlugin(config=>{
|
|
3
|
+
config=withInfoPlist(config,value=>{
|
|
4
|
+
value.modResults.UIBackgroundModes=[...new Set([...(value.modResults.UIBackgroundModes??[]),'remote-notification'])];
|
|
5
|
+
return value;
|
|
6
|
+
});
|
|
7
|
+
return withDangerousMod(config,['ios',async value=>{
|
|
3
8
|
require('./plugin/preserve-call-audio.cjs').install(value.modRequest.projectRoot);
|
|
4
9
|
return value;
|
|
5
|
-
}])
|
|
10
|
+
}]);
|
|
11
|
+
},'@robono/messaging-react-native',require('./package.json').version);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { MessagingAppearance, MessagingMessage } from '@robono/messaging';
|
|
2
|
+
export declare function bubbleCorners(appearance: MessagingAppearance, mine: boolean, caption?: boolean): {
|
|
3
|
+
borderTopLeftRadius: number;
|
|
4
|
+
borderTopRightRadius: number;
|
|
5
|
+
borderBottomLeftRadius: number;
|
|
6
|
+
borderBottomRightRadius: number;
|
|
7
|
+
};
|
|
8
|
+
export declare function bubbleDelivery(message: MessagingMessage, pending: 'sending' | 'queued' | 'failed' | undefined, receipts: boolean, appearance: MessagingAppearance): {
|
|
9
|
+
readonly phase: "failed" | "sent" | "consumed" | "delivered";
|
|
10
|
+
readonly color: string;
|
|
11
|
+
readonly style: "circle" | "bar";
|
|
12
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function bubbleCorners(appearance, mine, caption = false) {
|
|
2
|
+
const radius = appearance.presentation?.bubbleShape === 'square' ? 0 : appearance.presentation?.bubbleShape === 'rounded' ? 16 : 8;
|
|
3
|
+
const emphasized = appearance.presentation?.bubbleStyle === 'rounded-corner' ? Math.max(28, radius) : radius;
|
|
4
|
+
return { borderTopLeftRadius: radius, borderTopRightRadius: radius, borderBottomLeftRadius: caption ? 0 : mine ? radius : emphasized, borderBottomRightRadius: caption ? 0 : mine ? emphasized : radius };
|
|
5
|
+
}
|
|
6
|
+
export function bubbleDelivery(message, pending, receipts, appearance) {
|
|
7
|
+
const phase = pending === 'failed' || message.delivery?.state === 'failed' ? 'failed' : pending || message.delivery?.state === 'pending' ? 'sent' : receipts && !!message.readAt ? 'consumed' : 'delivered';
|
|
8
|
+
const colors = appearance.messageStatus;
|
|
9
|
+
const color = phase === 'failed' ? '#c94040' : phase === 'sent' ? colors?.sent ?? '#929292' : phase === 'delivered' ? colors?.delivered ?? '#ffffff' : colors?.consumed ?? appearance.colors.accent;
|
|
10
|
+
return { phase, color, style: colors?.style ?? 'bar' };
|
|
11
|
+
}
|
package/dist/call-message.js
CHANGED
|
@@ -2,12 +2,13 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { Text } from './typography.js';
|
|
3
3
|
import { useRobonoLocale } from './localization.js';
|
|
4
4
|
import { useEffect, useRef, useState } from 'react';
|
|
5
|
-
import { Pressable, View } from 'react-native';
|
|
5
|
+
import { Pressable, View, ActivityIndicator } from 'react-native';
|
|
6
|
+
import { MessageIcon } from './icons.js';
|
|
6
7
|
import { useMessagingUI } from './index.js';
|
|
7
8
|
/** A new, reviewed message after no answer. Never records or sends a call automatically. */
|
|
8
9
|
export function UnansweredCallMessage({ callId, onDismiss }) {
|
|
9
10
|
const { text: uiText, locale: uiLocale, number: uiNumber, count: uiCount } = useRobonoLocale();
|
|
10
|
-
const { client, design, state, pickAttachment, releaseAttachment, components } = useMessagingUI();
|
|
11
|
+
const { client, design, state, userId, pickAttachment, releaseAttachment, prepareAttachment, openAttachment, components } = useMessagingUI();
|
|
11
12
|
const [option, setOption] = useState(null);
|
|
12
13
|
const [draft, setDraft] = useState(null);
|
|
13
14
|
const [busy, setBusy] = useState(false), [error, setError] = useState(''), [attempt, setAttempt] = useState(0);
|
|
@@ -84,6 +85,7 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
|
|
|
84
85
|
setBusy(true);
|
|
85
86
|
setError('');
|
|
86
87
|
const id = generation.current;
|
|
88
|
+
let transferred = false;
|
|
87
89
|
try {
|
|
88
90
|
const current = await client.unansweredCall(callId);
|
|
89
91
|
if (id !== generation.current)
|
|
@@ -93,16 +95,29 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
|
|
|
93
95
|
setOption(current);
|
|
94
96
|
return;
|
|
95
97
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const
|
|
99
|
-
|
|
98
|
+
const content = { kind: draft.kind, media: draft.media, unansweredCallId: callId };
|
|
99
|
+
const media = draft.media, kind = draft.kind;
|
|
100
|
+
const previous = new Set(client.getSnapshot().pending.map(item => item.clientMessageId));
|
|
101
|
+
const work = client.send(content, prepareAttachment ? async () => ({ ...content, media: await prepareAttachment(kind, media) }) : undefined);
|
|
102
|
+
const queued = client.getSnapshot().pending.find(item => !previous.has(item.clientMessageId));
|
|
103
|
+
if (!queued) {
|
|
104
|
+
await work;
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
// Transfer the draft to the outgoing message. Failed uploads retain the
|
|
108
|
+
// local file for the standard retry; unmount must not remove it.
|
|
109
|
+
transferred = true;
|
|
110
|
+
prepared.current = null;
|
|
111
|
+
setDraft(null);
|
|
100
112
|
onDismiss();
|
|
101
113
|
await work;
|
|
114
|
+
const result = client.getSnapshot();
|
|
115
|
+
if (result.messages.some(message => message.clientMessageId === queued.clientMessageId))
|
|
116
|
+
await release.current?.(media);
|
|
102
117
|
}
|
|
103
118
|
catch {
|
|
104
119
|
if (id === generation.current)
|
|
105
|
-
setError(uiText("The message could not be sent. Check the conversation for a retry."));
|
|
120
|
+
setError(uiText(transferred ? "The message could not be sent. Check the conversation for a retry." : "Your recording was kept. Please try sending again."));
|
|
106
121
|
}
|
|
107
122
|
finally {
|
|
108
123
|
inFlight.current = false;
|
|
@@ -110,9 +125,24 @@ export function UnansweredCallMessage({ callId, onDismiss }) {
|
|
|
110
125
|
setBusy(false);
|
|
111
126
|
}
|
|
112
127
|
}
|
|
128
|
+
async function preview() {
|
|
129
|
+
if (!draft || !openAttachment || busy)
|
|
130
|
+
return;
|
|
131
|
+
const id = generation.current;
|
|
132
|
+
setError('');
|
|
133
|
+
const message = { id: 'call-draft-' + draft.media.assetId, clientMessageId: 'call-draft-' + draft.media.assetId, conversationId: state.conversationId, senderId: userId, createdAt: new Date().toISOString(), readAt: null, kind: draft.kind, media: draft.media };
|
|
134
|
+
try {
|
|
135
|
+
await openAttachment(message);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
if (id === generation.current)
|
|
139
|
+
setError(uiText('This recording could not be opened.'));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
113
142
|
if (!pickAttachment || !state.settings?.enabled || state.conversation?.canSend === false || (!option && !error))
|
|
114
143
|
return null;
|
|
115
144
|
const c = design.colors, VoiceAttachment = components?.VoiceAttachment;
|
|
116
|
-
const
|
|
117
|
-
|
|
145
|
+
const accentInk = parseInt(c.accent.slice(1, 3), 16) * .299 + parseInt(c.accent.slice(3, 5), 16) * .587 + parseInt(c.accent.slice(5, 7), 16) * .114 > 150 ? '#111111' : '#ffffff';
|
|
146
|
+
const action = (label, onPress, primary = false) => _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText(label), disabled: busy, onPress: onPress, style: { paddingVertical: 10, paddingHorizontal: 14, minHeight: 44, borderRadius: 22, backgroundColor: primary ? c.accent : 'transparent', borderWidth: primary ? 0 : 1, borderColor: c.secondary + '55', alignItems: 'center', justifyContent: 'center', flexDirection: 'row', gap: 8, opacity: busy ? .6 : 1 }, children: [primary && busy ? _jsx(ActivityIndicator, { size: "small", color: accentInk }) : primary && _jsx(MessageIcon, { name: draft ? 'send' : option?.kind === 'video' ? 'video' : 'mic', color: accentInk, size: 18 }), _jsx(Text, { style: { color: primary ? accentInk : c.incomingText, fontWeight: '600', fontSize: 14 }, children: uiText(label) })] });
|
|
147
|
+
return _jsxs(View, { testID: "unanswered-call-message", style: { backgroundColor: c.incoming, padding: 12, borderTopWidth: 1, borderTopColor: c.secondary + '30', gap: 10 }, children: [_jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', gap: 10 }, children: [_jsx(View, { style: { width: 36, height: 36, borderRadius: 18, backgroundColor: c.accent + '20', alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: option?.kind === 'video' ? 'video' : 'mic', color: c.accent, size: 20 }) }), _jsxs(View, { style: { flex: 1, gap: 2 }, children: [_jsx(Text, { style: { color: c.incomingText, fontSize: 16, fontWeight: '700' }, children: uiText("Leave a message") }), _jsx(Text, { style: { color: c.incomingText, opacity: .75, fontSize: 13 }, children: draft ? uiText("Review before sending.") : uiText("No answer. Send a recording instead.") })] })] }), draft && _jsx(View, { testID: "call-message-review", style: { borderWidth: 1, borderColor: c.secondary + '40', borderRadius: 12, padding: 8 }, children: draft.kind === 'voice' && VoiceAttachment ? _jsx(VoiceAttachment, { media: draft.media, appearance: design, disabled: busy, onRemove: clearDraft }) : _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText(draft.kind === 'video' ? 'Play video' : 'Play recording'), disabled: busy, onPress: () => void preview(), style: { minHeight: 60, flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 8 }, children: [_jsx(View, { style: { width: 40, height: 40, borderRadius: 20, backgroundColor: c.accent, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "play", size: 20, color: accentInk }) }), _jsxs(View, { children: [_jsx(Text, { style: { color: c.incomingText, fontSize: 15, fontWeight: '600' }, children: uiText(draft.kind === 'video' ? 'Play video' : 'Play recording') }), _jsxs(Text, { style: { color: c.incomingText, opacity: .65, fontSize: 12 }, children: [Math.floor((draft.media.durationMs ?? 0) / 60000), ":", String(Math.floor((draft.media.durationMs ?? 0) / 1000) % 60).padStart(2, '0')] })] })] }) }), _jsxs(View, { style: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 8, flexWrap: 'wrap' }, children: [action(draft ? 'Cancel' : 'Not now', () => { clearDraft(); onDismiss(); }), _jsxs(View, { style: { flexDirection: 'row', gap: 8, flexWrap: 'wrap', justifyContent: 'flex-end', flex: 1 }, children: [draft && action('Record again', () => void record()), option && action(draft ? 'Send message' : `Record ${option.kind === 'voice' ? 'voice' : 'video'} message`, () => void (draft ? send() : record()), true), !option && error && action('Try again', () => setAttempt(value => value + 1), true)] })] }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.incomingText, fontSize: 13 }, children: error })] });
|
|
118
148
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
/** A two-pixel inside edge, narrowing to a point at both bubble corners. */
|
|
3
|
+
export declare function DeliveryBar({ color, topRadius, bottomRadius }: {
|
|
4
|
+
color: string;
|
|
5
|
+
topRadius: number;
|
|
6
|
+
bottomRadius: number;
|
|
7
|
+
}): React.JSX.Element;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useState } from 'react';
|
|
3
|
+
import { View } from 'react-native';
|
|
4
|
+
import Svg, { Path, G } from 'react-native-svg';
|
|
5
|
+
/** A two-pixel inside edge, narrowing to a point at both bubble corners. */
|
|
6
|
+
export function DeliveryBar({ color, topRadius, bottomRadius }) {
|
|
7
|
+
const [height, setHeight] = useState(0);
|
|
8
|
+
const scale = height ? Math.min(1, height / Math.max(1, topRadius + bottomRadius)) : 1;
|
|
9
|
+
const top = topRadius * scale, bottom = bottomRadius * scale;
|
|
10
|
+
const capHeight = (radius) => radius > 0 ? radius : Math.min(8, height ? height / 2 : 8);
|
|
11
|
+
const cap = (radius, bottom = false) => {
|
|
12
|
+
const width = Math.max(2, radius), height = capHeight(radius);
|
|
13
|
+
const path = radius > 0
|
|
14
|
+
? `M 0 0 C ${radius * .5523} 0 ${radius} ${radius * .4477} ${radius} ${radius} L ${Math.max(0, radius - 2)} ${radius} C ${Math.max(0, radius - 2)} ${radius * .4477} ${radius * .5523} 1 0 0 Z`
|
|
15
|
+
: `M 2 0 L 2 ${height} L 0 ${height} Z`;
|
|
16
|
+
return _jsx(Svg, { width: width, height: height, viewBox: `0 0 ${width} ${height}`, style: { position: 'absolute', right: 0, ...(bottom ? { bottom: 0 } : { top: 0 }) }, accessible: false, children: _jsx(G, { transform: bottom ? `translate(0 ${height}) scale(1 -1)` : undefined, children: _jsx(Path, { d: path, fill: color }) }) });
|
|
17
|
+
};
|
|
18
|
+
return _jsxs(View, { pointerEvents: "none", onLayout: e => setHeight(e.nativeEvent.layout.height), style: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }, children: [_jsx(View, { style: { position: 'absolute', top: capHeight(top), bottom: capHeight(bottom), right: 0, width: 2, backgroundColor: color } }), cap(top), cap(bottom, true)] });
|
|
19
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Only disposable, SDK-owned entries belong here. Documents/drafts are excluded. */
|
|
2
|
+
export interface MessagingDiskCacheEntry {
|
|
3
|
+
key: string;
|
|
4
|
+
bytes: number;
|
|
5
|
+
modifiedAt: number;
|
|
6
|
+
protected: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface MessagingDiskCacheLimits {
|
|
9
|
+
maxBytes: number;
|
|
10
|
+
maxAgeMs: number;
|
|
11
|
+
minFreeBytes: number;
|
|
12
|
+
}
|
|
13
|
+
export declare const defaultMessagingDiskCacheLimits: MessagingDiskCacheLimits;
|
|
14
|
+
export declare function messagingDiskEvictions(entries: MessagingDiskCacheEntry[], limits: MessagingDiskCacheLimits, freeBytes: number, now: number, requiredBytes?: number): string[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const defaultMessagingDiskCacheLimits = { maxBytes: 150 * 1024 * 1024, maxAgeMs: 24 * 3600000, minFreeBytes: 100 * 1024 * 1024 };
|
|
2
|
+
export function messagingDiskEvictions(entries, limits, freeBytes, now, requiredBytes = 0) {
|
|
3
|
+
let bytes = entries.reduce((n, e) => n + e.bytes, 0), available = freeBytes;
|
|
4
|
+
const remove = [];
|
|
5
|
+
for (const entry of [...entries].sort((a, b) => a.modifiedAt - b.modifiedAt)) {
|
|
6
|
+
if (entry.protected)
|
|
7
|
+
continue;
|
|
8
|
+
if (now - entry.modifiedAt >= limits.maxAgeMs || bytes > limits.maxBytes || available < limits.minFreeBytes + requiredBytes) {
|
|
9
|
+
remove.push(entry.key);
|
|
10
|
+
bytes -= entry.bytes;
|
|
11
|
+
available += entry.bytes;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
return remove;
|
|
15
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type MessagingDiskCacheLimits } from './disk-cache.js';
|
|
2
|
+
export type { MessagingDiskCacheLimits } from './disk-cache.js';
|
|
3
|
+
export interface MessagingCacheMaintenanceResult {
|
|
4
|
+
bytesBefore: number;
|
|
5
|
+
bytesAfter: number;
|
|
6
|
+
protectedBytes: number;
|
|
7
|
+
removedFiles: number;
|
|
8
|
+
freeBytes: number;
|
|
9
|
+
limitReached: boolean;
|
|
10
|
+
}
|
|
11
|
+
export declare function configureExpoMessagingCache(options: Partial<MessagingDiskCacheLimits>): void;
|
|
12
|
+
export declare const messagingCacheRoot: () => string;
|
|
13
|
+
/** May run while Messenger is open. Active files are never eviction candidates.
|
|
14
|
+
* This does not erase saved messages, persistent drafts, host files or libraries. */
|
|
15
|
+
export declare function maintainExpoMessagingCache(options?: {
|
|
16
|
+
requiredBytes?: number;
|
|
17
|
+
clearUnused?: boolean;
|
|
18
|
+
}): Promise<MessagingCacheMaintenanceResult>;
|
|
19
|
+
export declare function allocateMessagingCache(requiredBytes?: number, draft?: boolean): Promise<string>;
|
|
20
|
+
export declare function removeMessagingCacheUri(uri: string): Promise<void>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import * as FS from 'expo-file-system/legacy';
|
|
2
|
+
import * as Crypto from 'expo-crypto';
|
|
3
|
+
import { defaultMessagingDiskCacheLimits, messagingDiskEvictions } from './disk-cache.js';
|
|
4
|
+
let limits = { ...defaultMessagingDiskCacheLimits };
|
|
5
|
+
// Allocations are leased before any await. Existing viewers, queued sends and
|
|
6
|
+
// selected attachments stay protected until their existing remove() lifecycle.
|
|
7
|
+
const active = new Set();
|
|
8
|
+
let maintenance, started = false, lastMaintenance = 0;
|
|
9
|
+
export function configureExpoMessagingCache(options) {
|
|
10
|
+
for (const [key, value] of Object.entries(options))
|
|
11
|
+
if (!Object.prototype.hasOwnProperty.call(limits, key) || !Number.isSafeInteger(value) || value < 0)
|
|
12
|
+
throw Error('Cache limits must be non-negative whole numbers.');
|
|
13
|
+
limits = { ...limits, ...options };
|
|
14
|
+
}
|
|
15
|
+
export const messagingCacheRoot = () => { if (!FS.cacheDirectory)
|
|
16
|
+
throw Error('Private device storage is unavailable.'); return FS.cacheDirectory + 'robono-messaging/'; };
|
|
17
|
+
const owned = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
18
|
+
/** May run while Messenger is open. Active files are never eviction candidates.
|
|
19
|
+
* This does not erase saved messages, persistent drafts, host files or libraries. */
|
|
20
|
+
export async function maintainExpoMessagingCache(options = {}) {
|
|
21
|
+
const required = options.requiredBytes ?? 0;
|
|
22
|
+
if (!Number.isSafeInteger(required) || required < 0)
|
|
23
|
+
throw Error('Invalid required storage.');
|
|
24
|
+
if (maintenance) {
|
|
25
|
+
await maintenance;
|
|
26
|
+
return maintainExpoMessagingCache(options);
|
|
27
|
+
}
|
|
28
|
+
const run = async () => {
|
|
29
|
+
const root = messagingCacheRoot(), entries = [];
|
|
30
|
+
if ((await FS.getInfoAsync(root)).exists)
|
|
31
|
+
for (const name of await FS.readDirectoryAsync(root)) {
|
|
32
|
+
if (!owned.test(name))
|
|
33
|
+
continue;
|
|
34
|
+
const dir = root + name + '/';
|
|
35
|
+
const info = await FS.getInfoAsync(dir);
|
|
36
|
+
if (!info.exists || !info.isDirectory)
|
|
37
|
+
continue;
|
|
38
|
+
let bytes = 0, modifiedAt = info.modificationTime * 1000, valid = true, draft = false;
|
|
39
|
+
for (const file of await FS.readDirectoryAsync(dir)) {
|
|
40
|
+
if (file === '__draft__')
|
|
41
|
+
draft = true;
|
|
42
|
+
const item = await FS.getInfoAsync(dir + file);
|
|
43
|
+
if (!item.exists)
|
|
44
|
+
continue;
|
|
45
|
+
if (item.isDirectory) {
|
|
46
|
+
valid = false;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
bytes += item.size;
|
|
50
|
+
modifiedAt = Math.max(modifiedAt, item.modificationTime * 1000);
|
|
51
|
+
}
|
|
52
|
+
if (valid)
|
|
53
|
+
entries.push({ key: dir, bytes, modifiedAt, protected: draft || active.has(dir) });
|
|
54
|
+
}
|
|
55
|
+
const free = await FS.getFreeDiskStorageAsync();
|
|
56
|
+
const selected = messagingDiskEvictions(entries, options.clearUnused ? { ...limits, maxBytes: 0, maxAgeMs: 0 } : limits, free, Date.now(), required);
|
|
57
|
+
let removedBytes = 0, removedFiles = 0;
|
|
58
|
+
for (const dir of selected) {
|
|
59
|
+
// Recheck immediately before deleting: no await may acquire this directory
|
|
60
|
+
// between this check and starting deletion. Allocations always get new UUIDs.
|
|
61
|
+
if (active.has(dir))
|
|
62
|
+
continue;
|
|
63
|
+
try {
|
|
64
|
+
await FS.deleteAsync(dir, { idempotent: true });
|
|
65
|
+
removedBytes += entries.find(e => e.key === dir).bytes;
|
|
66
|
+
removedFiles++;
|
|
67
|
+
}
|
|
68
|
+
catch { /* retry on next maintenance */ }
|
|
69
|
+
}
|
|
70
|
+
const bytesBefore = entries.reduce((n, e) => n + e.bytes, 0), bytesAfter = bytesBefore - removedBytes;
|
|
71
|
+
return { bytesBefore, bytesAfter, protectedBytes: entries.filter(e => e.protected || active.has(e.key)).reduce((n, e) => n + e.bytes, 0), removedFiles, freeBytes: await FS.getFreeDiskStorageAsync(), limitReached: bytesAfter > limits.maxBytes };
|
|
72
|
+
};
|
|
73
|
+
maintenance = run();
|
|
74
|
+
try {
|
|
75
|
+
return await maintenance;
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
maintenance = undefined;
|
|
79
|
+
lastMaintenance = Date.now();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function allocateMessagingCache(requiredBytes = 0, draft = false) {
|
|
83
|
+
const low = requiredBytes > 0 && (await FS.getFreeDiskStorageAsync()) < limits.minFreeBytes + requiredBytes;
|
|
84
|
+
if (!started || low || Date.now() - lastMaintenance > 60000) {
|
|
85
|
+
await maintainExpoMessagingCache({ requiredBytes });
|
|
86
|
+
started = true;
|
|
87
|
+
}
|
|
88
|
+
const dir = messagingCacheRoot() + Crypto.randomUUID() + '/';
|
|
89
|
+
active.add(dir);
|
|
90
|
+
try {
|
|
91
|
+
await FS.makeDirectoryAsync(dir, { intermediates: true });
|
|
92
|
+
if (draft)
|
|
93
|
+
await FS.writeAsStringAsync(dir + '__draft__', '');
|
|
94
|
+
return dir;
|
|
95
|
+
}
|
|
96
|
+
catch (e) {
|
|
97
|
+
active.delete(dir);
|
|
98
|
+
throw e;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export async function removeMessagingCacheUri(uri) {
|
|
102
|
+
const root = messagingCacheRoot();
|
|
103
|
+
if (!uri.startsWith(root))
|
|
104
|
+
return;
|
|
105
|
+
const relative = uri.slice(root.length), parts = relative.split('/');
|
|
106
|
+
if (parts.length !== 2 || !owned.test(parts[0]) || !parts[1] || parts[1] === '.' || parts[1] === '..')
|
|
107
|
+
return;
|
|
108
|
+
const dir = root + parts[0] + '/';
|
|
109
|
+
await FS.deleteAsync(dir, { idempotent: true });
|
|
110
|
+
active.delete(dir);
|
|
111
|
+
}
|
package/dist/expo-calling.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import { type ExpoMessagingScreenProps } from './expo.js';
|
|
2
|
+
import { type ExpoMessagingScreenProps } from './expo-screen.js';
|
|
3
3
|
import { type MessagingCallingScreenProps } from './calling.js';
|
|
4
4
|
export type ExpoMessagingCallingScreenProps = Omit<ExpoMessagingScreenProps, 'renderConversation'> & Pick<MessagingCallingScreenProps, 'onCall' | 'callLabel' | 'onVideoCall' | 'videoCallLabel' | 'unansweredCallId' | 'onDismissCallMessage'>;
|
|
5
5
|
/** Optional composition of the shared conversation, calling entry and native recording/review tools. */
|
package/dist/expo-calling.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { ExpoMessagingScreen } from './expo.js';
|
|
2
|
+
import { ExpoMessagingScreen } from './expo-screen.js';
|
|
3
3
|
import { MessagingCallingScreen } from './calling.js';
|
|
4
4
|
/** Optional composition of the shared conversation, calling entry and native recording/review tools. */
|
|
5
5
|
export function ExpoMessagingCallingScreen({ onCall, callLabel, onVideoCall, videoCallLabel, unansweredCallId, onDismissCallMessage, ...props }) {
|
package/dist/expo-media.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { allocateMessagingCache, removeMessagingCacheUri } from './expo-cache.js';
|
|
1
2
|
import { MessagingError } from '@robono/messaging';
|
|
2
3
|
import { MessagingMediaAccess } from './media-access.js';
|
|
3
4
|
import { awaitMediaScreening } from './media-screening';
|
|
@@ -7,7 +8,6 @@ import { AudioModule, RecordingPresets, createAudioPlayer, setAudioModeAsync } f
|
|
|
7
8
|
import * as Picker from 'expo-image-picker';
|
|
8
9
|
import * as Documents from 'expo-document-picker';
|
|
9
10
|
import * as FS from 'expo-file-system/legacy';
|
|
10
|
-
import * as Crypto from 'expo-crypto';
|
|
11
11
|
import { defaultAttachmentLimits } from '@robono/messaging';
|
|
12
12
|
let audioOwner = false;
|
|
13
13
|
/** Pass your app's call-state guard and restore mode, or supply your existing audio-session coordinator. */
|
|
@@ -47,25 +47,10 @@ export function createExpoMessagingAudioSession(options = {}) {
|
|
|
47
47
|
}
|
|
48
48
|
function check(signal) { if (signal.aborted)
|
|
49
49
|
throw Error('Cancelled.'); }
|
|
50
|
-
const
|
|
51
|
-
throw Error('Private device storage is unavailable.'); return FS.cacheDirectory + 'robono-messaging/'; };
|
|
52
|
-
const ownedDirectories = new Set();
|
|
53
|
-
async function cacheDirectory() { const dir = cacheRoot() + Crypto.randomUUID() + '/'; await FS.makeDirectoryAsync(dir, { intermediates: true }); ownedDirectories.add(dir); return dir; }
|
|
50
|
+
const cacheDirectory = allocateMessagingCache;
|
|
54
51
|
const cacheName = (name) => name.replace(/[^a-zA-Z0-9._-]/g, '_').slice(-90) || 'Attachment';
|
|
55
|
-
async function cachePath(name) { return (await cacheDirectory()) + cacheName(name); }
|
|
56
|
-
|
|
57
|
-
if (!uri.startsWith(cacheRoot()))
|
|
58
|
-
return;
|
|
59
|
-
const dir = uri.slice(0, uri.lastIndexOf('/') + 1);
|
|
60
|
-
// Each owned directory contains exactly one private copy. Remove it in one
|
|
61
|
-
// native operation rather than making the next open wait for two deletions.
|
|
62
|
-
if (ownedDirectories.has(dir)) {
|
|
63
|
-
await FS.deleteAsync(dir, { idempotent: true });
|
|
64
|
-
ownedDirectories.delete(dir);
|
|
65
|
-
}
|
|
66
|
-
else
|
|
67
|
-
await FS.deleteAsync(uri, { idempotent: true });
|
|
68
|
-
}
|
|
52
|
+
async function cachePath(name, bytes = 0) { return (await cacheDirectory(bytes)) + cacheName(name); }
|
|
53
|
+
const removeUri = removeMessagingCacheUri;
|
|
69
54
|
async function remove(file) { await removeUri(file.uri); }
|
|
70
55
|
async function pickedCopy(uri, fileName, mimeType, durationMs) {
|
|
71
56
|
try {
|
|
@@ -78,7 +63,7 @@ async function pickedCopy(uri, fileName, mimeType, durationMs) {
|
|
|
78
63
|
}
|
|
79
64
|
export async function copyMessagingCache(file) { return copied(file.uri, file.fileName, file.mimeType, file.durationMs); }
|
|
80
65
|
async function copied(uri, fileName, mimeType, durationMs) {
|
|
81
|
-
const target = await
|
|
66
|
+
const target = (await allocateMessagingCache(0, true)) + cacheName(fileName).replace(/^__draft__$/, 'Attachment');
|
|
82
67
|
try {
|
|
83
68
|
await FS.copyAsync({ from: uri, to: target });
|
|
84
69
|
const info = await FS.getInfoAsync(target);
|
|
@@ -397,7 +382,7 @@ export function createExpoMessagingStorage(options) {
|
|
|
397
382
|
throw Error('Invalid attachment preview.');
|
|
398
383
|
check(context.signal);
|
|
399
384
|
access.remember(message, plan.attachmentDownload);
|
|
400
|
-
const path = await cachePath('preview.jpg');
|
|
385
|
+
const path = await cachePath('preview.jpg', media.byteSize);
|
|
401
386
|
try {
|
|
402
387
|
const task = FS.createDownloadResumable(https(plan.url), path, { headers: plan.headers ?? {}, sessionType: FS.FileSystemSessionType.FOREGROUND }, progress => { if (progress.totalBytesWritten > media.byteSize)
|
|
403
388
|
void task.cancelAsync().catch(() => { }); });
|
|
@@ -420,7 +405,7 @@ export function createExpoMessagingStorage(options) {
|
|
|
420
405
|
// authorization, but never start the transfer until both have succeeded.
|
|
421
406
|
const [authorized, prepared] = await Promise.allSettled([
|
|
422
407
|
playbackPlan(message, context.signal, context.reauthorize),
|
|
423
|
-
cacheDirectory(),
|
|
408
|
+
cacheDirectory(message.media?.byteSize ?? 0),
|
|
424
409
|
]);
|
|
425
410
|
const dir = prepared.status === 'fulfilled' ? prepared.value : null;
|
|
426
411
|
let path = null;
|
package/dist/expo-messenger.js
CHANGED
|
@@ -55,6 +55,11 @@ export function createExpoMessenger(options) {
|
|
|
55
55
|
});
|
|
56
56
|
const calling = options.calling === false ? undefined : createExpoMessengerCalling({ ...options, inbox });
|
|
57
57
|
const audioSession = options.audioSession ?? createExpoMessagingAudioSession({ isCallActive: () => isNativeCallAudioActive() || calling?.isActive() === true || options.isCallActive?.() === true });
|
|
58
|
+
let notificationRevision;
|
|
59
|
+
const stopNotificationSync = inbox.subscribe(() => { const next = inbox.getSnapshot().inboxCursor; if (next && next !== notificationRevision) {
|
|
60
|
+
notificationRevision = next;
|
|
61
|
+
void connection?.reconcile().catch(() => { });
|
|
62
|
+
} });
|
|
58
63
|
let connection = null, pending = null, closed = false;
|
|
59
64
|
let openNotification;
|
|
60
65
|
const notifications = options.notifications === false ? undefined : {
|
|
@@ -97,10 +102,10 @@ export function createExpoMessenger(options) {
|
|
|
97
102
|
};
|
|
98
103
|
return { client, inbox, storage, audioSession, notifications, calling, availability, maps: mapConnection?.workspace, ...(connectedExtras ? { extras: connectedExtras.extras, components: { TrackingMap: connectedExtras.TrackingMap } } : {}),
|
|
99
104
|
async signOut() { if (closed)
|
|
100
|
-
return; closed = true; activitySubscription?.remove(); const extraCleanup = connectedExtras?.signOut(); inbox.dispose(); const results = await Promise.allSettled([availability?.signOut(), extraCleanup, calling?.dispose(), mapConnection?.signOut(), client.signOut(), (async () => { await pending?.catch(() => { }); await connection?.signOut(); })()]); const failed = results.find(r => r.status === 'rejected'); if (failed?.status === 'rejected')
|
|
105
|
+
return; closed = true; stopNotificationSync(); activitySubscription?.remove(); const extraCleanup = connectedExtras?.signOut(); inbox.dispose(); const results = await Promise.allSettled([availability?.signOut(), extraCleanup, calling?.dispose(), mapConnection?.signOut(), client.signOut(), (async () => { await pending?.catch(() => { }); await connection?.signOut(); })()]); const failed = results.find(r => r.status === 'rejected'); if (failed?.status === 'rejected')
|
|
101
106
|
throw failed.reason; },
|
|
102
107
|
dispose() { if (closed)
|
|
103
|
-
return; closed = true; activitySubscription?.remove(); availability?.dispose(); void calling?.dispose().catch(() => { }); mapConnection?.dispose(); void connectedExtras?.dispose().catch(() => { }); connection?.dispose(); inbox.dispose(); client.dispose(); },
|
|
108
|
+
return; closed = true; stopNotificationSync(); activitySubscription?.remove(); availability?.dispose(); void calling?.dispose().catch(() => { }); mapConnection?.dispose(); void connectedExtras?.dispose().catch(() => { }); connection?.dispose(); inbox.dispose(); client.dispose(); },
|
|
104
109
|
};
|
|
105
110
|
}
|
|
106
111
|
export async function createHostedExpoMessenger(options) {
|
|
@@ -161,6 +166,10 @@ function ExpoMessengerContent({ inbox, contacts = emptyContacts, initialConversa
|
|
|
161
166
|
const subscription = AppState.addEventListener('change', sync);
|
|
162
167
|
return () => { subscription.remove(); props.client.stop(); };
|
|
163
168
|
}, [selected?.id, props.client, props.active]);
|
|
169
|
+
useEffect(() => { const sync = (state) => { if (props.active !== false && (state === null || state === 'active'))
|
|
170
|
+
inbox.start();
|
|
171
|
+
else
|
|
172
|
+
inbox.stop(); }; sync(AppState.currentState); const sub = AppState.addEventListener('change', sync); return () => { sub.remove(); inbox.stop(); }; }, [inbox, props.active]);
|
|
164
173
|
const autoCalls = calling && selected && selected.contactId !== props.userId && groupAllowed ? { ...(callState.features.voice ? { voice: () => calling.call(selected.id, 'voice', selected.kind === 'group') } : {}), ...(callState.features.video ? { video: () => calling.call(selected.id, 'video', selected.kind === 'group') } : {}), voiceLabel: 'Internet call' } : undefined;
|
|
165
174
|
const setSelected = (row) => { setInternal(row); onSelectConversation?.(row); };
|
|
166
175
|
const [showMaps, setShowMaps] = useState(false), mapConnection = useMessengerMaps(maps), mapsAvailable = mapConnection.available;
|
|
@@ -185,5 +194,5 @@ function ExpoMessengerContent({ inbox, contacts = emptyContacts, initialConversa
|
|
|
185
194
|
const account = calling?.deviceCheck ? { name: 'Your account', ...notificationAccount, deviceCheck: calling.deviceCheck, renderCallPreview: (stream) => renderNativeCallVideo({ stream, local: true, style: { width: '100%', height: '100%' } }) } : notificationAccount;
|
|
186
195
|
const knownContact = contacts[selected?.contactId ?? ''];
|
|
187
196
|
const contact = useMemo(() => selected?.contactId === props.userId ? { name: 'Notes to self' } : selected?.kind === 'group' ? { name: selected.name ?? 'Group' } : knownContact ?? { name: selected?.contactId ?? 'Chat' }, [selected?.contactId, selected?.kind, selected?.name, props.userId, knownContact]);
|
|
188
|
-
return _jsxs(View, { style: { flex: 1, minHeight: 0 }, children: [_jsx(MessengerMapsNotice, { error: mapConnection.error, retry: mapConnection.retry }), showMaps && maps ? _jsx(RobonoMaps, { interfaceLocale: mapsLocale, workspace: maps, contacts: contacts, onClose: () => setShowMaps(false) }) : _jsx(ExpoMessagingScreen, { ...props, conversationActions: conversationActions, account: account, contact: contact, participants: props.participants ?? contacts, extras: selected ? props.extras : undefined, callActions: selected && selected.contactId !== props.userId ? { ...autoCalls, ...props.callActions, phoneNumber: contacts[selected.contactId ?? '']?.phoneNumber ?? props.callActions?.phoneNumber } : undefined, onBack: () => { props.client.stop(); setSelected(null); void inbox.refresh().catch(() => { }); }, renderConversation: screen => selected ? _jsx(MessagingCallingScreen, { ...screen, onCall: screen.callActions?.voice, onVideoCall: screen.callActions?.video, callLabel: "Internet call", unansweredCallId: callState.unanswered?.conversationId === selected.id ? callState.unanswered.id : undefined, onDismissCallMessage: calling?.dismissUnanswered }) : _jsxs(MessagingProvider, { ...screen, appearance: props.appearance ?? inboxState.appearance ?? undefined, children: [_jsx(MessagingInbox, { directory: props.directory, onOpenDirectoryContact: props.onOpenDirectoryContact, viewMemory: inboxMemory, client: inbox, userId: props.userId, contacts: contacts, companyName: props.companyName, appearance: props.appearance, active: props.active !== false, headerActions: _jsx(MessagingAccountMenu, { onNewConversation: props.onNewConversation, onPublicRooms: inboxState.publicRoomsAvailable ? () => setPublicRooms(true) : undefined, onMaps: mapsAvailable ? () => setShowMaps(true) : undefined, onNewGroup: inboxState.groupCreationAvailable ? () => setNewGroup(true) : undefined }), onSelect: open, onDeleted: id => props.client.forgetConversation(id) }), publicRooms && _jsx(MessagingPublicRooms, { inbox: inbox, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, createRequestId: () => props.client.createForwardId(), onClose: () => setPublicRooms(false), onJoined: (id, name) => { setPublicRooms(false); open(inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }); } }), newGroup && _jsx(MessagingGroupEditor, { client: props.client, inbox: inbox, userId: props.userId, contacts: contacts, groups: inboxState.groups, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, onClose: () => setNewGroup(false), onSaved: (id, name) => { setNewGroup(false); const row = inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }; open(row); } }), props.inboxOverlay] }) }), _jsx(ExpoMessengerCalls, { calling: calling, state: callState })] });
|
|
197
|
+
return _jsxs(View, { style: { flex: 1, minHeight: 0 }, children: [_jsx(MessengerMapsNotice, { error: mapConnection.error, retry: mapConnection.retry }), showMaps && maps ? _jsx(RobonoMaps, { interfaceLocale: mapsLocale, workspace: maps, contacts: contacts, onClose: () => setShowMaps(false) }) : _jsx(ExpoMessagingScreen, { ...props, conversationActions: conversationActions, account: account, contact: contact, participants: props.participants ?? contacts, extras: selected ? props.extras : undefined, callActions: selected && selected.contactId !== props.userId ? { ...autoCalls, ...props.callActions, phoneNumber: contacts[selected.contactId ?? '']?.phoneNumber ?? props.callActions?.phoneNumber } : undefined, onBack: () => { props.client.stop(); setSelected(null); void inbox.refresh().catch(() => { }); }, renderConversation: screen => selected ? _jsx(MessagingCallingScreen, { ...screen, onCall: screen.callActions?.voice, onVideoCall: screen.callActions?.video, callLabel: "Internet call", unansweredCallId: callState.unanswered?.conversationId === selected.id ? callState.unanswered.id : undefined, onDismissCallMessage: calling?.dismissUnanswered }) : _jsxs(MessagingProvider, { ...screen, appearance: props.appearance ?? inboxState.appearance ?? undefined, children: [_jsx(MessagingInbox, { manageUpdates: false, directory: props.directory, onOpenDirectoryContact: props.onOpenDirectoryContact, viewMemory: inboxMemory, client: inbox, userId: props.userId, contacts: contacts, companyName: props.companyName, appearance: props.appearance, active: props.active !== false, headerActions: _jsx(MessagingAccountMenu, { onNewConversation: props.onNewConversation, onPublicRooms: inboxState.publicRoomsAvailable ? () => setPublicRooms(true) : undefined, onMaps: mapsAvailable ? () => setShowMaps(true) : undefined, onNewGroup: inboxState.groupCreationAvailable ? () => setNewGroup(true) : undefined }), onSelect: open, onDeleted: id => props.client.forgetConversation(id) }), publicRooms && _jsx(MessagingPublicRooms, { inbox: inbox, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, createRequestId: () => props.client.createForwardId(), onClose: () => setPublicRooms(false), onJoined: (id, name) => { setPublicRooms(false); open(inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }); } }), newGroup && _jsx(MessagingGroupEditor, { client: props.client, inbox: inbox, userId: props.userId, contacts: contacts, groups: inboxState.groups, accent: (props.appearance ?? inboxState.appearance ?? defaultMessagingSettings().appearance).colors.accent, onClose: () => setNewGroup(false), onSaved: (id, name) => { setNewGroup(false); const row = inbox.getSnapshot().conversations.find(c => c.id === id) ?? { id, kind: 'group', name, contactId: null, lastMessage: null, unreadCount: 0, canSend: true }; open(row); } }), props.inboxOverlay] }) }), _jsx(ExpoMessengerCalls, { calling: calling, state: callState })] });
|
|
189
198
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import * as Notifications from 'expo-notifications';
|
|
2
|
+
export declare function notificationData(value: unknown): Record<string, unknown> | undefined;
|
|
3
|
+
export declare function presentedNotificationData(notification: Notifications.Notification): Record<string, unknown> | undefined;
|
|
4
|
+
export declare const rememberNotificationAccount: (scope: string, enabled: boolean) => Promise<void>;
|
|
5
|
+
export declare function notificationWasRead(value: unknown): Promise<boolean>;
|
|
6
|
+
export declare function dismissReadNotification(value: unknown): Promise<boolean>;
|
|
7
|
+
export declare function registerNotificationCleanup(): Promise<void>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import * as Notifications from 'expo-notifications';
|
|
2
|
+
import * as SecureStore from 'expo-secure-store';
|
|
3
|
+
import * as TaskManager from 'expo-task-manager';
|
|
4
|
+
import { parseMessagingReadNotification, readNotificationCovers, androidMessagingNotificationData } from '@robono/messaging';
|
|
5
|
+
const readKey = (scope) => 'robono.messaging.notification.read.' + scope;
|
|
6
|
+
const task = 'robono.messaging.read-cleanup.v1', accountsKey = 'robono.messaging.notification.accounts.v1';
|
|
7
|
+
let queue = Promise.resolve();
|
|
8
|
+
const serial = (fn) => { const next = queue.then(fn, fn); queue = next.catch(() => { }); return next; };
|
|
9
|
+
export function notificationData(value) {
|
|
10
|
+
if (!value || typeof value !== 'object')
|
|
11
|
+
return;
|
|
12
|
+
const d = value;
|
|
13
|
+
if (typeof d.event === 'string')
|
|
14
|
+
return d;
|
|
15
|
+
for (const v of [d.body, d.dataString, d.data?.dataString, d.data, d.notification?.request?.content?.data]) {
|
|
16
|
+
let decoded = v;
|
|
17
|
+
try {
|
|
18
|
+
if (typeof v === 'string')
|
|
19
|
+
decoded = JSON.parse(v);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (decoded && decoded !== value && typeof decoded === 'object') {
|
|
25
|
+
if (typeof decoded.event === 'string')
|
|
26
|
+
return decoded;
|
|
27
|
+
if (decoded.body && typeof decoded.body === 'object' && typeof decoded.body.event === 'string')
|
|
28
|
+
return decoded.body;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function presentedNotificationData(notification) { return notificationData(notification.request.content.data) ?? androidMessagingNotificationData(notification.request.identifier); }
|
|
33
|
+
async function accounts() { try {
|
|
34
|
+
const v = JSON.parse(await SecureStore.getItemAsync(accountsKey) ?? '[]');
|
|
35
|
+
return Array.isArray(v) ? v.filter(x => typeof x === 'string' && /^[a-f0-9]{64}$/.test(x)) : [];
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return [];
|
|
39
|
+
} }
|
|
40
|
+
export const rememberNotificationAccount = (scope, enabled) => serial(async () => {
|
|
41
|
+
const list = await accounts();
|
|
42
|
+
if (!enabled)
|
|
43
|
+
await SecureStore.deleteItemAsync(readKey(scope));
|
|
44
|
+
await SecureStore.setItemAsync(accountsKey, JSON.stringify(enabled ? [...new Set([...list, scope])] : list.filter(s => s !== scope)), { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY });
|
|
45
|
+
});
|
|
46
|
+
// Compact recent-read hints stay below the native secure-storage size limit.
|
|
47
|
+
// The authoritative foreground reconciliation covers older reads and cache misses.
|
|
48
|
+
async function savedReads(scope) {
|
|
49
|
+
try {
|
|
50
|
+
const data = JSON.parse(await SecureStore.getItemAsync(readKey(scope)) ?? '[]');
|
|
51
|
+
return Array.isArray(data) ? data.map(r => Array.isArray(r) ? { event: 'robono.messaging.read', accountScope: scope, conversationId: r[0], messageId: r[1], kind: r[2], savedAt: r[3] } : r).filter(r => parseMessagingReadNotification(r) && r.savedAt > Date.now() - 7 * 86400000) : [];
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function notificationWasRead(value) {
|
|
58
|
+
const data = notificationData(value);
|
|
59
|
+
if (data?.event !== 'robono.messaging' || typeof data.accountScope !== 'string' || !/^[a-f0-9]{64}$/.test(data.accountScope))
|
|
60
|
+
return false;
|
|
61
|
+
return serial(async () => (await savedReads(data.accountScope)).some(read => readNotificationCovers(read, data)));
|
|
62
|
+
}
|
|
63
|
+
export async function dismissReadNotification(value) {
|
|
64
|
+
const read = parseMessagingReadNotification(notificationData(value));
|
|
65
|
+
if (!read)
|
|
66
|
+
return false;
|
|
67
|
+
return serial(async () => {
|
|
68
|
+
if (!(await accounts()).includes(read.accountScope))
|
|
69
|
+
return false;
|
|
70
|
+
const reads = await savedReads(read.accountScope), previous = reads.find(r => r.conversationId === read.conversationId && r.kind === read.kind && (read.kind !== 'message' || r.messageId === read.messageId));
|
|
71
|
+
const newer = !previous || read.messageId.length > previous.messageId.length || read.messageId.length === previous.messageId.length && read.messageId >= previous.messageId;
|
|
72
|
+
if (newer)
|
|
73
|
+
await SecureStore.setItemAsync(readKey(read.accountScope), JSON.stringify([...reads.filter(r => r !== previous), { ...read, savedAt: Date.now() }].slice(-16).map(r => [r.conversationId, r.messageId, r.kind, r.savedAt])), { keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY });
|
|
74
|
+
for (const n of await Notifications.getPresentedNotificationsAsync())
|
|
75
|
+
if (readNotificationCovers(read, presentedNotificationData(n)))
|
|
76
|
+
await Notifications.dismissNotificationAsync(n.request.identifier);
|
|
77
|
+
return true;
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
// Loaded by the public Expo entry point, including headless background launches.
|
|
81
|
+
if (!TaskManager.isTaskDefined(task))
|
|
82
|
+
TaskManager.defineTask(task, async ({ data, error }) => {
|
|
83
|
+
if (!error) {
|
|
84
|
+
if (await dismissReadNotification(data))
|
|
85
|
+
return;
|
|
86
|
+
const event = notificationData(data);
|
|
87
|
+
if (event && await notificationWasRead(event))
|
|
88
|
+
for (const n of await Notifications.getPresentedNotificationsAsync()) {
|
|
89
|
+
const d = presentedNotificationData(n);
|
|
90
|
+
if (d?.accountScope === event.accountScope && d?.conversationId === event.conversationId && d?.messageId === event.messageId)
|
|
91
|
+
await Notifications.dismissNotificationAsync(n.request.identifier);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
export async function registerNotificationCleanup() { if (!await TaskManager.isTaskRegisteredAsync(task))
|
|
96
|
+
await Notifications.registerTaskAsync(task); }
|
|
@@ -17,6 +17,7 @@ export interface ExpoMessagingNotificationOptions {
|
|
|
17
17
|
/** One restored account. Never prompts on mount, replaces a global handler or opens an unverified call. */
|
|
18
18
|
export declare function connectExpoMessagingNotifications(options: ExpoMessagingNotificationOptions): Promise<{
|
|
19
19
|
ready: Promise<void>;
|
|
20
|
+
reconcile: () => Promise<void>;
|
|
20
21
|
/** Call only after the user chooses Enable notifications in your interface. */
|
|
21
22
|
enable(): Promise<boolean>;
|
|
22
23
|
/** Await before revoking your login session, so the old account's token is removed. */
|