ReviewOS

also looking at this

stacks/postline

Sync Bluesky engagement metrics into analytics

#12
Merged glennmichael123 wants to merge feat/metrics-sync into main
10 files +200 -4
app/Services/Social/BlueskyService.tsmodified+52-0
Changes to app/Services/Social/BlueskyService.ts
@@ -273,6 +273,58 @@ export class BlueskyService {
273273 }
274274 }
275275
276 /**
277 * Refresh engagement counts (likes/reposts/replies) for recently
278 * published Bluesky targets into `post_targets.metrics`. Batched 25
279 * URIs per API call; missing posts (deleted upstream) are skipped.
280 */
281 async syncMetrics(limit = 100): Promise<{ synced: number }> {
282 const identity = await this.requireIdentity()
283 await this.ensureDriver()
284
285 const targets = await database
286 .selectFrom('post_targets')
287 .select(['id', 'remote_uri'])
288 .where('provider', '=', 'bluesky')
289 .where('status', '=', 'published')
290 .where('remote_uri', 'like', 'at://%')
291 .orderBy('id', 'desc')
292 .limit(limit)
293 .execute()
294
295 if (targets.length === 0) return { synced: 0 }
296
297 let synced = 0
298 for (let offset = 0; offset < targets.length; offset += 25) {
299 const chunk = targets.slice(offset, offset + 25)
300 const metrics = await this.withFreshSession(identity, freshIdentity =>
301 this.driver.postMetrics({
302 handle: freshIdentity.handle,
303 did: freshIdentity.external_id || undefined,
304 accessToken: freshIdentity.access_token || undefined,
305 refreshToken: freshIdentity.refresh_token || undefined,
306 }, chunk.map((target: any) => String(target.remote_uri))),
307 )
308
309 const byUri = new Map(metrics.map(item => [item.uri, item]))
310 for (const target of chunk) {
311 const counts = byUri.get(String(target.remote_uri))
312 if (!counts) continue
313 await database.updateTable('post_targets').set({
314 metrics: JSON.stringify({
315 likes: counts.likeCount,
316 reposts: counts.repostCount,
317 replies: counts.replyCount,
318 syncedAt: now(),
319 }),
320 }).where('id', '=', target.id).execute()
321 synced += 1
322 }
323 }
324
325 return { synced }
326 }
327
276328 async syncTimeline(limit = 30): Promise<TimelineResult & { saved: number }> {
277329 const identity = await this.requireIdentity()
278330 const driver = await this.ensureDriver()