@feedbackrelay/react-native-replay 0.0.0-stage → 0.1.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/AGENTS.md +39 -0
- package/LICENSE +202 -0
- package/README.md +130 -2
- package/RelayReplay.podspec +20 -0
- package/android/build.gradle +17 -0
- package/android/src/main/java/app/feedbackrelay/reactnativereplay/RelayReplayModule.kt +121 -0
- package/android/src/main/java/app/feedbackrelay/reactnativereplay/RelayReplayPackage.kt +17 -0
- package/ios/RCTRelayReplay.h +4 -0
- package/ios/RCTRelayReplay.mm +68 -0
- package/ios/RelayReplayBridge.swift +122 -0
- package/lib/NativeRelayReplay.js +4 -0
- package/lib/client.d.ts +30 -0
- package/lib/client.js +300 -0
- package/lib/delivery.js +72 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +9 -0
- package/native/android/AndroidManifest.xml +1 -0
- package/native/android/java/app/feedbackrelay/replay/RelayReplayCapture.kt +615 -0
- package/native/android/java/app/feedbackrelay/replay/ReplayBuffer.kt +53 -0
- package/native/android/java/app/feedbackrelay/replay/ReplayEncoder.kt +268 -0
- package/native/android/java/app/feedbackrelay/sdk/RelayReplayProvider.kt +29 -0
- package/native/ios/Resources/PrivacyInfo.xcprivacy +16 -0
- package/native/ios/VideoRecorder.swift +450 -0
- package/package.json +73 -4
- package/react-native.config.js +4 -0
- package/src/NativeRelayReplay.ts +15 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import UIKit
|
|
3
|
+
|
|
4
|
+
@MainActor @objc(RelayReplayBridge)
|
|
5
|
+
public final class RelayReplayBridge: NSObject {
|
|
6
|
+
private final class Owner {
|
|
7
|
+
let recorder: String; let scope: String; let enabled: Bool
|
|
8
|
+
var attachment: UUID?
|
|
9
|
+
init(recorder: String, scope: String, enabled: Bool, attachment: UUID?) {
|
|
10
|
+
self.recorder = recorder; self.scope = scope; self.enabled = enabled; self.attachment = attachment
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
private final class Lease {
|
|
14
|
+
let recorder: String; let attachment: String; let value: UUID
|
|
15
|
+
var task: Task<Void, Never>?
|
|
16
|
+
var reject: ((String, String, NSError?) -> Void)?
|
|
17
|
+
init(recorder: String, attachment: String, value: UUID) { self.recorder = recorder; self.attachment = attachment; self.value = value }
|
|
18
|
+
}
|
|
19
|
+
private var recorders: [String: RelayVideoRecorder] = [:]
|
|
20
|
+
private var owners: [String: Owner] = [:]
|
|
21
|
+
private var leases: [String: Lease] = [:]
|
|
22
|
+
private var invalidated = false
|
|
23
|
+
private var ownershipObserver: NSObjectProtocol?
|
|
24
|
+
public override init() {
|
|
25
|
+
super.init()
|
|
26
|
+
ownershipObserver = NotificationCenter.default.addObserver(forName: RelayVideoRecorder.ownershipAvailable, object: nil, queue: .main) { [weak self] _ in
|
|
27
|
+
Task { @MainActor in self?.rebind() }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
deinit { if let ownershipObserver { NotificationCenter.default.removeObserver(ownershipObserver) } }
|
|
31
|
+
private func rebind() {
|
|
32
|
+
guard !invalidated else { return }
|
|
33
|
+
for owner in owners.values where owner.enabled && owner.attachment == nil {
|
|
34
|
+
guard let recorder = recorders[owner.recorder] else { continue }
|
|
35
|
+
owner.attachment = recorder.attach(scope: owner.scope, enabled: owner.enabled)
|
|
36
|
+
if owner.attachment != nil { recorder.setWindow(Self.window()) }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
private func object(_ json: String) -> [String: Any]? { (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any] }
|
|
40
|
+
@objc public func create(_ json: String) -> String {
|
|
41
|
+
guard !invalidated else { return "" }
|
|
42
|
+
let fps = (object(json)?["fps"] as? NSNumber)?.intValue
|
|
43
|
+
let id = UUID().uuidString.lowercased(); recorders[id] = RelayVideoRecorder(fps: fps); return id
|
|
44
|
+
}
|
|
45
|
+
@objc public func getCurrentFPS(_ id: String) -> Double {
|
|
46
|
+
guard !invalidated else { return 0 }
|
|
47
|
+
return Double(recorders[id]?.currentFPS ?? 0)
|
|
48
|
+
}
|
|
49
|
+
@objc public func attach(_ json: String) -> String {
|
|
50
|
+
guard !invalidated, let value = object(json), let recorderID = value["recorderId"] as? String,
|
|
51
|
+
let recorder = recorders[recorderID], let base = value["baseUrl"] as? String,
|
|
52
|
+
let team = value["teamId"] as? String, let app = value["appId"] as? String else { return "" }
|
|
53
|
+
let enabled = value["enabled"] as? Bool ?? false
|
|
54
|
+
guard let data = try? JSONSerialization.data(withJSONObject: [base, team, app]) else { return "" }
|
|
55
|
+
let scope = String(decoding: data, as: UTF8.self)
|
|
56
|
+
let attachment = recorder.attach(scope: scope, enabled: enabled)
|
|
57
|
+
if attachment != nil, enabled { recorder.setWindow(Self.window()) }
|
|
58
|
+
let id = UUID().uuidString.lowercased(); owners[id] = Owner(recorder: recorderID, scope: scope, enabled: enabled, attachment: attachment); return id
|
|
59
|
+
}
|
|
60
|
+
@objc public func freeze(_ json: String) -> String {
|
|
61
|
+
guard !invalidated, let value = object(json), let ownerID = value["attachmentId"] as? String,
|
|
62
|
+
let owner = owners[ownerID], let recorder = recorders[owner.recorder], let submission = value["submissionId"] as? String else { return "" }
|
|
63
|
+
if owner.attachment != nil, owner.enabled, value["allowed"] as? Bool == true { recorder.setWindow(Self.window()) }
|
|
64
|
+
let frozen = recorder.freeze(attachmentID: owner.attachment ?? UUID(), submissionID: submission,
|
|
65
|
+
isRetry: value["isRetry"] as? Bool ?? false, allowed: value["allowed"] as? Bool ?? false)
|
|
66
|
+
let id = UUID().uuidString.lowercased(); leases[id] = Lease(recorder: owner.recorder, attachment: ownerID, value: frozen); return id
|
|
67
|
+
}
|
|
68
|
+
@objc public func preview(_ json: String) -> String {
|
|
69
|
+
guard !invalidated, let ownerID = object(json)?["attachmentId"] as? String,
|
|
70
|
+
let owner = owners[ownerID], let recorder = recorders[owner.recorder] else { return "" }
|
|
71
|
+
let value = recorder.preview(attachmentID: owner.attachment ?? UUID(), window: Self.window())
|
|
72
|
+
let id = UUID().uuidString.lowercased(); leases[id] = Lease(recorder: owner.recorder, attachment: ownerID, value: value); return id
|
|
73
|
+
}
|
|
74
|
+
@objc(materialize:resolve:reject:)
|
|
75
|
+
public func materialize(_ id: String, resolve: @escaping (Any?) -> Void, reject: @escaping (String, String, NSError?) -> Void) {
|
|
76
|
+
guard !invalidated, let lease = leases[id], lease.reject == nil, let recorder = recorders[lease.recorder] else { reject("E_REPLAY", "Replay lease is unavailable.", nil); return }
|
|
77
|
+
lease.reject = reject
|
|
78
|
+
lease.task = Task { [weak self] in
|
|
79
|
+
do {
|
|
80
|
+
let video = try await recorder.materialize(leaseID: lease.value)
|
|
81
|
+
guard let self, self.leases[id] === lease, !Task.isCancelled else { return }
|
|
82
|
+
var result: [String: Any] = ["width": video.width, "height": video.height, "byteSize": video.byteSize,
|
|
83
|
+
"durationMs": video.durationMs, "startedBeforeEventMs": video.startedBeforeEventMs, "endedBeforeEventMs": video.endedBeforeEventMs]
|
|
84
|
+
if let url = video.url { result["uri"] = url.absoluteString }
|
|
85
|
+
if let omitted = video.omitted { result["omitted"] = omitted }
|
|
86
|
+
let data = try JSONSerialization.data(withJSONObject: result)
|
|
87
|
+
lease.reject = nil; lease.task = nil; resolve(String(decoding: data, as: UTF8.self))
|
|
88
|
+
} catch {
|
|
89
|
+
guard let self, self.leases[id] === lease else { return }
|
|
90
|
+
lease.reject = nil; lease.task = nil; reject("E_REPLAY", "Could not materialize replay.", nil)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
@objc public func release(_ id: String) -> Bool {
|
|
95
|
+
guard let lease = leases.removeValue(forKey: id) else { return true }
|
|
96
|
+
lease.task?.cancel(); lease.task = nil
|
|
97
|
+
lease.reject?("E_CANCELLED", "Replay lease was released.", nil); lease.reject = nil
|
|
98
|
+
recorders[lease.recorder]?.release(leaseID: lease.value); return true
|
|
99
|
+
}
|
|
100
|
+
@objc public func detach(_ id: String) -> Bool {
|
|
101
|
+
guard let owner = owners.removeValue(forKey: id) else { return true }
|
|
102
|
+
for key in leases.keys.filter({ leases[$0]?.attachment == id }) { _ = release(key) }
|
|
103
|
+
if let attachment = owner.attachment { recorders[owner.recorder]?.detach(attachmentID: attachment) }; return true
|
|
104
|
+
}
|
|
105
|
+
@objc public func clear(_ id: String) -> Bool {
|
|
106
|
+
for key in leases.keys.filter({ leases[$0]?.recorder == id }) { _ = release(key) }
|
|
107
|
+
recorders[id]?.clear(); return true
|
|
108
|
+
}
|
|
109
|
+
@objc public func destroy(_ id: String) -> Bool {
|
|
110
|
+
for key in owners.keys.filter({ owners[$0]?.recorder == id }) { _ = detach(key) }
|
|
111
|
+
_ = clear(id); recorders.removeValue(forKey: id)?.destroy(); return true
|
|
112
|
+
}
|
|
113
|
+
@objc public func invalidate() {
|
|
114
|
+
invalidated = true
|
|
115
|
+
if let ownershipObserver { NotificationCenter.default.removeObserver(ownershipObserver); self.ownershipObserver = nil }
|
|
116
|
+
for id in Array(recorders.keys) { _ = destroy(id) }
|
|
117
|
+
}
|
|
118
|
+
private static func window() -> UIWindow? {
|
|
119
|
+
let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.filter { $0.activationState == .foregroundActive }.flatMap(\.windows).filter(\.isKeyWindow)
|
|
120
|
+
return windows.count == 1 ? windows[0] : nil
|
|
121
|
+
}
|
|
122
|
+
}
|
package/lib/client.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { RelayReplayProvider } from '@feedbackrelay/react-native';
|
|
2
|
+
export interface ReplayOptions {
|
|
3
|
+
fps?: 'auto' | number;
|
|
4
|
+
}
|
|
5
|
+
export interface ReplayPreview {
|
|
6
|
+
uri?: string;
|
|
7
|
+
omitted?: string;
|
|
8
|
+
byteSize: number;
|
|
9
|
+
width: number;
|
|
10
|
+
height: number;
|
|
11
|
+
durationMs: number;
|
|
12
|
+
release(): void;
|
|
13
|
+
}
|
|
14
|
+
export interface ReplayRecorder extends RelayReplayProvider {
|
|
15
|
+
readonly currentFPS: number | undefined;
|
|
16
|
+
preview(): Promise<ReplayPreview>;
|
|
17
|
+
}
|
|
18
|
+
export interface NativeBridge {
|
|
19
|
+
create(optionsJson: string): string;
|
|
20
|
+
attach(optionsJson: string): string;
|
|
21
|
+
freeze(optionsJson: string): string;
|
|
22
|
+
preview(optionsJson: string): string;
|
|
23
|
+
getCurrentFPS(recorderId: string): number;
|
|
24
|
+
materialize(leaseId: string): Promise<string>;
|
|
25
|
+
release(leaseId: string): boolean;
|
|
26
|
+
detach(attachmentId: string): boolean;
|
|
27
|
+
clear(recorderId: string): boolean;
|
|
28
|
+
destroy(recorderId: string): boolean;
|
|
29
|
+
}
|
|
30
|
+
export declare function createRecorder(native: NativeBridge | null, options?: ReplayOptions): ReplayRecorder;
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createRecorder = createRecorder;
|
|
4
|
+
const delivery_1 = require("./delivery");
|
|
5
|
+
const omitted = (reason) => ({ omitted: reason, byteSize: 0, width: 0, height: 0, durationMs: 0, startedBeforeEventMs: 0, endedBeforeEventMs: 0 });
|
|
6
|
+
let activeRecorder;
|
|
7
|
+
function createRecorder(native, options = {}) {
|
|
8
|
+
if (!native)
|
|
9
|
+
throw new TypeError('RelayReplay native module is unavailable. Rebuild the native app; Expo Go is unsupported.');
|
|
10
|
+
let requestedFPS;
|
|
11
|
+
try {
|
|
12
|
+
requestedFPS = options?.fps;
|
|
13
|
+
}
|
|
14
|
+
catch { }
|
|
15
|
+
const fps = typeof requestedFPS === 'number' && Number.isInteger(requestedFPS) && requestedFPS >= 1 && requestedFPS <= 10 ? requestedFPS : undefined;
|
|
16
|
+
let recorderId = '';
|
|
17
|
+
try {
|
|
18
|
+
recorderId = native.create(JSON.stringify({ ...(fps === undefined ? {} : { fps }) }));
|
|
19
|
+
}
|
|
20
|
+
catch { }
|
|
21
|
+
let destroyed = false;
|
|
22
|
+
let binding;
|
|
23
|
+
let running = false;
|
|
24
|
+
let preview;
|
|
25
|
+
const token = {};
|
|
26
|
+
const attachments = new Map();
|
|
27
|
+
const entries = new Set();
|
|
28
|
+
let queue = [];
|
|
29
|
+
const quiet = (action) => { try {
|
|
30
|
+
action();
|
|
31
|
+
}
|
|
32
|
+
catch { } };
|
|
33
|
+
const attachNative = (scope) => {
|
|
34
|
+
if (!scope.enabled || activeRecorder !== undefined && activeRecorder !== token)
|
|
35
|
+
return '';
|
|
36
|
+
activeRecorder = token;
|
|
37
|
+
try {
|
|
38
|
+
return recorderId ? native.attach(JSON.stringify({ recorderId, ...scope })) : '';
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return '';
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const settlePreview = (entry, video) => {
|
|
45
|
+
const resolve = entry.preview?.resolve;
|
|
46
|
+
if (!resolve)
|
|
47
|
+
return;
|
|
48
|
+
entry.preview.resolve = undefined;
|
|
49
|
+
resolve({ ...(video.uri ? { uri: video.uri } : {}), ...(video.omitted ? { omitted: video.omitted } : {}),
|
|
50
|
+
byteSize: video.byteSize, width: video.width, height: video.height, durationMs: video.durationMs, release: () => release(entry) });
|
|
51
|
+
};
|
|
52
|
+
const dispose = (entry) => {
|
|
53
|
+
entries.delete(entry);
|
|
54
|
+
clearTimeout(entry.timer);
|
|
55
|
+
if (preview === entry)
|
|
56
|
+
preview = undefined;
|
|
57
|
+
if (entry.nativeId)
|
|
58
|
+
quiet(() => native.release(entry.nativeId));
|
|
59
|
+
entry.nativeId = undefined;
|
|
60
|
+
entry.video = undefined;
|
|
61
|
+
};
|
|
62
|
+
const release = (entry) => {
|
|
63
|
+
if (entry.cancelled)
|
|
64
|
+
return;
|
|
65
|
+
entry.cancelled = true;
|
|
66
|
+
entries.delete(entry);
|
|
67
|
+
clearTimeout(entry.timer);
|
|
68
|
+
settlePreview(entry, omitted('cancelled'));
|
|
69
|
+
quiet(() => entry.controller?.abort());
|
|
70
|
+
if (entry.phase === 'materializing' && entry.nativeId) {
|
|
71
|
+
quiet(() => native.release(entry.nativeId));
|
|
72
|
+
entry.nativeId = undefined;
|
|
73
|
+
}
|
|
74
|
+
if (!entry.running)
|
|
75
|
+
dispose(entry);
|
|
76
|
+
};
|
|
77
|
+
const pump = () => {
|
|
78
|
+
if (running || destroyed)
|
|
79
|
+
return;
|
|
80
|
+
let entry;
|
|
81
|
+
while ((entry = queue.shift()) && (!entries.has(entry) || Date.now() >= entry.expiresAt)) {
|
|
82
|
+
if (entries.has(entry))
|
|
83
|
+
release(entry);
|
|
84
|
+
}
|
|
85
|
+
if (!entry)
|
|
86
|
+
return;
|
|
87
|
+
const current = entry;
|
|
88
|
+
running = true;
|
|
89
|
+
current.running = true;
|
|
90
|
+
const deadline = Math.min(current.expiresAt, Date.now() + 30_000);
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
current.controller = controller;
|
|
93
|
+
const timer = setTimeout(() => {
|
|
94
|
+
quiet(() => controller.abort());
|
|
95
|
+
if (current.phase === 'materializing' && current.nativeId)
|
|
96
|
+
quiet(() => native.release(current.nativeId));
|
|
97
|
+
}, Math.max(0, deadline - Date.now()));
|
|
98
|
+
const work = async () => {
|
|
99
|
+
if (!current.video) {
|
|
100
|
+
current.phase = 'materializing';
|
|
101
|
+
try {
|
|
102
|
+
current.video = current.nativeId ? JSON.parse(await native.materialize(current.nativeId)) : omitted(current.omitted ?? 'capture-failed');
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
current.video = omitted('capture-failed');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (current.omitted)
|
|
109
|
+
current.video = omitted(current.omitted);
|
|
110
|
+
if (!entries.has(current) || controller.signal.aborted || Date.now() >= deadline)
|
|
111
|
+
throw new Error('Replay cancelled.');
|
|
112
|
+
if (current.preview) {
|
|
113
|
+
if (typeof current.video.omitted === 'string' && current.video.omitted)
|
|
114
|
+
current.video = omitted(/^[\x20-\x7e]{1,64}$/.test(current.video.omitted) ? current.video.omitted : 'capture-failed');
|
|
115
|
+
else
|
|
116
|
+
(0, delivery_1.validateVideo)(current.video);
|
|
117
|
+
settlePreview(current, current.video);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
current.phase = 'uploading';
|
|
121
|
+
await (0, delivery_1.sendReplay)(current.scope, current.id, current.video, controller.signal, deadline);
|
|
122
|
+
};
|
|
123
|
+
void work().then(() => { if (!current.preview || current.video?.omitted)
|
|
124
|
+
dispose(current); }, () => {
|
|
125
|
+
if (current.preview) {
|
|
126
|
+
settlePreview(current, omitted('capture-failed'));
|
|
127
|
+
dispose(current);
|
|
128
|
+
}
|
|
129
|
+
// Event media retains the original artifact for an explicit retry, never automatically.
|
|
130
|
+
}).finally(() => {
|
|
131
|
+
clearTimeout(timer);
|
|
132
|
+
current.running = false;
|
|
133
|
+
current.phase = undefined;
|
|
134
|
+
current.controller = undefined;
|
|
135
|
+
current.accepted = false;
|
|
136
|
+
if (current.video?.omitted && current.nativeId) {
|
|
137
|
+
quiet(() => native.release(current.nativeId));
|
|
138
|
+
current.nativeId = undefined;
|
|
139
|
+
}
|
|
140
|
+
if (current.cancelled || !entries.has(current))
|
|
141
|
+
dispose(current);
|
|
142
|
+
running = false;
|
|
143
|
+
if (destroyed && activeRecorder === token)
|
|
144
|
+
activeRecorder = undefined;
|
|
145
|
+
pump();
|
|
146
|
+
}).catch(() => { });
|
|
147
|
+
};
|
|
148
|
+
const clear = () => { for (const entry of [...entries])
|
|
149
|
+
release(entry); queue = []; if (recorderId)
|
|
150
|
+
quiet(() => native.clear(recorderId)); };
|
|
151
|
+
return {
|
|
152
|
+
get currentFPS() {
|
|
153
|
+
if (destroyed || !recorderId)
|
|
154
|
+
return undefined;
|
|
155
|
+
try {
|
|
156
|
+
const value = native.getCurrentFPS(recorderId);
|
|
157
|
+
return Number.isInteger(value) && value >= 1 && value <= 10 ? value : undefined;
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
attach(scope) {
|
|
164
|
+
if (destroyed)
|
|
165
|
+
throw new TypeError('Replay recorder has been destroyed.');
|
|
166
|
+
const url = new URL(scope.baseUrl);
|
|
167
|
+
url.pathname = url.pathname.replace(/\/+$/, '');
|
|
168
|
+
const normalized = { ...scope, baseUrl: url.href.replace(/\/+$/, '') };
|
|
169
|
+
const key = JSON.stringify([normalized.baseUrl, scope.teamId, scope.appId]);
|
|
170
|
+
if (binding !== undefined && binding !== key)
|
|
171
|
+
throw new TypeError('A replay recorder can only be shared by the same backend, team and app.');
|
|
172
|
+
binding = key;
|
|
173
|
+
const owner = {};
|
|
174
|
+
let detached = false;
|
|
175
|
+
const attachment = { id: attachNative(normalized), scope: normalized };
|
|
176
|
+
attachments.set(owner, attachment);
|
|
177
|
+
return {
|
|
178
|
+
freeze(id, isRetry, allowed) {
|
|
179
|
+
let existing = [...entries].find(entry => entry.owner === owner && entry.id === id);
|
|
180
|
+
if (existing && Date.now() >= existing.expiresAt) {
|
|
181
|
+
release(existing);
|
|
182
|
+
existing = undefined;
|
|
183
|
+
}
|
|
184
|
+
if (existing) {
|
|
185
|
+
if (!allowed || !normalized.enabled) {
|
|
186
|
+
existing.omitted = 'capture-disabled';
|
|
187
|
+
existing.video = omitted('capture-disabled');
|
|
188
|
+
quiet(() => existing.controller?.abort());
|
|
189
|
+
if ((!existing.running || existing.phase === 'materializing') && existing.nativeId) {
|
|
190
|
+
quiet(() => native.release(existing.nativeId));
|
|
191
|
+
existing.nativeId = undefined;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return existing.lease;
|
|
195
|
+
}
|
|
196
|
+
if (destroyed || detached || entries.size >= 4)
|
|
197
|
+
return { accepted() { }, cancel() { } };
|
|
198
|
+
if (!attachment.id)
|
|
199
|
+
attachment.id = attachNative(normalized);
|
|
200
|
+
let nativeId = '';
|
|
201
|
+
let reason;
|
|
202
|
+
if (!allowed || !normalized.enabled)
|
|
203
|
+
reason = 'capture-disabled';
|
|
204
|
+
else if (isRetry)
|
|
205
|
+
reason = 'retry';
|
|
206
|
+
else if (!attachment.id)
|
|
207
|
+
reason = activeRecorder === token ? 'capture-unavailable' : 'recorder-in-use';
|
|
208
|
+
else {
|
|
209
|
+
try {
|
|
210
|
+
nativeId = native.freeze(JSON.stringify({ attachmentId: attachment.id, submissionId: id, isRetry, allowed }));
|
|
211
|
+
}
|
|
212
|
+
catch { }
|
|
213
|
+
if (!nativeId)
|
|
214
|
+
reason = 'capture-failed';
|
|
215
|
+
}
|
|
216
|
+
const entry = {};
|
|
217
|
+
const lease = {
|
|
218
|
+
accepted(receipt) {
|
|
219
|
+
if (Date.now() >= entry.expiresAt) {
|
|
220
|
+
release(entry);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (!entries.has(entry) || entry.accepted || receipt.submissionId !== id)
|
|
224
|
+
return;
|
|
225
|
+
entry.accepted = true;
|
|
226
|
+
queue.push(entry);
|
|
227
|
+
pump();
|
|
228
|
+
},
|
|
229
|
+
cancel() { release(entry); },
|
|
230
|
+
};
|
|
231
|
+
Object.assign(entry, { id, owner, scope: normalized, nativeId: nativeId || undefined, omitted: reason, running: false, cancelled: false, accepted: false, lease, expiresAt: Date.now() + 60_000,
|
|
232
|
+
timer: setTimeout(() => release(entry), 60_000) });
|
|
233
|
+
entries.add(entry);
|
|
234
|
+
return lease;
|
|
235
|
+
},
|
|
236
|
+
detach() {
|
|
237
|
+
if (detached)
|
|
238
|
+
return;
|
|
239
|
+
detached = true;
|
|
240
|
+
for (const entry of [...entries])
|
|
241
|
+
if (entry.owner === owner)
|
|
242
|
+
release(entry);
|
|
243
|
+
attachments.delete(owner);
|
|
244
|
+
if (attachment.id)
|
|
245
|
+
quiet(() => native.detach(attachment.id));
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
},
|
|
249
|
+
preview() {
|
|
250
|
+
const unavailable = (reason) => Promise.resolve({ omitted: reason, byteSize: 0, width: 0, height: 0, durationMs: 0, release() { } });
|
|
251
|
+
if (destroyed)
|
|
252
|
+
return unavailable('destroyed');
|
|
253
|
+
if (preview && Date.now() >= preview.expiresAt)
|
|
254
|
+
release(preview);
|
|
255
|
+
if (preview || entries.size >= 4)
|
|
256
|
+
return unavailable('resource-pressure');
|
|
257
|
+
const selected = [...attachments].find(([, attachment]) => attachment.scope.enabled);
|
|
258
|
+
if (!selected)
|
|
259
|
+
return unavailable(activeRecorder && activeRecorder !== token ? 'recorder-in-use' : 'capture-unavailable');
|
|
260
|
+
const [owner, attachment] = selected;
|
|
261
|
+
if (!attachment.id)
|
|
262
|
+
attachment.id = attachNative(attachment.scope);
|
|
263
|
+
if (!attachment.id)
|
|
264
|
+
return unavailable(activeRecorder && activeRecorder !== token ? 'recorder-in-use' : 'capture-unavailable');
|
|
265
|
+
let nativeId = '';
|
|
266
|
+
try {
|
|
267
|
+
nativeId = native.preview(JSON.stringify({ attachmentId: attachment.id }));
|
|
268
|
+
}
|
|
269
|
+
catch { }
|
|
270
|
+
if (!nativeId)
|
|
271
|
+
return unavailable('capture-failed');
|
|
272
|
+
return new Promise(resolve => {
|
|
273
|
+
const entry = {};
|
|
274
|
+
Object.assign(entry, { id: '', owner, scope: attachment.scope, nativeId, running: false, cancelled: false, accepted: false,
|
|
275
|
+
lease: { accepted() { }, cancel() { release(entry); } }, preview: { resolve }, expiresAt: Date.now() + 60_000,
|
|
276
|
+
timer: setTimeout(() => release(entry), 60_000) });
|
|
277
|
+
preview = entry;
|
|
278
|
+
entries.add(entry);
|
|
279
|
+
queue.push(entry);
|
|
280
|
+
pump();
|
|
281
|
+
});
|
|
282
|
+
},
|
|
283
|
+
clear,
|
|
284
|
+
destroy() {
|
|
285
|
+
if (destroyed)
|
|
286
|
+
return;
|
|
287
|
+
destroyed = true;
|
|
288
|
+
clear();
|
|
289
|
+
for (const attachment of attachments.values())
|
|
290
|
+
if (attachment.id)
|
|
291
|
+
quiet(() => native.detach(attachment.id));
|
|
292
|
+
attachments.clear();
|
|
293
|
+
if (recorderId)
|
|
294
|
+
quiet(() => native.destroy(recorderId));
|
|
295
|
+
recorderId = '';
|
|
296
|
+
if (!running && activeRecorder === token)
|
|
297
|
+
activeRecorder = undefined;
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
}
|
package/lib/delivery.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateVideo = validateVideo;
|
|
4
|
+
exports.sendReplay = sendReplay;
|
|
5
|
+
function httpURL(value) {
|
|
6
|
+
const url = new URL(value);
|
|
7
|
+
if (!/^https?:\/\//i.test(value) || !/^https?:$/.test(url.protocol) || !url.hostname || url.username || url.password || url.href.includes('#'))
|
|
8
|
+
throw new Error('Invalid replay URL.');
|
|
9
|
+
return url.href;
|
|
10
|
+
}
|
|
11
|
+
function check(signal, deadline) { if (signal.aborted || Date.now() >= deadline)
|
|
12
|
+
throw new Error('Replay cancelled or expired.'); }
|
|
13
|
+
function validateVideo(video) {
|
|
14
|
+
if (typeof video.uri !== 'string' || !video.uri.startsWith('file://') || !Number.isSafeInteger(video.byteSize) || video.byteSize <= 0 || video.byteSize > 2 * 1024 * 1024 ||
|
|
15
|
+
!Number.isSafeInteger(video.width) || video.width <= 0 || video.width > 720 || video.width % 2 !== 0 || !Number.isSafeInteger(video.height) || video.height <= 0 || video.height > 720 || video.height % 2 !== 0 ||
|
|
16
|
+
![video.durationMs, video.startedBeforeEventMs, video.endedBeforeEventMs].every(value => Number.isSafeInteger(value) && value >= 0 && value <= 10_000) || video.durationMs === 0 || video.endedBeforeEventMs > video.startedBeforeEventMs || Math.abs(video.durationMs - video.startedBeforeEventMs + video.endedBeforeEventMs) > 1)
|
|
17
|
+
throw new Error('Invalid replay video.');
|
|
18
|
+
}
|
|
19
|
+
async function request(url, init, signal, json = true, deadline = Infinity) {
|
|
20
|
+
check(signal, deadline);
|
|
21
|
+
const transport = init.body instanceof FormData ? require('react-native/Libraries/Network/fetch').fetch : fetch;
|
|
22
|
+
const response = await transport(url, { ...init, signal, credentials: 'omit', redirect: 'error' });
|
|
23
|
+
check(signal, deadline);
|
|
24
|
+
if (!response.ok)
|
|
25
|
+
throw new Error('Replay request failed.');
|
|
26
|
+
if (!json)
|
|
27
|
+
return {};
|
|
28
|
+
const text = await response.text();
|
|
29
|
+
check(signal, deadline);
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
for (const character of text) {
|
|
32
|
+
const code = character.codePointAt(0);
|
|
33
|
+
bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : code <= 0xffff ? 3 : 4;
|
|
34
|
+
if (bytes > 64 * 1024)
|
|
35
|
+
throw new Error('Replay response is too large.');
|
|
36
|
+
}
|
|
37
|
+
const value = JSON.parse(text);
|
|
38
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
39
|
+
throw new Error('Invalid replay response.');
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
async function sendReplay(scope, submissionId, video, signal, deadline = Infinity) {
|
|
43
|
+
const endpoint = `${scope.baseUrl}/v1/sdk/teams/${encodeURIComponent(scope.teamId)}/relays/${encodeURIComponent(scope.relayId)}/replays`;
|
|
44
|
+
const post = (url, body) => request(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Relay-Key': scope.publishableKey }, body: JSON.stringify(body) }, signal, true, deadline);
|
|
45
|
+
let description;
|
|
46
|
+
if (typeof video.omitted === 'string' && video.omitted)
|
|
47
|
+
description = { omitted: /^[\x20-\x7e]{1,64}$/.test(video.omitted) ? video.omitted : 'capture-failed' };
|
|
48
|
+
else {
|
|
49
|
+
validateVideo(video);
|
|
50
|
+
description = { video: { mimeType: 'video/mp4', byteSize: video.byteSize, width: video.width, height: video.height,
|
|
51
|
+
durationMs: video.durationMs, startedBeforeEventMs: video.startedBeforeEventMs, endedBeforeEventMs: video.endedBeforeEventMs } };
|
|
52
|
+
}
|
|
53
|
+
const result = await post(endpoint, { protocolVersion: 1, submissionId, ...description });
|
|
54
|
+
if (typeof result.id !== 'string' || !result.id || result.id === '.' || result.id === '..' || result.id.length > 512 || !['pending', 'ready', 'omitted', 'failed', 'expired'].includes(result.status))
|
|
55
|
+
throw new Error('Invalid replay receipt.');
|
|
56
|
+
if (result.status !== 'pending')
|
|
57
|
+
return;
|
|
58
|
+
const upload = result.upload;
|
|
59
|
+
if (!video.uri || video.omitted || !upload || typeof upload.url !== 'string' || !upload.fields || typeof upload.fields !== 'object' || Array.isArray(upload.fields))
|
|
60
|
+
throw new Error('Invalid replay ticket.');
|
|
61
|
+
const body = new FormData();
|
|
62
|
+
for (const [name, value] of Object.entries(upload.fields)) {
|
|
63
|
+
if (typeof value !== 'string')
|
|
64
|
+
throw new Error('Invalid replay field.');
|
|
65
|
+
body.append(name, value);
|
|
66
|
+
}
|
|
67
|
+
body.append('file', { uri: video.uri, type: 'video/mp4', name: `${submissionId}.mp4` });
|
|
68
|
+
await request(httpURL(upload.url), { method: 'POST', body }, signal, false, deadline);
|
|
69
|
+
const completed = await post(`${endpoint}/${encodeURIComponent(result.id)}/complete`, {});
|
|
70
|
+
if (completed.id !== result.id || completed.status !== 'ready')
|
|
71
|
+
throw new Error('Invalid replay completion.');
|
|
72
|
+
}
|
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createReplayRecorder = createReplayRecorder;
|
|
7
|
+
const NativeRelayReplay_1 = __importDefault(require("./NativeRelayReplay"));
|
|
8
|
+
const client_1 = require("./client");
|
|
9
|
+
function createReplayRecorder(options = {}) { return (0, client_1.createRecorder)(NativeRelayReplay_1.default, options); }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<manifest />
|