Skip to content

Commit

Permalink
fix: twitch event revokes
Browse files Browse the repository at this point in the history
  • Loading branch information
Geczy committed Jul 2, 2024
1 parent 66125bb commit c92aecd
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 23 deletions.
Binary file modified bun.lockb
Binary file not shown.
2 changes: 0 additions & 2 deletions packages/twitch-events/src/SubscribeEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { transformBetData } from './twitch/events/transformers/transformBetData.
import { transformPollData } from './twitch/events/transformers/transformPollData.js'
import { offlineEvent } from './twitch/lib/offlineEvent.js'
import { onlineEvent } from './twitch/lib/onlineEvent.js'
import { revokeEvent } from './twitch/lib/revokeEvent.js'
import { updateUserEvent } from './twitch/lib/updateUserEvent.js'
import { DOTABOD_EVENTS_ROOM, eventsIOConnected, socketIo } from './utils/socketUtils.js'

Expand All @@ -18,7 +17,6 @@ export const SubscribeEvents = (accountIds: string[]) => {
const promises: any[] = []
accountIds.forEach((userId) => {
try {
promises.push(listener.onUserAuthorizationRevoke(userId, revokeEvent))
promises.push(listener.onStreamOnline(userId, onlineEvent))
promises.push(listener.onStreamOffline(userId, offlineEvent))
promises.push(listener.onUserUpdate(userId, updateUserEvent))
Expand Down
4 changes: 2 additions & 2 deletions packages/twitch-events/src/handleNewUser.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { SubscribeEvents } from './SubscribeEvents.js'
import supabase from './db/supabase.js'
import BotAPI from './twitch/lib/BotApiSingleton.js'
import { getBotInstance } from './twitch/lib/BotApiSingleton.js'

const botApi = BotAPI.getInstance()
const botApi = getBotInstance()
export async function handleNewUser(providerAccountId: string) {
console.log("[TWITCHEVENTS] New user, let's get their info", { userId: providerAccountId })

Expand Down
4 changes: 2 additions & 2 deletions packages/twitch-events/src/listener.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { EventSubHttpListener, ReverseProxyAdapter } from '@twurple/eventsub-http'
import { getBotInstance } from './twitch/lib/BotApiSingleton.js'

import BotAPI from './twitch/lib/BotApiSingleton.js'
const { EVENTSUB_HOST, TWITCH_EVENTSUB_SECRET } = process.env

if (!EVENTSUB_HOST || !TWITCH_EVENTSUB_SECRET) {
throw new Error('Missing EVENTSUB_HOST or TWITCH_EVENTSUB_SECRET')
}

export const listener = new EventSubHttpListener({
apiClient: BotAPI.getInstance(),
apiClient: getBotInstance(),
legacySecrets: true,
adapter: new ReverseProxyAdapter({
hostName: EVENTSUB_HOST, // The host name the server is available from
Expand Down
6 changes: 1 addition & 5 deletions packages/twitch-events/src/twitch/lib/BotApiSingleton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { AppTokenAuthProvider } from '@twurple/auth'

let instance: ApiClient | null = null

function getInstance() {
export function getBotInstance() {
if (!instance) {
console.log('[TWITCH] Retrieving twitch dotabod api')
const authProvider = new AppTokenAuthProvider(
Expand All @@ -21,7 +21,3 @@ function getInstance() {
}
return instance
}

export default {
getInstance,
}
4 changes: 4 additions & 0 deletions packages/twitch-events/src/twitch/lib/getAccountIds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export async function getAccountIds(): Promise<string[]> {
// Filter out undefined values, if any.
const filteredProviderIds = providerIds.filter(Boolean)

if (filteredProviderIds.length < 10) {
console.log({ filteredProviderIds })
}

console.log('[TWITCHEVENTS] joining', filteredProviderIds.length, 'channels')
return filteredProviderIds
}
21 changes: 12 additions & 9 deletions packages/twitch-events/src/twitch/lib/revokeEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,14 @@ export async function fetchSubscriptions(providerId: string, cursor?: string): P
} // ${await response.text()}`,
)
}
return response.json()
const text = await response.json()
if (Array.isArray(text.data)) {
text.data = text.data.filter(
(sub: any) =>
(sub.condition.broadcaster_user_id || sub.condition.user_id) === `${providerId}`,
)
}
return text
}

function sleep(ms: number) {
Expand Down Expand Up @@ -139,20 +146,16 @@ async function deleteAllSubscriptionsForProvider(providerId: string): Promise<vo
let cursor: string | undefined
do {
// Fetch subscriptions for the given provider ID
const data = await fetchSubscriptions(providerId, cursor)
const subscriptionsForProvider = data.data.filter(
(sub: any) => sub.condition.broadcaster_user_id === providerId,
)

console.log('Found subscriptions', subscriptionsForProvider.length)
const subs = await fetchSubscriptions(providerId, cursor)
console.log('Found subscriptions', subs.data.length)

// Delete each subscription found for the provider
for (const sub of subscriptionsForProvider) {
for (const sub of subs.data) {
await deleteSubscription(sub.id)
}

// Update cursor for next page of subscriptions, if any
cursor = data.pagination?.cursor
cursor = subs.pagination?.cursor
} while (cursor) // Continue until there are no more pages

console.log(`All subscriptions deleted for provider ID: ${providerId}`)
Expand Down
10 changes: 7 additions & 3 deletions packages/twitch-events/src/utils/webhookUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@ import type { Tables } from '../db/supabase-types.js'
import { handleNewUser } from '../handleNewUser.js'
import { listener } from '../listener.js'
import { getAccountIds } from '../twitch/lib/getAccountIds.js'
import { revokeEvent } from '../twitch/lib/revokeEvent.js'
import type { InsertPayload, UpdatePayload } from '../types.js'
import { isAuthenticated } from './authUtils.js'

export const setupWebhooks = () => {
const webhookApp = express()

const { DOTABOD_ENV } = process.env

const IS_DEV = DOTABOD_ENV !== 'production'
const IS_DEV = process.env.DOTABOD_ENV !== 'production'
const DEV_CHANNELS = process.env.DEV_CHANNELS?.split(',') ?? []
const DEV_CHANNELIDS = process.env.DEV_CHANNELIDS?.split(',') ?? []

Expand Down Expand Up @@ -128,6 +127,11 @@ export const setupWebhooks = () => {
console.log('[TWITCHEVENTS] Webhooks Listening on port 5011')

listener.start()
try {
listener.onUserAuthorizationRevoke(process.env.TWITCH_CLIENT_ID ?? '', revokeEvent)
} catch (e) {
console.log('[TWITCHEVENTS] error on listener.onUserAuthorizationRevoke', { e })
}

// Load every account id when booting server
const accountIds = await getAccountIds()
Expand Down

0 comments on commit c92aecd

Please sign in to comment.