forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublic.ts
More file actions
420 lines (385 loc) · 10.9 KB
/
Copy pathpublic.ts
File metadata and controls
420 lines (385 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/**
* Public API module for marketplace
* These endpoints don't require authentication
*/
// For public marketplace, use the configured API base URL or fallback to production
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'https://api.omi.me';
/**
* Base URL for public reads.
*
* In a browser these pages run on the web origin, and the backend allows no
* cross-origin callers by default (`CORS_ALLOWED_ORIGINS` is empty in
* `backend/main.py`), so a direct call is blocked before it is sent. Go through
* the same-origin passthrough instead. On the server (build, sitemap, route
* handlers) there is no origin to be same as, so call the API directly.
*/
export function publicApiBaseUrl(): string {
return typeof window === 'undefined' ? API_BASE_URL : '/api/proxy/public';
}
/**
* Fetch approved apps for the public marketplace
* Cached and doesn't require authentication
*/
export async function getApprovedApps(): Promise<{
plugins: Array<{
id: string;
name: string;
description: string;
author: string;
image: string;
category: string;
installs: number;
rating_avg: number;
rating_count: number;
capabilities: string[];
created_at: string;
is_paid?: boolean;
price?: number;
payment_plan?: 'one_time' | 'monthly_recurring' | null;
is_popular?: boolean;
}>;
stats: Array<{
id: string;
money: number;
}>;
}> {
try {
// Cache for 5 minutes
const response = await fetch(
`${publicApiBaseUrl()}/v1/approved-apps?include_reviews=true`,
);
if (!response.ok) {
console.error('Failed to fetch approved apps:', response.status);
return { plugins: [], stats: [] };
}
const data = await response.json();
// Transform the data to include capabilities as an array
return {
plugins: data.plugins || data || [],
stats: data.stats || [],
};
} catch (error) {
console.error('Error fetching approved apps:', error);
return { plugins: [], stats: [] };
}
}
/**
* Fetch a single app by ID for the public detail page
* Fetches all apps and finds the matching one (since individual endpoint doesn't exist)
* Cached and doesn't require authentication
*/
export async function getAppById(appId: string): Promise<{
id: string;
name: string;
description: string;
author: string;
image: string;
category: string;
installs: number;
rating_avg: number;
rating_count: number;
capabilities: string[];
created_at: string;
is_paid?: boolean;
price?: number;
payment_plan?: 'one_time' | 'monthly_recurring' | null;
is_popular?: boolean;
reviews?: Array<{
id: string;
user_name: string;
rating: number;
review: string;
created_at: string;
}>;
} | null> {
try {
// Fetch all approved apps and find the one by ID
const { plugins } = await getApprovedApps();
const app = plugins.find((p) => p.id === appId);
return app || null;
} catch (error) {
console.error('Error fetching app:', error);
return null;
}
}
/**
* Transform raw API data to Plugin format with Set for capabilities
*/
export function transformToPlugin(raw: {
id: string;
name: string;
description: string;
author: string;
image: string;
category: string;
installs: number;
rating_avg: number;
rating_count: number;
capabilities: string[];
created_at: string | null;
is_paid?: boolean;
price?: number;
payment_plan?: 'one_time' | 'monthly_recurring' | null;
is_popular?: boolean;
}): {
id: string;
name: string;
description: string;
author: string;
image: string;
category: string;
installs: number;
rating_avg: number;
rating_count: number;
capabilities: Set<string>;
created_at: string | null;
is_paid?: boolean;
price?: number;
payment_plan?: 'one_time' | 'monthly_recurring' | null;
is_popular?: boolean;
} {
return {
...raw,
capabilities: new Set(raw.capabilities || []),
};
}
// ============================================================================
// V2 API Types and Functions
// ============================================================================
/**
* V2 API type definitions for paginated app responses
*/
export interface V2PaginationInfo {
total: number;
count: number;
offset: number;
limit: number;
hasNext: boolean;
hasPrevious: boolean;
links: {
next: string | null;
previous: string | null;
};
}
export interface V2AppData {
id: string;
name: string;
description: string;
author: string;
image: string;
category: string;
installs: number;
rating_avg: number;
rating_count: number;
capabilities: string[];
created_at: string | null;
is_paid?: boolean;
price?: number;
payment_plan?: 'one_time' | 'monthly_recurring' | null;
is_popular?: boolean;
approved?: boolean;
status?: string;
uid?: string | null;
private?: boolean;
enabled?: boolean;
trigger_workflow_memories?: boolean;
score?: number;
proactive_notification?: any;
external_integration?: any;
username?: string;
connected_accounts?: any[];
chat_tools?: any[];
thumbnails?: any[];
thumbnail_urls?: string[];
is_influencer?: boolean;
is_user_paid?: boolean;
payment_link?: string | null;
}
export interface V2CapabilityGroup {
capability: {
id: string;
title: string;
};
data: V2AppData[];
pagination: V2PaginationInfo;
}
export interface V2AppsResponse {
groups: V2CapabilityGroup[];
meta: {
capabilities: Array<{
id: string;
title: string;
}>;
groupCount: number;
limit: number;
offset: number;
};
}
export interface V2SingleCapabilityResponse {
data: V2AppData[];
pagination: V2PaginationInfo;
capability: {
id: string;
title: string;
};
}
/**
* Fetch apps from v2/apps endpoint (grouped by capability)
* Returns paginated groups of apps (much smaller than v1)
* @param includeReviews - Whether to include review data (default: false)
*/
export async function getAppsV2(includeReviews = false): Promise<V2AppsResponse> {
try {
const url = `${publicApiBaseUrl()}/v2/apps${includeReviews ? '?include_reviews=true' : ''}`;
// Cache for 5 minutes
const response = await fetch(url);
if (!response.ok) {
console.error('Failed to fetch v2 apps:', response.status);
return {
groups: [],
meta: { capabilities: [], groupCount: 0, limit: 20, offset: 0 },
};
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching v2 apps:', error);
return {
groups: [],
meta: { capabilities: [], groupCount: 0, limit: 20, offset: 0 },
};
}
}
/**
* Fetch apps for a specific capability from v2/apps endpoint
* @param capability - The capability ID (e.g., 'chat', 'memories', 'external_integration')
* @param offset - Pagination offset (default: 0)
* @param limit - Number of items per page (default: 50, max: 50)
* @param includeReviews - Whether to include review data (default: false)
*/
export async function getAppsByCapability(
capability: string,
offset = 0,
limit = 50,
includeReviews = false,
): Promise<V2SingleCapabilityResponse> {
try {
const params = new URLSearchParams({
capability,
offset: offset.toString(),
limit: limit.toString(),
});
if (includeReviews) {
params.append('include_reviews', 'true');
}
const url = `${publicApiBaseUrl()}/v2/apps?${params.toString()}`;
// Cache for 5 minutes
const response = await fetch(url);
if (!response.ok) {
console.error(
`Failed to fetch apps for capability ${capability}:`,
response.status,
);
return {
data: [],
pagination: {
total: 0,
count: 0,
offset: 0,
limit: limit,
hasNext: false,
hasPrevious: false,
links: { next: null, previous: null },
},
capability: { id: capability, title: capability },
};
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Error fetching apps for capability ${capability}:`, error);
return {
data: [],
pagination: {
total: 0,
count: 0,
offset: 0,
limit: limit,
hasNext: false,
hasPrevious: false,
links: { next: null, previous: null },
},
capability: { id: capability, title: capability },
};
}
}
/**
* Fetch ALL apps from v2 by paginating through all capability groups
* This should only be used during build time for SSG
* Makes multiple requests but ensures all apps are available
* @param includeReviews - Whether to include review/rating data (default: false)
*/
export async function getAllAppsV2(includeReviews = false): Promise<V2AppData[]> {
try {
const allApps: V2AppData[] = [];
const { groups } = await getAppsV2(includeReviews);
console.log('Fetching all v2 apps with pagination...');
// For each capability group
for (const group of groups) {
console.log(
`- ${group.capability.id}: ${group.pagination.count} of ${group.pagination.total} apps`,
);
// Add first page apps
allApps.push(...group.data);
// If there are more pages, fetch them
if (group.pagination.hasNext) {
const totalPages = Math.ceil(group.pagination.total / group.pagination.limit);
// Fetch remaining pages
for (let page = 1; page < totalPages; page++) {
const offset = page * group.pagination.limit;
const response = await getAppsByCapability(
group.capability.id,
offset,
group.pagination.limit,
includeReviews,
);
console.log(
` Fetched page ${page + 1}/${totalPages} (${response.data.length} apps)`,
);
allApps.push(...response.data);
}
}
}
console.log(`Total apps fetched: ${allApps.length}`);
// Deduplicate apps by ID (apps can appear in multiple capability groups)
const uniqueAppsMap = new Map<string, V2AppData>();
for (const app of allApps) {
if (!uniqueAppsMap.has(app.id)) {
uniqueAppsMap.set(app.id, app);
}
}
const uniqueApps = Array.from(uniqueAppsMap.values());
console.log(`Unique apps after deduplication: ${uniqueApps.length}`);
return uniqueApps;
} catch (error) {
console.error('Error fetching all v2 apps:', error);
return [];
}
}
/**
* Find a specific app by ID from v2/apps response
* Searches through ALL apps (paginated) to find the app
* @param id - The app ID to search for
*/
export async function findAppById(id: string): Promise<V2AppData | null> {
try {
// Use getAllAppsV2 to search through all 625 apps, not just first 85
// Include reviews to get rating data
const allApps = await getAllAppsV2(true);
const app = allApps.find((app) => app.id === id);
return app || null;
} catch (error) {
console.error(`Error finding app by ID ${id}:`, error);
return null;
}
}