@robono/messaging-react-native 0.24.0 → 0.25.1
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 +11 -0
- package/README.md +77 -1
- package/RobonoMessagingRuntime.podspec +2 -0
- package/SBOM.spdx.json +1832 -560
- package/android/build.gradle +4 -1
- 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 +1 -1
- package/app.plugin.cjs +14 -1
- 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 +2 -1
- package/dist/account.js +6 -2
- 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.js +61 -16
- package/dist/bubble-design.d.ts +1 -1
- package/dist/cloudkit-backup.d.ts +14 -0
- package/dist/cloudkit-backup.js +193 -0
- package/dist/conversation-details.js +1 -1
- package/dist/customization.d.ts +1 -0
- package/dist/delivery-bar.d.ts +1 -1
- package/dist/delivery-bar.js +5 -2
- package/dist/delivery-notice.d.ts +9 -0
- package/dist/delivery-notice.js +15 -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-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 +7 -0
- package/dist/expo-backup-passkeys.js +31 -7
- package/dist/expo-backup-settings.js +26 -8
- 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-connected-calling.d.ts +1 -0
- package/dist/expo-connected-calling.js +13 -2
- 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-media.d.ts +2 -0
- package/dist/expo-media.js +15 -21
- package/dist/expo-messenger.d.ts +10 -0
- package/dist/expo-messenger.js +18 -7
- 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 +4 -1
- package/dist/expo-reviews.js +122 -17
- package/dist/expo-screen.js +5 -4
- package/dist/expo-thumbnails.d.ts +2 -2
- package/dist/expo-thumbnails.js +48 -5
- package/dist/expo.d.ts +10 -0
- package/dist/expo.js +8 -0
- package/dist/header-calls.js +1 -1
- package/dist/inbox-search.d.ts +1 -1
- package/dist/inbox-search.js +7 -3
- package/dist/inbox.d.ts +1 -0
- package/dist/inbox.js +5 -5
- package/dist/index.d.ts +8 -3
- package/dist/index.js +138 -63
- package/dist/linked-apps.d.ts +45 -0
- package/dist/linked-apps.js +40 -0
- package/dist/loading-messages.d.ts +1 -1
- package/dist/loading-messages.js +1 -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/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 +8 -4
- package/dist/reviews.js +53 -26
- package/dist/scheduled.js +2 -2
- package/dist/search.js +18 -8
- package/ios/RobonoBackupCloudKit.m +96 -0
- package/ios/RobonoHistoryStore.m +170 -0
- package/package.json +23 -5
- package/plugin/backup-expiration.cjs +23 -0
- package/plugin/prepare-native.cjs +12 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type Size = {
|
|
2
|
+
width: number;
|
|
3
|
+
height: number;
|
|
4
|
+
};
|
|
5
|
+
/** Read only JPEG header bytes already present in an authorized local preview.
|
|
6
|
+
* No fetch, native decode, Buffer or atob is needed for the first rendered frame.
|
|
7
|
+
* Smaller disk previews can have a different URI from the earlier display copy.
|
|
8
|
+
*/
|
|
9
|
+
export declare function localPreviewSize(uri: string): Size | undefined;
|
|
10
|
+
export declare function readPreviewSize(scope: object, key: string, uri: string | undefined, now?: number): Size | undefined;
|
|
11
|
+
export declare function rememberPreviewSize(scope: object, key: string, uri: string, width: number, height: number, now?: number): Size | undefined;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const scopes = new WeakMap();
|
|
2
|
+
/** Read only JPEG header bytes already present in an authorized local preview.
|
|
3
|
+
* No fetch, native decode, Buffer or atob is needed for the first rendered frame.
|
|
4
|
+
* Smaller disk previews can have a different URI from the earlier display copy.
|
|
5
|
+
*/
|
|
6
|
+
export function localPreviewSize(uri) {
|
|
7
|
+
const prefix = 'data:image/jpeg;base64,';
|
|
8
|
+
if (!uri.startsWith(prefix) || uri.length > 300000)
|
|
9
|
+
return;
|
|
10
|
+
const text = uri.slice(prefix.length);
|
|
11
|
+
if (text.length % 4 !== 0 || text.length < 12)
|
|
12
|
+
return;
|
|
13
|
+
const length = text.length / 4 * 3 - (text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0);
|
|
14
|
+
const digit = (i) => {
|
|
15
|
+
const c = text.charCodeAt(i);
|
|
16
|
+
return c >= 65 && c <= 90 ? c - 65 : c >= 97 && c <= 122 ? c - 71 : c >= 48 && c <= 57 ? c + 4 : c === 43 ? 62 : c === 47 ? 63 : -1;
|
|
17
|
+
};
|
|
18
|
+
const byte = (i) => {
|
|
19
|
+
if (i < 0 || i >= length)
|
|
20
|
+
return -1;
|
|
21
|
+
const p = Math.floor(i / 3) * 4, r = i % 3, a = digit(p + r), b = digit(p + r + 1);
|
|
22
|
+
if (a < 0 || b < 0)
|
|
23
|
+
return -1;
|
|
24
|
+
return r === 0 ? (a << 2) | (b >> 4) : r === 1 ? ((a & 15) << 4) | (b >> 2) : ((a & 3) << 6) | b;
|
|
25
|
+
};
|
|
26
|
+
const word = (i) => { const a = byte(i), b = byte(i + 1); return a < 0 || b < 0 ? -1 : (a << 8) | b; };
|
|
27
|
+
if (byte(0) !== 255 || byte(1) !== 216)
|
|
28
|
+
return;
|
|
29
|
+
let orientation = 1, size;
|
|
30
|
+
for (let offset = 2, segments = 0; offset + 3 < length && segments++ < 128;) {
|
|
31
|
+
if (byte(offset++) !== 255)
|
|
32
|
+
return;
|
|
33
|
+
while (byte(offset) === 255)
|
|
34
|
+
offset++;
|
|
35
|
+
const marker = byte(offset++);
|
|
36
|
+
if (marker === 217 || marker === 218)
|
|
37
|
+
break;
|
|
38
|
+
const count = word(offset);
|
|
39
|
+
if (count < 2 || offset + count > length)
|
|
40
|
+
return;
|
|
41
|
+
if (marker === 225 && count >= 16 && [69, 120, 105, 102, 0, 0].every((v, i) => byte(offset + 2 + i) === v)) {
|
|
42
|
+
const base = offset + 8, end = offset + count, little = byte(base) === 73 && byte(base + 1) === 73;
|
|
43
|
+
const big = byte(base) === 77 && byte(base + 1) === 77;
|
|
44
|
+
const u16 = (p) => p >= base && p + 2 <= end ? (little ? (byte(p + 1) << 8) | byte(p) : word(p)) : -1;
|
|
45
|
+
const u32 = (p) => p >= base && p + 4 <= end ? (little ? u16(p) + u16(p + 2) * 65536 : u16(p) * 65536 + u16(p + 2)) : -1;
|
|
46
|
+
if ((little || big) && u16(base + 2) === 42) {
|
|
47
|
+
const dir = base + u32(base + 4), entries = u16(dir);
|
|
48
|
+
for (let i = 0; i < Math.min(entries, 128); i++) {
|
|
49
|
+
const p = dir + 2 + i * 12;
|
|
50
|
+
if (p + 12 > end)
|
|
51
|
+
break;
|
|
52
|
+
if (u16(p) === 274 && u16(p + 2) === 3 && u32(p + 4) === 1) {
|
|
53
|
+
const value = u16(p + 8);
|
|
54
|
+
if (value >= 1 && value <= 8)
|
|
55
|
+
orientation = value;
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if ([192, 193, 194, 195, 197, 198, 199, 201, 202, 203, 205, 206, 207].includes(marker)) {
|
|
62
|
+
if (count < 8)
|
|
63
|
+
return;
|
|
64
|
+
const height = word(offset + 3), width = word(offset + 5);
|
|
65
|
+
if (width <= 0 || height <= 0)
|
|
66
|
+
return;
|
|
67
|
+
size = { width, height };
|
|
68
|
+
}
|
|
69
|
+
offset += count;
|
|
70
|
+
}
|
|
71
|
+
return size && (orientation >= 5 ? { width: size.height, height: size.width } : size);
|
|
72
|
+
}
|
|
73
|
+
// Match the short-lived preview cache. These are layout hints, never media
|
|
74
|
+
// access grants: callers must already have the current authorized preview URI.
|
|
75
|
+
export function readPreviewSize(scope, key, uri, now = Date.now()) {
|
|
76
|
+
if (!uri)
|
|
77
|
+
return;
|
|
78
|
+
const rows = scopes.get(scope), entry = rows?.get(key);
|
|
79
|
+
if (entry && entry.expires <= now)
|
|
80
|
+
rows.delete(key);
|
|
81
|
+
else if (entry?.uri === uri)
|
|
82
|
+
return { width: entry.width, height: entry.height };
|
|
83
|
+
const size = localPreviewSize(uri);
|
|
84
|
+
return size ? rememberPreviewSize(scope, key, uri, size.width, size.height, now) : undefined;
|
|
85
|
+
}
|
|
86
|
+
export function rememberPreviewSize(scope, key, uri, width, height, now = Date.now()) {
|
|
87
|
+
if (!uri || !Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0 || width > 100000 || height > 100000)
|
|
88
|
+
return;
|
|
89
|
+
let rows = scopes.get(scope);
|
|
90
|
+
if (!rows) {
|
|
91
|
+
rows = new Map();
|
|
92
|
+
scopes.set(scope, rows);
|
|
93
|
+
}
|
|
94
|
+
for (const [id, entry] of rows)
|
|
95
|
+
if (entry.expires <= now)
|
|
96
|
+
rows.delete(id);
|
|
97
|
+
rows.delete(key);
|
|
98
|
+
rows.set(key, { uri, width, height, expires: now + 60000 });
|
|
99
|
+
while (rows.size > 60)
|
|
100
|
+
rows.delete(rows.keys().next().value);
|
|
101
|
+
return { width, height };
|
|
102
|
+
}
|
package/dist/recent-media.js
CHANGED
|
@@ -39,7 +39,8 @@ export class RecentMessagingMedia {
|
|
|
39
39
|
download: async (message, context) => {
|
|
40
40
|
if (context.signal.aborted)
|
|
41
41
|
throw Error('Cancelled.');
|
|
42
|
-
|
|
42
|
+
if (context.purpose !== 'preview')
|
|
43
|
+
this.prioritize(context.signal, key(message));
|
|
43
44
|
if (context.reauthorize)
|
|
44
45
|
return this.source.download(message, context);
|
|
45
46
|
const id = key(message), entry = this.entries.get(id);
|
package/dist/reviews.d.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
|
+
import { type MessagingAppearance } from '@robono/messaging';
|
|
1
2
|
import React from "react";
|
|
2
3
|
import { MessageReviewClient } from "@robono/messaging";
|
|
3
4
|
export interface MessagingReviewInboxProps {
|
|
4
5
|
client: MessageReviewClient;
|
|
6
|
+
/** Optional notification/deep-link target. It is fetched with current reviewer authorization. */
|
|
7
|
+
reviewId?: string;
|
|
8
|
+
appearance?: MessagingAppearance;
|
|
5
9
|
name?: (id: string) => string;
|
|
6
|
-
conversationName: (conversationId: string,
|
|
10
|
+
conversationName: (conversationId: string, subjectId: string) => string;
|
|
7
11
|
renderMedia?: (input: {
|
|
8
12
|
url: string;
|
|
9
13
|
kind: string;
|
|
10
14
|
label: string;
|
|
15
|
+
foreground: string;
|
|
16
|
+
file?: import('@robono/messaging').MessageMedia;
|
|
11
17
|
}) => React.ReactNode;
|
|
12
18
|
}
|
|
13
|
-
|
|
14
|
-
* Media URLs live only while the selected review remains open. */
|
|
15
|
-
export declare function MessagingReviewInbox({ client, name, conversationName, renderMedia }: MessagingReviewInboxProps): React.JSX.Element;
|
|
19
|
+
export declare function MessagingReviewInbox(props: MessagingReviewInboxProps): React.JSX.Element;
|
package/dist/reviews.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { messageReviewSubject, messageReviewSender, messagingContrastInk, defaultMessagingSettings } from '@robono/messaging';
|
|
3
|
+
import { useMessagingPopupColors, useMessagingAppearance } from './appearance-context.js';
|
|
4
|
+
import { Text, MessagingTypography } from './typography.js';
|
|
2
5
|
import { useEffect, useRef, useState } from "react";
|
|
3
|
-
import { AppState, Image, Pressable, ScrollView,
|
|
6
|
+
import { AppState, ActivityIndicator, Image, Pressable, ScrollView, View, } from "react-native";
|
|
4
7
|
const reviewStateLabel = (state) => ({
|
|
5
8
|
pending: "Waiting for review",
|
|
6
9
|
approved: "Approved — waiting for delivery",
|
|
@@ -9,11 +12,18 @@ const reviewStateLabel = (state) => ({
|
|
|
9
12
|
expired: "Expired",
|
|
10
13
|
cancelled: "Cancelled",
|
|
11
14
|
})[state];
|
|
12
|
-
/** Shared
|
|
15
|
+
/** Shared authorized-review inbox. Completed decisions have no approve/reject controls.
|
|
13
16
|
* Media URLs live only while the selected review remains open. */
|
|
14
|
-
|
|
17
|
+
const defaultAppearance = defaultMessagingSettings().appearance;
|
|
18
|
+
export function MessagingReviewInbox(props) {
|
|
19
|
+
const inherited = useMessagingAppearance(), appearance = props.appearance ?? inherited ?? defaultAppearance;
|
|
20
|
+
return _jsx(MessagingTypography, { appearance: appearance, screen: "panels", children: _jsx(MessageReviewInboxContent, { ...props, appearance: appearance }) });
|
|
21
|
+
}
|
|
22
|
+
function MessageReviewInboxContent({ client, reviewId, appearance, name = (id) => id, conversationName, renderMedia }) {
|
|
23
|
+
const colors = useMessagingPopupColors(appearance);
|
|
24
|
+
const [imageReady, setImageReady] = useState(false);
|
|
15
25
|
const [items, setItems] = useState([]), [selected, setSelected] = useState(null), [completed, setCompleted] = useState(false), [media, setMedia] = useState(null), [error, setError] = useState(""), [busy, setBusy] = useState(false), [nextCursor, setNextCursor] = useState(null);
|
|
16
|
-
const generation = useRef(0);
|
|
26
|
+
const generation = useRef(0), activeClient = useRef(client);
|
|
17
27
|
const load = async (history = completed, append = false) => {
|
|
18
28
|
const g = ++generation.current;
|
|
19
29
|
setBusy(true);
|
|
@@ -30,6 +40,8 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
30
40
|
}
|
|
31
41
|
catch {
|
|
32
42
|
if (g === generation.current) {
|
|
43
|
+
setItems([]);
|
|
44
|
+
setNextCursor(null);
|
|
33
45
|
setError("Reviews could not be loaded. Refresh and try again.");
|
|
34
46
|
}
|
|
35
47
|
}
|
|
@@ -39,11 +51,17 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
39
51
|
}
|
|
40
52
|
};
|
|
41
53
|
useEffect(() => {
|
|
42
|
-
|
|
54
|
+
activeClient.current = client;
|
|
55
|
+
setItems([]);
|
|
56
|
+
setNextCursor(null);
|
|
57
|
+
if (reviewId)
|
|
58
|
+
void open({ id: reviewId });
|
|
59
|
+
else
|
|
60
|
+
void load();
|
|
43
61
|
return () => {
|
|
44
62
|
generation.current++;
|
|
45
63
|
};
|
|
46
|
-
}, [client]);
|
|
64
|
+
}, [client, reviewId]);
|
|
47
65
|
useEffect(() => {
|
|
48
66
|
if (!selected)
|
|
49
67
|
return;
|
|
@@ -61,10 +79,12 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
61
79
|
if (g === generation.current) {
|
|
62
80
|
setSelected(null);
|
|
63
81
|
setMedia(null);
|
|
82
|
+
setItems([]);
|
|
83
|
+
setNextCursor(null);
|
|
64
84
|
setError("This review is no longer available to you.");
|
|
65
85
|
}
|
|
66
86
|
});
|
|
67
|
-
},
|
|
87
|
+
}, 5000);
|
|
68
88
|
const background = AppState.addEventListener("change", (state) => {
|
|
69
89
|
if (state !== "active")
|
|
70
90
|
setMedia(null);
|
|
@@ -88,6 +108,8 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
88
108
|
}
|
|
89
109
|
catch {
|
|
90
110
|
if (g === generation.current) {
|
|
111
|
+
setItems([]);
|
|
112
|
+
setNextCursor(null);
|
|
91
113
|
setError("This review is no longer available to you.");
|
|
92
114
|
}
|
|
93
115
|
}
|
|
@@ -110,6 +132,7 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
110
132
|
result.digest !== selected.digest)
|
|
111
133
|
throw Error("Changed");
|
|
112
134
|
setMedia(result);
|
|
135
|
+
setImageReady(false);
|
|
113
136
|
}
|
|
114
137
|
catch {
|
|
115
138
|
if (g === generation.current) {
|
|
@@ -155,34 +178,37 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
155
178
|
setBusy(false);
|
|
156
179
|
}
|
|
157
180
|
};
|
|
158
|
-
const button = (label, onPress) => (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, disabled: busy, onPress: onPress, style: {
|
|
181
|
+
const button = (label, onPress, primary = false) => (_jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, disabled: busy, onPress: onPress, style: {
|
|
159
182
|
padding: 12,
|
|
160
183
|
minHeight: 44,
|
|
161
184
|
borderWidth: 1,
|
|
162
|
-
borderColor:
|
|
185
|
+
borderColor: primary ? colors.accent : colors.secondary,
|
|
186
|
+
backgroundColor: primary ? colors.accent : 'transparent',
|
|
163
187
|
borderRadius: 8,
|
|
164
188
|
margin: 4,
|
|
165
189
|
opacity: busy ? .5 : 1,
|
|
166
|
-
}, children: _jsx(Text, { style: { color:
|
|
167
|
-
|
|
190
|
+
}, children: _jsx(Text, { style: { color: primary ? messagingContrastInk(colors.accent) : colors.foreground, fontWeight: primary ? '700' : '400' }, children: label }) }));
|
|
191
|
+
// A new authenticated client must never render the previous account's list
|
|
192
|
+
// during the effect/loading transition.
|
|
193
|
+
if (activeClient.current !== client)
|
|
194
|
+
return null;
|
|
195
|
+
return (_jsxs(ScrollView, { testID: "message-review-inbox", style: { backgroundColor: colors.background }, contentContainerStyle: { padding: 16, gap: 12 }, children: [_jsx(Text, { accessibilityRole: "header", style: { fontSize: 22, fontWeight: "700", color: colors.foreground }, children: selected ? 'Review message' : 'Message reviews' }), !selected && _jsx(Text, { style: { color: colors.secondary }, children: "Messages stay private until an authorized reviewer approves delivery." }), !selected && _jsxs(View, { style: { flexDirection: "row", flexWrap: "wrap" }, children: [button("Pending", () => {
|
|
168
196
|
setCompleted(false);
|
|
169
197
|
void load(false);
|
|
170
|
-
}), button("Completed", () => {
|
|
198
|
+
}, !completed), button("Completed", () => {
|
|
171
199
|
setCompleted(true);
|
|
172
200
|
void load(true);
|
|
173
|
-
}), button("Refresh", () => void load())] }), !!error && (_jsx(Text, { accessibilityRole: "alert", style: { color:
|
|
201
|
+
}, completed), button("Refresh", () => void load())] }), !!error && (_jsx(Text, { accessibilityRole: "alert", style: { color: colors.danger }, children: error })), selected
|
|
174
202
|
? (_jsxs(View, { testID: "selected-message-review", style: { gap: 12 }, children: [button("Back to reviews", () => {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
setMedia(null);
|
|
178
|
-
setError("");
|
|
179
|
-
}), _jsxs(Text, { style: { color: "#17251c", fontWeight: "700" }, children: ["Message from ", name(selected.childId)] }), _jsxs(Text, { style: { color: "#44534a" }, children: ["To ", conversationName(selected.conversationId, selected.childId)] }), _jsx(Text, { selectable: true, style: { color: "#17251c" }, children: selected.content.text }), selected.content.media && (_jsxs(_Fragment, { children: [_jsx(Text, { style: { color: "#44534a" }, children: selected.content.media.fileName }), ["pending", "approved"].includes(selected.state) &&
|
|
203
|
+
void load();
|
|
204
|
+
}), _jsxs(Text, { style: { color: colors.foreground, fontWeight: "700" }, children: ["Message from ", name(messageReviewSender(selected))] }), _jsxs(Text, { style: { color: colors.secondary }, children: ["To ", selected.direction === 'incoming' ? name(messageReviewSubject(selected)) : conversationName(selected.conversationId, messageReviewSubject(selected))] }), !!selected.content.text && _jsx(Text, { selectable: true, style: { color: colors.foreground }, children: selected.content.text }), selected.content.media && (_jsxs(_Fragment, { children: [_jsx(Text, { style: { color: colors.secondary }, children: selected.content.media.fileName }), ["pending", "approved"].includes(selected.state) &&
|
|
180
205
|
button("Open attachment", () => void preview())] })), media && (media.kind === "image"
|
|
181
|
-
? (_jsx(Image, { accessibilityLabel: "Held photo", source: { uri: media.url }, style: { height: 240, width: "100%", resizeMode: "contain" } }))
|
|
206
|
+
? (_jsxs(View, { style: { height: 240, width: '100%' }, children: [_jsx(Image, { accessibilityLabel: "Held photo", accessibilityState: { busy: !imageReady }, onLoad: () => setImageReady(true), onError: () => { setImageReady(true); setError('This photo could not be displayed. Reopen the attachment to try again.'); }, source: { uri: media.url }, style: { height: 240, width: "100%", resizeMode: "contain" } }), !imageReady && _jsx(ActivityIndicator, { color: colors.accent, style: { position: 'absolute', alignSelf: 'center', top: 100 } })] }))
|
|
182
207
|
: renderMedia?.({
|
|
183
208
|
...media,
|
|
184
|
-
|
|
185
|
-
|
|
209
|
+
file: selected.content.media,
|
|
210
|
+
label: selected.content.media?.fileName ?? "Held attachment", foreground: colors.foreground,
|
|
211
|
+
}) ?? (_jsx(Text, { children: "Open this review in a supported media viewer before approving." }))), _jsx(Text, { testID: "review-state", style: { color: colors.secondary }, children: selected.state === "pending"
|
|
186
212
|
? "Waiting for your decision"
|
|
187
213
|
: selected.state === "approved"
|
|
188
214
|
? "Approved — waiting for delivery"
|
|
@@ -190,15 +216,16 @@ export function MessagingReviewInbox({ client, name = (id) => id, conversationNa
|
|
|
190
216
|
? "Delivered"
|
|
191
217
|
: selected.state === "rejected"
|
|
192
218
|
? "Not approved"
|
|
193
|
-
: "Expired" }), selected.state === "pending" && (_jsxs(View, { style: { flexDirection: "row", flexWrap: "wrap" }, children: [button("Approve
|
|
219
|
+
: "Expired" }), selected.state === "pending" && (_jsxs(View, { style: { flexDirection: "row", flexWrap: "wrap" }, children: [button("Approve", () => void decide("approve"), true), button("Reject", () => void decide("reject"))] })), selected.state === "approved" &&
|
|
194
220
|
button("Retry delivery", () => void decide("release"))] }))
|
|
195
|
-
: (_jsxs(_Fragment, { children: [items.map((item) => (_jsxs(Pressable, { testID: "review-item-" + item.id, accessibilityRole: "button", accessibilityLabel: "Review message from " + name(item
|
|
221
|
+
: (_jsxs(_Fragment, { children: [items.map((item) => (_jsxs(Pressable, { testID: "review-item-" + item.id, accessibilityRole: "button", accessibilityLabel: "Review message from " + name(messageReviewSender(item)), disabled: busy, onPress: () => void open(item), style: {
|
|
196
222
|
padding: 16,
|
|
197
223
|
borderWidth: 1,
|
|
198
|
-
borderColor: "
|
|
224
|
+
borderColor: colors.foreground + "22",
|
|
225
|
+
backgroundColor: colors.background,
|
|
199
226
|
borderRadius: 8,
|
|
200
227
|
gap: 5,
|
|
201
|
-
}, children: [_jsxs(Text, { style: { color:
|
|
202
|
-
"Message" }), _jsx(Text, { style: { color:
|
|
228
|
+
}, children: [_jsxs(Text, { style: { color: colors.foreground, fontWeight: "600" }, children: [name(messageReviewSender(item)), " \u2192", " ", item.direction === 'incoming' ? name(messageReviewSubject(item)) : conversationName(item.conversationId, messageReviewSubject(item))] }), _jsx(Text, { numberOfLines: 2, style: { color: colors.secondary }, children: item.content.text ?? item.content.media?.fileName ??
|
|
229
|
+
"Message" }), _jsx(Text, { style: { color: colors.secondary }, children: reviewStateLabel(item.state) })] }, item.id))), !busy && !items.length && (_jsxs(Text, { style: { color: colors.secondary }, children: ["No ", completed ? "completed" : "pending", " reviews."] })), nextCursor &&
|
|
203
230
|
button("Load more", () => void load(completed, true))] }))] }));
|
|
204
231
|
}
|
package/dist/scheduled.js
CHANGED
|
@@ -3,7 +3,7 @@ import { messagingContrastInk } from '@robono/messaging';
|
|
|
3
3
|
import { Text, TextInput } from './typography.js';
|
|
4
4
|
import { useRobonoLocale } from './localization.js';
|
|
5
5
|
import { useEffect, useRef, useState } from 'react';
|
|
6
|
-
import { Pressable, ScrollView, View } from 'react-native';
|
|
6
|
+
import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native';
|
|
7
7
|
import { MessagingPopup, useMessagingPopupColors } from './popup.js';
|
|
8
8
|
const pad = (n) => String(n).padStart(2, '0');
|
|
9
9
|
/** Same bounded popup as the other Messenger tools; all dates are shown locally. */
|
|
@@ -81,5 +81,5 @@ export function ScheduledMessages({ client, accent, onClose }) {
|
|
|
81
81
|
} };
|
|
82
82
|
if (editing)
|
|
83
83
|
return _jsx(ScheduleTimePicker, { initial: editing.sendAt, title: uiText("Reschedule message"), accent: accent, busy: busy, error: error, onSave: time => void change(editing, time), onClose: () => setEditing(null) });
|
|
84
|
-
return _jsx(MessagingPopup, { screen: "scheduled", title: uiText("Scheduled messages"), description: uiText("Only you can see these until they are sent."), background: colors.background, onClose: onClose, contentWidth: 640, children: _jsxs(ScrollView, { contentContainerStyle: { padding: 12, gap: 12 }, children: [loading && _jsx(
|
|
84
|
+
return _jsx(MessagingPopup, { screen: "scheduled", title: uiText("Scheduled messages"), description: uiText("Only you can see these until they are sent."), background: colors.background, onClose: onClose, contentWidth: 640, children: _jsxs(ScrollView, { contentContainerStyle: { padding: 12, gap: 12, minHeight: 100 }, children: [loading && _jsx(View, { pointerEvents: "none", style: { position: 'absolute', top: 12, left: 12, right: 12, height: 48, alignItems: 'center', justifyContent: 'center' }, children: _jsx(ActivityIndicator, { accessibilityLabel: uiText("Loading…"), color: colors.foreground }) }), !loading && !items.length && !error && _jsx(Text, { style: { color: colors.foreground, fontSize: 17 }, children: uiText("No scheduled messages. Hold Send after writing a message to choose a time.") }), !!error && _jsx(Pressable, { onPress: () => void load(), accessibilityRole: "button", accessibilityLabel: uiText("Retry scheduled messages"), children: _jsxs(Text, { accessibilityRole: "alert", style: { color: colors.foreground }, children: [error, ' ', uiText("Tap to refresh.")] }) }), items.map(item => _jsxs(View, { style: { borderRadius: 12, backgroundColor: colors.incoming, padding: 12, gap: 8 }, children: [_jsxs(Text, { style: { color: colors.foreground, fontWeight: '600', fontSize: 16 }, children: [new Date(item.sendAt).toLocaleString(uiLocale, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }), " \u00B7 ", item.state === 'pending' ? uiText("Scheduled") : item.state === 'failed' ? uiText("Not sent") : item.state === 'sent' ? uiText("Sent") : uiText("Cancelled")] }), item.content && _jsx(Text, { numberOfLines: 4, style: { color: colors.foreground, fontSize: 16 }, children: item.content.text || item.content.media?.fileName || item.content.poll?.question || item.content.kind }), item.state === 'failed' && _jsxs(Text, { style: { color: colors.secondary }, children: [uiText("Not sent."), ' ', item.errorCode === 'schedule_expired' ? uiText("The sending window passed.") : item.errorCode?.includes('screening') ? uiText("The app’s safety check did not allow delivery.") : item.errorCode?.includes('billing') || item.errorCode?.includes('spending') ? uiText("The app’s spending limit or billing stopped delivery.") : uiText("Access, message rules or service availability changed.")] }), item.state === 'pending' && _jsxs(View, { style: { flexDirection: 'row', gap: 12 }, children: [_jsx(Pressable, { disabled: busy, onPress: () => setEditing(item), style: { minHeight: 44, justifyContent: 'center' }, children: _jsx(Text, { style: { color: accent, fontSize: 16 }, children: uiText("Reschedule") }) }), _jsx(Pressable, { disabled: busy, onPress: () => void change(item), style: { minHeight: 44, justifyContent: 'center' }, children: _jsx(Text, { style: { color: accent, fontSize: 16 }, children: uiText("Cancel message") }) })] })] }, item.id))] }) });
|
|
85
85
|
}
|
package/dist/search.js
CHANGED
|
@@ -31,9 +31,18 @@ export function MessagingSearch({ client, appearance, onClose }) {
|
|
|
31
31
|
setBusy(true);
|
|
32
32
|
setError('');
|
|
33
33
|
try {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
let cursor = more ? next : null, result = { messages: [], hasMore: false, nextCursor: null };
|
|
35
|
+
// Permission filtering may produce an empty page with older matches still
|
|
36
|
+
// available. Advance bounded pages automatically; keep Next usable if the
|
|
37
|
+
// remaining range is larger, rather than incorrectly showing a final zero.
|
|
38
|
+
for (let page = 0; page < 5; page++) {
|
|
39
|
+
result = await client.search(term, { ...(cursor ? { before: cursor } : {}), signal: control.signal });
|
|
40
|
+
if (id !== generation.current)
|
|
41
|
+
return;
|
|
42
|
+
if (result.messages.length || !result.hasMore || !result.nextCursor || result.nextCursor === cursor)
|
|
43
|
+
break;
|
|
44
|
+
cursor = result.nextCursor;
|
|
45
|
+
}
|
|
37
46
|
const rows = more ? [...messages, ...result.messages.filter(m => !messages.some(old => old.id === m.id))] : result.messages;
|
|
38
47
|
const target = more ? Math.min(index + 1, Math.max(0, rows.length - 1)) : 0;
|
|
39
48
|
setMessages(rows);
|
|
@@ -54,11 +63,12 @@ export function MessagingSearch({ client, appearance, onClose }) {
|
|
|
54
63
|
useEffect(() => { if (query.trim())
|
|
55
64
|
timer.current = setTimeout(() => void search(), 300); return () => clearTimeout(timer.current); }, [query]);
|
|
56
65
|
function change(value) { generation.current++; request.current?.abort(); clearTimeout(timer.current); setBusy(Boolean(value.trim())); setQuery(value); setMessages([]); setIndex(0); setNext(null); setError(''); }
|
|
57
|
-
async function move(direction) { if (busy
|
|
58
|
-
return; if (direction > 0 && index === messages.length - 1 && next) {
|
|
66
|
+
async function move(direction) { if (busy)
|
|
67
|
+
return; if (direction > 0 && (!messages.length || index === messages.length - 1) && next) {
|
|
59
68
|
await search(true);
|
|
60
69
|
return;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
70
|
+
} if (!messages.length)
|
|
71
|
+
return; const target = (index + direction + messages.length) % messages.length; setIndex(target); await focus(messages[target], generation.current); }
|
|
72
|
+
const nav = (label, icon, direction) => { const disabled = busy || !messages.length && !(direction > 0 && next); return _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: label, disabled: disabled, onPress: () => void move(direction), style: { width: 36, height: 44, alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.4 : 1 }, children: _jsx(MessageIcon, { name: icon, size: 20, color: c.foreground }) }); };
|
|
73
|
+
return _jsx(MessagingTypography, { appearance: appearance, screen: "search", children: _jsxs(View, { testID: "conversation-search", style: { backgroundColor: c.background, borderBottomWidth: 1, borderBottomColor: c.foreground + '20' }, children: [_jsxs(View, { style: { flexDirection: 'row', alignItems: 'center', paddingLeft: 10, gap: 4 }, children: [_jsx(MessageIcon, { name: "search", size: 18, color: c.secondary }), _jsx(TextInput, { accessibilityLabel: uiText("Search this chat"), placeholder: uiText("Search this chat"), value: query, onChangeText: change, onSubmitEditing: () => void search(), autoFocus: true, autoCapitalize: "none", autoCorrect: false, maxLength: 200, returnKeyType: "search", placeholderTextColor: c.secondary, style: { flex: 1, minWidth: 0, minHeight: 44, color: c.foreground, fontSize: 15 } }), busy ? _jsx(ActivityIndicator, { accessibilityLabel: uiText("Searching messages"), color: c.accent }) : !!query.trim() && _jsx(Text, { accessibilityLiveRegion: "polite", style: { color: c.secondary, fontSize: 12 }, children: messages.length ? `${index + 1}/${messages.length}${next ? '+' : ''}` : next ? '0+' : '0' }), nav('Previous search result', 'chevron-up', -1), nav('Next search result', 'chevron-down', 1), _jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: uiText("Close search"), onPress: onClose, style: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' }, children: _jsx(MessageIcon, { name: "close", size: 20, color: c.foreground }) })] }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: c.foreground, paddingHorizontal: 12, paddingBottom: 8, fontSize: 13 }, children: error })] }) });
|
|
64
74
|
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
#import <CloudKit/CloudKit.h>
|
|
3
|
+
#import <CommonCrypto/CommonDigest.h>
|
|
4
|
+
|
|
5
|
+
// Private CloudKit records contain only encrypted archive parts and opaque IDs.
|
|
6
|
+
// A successful local file write never counts as a cloud upload acknowledgement.
|
|
7
|
+
@interface RobonoBackupCloudKit : NSObject <RCTBridgeModule>
|
|
8
|
+
@property(nonatomic,strong) NSMutableDictionary *requests;
|
|
9
|
+
@property(nonatomic) NSUInteger generation;
|
|
10
|
+
@end
|
|
11
|
+
@implementation RobonoBackupCloudKit
|
|
12
|
+
RCT_EXPORT_MODULE();
|
|
13
|
+
+ (BOOL)requiresMainQueueSetup{return NO;}
|
|
14
|
+
- (instancetype)init{if((self=[super init])){_requests=[NSMutableDictionary new];[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(accountChanged) name:CKAccountChangedNotification object:nil];dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{
|
|
15
|
+
NSString *folder=[NSTemporaryDirectory()stringByAppendingPathComponent:@"RobonoBackupCloudKit"];
|
|
16
|
+
NSDirectoryEnumerator *files=[NSFileManager.defaultManager enumeratorAtURL:[NSURL fileURLWithPath:folder] includingPropertiesForKeys:@[NSURLContentModificationDateKey,NSURLIsRegularFileKey] options:NSDirectoryEnumerationSkipsSubdirectoryDescendants errorHandler:nil];NSUInteger scanned=0;
|
|
17
|
+
for(NSURL *url in files){if(++scanned>1000)break;NSDate *date;NSNumber *regular;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];[url getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil];if(regular.boolValue&&date&&[date timeIntervalSinceNow]<-86400)[NSFileManager.defaultManager removeItemAtURL:url error:nil];}
|
|
18
|
+
});}return self;}
|
|
19
|
+
- (void)dealloc{[[NSNotificationCenter defaultCenter]removeObserver:self];}
|
|
20
|
+
- (void)accountChanged{@synchronized(self){self.generation++;for(NSMutableDictionary *r in self.requests.allValues){r[@"cancelled"]=@YES;[(NSOperation *)r[@"operation"]cancel];}}}
|
|
21
|
+
static BOOL matches(NSString *text,NSString *pattern){return [text isKindOfClass:NSString.class]&&[text rangeOfString:pattern options:NSRegularExpressionSearch].location!=NSNotFound;}
|
|
22
|
+
static NSString *digest(NSData *data){unsigned char bytes[CC_SHA256_DIGEST_LENGTH];CC_SHA256(data.bytes,(CC_LONG)data.length,bytes);NSMutableString *s=[NSMutableString new];for(int i=0;i<CC_SHA256_DIGEST_LENGTH;i++)[s appendFormat:@"%02x",bytes[i]];return s;}
|
|
23
|
+
static NSString *errorCode(NSError *e){if([e.domain isEqualToString:CKErrorDomain]){if(e.code==CKErrorQuotaExceeded)return @"storage_full";if(e.code==CKErrorOperationCancelled)return @"cancelled";if(e.code==CKErrorUnknownItem||e.code==CKErrorServerRecordChanged)return @"invalid_backup";}return @"connection";}
|
|
24
|
+
RCT_EXPORT_METHOD(cancel:(NSString *)identifier){@synchronized(self){NSMutableDictionary *r=self.requests[identifier];r[@"cancelled"]=@YES;[(NSOperation *)r[@"operation"]cancel];}}
|
|
25
|
+
RCT_REMAP_METHOD(request, requestIdentifier:(NSString *)identifier input:(NSDictionary *)input resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
|
|
26
|
+
NSString *containerId=input[@"container"],*action=input[@"action"],*scope=input[@"scope"],*snapshot=input[@"snapshot"],*part=input[@"part"];
|
|
27
|
+
if(!matches(identifier,@"^[a-f0-9-]{36}$")||!matches(containerId,@"^iCloud\\.[A-Za-z0-9.-]{1,180}$")||![@[@"account",@"list",@"read",@"write",@"delete"]containsObject:action]){reject(@"invalid_backup",@"Invalid backup request",nil);return;}
|
|
28
|
+
BOOL account=[action isEqualToString:@"account"],listing=[action isEqualToString:@"list"];
|
|
29
|
+
if(!account&&(!matches(input[@"account"],@"^[a-f0-9]{64}$")||!matches(scope,@"^[a-f0-9]{64}$")||(!listing&&(!matches(snapshot,@"^[a-f0-9]{32}$")||!matches(part,@"^(manifest|protection|commit|[0-9]{1,6})$"))))){reject(@"invalid_backup",@"Invalid backup identity",nil);return;}
|
|
30
|
+
NSMutableDictionary *state=[NSMutableDictionary new];NSUInteger epoch;
|
|
31
|
+
@synchronized(self){if(self.requests[identifier]){reject(@"invalid_backup",@"Duplicate backup request",nil);return;}self.requests[identifier]=state;epoch=self.generation;}
|
|
32
|
+
void (^finish)(id,NSString *,NSError *)=^(id result,NSString *code,NSError *error){
|
|
33
|
+
@synchronized(self){if(state[@"finished"])return;state[@"finished"]=@YES;[self.requests removeObjectForKey:identifier];[state removeObjectForKey:@"operation"];if(state[@"cancelled"]||epoch!=self.generation)code=@"cancelled";}
|
|
34
|
+
NSString *temporary=state[@"temporary"];if(temporary)[NSFileManager.defaultManager removeItemAtPath:temporary error:nil];
|
|
35
|
+
if(code)reject(code,@"Your iCloud backup could not finish. Your previous backup is still available.",error);else resolve(result);
|
|
36
|
+
};
|
|
37
|
+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,120*NSEC_PER_SEC),dispatch_get_global_queue(QOS_CLASS_UTILITY,0),^{@synchronized(self){if(state[@"finished"])return;[(NSOperation *)state[@"operation"]cancel];}finish(nil,@"connection",nil);});
|
|
38
|
+
CKContainer *container;
|
|
39
|
+
@try{container=[CKContainer containerWithIdentifier:containerId];}@catch(NSException *e){finish(nil,@"unavailable",nil);return;}
|
|
40
|
+
[container accountStatusWithCompletionHandler:^(CKAccountStatus status,NSError *error){
|
|
41
|
+
if(error||status!=CKAccountStatusAvailable){if(account&&!error&&status==CKAccountStatusNoAccount)finish(NSNull.null,nil,nil);else finish(nil,@"connection",error);return;}
|
|
42
|
+
[container fetchUserRecordIDWithCompletionHandler:^(CKRecordID *user,NSError *error){
|
|
43
|
+
if(error||!user){finish(nil,@"connection",error);return;}
|
|
44
|
+
NSString *identity=digest([[containerId stringByAppendingFormat:@":%@",user.recordName]dataUsingEncoding:NSUTF8StringEncoding]);
|
|
45
|
+
@synchronized(self){if(state[@"finished"])return;if(state[@"cancelled"]||epoch!=self.generation){finish(nil,@"cancelled",nil);return;}}
|
|
46
|
+
if(account){finish(@{@"id":identity,@"label":@"iCloud",@"provider":@"icloud"},nil,nil);return;}
|
|
47
|
+
if(![identity isEqualToString:input[@"account"]]){finish(nil,@"connection",nil);return;}
|
|
48
|
+
CKDatabase *database=container.privateCloudDatabase;CKDatabaseOperation *operation;
|
|
49
|
+
CKRecordID *recordId=listing?nil:[[CKRecordID alloc]initWithRecordName:[NSString stringWithFormat:@"%@:%@:%@",scope,snapshot,part]];
|
|
50
|
+
NSUInteger limit=[part isEqualToString:@"manifest"]?16*1024*1024+28:([@[@"commit",@"protection"]containsObject:(part?:@"")]?8192:4*1024*1024+28);
|
|
51
|
+
if(listing){
|
|
52
|
+
NSString *cursor=input[@"cursor"];CKQueryOperation *query;
|
|
53
|
+
if(cursor){if(![cursor isKindOfClass:NSString.class]||cursor.length>32768){finish(nil,@"invalid_backup",nil);return;}NSError *decodeError;NSData *data=[[NSData alloc]initWithBase64EncodedString:cursor options:0];CKQueryCursor *saved;@try{saved=data?[NSKeyedUnarchiver unarchivedObjectOfClass:CKQueryCursor.class fromData:data error:&decodeError]:nil;}@catch(NSException *exception){finish(nil,@"invalid_backup",nil);return;}if(!saved){finish(nil,@"invalid_backup",decodeError);return;}query=[[CKQueryOperation alloc]initWithCursor:saved];}
|
|
54
|
+
else query=[[CKQueryOperation alloc]initWithQuery:[[CKQuery alloc]initWithRecordType:@"RobonoChatBackup" predicate:[NSPredicate predicateWithFormat:@"scope == %@",scope]]];
|
|
55
|
+
query.resultsLimit=200;query.desiredKeys=@[@"scope",@"snapshot",@"part",@"length"];
|
|
56
|
+
NSMutableArray *files=[NSMutableArray new];__block NSError *recordError;
|
|
57
|
+
query.recordMatchedBlock=^(CKRecordID *rid,CKRecord *record,NSError *error){if(error){recordError=error;return;}if(![record[@"scope"]isEqualToString:scope]){recordError=[NSError errorWithDomain:@"RobonoBackup" code:1 userInfo:nil];return;}[files addObject:@{@"snapshot":record[@"snapshot"]?:@"",@"part":record[@"part"]?:@"",@"byteSize":record[@"length"]?:@0,@"createdAt":@([record.creationDate timeIntervalSince1970]*1000)}];};
|
|
58
|
+
query.queryCompletionBlock=^(CKQueryCursor *cursor,NSError *error){if(error||recordError){finish(nil,@"connection",error?:recordError);return;}NSError *encodingError;NSData *data=cursor?[NSKeyedArchiver archivedDataWithRootObject:cursor requiringSecureCoding:YES error:&encodingError]:nil;if(encodingError){finish(nil,@"connection",encodingError);return;}finish(@{@"files":files,@"cursor":data?[data base64EncodedStringWithOptions:0]:NSNull.null},nil,nil);};operation=query;
|
|
59
|
+
}else if([action isEqualToString:@"read"]){
|
|
60
|
+
CKFetchRecordsOperation *fetch=[[CKFetchRecordsOperation alloc]initWithRecordIDs:@[recordId]];
|
|
61
|
+
fetch.fetchRecordsCompletionBlock=^(NSDictionary<CKRecordID *,CKRecord *> *records,NSError *error){
|
|
62
|
+
CKRecord *record=records[recordId];if(error||!record){finish(nil,errorCode(error),error);return;}
|
|
63
|
+
CKAsset *asset=record[@"bytes"];if(![asset isKindOfClass:CKAsset.class]||![record[@"length"]isKindOfClass:NSNumber.class]){finish(nil,@"invalid_backup",nil);return;}NSError *readError;NSDictionary *attrs=[NSFileManager.defaultManager attributesOfItemAtPath:asset.fileURL.path error:&readError];NSNumber *length=record[@"length"];
|
|
64
|
+
if(![asset isKindOfClass:CKAsset.class]||!length||length.unsignedLongLongValue>limit||!attrs||[attrs fileSize]!=length.unsignedLongLongValue){finish(nil,@"invalid_backup",readError);return;}
|
|
65
|
+
NSData *bytes=[NSData dataWithContentsOfURL:asset.fileURL options:NSDataReadingMappedIfSafe error:&readError];if(!bytes||bytes.length!=length.unsignedLongLongValue){finish(nil,@"invalid_backup",readError);return;}finish(@{@"base64":[bytes base64EncodedStringWithOptions:0]},nil,nil);
|
|
66
|
+
};operation=fetch;
|
|
67
|
+
}else{
|
|
68
|
+
CKRecord *record;
|
|
69
|
+
if([action isEqualToString:@"write"]){
|
|
70
|
+
NSString *encoded=input[@"base64"];if(![encoded isKindOfClass:NSString.class]||encoded.length>((limit+2)/3)*4){finish(nil,@"invalid_backup",nil);return;}
|
|
71
|
+
NSData *data=[[NSData alloc]initWithBase64EncodedString:encoded options:0];if(!data||data.length>limit){finish(nil,@"invalid_backup",nil);return;}
|
|
72
|
+
NSString *folder=[NSTemporaryDirectory()stringByAppendingPathComponent:@"RobonoBackupCloudKit"];NSError *fileError;
|
|
73
|
+
if(![NSFileManager.defaultManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:@{NSFileProtectionKey:NSFileProtectionCompleteUntilFirstUserAuthentication} error:&fileError]){finish(nil,@"connection",fileError);return;}
|
|
74
|
+
NSString *file=[folder stringByAppendingPathComponent:identifier];@synchronized(self){if(state[@"finished"])return;state[@"temporary"]=file;}
|
|
75
|
+
if(![data writeToFile:file options:NSDataWritingAtomic|NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication error:&fileError]){finish(nil,@"connection",fileError);return;}
|
|
76
|
+
@synchronized(self){if(state[@"finished"]){[NSFileManager.defaultManager removeItemAtPath:file error:nil];return;}}
|
|
77
|
+
record=[[CKRecord alloc]initWithRecordType:@"RobonoChatBackup" recordID:recordId];record[@"scope"]=scope;record[@"snapshot"]=snapshot;record[@"part"]=part;record[@"length"]=@(data.length);record[@"bytes"]=[[CKAsset alloc]initWithFileURL:[NSURL fileURLWithPath:file]];
|
|
78
|
+
}
|
|
79
|
+
CKModifyRecordsOperation *modify=[[CKModifyRecordsOperation alloc]initWithRecordsToSave:record?@[record]:nil recordIDsToDelete:record?nil:@[recordId]];
|
|
80
|
+
modify.savePolicy=CKRecordSaveIfServerRecordUnchanged;
|
|
81
|
+
modify.modifyRecordsCompletionBlock=^(NSArray<CKRecord *> *saved,NSArray<CKRecordID *> *deleted,NSError *error){
|
|
82
|
+
if(!record&&[error.domain isEqualToString:CKErrorDomain]){
|
|
83
|
+
NSError *item=error.userInfo[CKPartialErrorsByItemIDKey][recordId];
|
|
84
|
+
if(error.code==CKErrorUnknownItem||(error.code==CKErrorPartialFailure&&[item.domain isEqualToString:CKErrorDomain]&&item.code==CKErrorUnknownItem)){finish(@{@"confirmed":@YES},nil,nil);return;}
|
|
85
|
+
}
|
|
86
|
+
if(error){finish(nil,errorCode(error),error);return;}
|
|
87
|
+
if(record?(saved.count!=1||![saved.firstObject.recordID isEqual:recordId]):(deleted.count!=1||![deleted.firstObject isEqual:recordId])){finish(nil,@"connection",nil);return;}
|
|
88
|
+
finish(@{@"confirmed":@YES},nil,nil);
|
|
89
|
+
};operation=modify;
|
|
90
|
+
}
|
|
91
|
+
operation.qualityOfService=NSQualityOfServiceUtility;operation.configuration.timeoutIntervalForRequest=60;operation.configuration.timeoutIntervalForResource=110;
|
|
92
|
+
@synchronized(self){if(state[@"finished"]||state[@"cancelled"]||epoch!=self.generation){finish(nil,@"cancelled",nil);return;}state[@"operation"]=operation;[database addOperation:operation];}
|
|
93
|
+
}];
|
|
94
|
+
}];
|
|
95
|
+
}
|
|
96
|
+
@end
|