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/InstagramService.tsmodified+19-3
Changes to app/Services/Social/InstagramService.ts
@@ -2,7 +2,7 @@ import type { CrosspostTargetResult, PublishContent } from '../../Support/Social
22import { db } from '@stacksjs/database'
33import { env } from '@stacksjs/env'
44import { InstagramApiError, InstagramDriver } from './Drivers/InstagramDriver'
5import { ensureAccount, now, uuid } from './support'
5import { ensureAccount, expiresAt, 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 InstagramService {
118119 code,
119120 })
120121
121 const account = await this.driver.resolveAccount(token.accessToken)
122 // Exchange the short-lived user token for a long-lived (~60-day) one before
123 // resolving the Page — a Page token minted from a long-lived user token does
124 // not expire on its own, so there's no per-publish refresh grant to run.
125 // Best-effort: fall back to the short-lived token if the exchange fails.
126 let userToken = token.accessToken
127 let expiresIn: number | undefined
128 try {
129 const longLived = await this.driver.exchangeLongLivedUserToken(cfg.clientId, cfg.clientSecret, token.accessToken)
130 userToken = longLived.accessToken
131 expiresIn = longLived.expiresIn
132 }
133 catch {}
134
135 const account = await this.driver.resolveAccount(userToken)
122136 const identity = await this.saveSession({
123137 accessToken: account.pageAccessToken,
124138 igUserId: account.igUserId,
125139 username: account.username,
140 expiresIn,
126141 })
127142 return this.publicIdentity(identity)
128143 }
@@ -260,7 +275,7 @@ export class InstagramService {
260275 .executeTakeFirst()
261276 }
262277
263 private async saveSession(input: { accessToken: string, igUserId: string, username?: string }): Promise<SocialIdentityRow> {
278 private async saveSession(input: { accessToken: string, igUserId: string, username?: string, expiresIn?: number }): Promise<SocialIdentityRow> {
264279 const accountId = await ensureAccount()
265280 const driver = await this.ensureDriver()
266281 const existing = await this.findIdentity()
@@ -275,6 +290,7 @@ export class InstagramService {
275290 auth_status: 'connected',
276291 access_token: input.accessToken,
277292 refresh_token: null,
293 token_expires_at: expiresAt(input.expiresIn),
278294 account_id: accountId,
279295 social_driver_id: driver.id,
280296 updated_at: savedAt,