1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import React from 'react'
import {createClient} from '@segment/analytics-react'
import {sha256} from 'js-sha256'
import {Browser} from 'sentry-expo'
import {TrackEvent, AnalyticsMethods} from './types'
import {useSession, SessionAccount} from '#/state/session'
import {logger} from '#/logger'
type SegmentClient = ReturnType<typeof createClient>
// Delay creating until first actual use.
let segmentClient: SegmentClient | null = null
function getClient(): SegmentClient {
if (!segmentClient) {
segmentClient = createClient(
{
writeKey: '8I6DsgfiSLuoONyaunGoiQM7A6y2ybdI',
},
{
integrations: {
'Segment.io': {
apiHost: 'api.events.bsky.app/v1',
},
},
},
)
}
return segmentClient
}
export const track: TrackEvent = async (...args) => {
logger.info('analytics: track', {args})
await getClient().track(...args)
}
export function useAnalytics(): AnalyticsMethods {
const {hasSession} = useSession()
return React.useMemo(() => {
if (hasSession) {
return {
async screen(...args) {
logger.info('analytics: screen', {args})
await getClient().screen(...args)
},
async track(...args) {
logger.info('analytics: track', {args})
await getClient().track(...args)
},
}
}
// dont send analytics pings for anonymous users
return {
screen: async () => {},
track: async () => {},
}
}, [hasSession])
}
export function init(account: SessionAccount | undefined) {
if (account) {
const client = getClient()
if (account.did) {
const did_hashed = sha256(account.did)
client.identify(did_hashed, {did_hashed})
Browser.setUser({id: did_hashed})
logger.debug('Ping w/hash')
} else {
logger.debug('Ping w/o hash')
client.identify()
}
}
}
|