about summary refs log tree commit diff
path: root/src/state/feed-feedback.tsx
blob: 64bdd4b893a8106da0d4cc12ae43a0a5ffd1dd5e (plain) (blame)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import React from 'react'
import {AppState, AppStateStatus} from 'react-native'
import {AppBskyFeedDefs, BskyAgent} from '@atproto/api'
import throttle from 'lodash.throttle'

import {PROD_DEFAULT_FEED} from '#/lib/constants'
import {logger} from '#/logger'
import {
  FeedDescriptor,
  FeedPostSliceItem,
  isFeedPostSlice,
} from '#/state/queries/post-feed'
import {useAgent} from './session'

type StateContext = {
  enabled: boolean
  onItemSeen: (item: any) => void
  sendInteraction: (interaction: AppBskyFeedDefs.Interaction) => void
}

const stateContext = React.createContext<StateContext>({
  enabled: false,
  onItemSeen: (_item: any) => {},
  sendInteraction: (_interaction: AppBskyFeedDefs.Interaction) => {},
})

export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) {
  const agent = useAgent()
  const enabled = isDiscoverFeed(feed) && hasSession
  const queue = React.useRef<Set<string>>(new Set())
  const history = React.useRef<
    // Use a WeakSet so that we don't need to clear it.
    // This assumes that referential identity of slice items maps 1:1 to feed (re)fetches.
    WeakSet<FeedPostSliceItem | AppBskyFeedDefs.Interaction>
  >(new WeakSet())

  const sendToFeedNoDelay = React.useCallback(() => {
    const proxyAgent = agent.withProxy(
      // @ts-ignore TODO need to update withProxy() to support this key -prf
      'bsky_fg',
      // TODO when we start sending to other feeds, we need to grab their DID -prf
      'did:web:discover.bsky.app',
    ) as BskyAgent

    const interactions = Array.from(queue.current).map(toInteraction)
    queue.current.clear()

    proxyAgent.app.bsky.feed
      .sendInteractions({interactions})
      .catch((e: any) => {
        logger.warn('Failed to send feed interactions', {error: e})
      })
  }, [agent])

  const sendToFeed = React.useMemo(
    () =>
      throttle(sendToFeedNoDelay, 15e3, {
        leading: false,
        trailing: true,
      }),
    [sendToFeedNoDelay],
  )

  React.useEffect(() => {
    if (!enabled) {
      return
    }
    const sub = AppState.addEventListener('change', (state: AppStateStatus) => {
      if (state === 'background') {
        sendToFeed.flush()
      }
    })
    return () => sub.remove()
  }, [enabled, sendToFeed])

  const onItemSeen = React.useCallback(
    (slice: any) => {
      if (!enabled) {
        return
      }
      if (!isFeedPostSlice(slice)) {
        return
      }
      for (const postItem of slice.items) {
        if (!history.current.has(postItem)) {
          history.current.add(postItem)
          queue.current.add(
            toString({
              item: postItem.uri,
              event: 'app.bsky.feed.defs#interactionSeen',
              feedContext: postItem.feedContext,
            }),
          )
          sendToFeed()
        }
      }
    },
    [enabled, sendToFeed],
  )

  const sendInteraction = React.useCallback(
    (interaction: AppBskyFeedDefs.Interaction) => {
      if (!enabled) {
        return
      }
      if (!history.current.has(interaction)) {
        history.current.add(interaction)
        queue.current.add(toString(interaction))
        sendToFeed()
      }
    },
    [enabled, sendToFeed],
  )

  return React.useMemo(() => {
    return {
      enabled,
      // pass this method to the <List> onItemSeen
      onItemSeen,
      // call on various events
      // queues the event to be sent with the throttled sendToFeed call
      sendInteraction,
    }
  }, [enabled, onItemSeen, sendInteraction])
}

export const FeedFeedbackProvider = stateContext.Provider

export function useFeedFeedbackContext() {
  return React.useContext(stateContext)
}

// TODO
// We will introduce a permissions framework for 3p feeds to
// take advantage of the feed feedback API. Until that's in
// place, we're hardcoding it to the discover feed.
// -prf
function isDiscoverFeed(feed: FeedDescriptor) {
  return feed === `feedgen|${PROD_DEFAULT_FEED('whats-hot')}`
}

function toString(interaction: AppBskyFeedDefs.Interaction): string {
  return `${interaction.item}|${interaction.event}|${
    interaction.feedContext || ''
  }`
}

function toInteraction(str: string): AppBskyFeedDefs.Interaction {
  const [item, event, feedContext] = str.split('|')
  return {item, event, feedContext}
}