ReviewOS

also looking at this

stacks/postline

feat: crossposting — media (LinkedIn/IG/Threads), OAuth token refresh, and X/Twitter

#30
Merged glennmichael123 wants to merge feat/crosspost-media-and-token-refresh into main
28 files +1810 -109
app/Services/Social/ThreadsService.tsmodified+48-4
Changes to app/Services/Social/ThreadsService.ts
@@ -2,7 +2,7 @@ import type { CrosspostTargetResult, PublishContent } from '../../Support/Social
22import { db } from '@stacksjs/database'
33import { env } from '@stacksjs/env'
44import { ThreadsApiError, ThreadsDriver } from './Drivers/ThreadsDriver'
5import { ensureAccount, now, uuid } from './support'
5import { ensureAccount, expiresAt, isExpiringSoon, now, uuid } from './support'
66
77const database = db as any
88
@@ -15,6 +15,7 @@ type SocialIdentityRow = {
1515 auth_status: 'connected' | 'expired' | 'revoked' | 'missing'
1616 access_token?: string | null
1717 refresh_token?: string | null
18 token_expires_at?: string | null
1819 account_id?: number | null
1920 social_driver_id?: number | null
2021}
@@ -118,11 +119,25 @@ export class ThreadsService {
118119 code,
119120 })
120121
121 const account = await this.driver.resolveAccount(token.accessToken)
122 // Upgrade the short-lived (~1h) token to a long-lived (~60-day) one so
123 // scheduled posts keep working, then resolve the account against it. If the
124 // exchange fails, fall back to the short-lived token — publishing still
125 // works, just briefly.
126 let accessToken = token.accessToken
127 let expiresIn = token.expiresIn
128 try {
129 const longLived = await this.driver.exchangeLongLivedToken(cfg.clientSecret, token.accessToken)
130 accessToken = longLived.accessToken
131 expiresIn = longLived.expiresIn
132 }
133 catch {}
134
135 const account = await this.driver.resolveAccount(accessToken)
122136 const identity = await this.saveSession({
123137 accessToken: account.accessToken,
124138 threadsUserId: account.threadsUserId,
125139 username: account.username,
140 expiresIn,
126141 })
127142 return this.publicIdentity(identity)
128143 }
@@ -235,7 +250,9 @@ export class ThreadsService {
235250
236251 private async requireIdentity(): Promise<SocialIdentityRow> {
237252 const existing = await this.findIdentity()
238 if (existing?.access_token && existing.auth_status === 'connected') return existing
253 if (existing?.access_token && existing.auth_status === 'connected') {
254 return await this.refreshIfExpiring(existing)
255 }
239256
240257 if (this.config().accessToken) {
241258 await this.connectFromEnv()
@@ -246,6 +263,32 @@ export class ThreadsService {
246263 throw new Error('Connect Threads before publishing.')
247264 }
248265
266 /**
267 * Refresh a long-lived token that's within its pre-expiry window, extending
268 * it another ~60 days. Best-effort: a refresh failure leaves the current
269 * token in place, so a genuinely dead token still surfaces at publish time
270 * (marking the identity expired and prompting a reconnect) rather than here.
271 */
272 private async refreshIfExpiring(identity: SocialIdentityRow): Promise<SocialIdentityRow> {
273 if (!identity.access_token || !isExpiringSoon(identity.token_expires_at)) return identity
274
275 try {
276 const refreshed = await this.driver.refreshLongLivedToken(identity.access_token)
277 const nextExpiry = expiresAt(refreshed.expiresIn)
278 await database.updateTable('social_identities').set({
279 access_token: refreshed.accessToken,
280 token_expires_at: nextExpiry,
281 auth_status: 'connected',
282 updated_at: now(),
283 }).where('id', '=', identity.id).execute()
284
285 return { ...identity, access_token: refreshed.accessToken, token_expires_at: nextExpiry }
286 }
287 catch {
288 return identity
289 }
290 }
291
249292 private async findIdentity(): Promise<SocialIdentityRow | undefined> {
250293 return await database
251294 .selectFrom('social_identities')
@@ -255,7 +298,7 @@ export class ThreadsService {
255298 .executeTakeFirst()
256299 }
257300
258 private async saveSession(input: { accessToken: string, threadsUserId: string, username?: string }): Promise<SocialIdentityRow> {
301 private async saveSession(input: { accessToken: string, threadsUserId: string, username?: string, expiresIn?: number }): Promise<SocialIdentityRow> {
259302 const accountId = await ensureAccount()
260303 const driver = await this.ensureDriver()
261304 const existing = await this.findIdentity()
@@ -270,6 +313,7 @@ export class ThreadsService {
270313 auth_status: 'connected',
271314 access_token: input.accessToken,
272315 refresh_token: null,
316 token_expires_at: expiresAt(input.expiresIn),
273317 account_id: accountId,
274318 social_driver_id: driver.id,
275319 updated_at: savedAt,