also looking at this
feat: crosspost to LinkedIn and Instagram
#1
31 files
+2335
-87
| @@ -0,0 +1,374 @@ | ||
| 1 | import type { CrosspostTargetResult, PublishContent } from '../../Support/Social/types' | |
| 2 | import { db } from '@stacksjs/database' | |
| 3 | import { env } from '@stacksjs/env' | |
| 4 | import { InstagramApiError, InstagramDriver } from './Drivers/InstagramDriver' | |
| 5 | import { ensureAccount, now, uuid } from './support' | |
| 6 | ||
| 7 | const database = db as any | |
| 8 | ||
| 9 | type SocialIdentityRow = { | |
| 10 | id: number | |
| 11 | handle: string | |
| 12 | display_name?: string | null | |
| 13 | provider: 'instagram' | |
| 14 | external_id?: string | null | |
| 15 | auth_status: 'connected' | 'expired' | 'revoked' | 'missing' | |
| 16 | access_token?: string | null | |
| 17 | refresh_token?: string | null | |
| 18 | account_id?: number | null | |
| 19 | social_driver_id?: number | null | |
| 20 | } | |
| 21 | ||
| 22 | type SocialDriverRow = { | |
| 23 | id: number | |
| 24 | provider: 'instagram' | |
| 25 | display_name: string | |
| 26 | status: 'active' | 'planned' | 'disabled' | |
| 27 | character_limit: number | |
| 28 | } | |
| 29 | ||
| 30 | interface InstagramConfig { | |
| 31 | clientId: string | |
| 32 | clientSecret: string | |
| 33 | redirectUrl: string | |
| 34 | graphVersion: string | |
| 35 | accessToken: string | |
| 36 | userId: string | |
| 37 | username: string | |
| 38 | scopes: string[] | |
| 39 | } | |
| 40 | ||
| 41 | function randomState(): string { | |
| 42 | const bytes = new Uint8Array(24) | |
| 43 | crypto.getRandomValues(bytes) | |
| 44 | return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('') | |
| 45 | } | |
| 46 | ||
| 47 | export class InstagramService { | |
| 48 | private driver: InstagramDriver | |
| 49 | private pendingState: string | null = null | |
| 50 | ||
| 51 | constructor() { | |
| 52 | this.driver = new InstagramDriver({ graphVersion: this.config().graphVersion }) | |
| 53 | } | |
| 54 | ||
| 55 | private config(): InstagramConfig { | |
| 56 | return { | |
| 57 | clientId: String(env.INSTAGRAM_CLIENT_ID || '').trim(), | |
| 58 | clientSecret: String(env.INSTAGRAM_CLIENT_SECRET || '').trim(), | |
| 59 | redirectUrl: String(env.INSTAGRAM_REDIRECT_URL || '').trim(), | |
| 60 | graphVersion: String(env.INSTAGRAM_GRAPH_VERSION || 'v21.0').trim(), | |
| 61 | accessToken: String(env.INSTAGRAM_ACCESS_TOKEN || '').trim(), | |
| 62 | userId: String(env.INSTAGRAM_USER_ID || '').trim(), | |
| 63 | username: String(env.INSTAGRAM_USERNAME || '').trim(), | |
| 64 | scopes: ['instagram_basic', 'instagram_content_publish', 'pages_show_list', 'pages_read_engagement'], | |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | async status() { | |
| 69 | const identity = await this.findIdentity() | |
| 70 | const cfg = this.config() | |
| 71 | const connected = identity?.auth_status === 'connected' && Boolean(identity.access_token) | |
| 72 | ||
| 73 | return { | |
| 74 | connected, | |
| 75 | provider: 'instagram', | |
| 76 | handle: identity?.handle || null, | |
| 77 | displayName: identity?.display_name || null, | |
| 78 | did: identity?.external_id || null, | |
| 79 | authStatus: connected ? 'connected' : (identity?.handle ? identity.auth_status : 'missing'), | |
| 80 | characterLimit: this.driver.characterLimit, | |
| 81 | canPublish: connected, | |
| 82 | requiresMedia: true, | |
| 83 | configuredFromEnv: Boolean(cfg.accessToken && cfg.userId), | |
| 84 | oauthConfigured: Boolean(cfg.clientId && cfg.clientSecret && cfg.redirectUrl), | |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | getAuthUrl(): string { | |
| 89 | const cfg = this.config() | |
| 90 | if (!cfg.clientId || !cfg.clientSecret) { | |
| 91 | throw new Error('Set INSTAGRAM_CLIENT_ID and INSTAGRAM_CLIENT_SECRET to connect Instagram.') | |
| 92 | } | |
| 93 | if (!cfg.redirectUrl) { | |
| 94 | throw new Error('Set INSTAGRAM_REDIRECT_URL to connect Instagram.') | |
| 95 | } | |
| 96 | ||
| 97 | this.pendingState = randomState() | |
| 98 | return this.driver.getAuthUrl({ | |
| 99 | clientId: cfg.clientId, | |
| 100 | redirectUrl: cfg.redirectUrl, | |
| 101 | scopes: cfg.scopes, | |
| 102 | state: this.pendingState, | |
| 103 | }) | |
| 104 | } | |
| 105 | ||
| 106 | async handleCallback(code: string, state: string) { | |
| 107 | const cfg = this.config() | |
| 108 | if (!code) throw new Error('Facebook did not return an authorization code.') | |
| 109 | if (this.pendingState && state !== this.pendingState) { | |
| 110 | throw new Error('Instagram OAuth state mismatch. Please start the connection again.') | |
| 111 | } | |
| 112 | this.pendingState = null | |
| 113 | ||
| 114 | const token = await this.driver.exchangeCode({ | |
| 115 | clientId: cfg.clientId, | |
| 116 | clientSecret: cfg.clientSecret, | |
| 117 | redirectUrl: cfg.redirectUrl, | |
| 118 | code, | |
| 119 | }) | |
| 120 | ||
| 121 | const account = await this.driver.resolveAccount(token.accessToken) | |
| 122 | const identity = await this.saveSession({ | |
| 123 | accessToken: account.pageAccessToken, | |
| 124 | igUserId: account.igUserId, | |
| 125 | username: account.username, | |
| 126 | }) | |
| 127 | return this.publicIdentity(identity) | |
| 128 | } | |
| 129 | ||
| 130 | async connectFromEnv() { | |
| 131 | const cfg = this.config() | |
| 132 | if (!cfg.accessToken) { | |
| 133 | throw new Error('Set INSTAGRAM_ACCESS_TOKEN (or connect via OAuth) before using Instagram.') | |
| 134 | } | |
| 135 | ||
| 136 | let igUserId = cfg.userId | |
| 137 | let username = cfg.username || undefined | |
| 138 | let pageAccessToken = cfg.accessToken | |
| 139 | if (!igUserId) { | |
| 140 | const account = await this.driver.resolveAccount(cfg.accessToken) | |
| 141 | igUserId = account.igUserId | |
| 142 | username = account.username | |
| 143 | pageAccessToken = account.pageAccessToken | |
| 144 | } | |
| 145 | ||
| 146 | const identity = await this.saveSession({ accessToken: pageAccessToken, igUserId, username }) | |
| 147 | return this.publicIdentity(identity) | |
| 148 | } | |
| 149 | ||
| 150 | /** | |
| 151 | * Publish an already-created post row to Instagram. Never throws — failures | |
| 152 | * (including the "image required" case) are recorded on the target and | |
| 153 | * returned so other crosspost providers still succeed. | |
| 154 | */ | |
| 155 | async publishToPost( | |
| 156 | post: { id: number, body: string }, | |
| 157 | content?: PublishContent, | |
| 158 | ): Promise<CrosspostTargetResult> { | |
| 159 | const media = content?.media?.[0] | |
| 160 | if (!media?.url) { | |
| 161 | return { provider: 'instagram', ok: false, error: 'Instagram requires an image — add an image URL.' } | |
| 162 | } | |
| 163 | ||
| 164 | const driver = await this.ensureDriver() | |
| 165 | ||
| 166 | let identity: SocialIdentityRow | |
| 167 | try { | |
| 168 | identity = await this.requireIdentity() | |
| 169 | } | |
| 170 | catch (error) { | |
| 171 | return { provider: 'instagram', ok: false, error: messageOf(error) } | |
| 172 | } | |
| 173 | ||
| 174 | if (post.body.length > this.driver.characterLimit) { | |
| 175 | return { | |
| 176 | provider: 'instagram', | |
| 177 | ok: false, | |
| 178 | error: `Instagram captions must be ${this.driver.characterLimit} characters or fewer.`, | |
| 179 | } | |
| 180 | } | |
| 181 | ||
| 182 | const targetUuid = uuid() | |
| 183 | const createdAt = now() | |
| 184 | await database.insertInto('post_targets').values({ | |
| 185 | uuid: targetUuid, | |
| 186 | provider: 'instagram', | |
| 187 | status: 'publishing', | |
| 188 | post_id: post.id, | |
| 189 | social_driver_id: driver.id, | |
| 190 | social_identity_id: identity.id, | |
| 191 | created_at: createdAt, | |
| 192 | updated_at: createdAt, | |
| 193 | }).execute() | |
| 194 | ||
| 195 | const target = await database | |
| 196 | .selectFrom('post_targets') | |
| 197 | .selectAll() | |
| 198 | .where('uuid', '=', targetUuid) | |
| 199 | .executeTakeFirstOrThrow() | |
| 200 | ||
| 201 | try { | |
| 202 | const published = await this.driver.publish({ | |
| 203 | handle: identity.handle, | |
| 204 | did: identity.external_id || undefined, | |
| 205 | accessToken: identity.access_token || undefined, | |
| 206 | }, { | |
| 207 | text: post.body, | |
| 208 | media: content?.media, | |
| 209 | }) | |
| 210 | ||
| 211 | await database.updateTable('post_targets').set({ | |
| 212 | status: 'published', | |
| 213 | remote_uri: published.uri || null, | |
| 214 | failure_reason: null, | |
| 215 | updated_at: now(), | |
| 216 | }).where('id', '=', target.id).execute() | |
| 217 | ||
| 218 | return { | |
| 219 | provider: 'instagram', | |
| 220 | ok: true, | |
| 221 | url: published.url, | |
| 222 | uri: published.uri, | |
| 223 | targetId: Number(target.id), | |
| 224 | } | |
| 225 | } | |
| 226 | catch (error) { | |
| 227 | const message = messageOf(error) | |
| 228 | if (error instanceof InstagramApiError && error.isAuthError) { | |
| 229 | await this.markExpired(identity.id) | |
| 230 | } | |
| 231 | await database.updateTable('post_targets').set({ | |
| 232 | status: 'failed', | |
| 233 | failure_reason: message, | |
| 234 | updated_at: now(), | |
| 235 | }).where('id', '=', target.id).execute() | |
| 236 | ||
| 237 | return { provider: 'instagram', ok: false, error: message, targetId: Number(target.id) } | |
| 238 | } | |
| 239 | } | |
| 240 | ||
| 241 | private async requireIdentity(): Promise<SocialIdentityRow> { | |
| 242 | const existing = await this.findIdentity() | |
| 243 | if (existing?.access_token && existing.auth_status === 'connected') return existing | |
| 244 | ||
| 245 | if (this.config().accessToken) { | |
| 246 | await this.connectFromEnv() | |
| 247 | const connected = await this.findIdentity() | |
| 248 | if (connected?.access_token) return connected | |
| 249 | } | |
| 250 | ||
| 251 | throw new Error('Connect Instagram before publishing.') | |
| 252 | } | |
| 253 | ||
| 254 | private async findIdentity(): Promise<SocialIdentityRow | undefined> { | |
| 255 | return await database | |
| 256 | .selectFrom('social_identities') | |
| 257 | .selectAll() | |
| 258 | .where('provider', '=', 'instagram') | |
| 259 | .orderBy('updated_at', 'desc') | |
| 260 | .executeTakeFirst() | |
| 261 | } | |
| 262 | ||
| 263 | private async saveSession(input: { accessToken: string, igUserId: string, username?: string }): Promise<SocialIdentityRow> { | |
| 264 | const accountId = await ensureAccount() | |
| 265 | const driver = await this.ensureDriver() | |
| 266 | const existing = await this.findIdentity() | |
| 267 | const savedAt = now() | |
| 268 | const handle = (input.username || input.igUserId).trim() | |
| 269 | ||
| 270 | const values = { | |
| 271 | handle, | |
| 272 | display_name: input.username || null, | |
| 273 | provider: 'instagram', | |
| 274 | external_id: input.igUserId, | |
| 275 | auth_status: 'connected', | |
| 276 | access_token: input.accessToken, | |
| 277 | refresh_token: null, | |
| 278 | account_id: accountId, | |
| 279 | social_driver_id: driver.id, | |
| 280 | updated_at: savedAt, | |
| 281 | } | |
| 282 | ||
| 283 | if (existing) { | |
| 284 | await database.updateTable('social_identities').set(values).where('id', '=', existing.id).execute() | |
| 285 | } | |
| 286 | else { | |
| 287 | await database.insertInto('social_identities').values({ | |
| 288 | uuid: uuid(), | |
| 289 | ...values, | |
| 290 | created_at: savedAt, | |
| 291 | }).execute() | |
| 292 | } | |
| 293 | ||
| 294 | return await this.findIdentity() as SocialIdentityRow | |
| 295 | } | |
| 296 | ||
| 297 | private async markExpired(id: number): Promise<void> { | |
| 298 | await database.updateTable('social_identities').set({ | |
| 299 | auth_status: 'expired', | |
| 300 | updated_at: now(), | |
| 301 | }).where('id', '=', id).execute() | |
| 302 | } | |
| 303 | ||
| 304 | private async ensureDriver(): Promise<SocialDriverRow> { | |
| 305 | const existing = await database | |
| 306 | .selectFrom('social_drivers') | |
| 307 | .selectAll() | |
| 308 | .where('provider', '=', 'instagram') | |
| 309 | .executeTakeFirst() | |
| 310 | ||
| 311 | if (existing) { | |
| 312 | if (existing.status !== 'active' || existing.character_limit !== this.driver.characterLimit) { | |
| 313 | await database.updateTable('social_drivers').set({ | |
| 314 | status: 'active', | |
| 315 | character_limit: this.driver.characterLimit, | |
| 316 | updated_at: now(), | |
| 317 | }).where('id', '=', existing.id).execute() | |
| 318 | } | |
| 319 | ||
| 320 | return await database | |
| 321 | .selectFrom('social_drivers') | |
| 322 | .selectAll() | |
| 323 | .where('id', '=', existing.id) | |
| 324 | .executeTakeFirstOrThrow() | |
| 325 | } | |
| 326 | ||
| 327 | const driverUuid = uuid() | |
| 328 | await database.insertInto('social_drivers').values({ | |
| 329 | uuid: driverUuid, | |
| 330 | provider: 'instagram', | |
| 331 | display_name: 'Instagram', | |
| 332 | status: 'active', | |
| 333 | character_limit: this.driver.characterLimit, | |
| 334 | capabilities: JSON.stringify({ posts: true, timelines: false, oauth: true, requiresMedia: true }), | |
| 335 | created_at: now(), | |
| 336 | updated_at: now(), | |
| 337 | }).execute() | |
| 338 | ||
| 339 | return await database | |
| 340 | .selectFrom('social_drivers') | |
| 341 | .selectAll() | |
| 342 | .where('uuid', '=', driverUuid) | |
| 343 | .executeTakeFirstOrThrow() | |
| 344 | } | |
| 345 | ||
| 346 | private publicIdentity(row: SocialIdentityRow | undefined) { | |
| 347 | if (!row) { | |
| 348 | return { | |
| 349 | connected: false, | |
| 350 | provider: 'instagram', | |
| 351 | handle: null, | |
| 352 | displayName: null, | |
| 353 | did: null, | |
| 354 | authStatus: 'missing', | |
| 355 | } | |
| 356 | } | |
| 357 | ||
| 358 | const connected = row.auth_status === 'connected' && Boolean(row.access_token) | |
| 359 | return { | |
| 360 | connected, | |
| 361 | provider: 'instagram', | |
| 362 | handle: row.handle, | |
| 363 | displayName: row.display_name || null, | |
| 364 | did: row.external_id || null, | |
| 365 | authStatus: connected ? 'connected' : 'missing', | |
| 366 | } | |
| 367 | } | |
| 368 | } | |
| 369 | ||
| 370 | function messageOf(error: unknown): string { | |
| 371 | return error instanceof Error ? error.message : String(error) | |
| 372 | } | |
| 373 | ||
| 374 | export const instagram = new InstagramService() | |