From 3e478cae961483b80ff2bdb24fbbdbfdece389b7 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Tue, 29 Sep 2026 12:23:30 -0400 Subject: [PATCH] feat(live): watch Streamplace streams and chat in-app (#202) * feat(live): parse stream.place links and build playback urls * feat(live): treat stream.place links as an external embed source * feat(live): reduce streamplace websocket events into chat and live state * feat(live): subscribe to a streamplace channel over its websocket * feat(live): send chat messages with delivery confirmation * feat(live): hydrate chat senders and apply viewer moderation * feat(live): add an hls live player for native and web * feat(live): add livestream chat list and composer * feat(live): add the in-app livestream watch screen * feat(live): open stream.place link cards in the watch screen * feat(live): watch streamplace streams in-app from live status * fix(live): send chat on return, keep failed rows legible, format files Single-line composer so return submits on native and web, full opacity for not-delivered rows, no media border on text-only stream.place cards, prettier across the feature. * fix(live): keep the watch screen in the center column with its own chat scroll Wrap the screen in Layout.Center with minimalShell and a viewport-height layout, like the DM screen. Chat uses a FlatList that scrolls on its own and sticks to the newest message, so the composer stays visible above the fold. Style the composer as an input and fall back to the websocket handle when the appview reports handle.invalid. * fix(live): retry live playback instead of declaring the stream offline Prefer hls.js over native HLS (Chrome now reports native support), retry fatal network errors every 2s, recover media errors, and only show the offline state after 10s of failed retries, clearing it once playback resumes. Native player retries on status errors the same way. * fix(live): treat web playback as live and drop played video from memory liveDurationInfinity removes the finite duration the native controls showed, and a 10s back buffer stops unbounded memory growth and limits seeking to the live window. * fix(live): address review findings on entry points, sending and playback Catch bad percent-escapes in stream.place links so a post can't crash rendering. Watch now works from the web hover card, opens the linked channel, and falls back to the browser when logged out or when Streamplace embeds are hidden; logged-out link cards keep opening stream.place. Resolve handles to a DID before connecting, disable the composer until then, only time out sends after the record exists, ignore duplicate retries, and confirm against moderated messages. Hide blurred senders, order chat by server indexedAt, cap hls media recovery, surface a failed hls chunk load, and pause playback when the screen loses focus. * fix(live): navigate to the watch screen with the caller's navigation LiveStatus renders inside a portaled dialog where useNavigation returns the root navigator, which has no push. Take an onPressWatch callback like onPressOpenProfile, so the dialog closes then pushes and the web hover card hides then pushes with their own stack navigation. * feat(live): gate the streamplace watch screen behind a feature flag streamplace:watch:enable (default off) controls every entry point: stream.place link cards keep their previous behaviour, Watch now opens the browser, the Streamplace row is hidden from external media settings, and /live/:actor shows an unavailable state with a link to stream.place. * fix(live): stop pausing the native player after it is released Leaving the watch screen blurs and unmounts it together; useVideoPlayer releases the native player on unmount, so the focus-effect cleanup's pause() hit a released shared object and threw. Pause and resume from useIsFocused instead, which never touches the player on unmount. --- bskyweb/cmd/bskyweb/server.go | 1 + src/Navigation.tsx | 6 + src/analytics/features/types.ts | 1 + src/analytics/metrics/types.ts | 2 + .../Post/Embed/ExternalEmbed/index.tsx | 27 +- src/components/ProfileHoverCard/index.web.tsx | 9 + .../liveNow/components/LiveStatusDialog.tsx | 31 ++- src/features/streamplace/ChatComposer.tsx | 77 ++++++ src/features/streamplace/ChatList.tsx | 121 ++++++++ src/features/streamplace/LiveOffline.tsx | 37 +++ src/features/streamplace/LivePlayer.tsx | 72 +++++ src/features/streamplace/LivePlayer.web.tsx | 118 ++++++++ .../streamplace/__tests__/live-state.test.ts | 117 ++++++++ .../streamplace/__tests__/pending.test.ts | 37 +++ .../streamplace/__tests__/url.test.ts | 40 +++ .../__tests__/useStreamplaceLive.test.ts | 49 ++++ .../streamplace/__tests__/visible.test.ts | 33 +++ src/features/streamplace/live-state.ts | 126 +++++++++ src/features/streamplace/pending.ts | 30 ++ src/features/streamplace/url.ts | 34 +++ src/features/streamplace/useChatProfiles.ts | 37 +++ src/features/streamplace/useSendChat.ts | 98 +++++++ .../streamplace/useStreamplaceLive.ts | 60 ++++ src/features/streamplace/visible.ts | 26 ++ src/lib/routes/types.ts | 1 + .../embed-player-streamplace.test.ts | 15 + src/lib/strings/embed-player.ts | 16 ++ src/routes.ts | 1 + .../Settings/ExternalMediaPreferences.tsx | 8 +- src/screens/StreamplaceWatch/index.tsx | 260 ++++++++++++++++++ src/state/persisted/schema.ts | 1 + 31 files changed, 1482 insertions(+), 9 deletions(-) create mode 100644 src/features/streamplace/ChatComposer.tsx create mode 100644 src/features/streamplace/ChatList.tsx create mode 100644 src/features/streamplace/LiveOffline.tsx create mode 100644 src/features/streamplace/LivePlayer.tsx create mode 100644 src/features/streamplace/LivePlayer.web.tsx create mode 100644 src/features/streamplace/__tests__/live-state.test.ts create mode 100644 src/features/streamplace/__tests__/pending.test.ts create mode 100644 src/features/streamplace/__tests__/url.test.ts create mode 100644 src/features/streamplace/__tests__/useStreamplaceLive.test.ts create mode 100644 src/features/streamplace/__tests__/visible.test.ts create mode 100644 src/features/streamplace/live-state.ts create mode 100644 src/features/streamplace/pending.ts create mode 100644 src/features/streamplace/url.ts create mode 100644 src/features/streamplace/useChatProfiles.ts create mode 100644 src/features/streamplace/useSendChat.ts create mode 100644 src/features/streamplace/useStreamplaceLive.ts create mode 100644 src/features/streamplace/visible.ts create mode 100644 src/lib/strings/__tests__/embed-player-streamplace.test.ts create mode 100644 src/screens/StreamplaceWatch/index.tsx diff --git a/bskyweb/cmd/bskyweb/server.go b/bskyweb/cmd/bskyweb/server.go index 70ee06c39..65d1d8241 100644 --- a/bskyweb/cmd/bskyweb/server.go +++ b/bskyweb/cmd/bskyweb/server.go @@ -423,6 +423,7 @@ func serve(cctx *cli.Context) error { // bookmarks e.GET("/saved", server.WebGenericNoindex) + e.GET("/live/:actor", server.WebGenericNoindex) // ipcc e.GET("/ipcc", server.WebIpCC) diff --git a/src/Navigation.tsx b/src/Navigation.tsx index 5bfbc7e8d..7d1066128 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -132,6 +132,7 @@ import { StarterPackScreenShort, } from '#/screens/StarterPack/StarterPackScreen' import {Wizard} from '#/screens/StarterPack/Wizard' +import {StreamplaceWatchScreen} from '#/screens/StreamplaceWatch' import TopicScreen from '#/screens/Topic' import {VideoFeed} from '#/screens/VideoFeed' import {type Theme, useTheme} from '#/alf' @@ -585,6 +586,11 @@ function commonScreens(Stack: typeof Flat, unreadCountLabel?: string) { requireAuth: true, }} /> + StreamplaceWatchScreen} + options={{title: title(msg`Live`), requireAuth: true}} + /> BookmarksScreen} diff --git a/src/analytics/features/types.ts b/src/analytics/features/types.ts index 58dce064b..d84cc8f0f 100644 --- a/src/analytics/features/types.ts +++ b/src/analytics/features/types.ts @@ -17,6 +17,7 @@ export enum Features { AppviewFallbackMode = 'appview_fallback:mode', AppviewFallbackThresholds = 'appview_fallback:thresholds', SearchAppviewRoute = 'search_appview:route', + StreamplaceWatchEnable = 'streamplace:watch:enable', AATest = 'aa-test', } diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 041ca6d5a..10d611d96 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -1149,6 +1149,8 @@ export type Events = { 'live:remove': {} 'live:card:open': {subject: string; from: 'post' | 'profile'} 'live:card:watch': {subject: string} + 'live:watch:open': {subject: string} + 'live:chat:send': {subject: string} 'live:card:openProfile': {subject: string} 'live:view:profile': {subject: string} 'live:view:post': {subject: string; feed?: string} diff --git a/src/components/Post/Embed/ExternalEmbed/index.tsx b/src/components/Post/Embed/ExternalEmbed/index.tsx index 4d7bd9f03..906eb5ad0 100644 --- a/src/components/Post/Embed/ExternalEmbed/index.tsx +++ b/src/components/Post/Embed/ExternalEmbed/index.tsx @@ -14,12 +14,15 @@ import { } from '#/lib/strings/embed-player' import {toNiceDomain} from '#/lib/strings/url-helpers' import {useExternalEmbedsPrefs} from '#/state/preferences' +import {useSession} from '#/state/session' import {atoms as a, useTheme} from '#/alf' import {Divider} from '#/components/Divider' import {Earth_Stroke2_Corner0_Rounded as Globe} from '#/components/icons/Globe' import {Link} from '#/components/Link' import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' import {IS_NATIVE} from '#/env' +import {parseStreamplaceActor} from '#/features/streamplace/url' import {AssemblyEmbed} from './AssemblyEmbed' import {ExternalGif} from './ExternalGif' import {ExternalPlayer} from './ExternalPlayer' @@ -39,18 +42,30 @@ export const ExternalEmbed = ({ const {_} = useLingui() const t = useTheme() const playHaptic = useHaptics() + const ax = useAnalytics() const externalEmbedPrefs = useExternalEmbedsPrefs() + const {hasSession} = useSession() const niceUrl = toNiceDomain(link.uri) const imageUri = link.thumb const embedPlayerParams = useMemo(() => { const params = parseEmbedPlayerFromUrl(link.uri) if (!params) return + if ( + params.source === 'streamplace' && + !ax.features.enabled(ax.features.StreamplaceWatchEnable) + ) { + return + } const canShow = externalEmbedPrefs?.[params.source] !== 'hide' if (canShow || exemptExternalEmbedSources.has(params.source)) { return params } - }, [link.uri, externalEmbedPrefs]) - const hasMedia = Boolean(imageUri || embedPlayerParams) + }, [link.uri, externalEmbedPrefs, ax]) + const streamplaceActor = + hasSession && embedPlayerParams?.type === 'streamplace_stream' + ? parseStreamplaceActor(link.uri) + : undefined + const hasMedia = Boolean(imageUri || (embedPlayerParams && !streamplaceActor)) const onPress = () => { playHaptic('Light') @@ -95,8 +110,8 @@ export const ExternalEmbed = ({ return ( - {imageUri && !embedPlayerParams ? ( + {imageUri && (!embedPlayerParams || streamplaceActor) ? ( - ) : embedPlayerParams ? ( + ) : embedPlayerParams && !streamplaceActor ? ( ) : undefined} diff --git a/src/components/ProfileHoverCard/index.web.tsx b/src/components/ProfileHoverCard/index.web.tsx index 46dade016..6471d8b29 100644 --- a/src/components/ProfileHoverCard/index.web.tsx +++ b/src/components/ProfileHoverCard/index.web.tsx @@ -372,6 +372,14 @@ let Card = ({ }) }, [hide, navigation, status, data]) + const onPressWatch = useCallback( + (actor: string) => { + hide() + navigation.push('StreamplaceWatch', {actor}) + }, + [hide, navigation], + ) + return ( ) : ( diff --git a/src/features/liveNow/components/LiveStatusDialog.tsx b/src/features/liveNow/components/LiveStatusDialog.tsx index 9e916678f..acec9387c 100644 --- a/src/features/liveNow/components/LiveStatusDialog.tsx +++ b/src/features/liveNow/components/LiveStatusDialog.tsx @@ -14,8 +14,10 @@ import {useOpenLink} from '#/lib/hooks/useOpenLink' import {type NavigationProp} from '#/lib/routes/types' import {sanitizeHandle} from '#/lib/strings/handles' import {toNiceDomain} from '#/lib/strings/url-helpers' +import {useExternalEmbedsPrefs} from '#/state/preferences' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {unstableCacheProfileView} from '#/state/queries/profile' +import {useSession} from '#/state/session' import {android, atoms as a, platform, tokens, useTheme, web} from '#/alf' import {Button, ButtonIcon, ButtonText} from '#/components/Button' import * as Dialog from '#/components/Dialog' @@ -30,6 +32,7 @@ import * as ProfileCard from '#/components/ProfileCard' import {Text} from '#/components/Typography' import {useAnalytics} from '#/analytics' import {LiveIndicator} from '#/features/liveNow/components/LiveIndicator' +import {parseStreamplaceActor} from '#/features/streamplace/url' import type * as bsky from '#/types/bsky' export function LiveStatusDialog({ @@ -79,6 +82,15 @@ function DialogInner({ }) }, [navigation, profile.handle, control]) + const onPressWatch = useCallback( + (actor: string) => { + control.close(() => { + navigation.push('StreamplaceWatch', {actor}) + }) + }, + [navigation, control], + ) + return ( @@ -101,12 +114,14 @@ export function LiveStatus({ embed, padding = 'xl', onPressOpenProfile, + onPressWatch, }: { status: AppBskyActorDefs.StatusView profile: bsky.profile.AnyProfileView embed: AppBskyEmbedExternal.View padding?: 'lg' | 'xl' onPressOpenProfile: () => void + onPressWatch: (actor: string) => void }) { const ax = useAnalytics() const {t: l} = useLingui() @@ -116,6 +131,14 @@ export function LiveStatus({ const moderationOpts = useModerationOpts() const reportDialogControl = useGlobalReportDialogControl() const dialogContext = Dialog.useDialogContext() + const {hasSession} = useSession() + const externalEmbedsPrefs = useExternalEmbedsPrefs() + const streamplaceActor = + hasSession && + externalEmbedsPrefs?.streamplace !== 'hide' && + ax.features.enabled(ax.features.StreamplaceWatchEnable) + ? parseStreamplaceActor(embed.external.uri) + : undefined const moderation = useMemo(() => { if (!moderationOpts) return undefined return moderateStatus(profile, moderationOpts) @@ -193,12 +216,16 @@ export function LiveStatus({ variant="solid" onPress={() => { ax.metric('live:card:watch', {subject: profile.did}) - openLink(embed.external.uri, false) + if (streamplaceActor) { + onPressWatch(streamplaceActor) + } else { + openLink(embed.external.uri, false) + } }}> Watch now - + {!streamplaceActor && } {moderationOpts && ( diff --git a/src/features/streamplace/ChatComposer.tsx b/src/features/streamplace/ChatComposer.tsx new file mode 100644 index 000000000..6a72c7947 --- /dev/null +++ b/src/features/streamplace/ChatComposer.tsx @@ -0,0 +1,77 @@ +import {useState} from 'react' +import {TextInput, View} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {countGraphemes} from 'unicode-segmenter/grapheme' + +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' + +const MAX_GRAPHEMES = 300 + +export function ChatComposer({ + onSend, + disabled: notReady, +}: { + onSend: (text: string) => void + disabled?: boolean +}) { + const {_} = useLingui() + const t = useTheme() + const [text, setText] = useState('') + const trimmed = text.trim() + const disabled = + notReady || trimmed.length === 0 || countGraphemes(text) > MAX_GRAPHEMES + + const submit = () => { + if (disabled) return + setText('') + onSend(trimmed) + } + + return ( + + + + + ) +} diff --git a/src/features/streamplace/ChatList.tsx b/src/features/streamplace/ChatList.tsx new file mode 100644 index 000000000..617a81e3f --- /dev/null +++ b/src/features/streamplace/ChatList.tsx @@ -0,0 +1,121 @@ +import {useRef} from 'react' +import {FlatList, Pressable, View} from 'react-native' +import { + type AppBskyActorDefs, + moderateProfile, + type ModerationOpts, +} from '@atproto/api' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {UserAvatar} from '#/view/com/util/UserAvatar' +import {atoms as a, useTheme} from '#/alf' +import {Text} from '#/components/Typography' +import {type ChatMessage} from './live-state' +import {type PendingMessage} from './pending' + +type VisibleMessage = { + message: ChatMessage + profile: AppBskyActorDefs.ProfileViewDetailed +} + +type ChatItem = + | {kind: 'message'; item: VisibleMessage} + | {kind: 'pending'; item: PendingMessage} + +export function ChatList({ + messages, + pending, + moderationOpts, + onRetry, +}: { + messages: VisibleMessage[] + pending: PendingMessage[] + moderationOpts: ModerationOpts + onRetry: (message: PendingMessage) => void +}) { + const {_} = useLingui() + const t = useTheme() + const data: ChatItem[] = [ + ...messages.map(item => ({kind: 'message' as const, item})), + ...pending.map(item => ({kind: 'pending' as const, item})), + ] + const listRef = useRef>(null) + const atBottom = useRef(true) + + return ( + { + const {contentOffset, contentSize, layoutMeasurement} = e.nativeEvent + atBottom.current = + contentOffset.y + layoutMeasurement.height >= contentSize.height - 40 + }} + onContentSizeChange={() => { + if (atBottom.current) listRef.current?.scrollToEnd({animated: false}) + }} + keyExtractor={(item: ChatItem) => + item.kind === 'message' + ? item.item.message.uri + : `pending:${item.item.localId}` + } + ListEmptyComponent={ + + No messages yet + + } + renderItem={({item}: {item: ChatItem}) => { + if (item.kind === 'pending') { + const failed = item.item.status === 'failed' + return ( + onRetry(item.item)} + style={[a.px_md, a.py_xs, !failed && {opacity: 0.5}]} + accessibilityRole={failed ? 'button' : undefined}> + + {failed + ? _(msg`Not delivered · Tap to retry`) + : _(msg`sending…`)} + + {item.item.text} + + ) + } + + const {message, profile} = item.item + const displayName = + profile.displayName || + (profile.handle === 'handle.invalid' + ? message.handle + : profile.handle) + const moderation = moderateProfile(profile, moderationOpts) + return ( + + + + {displayName} {message.text} + + + ) + }} + /> + ) +} diff --git a/src/features/streamplace/LiveOffline.tsx b/src/features/streamplace/LiveOffline.tsx new file mode 100644 index 000000000..b4222c6b5 --- /dev/null +++ b/src/features/streamplace/LiveOffline.tsx @@ -0,0 +1,37 @@ +import {View} from 'react-native' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' + +import {atoms as a} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import {Text} from '#/components/Typography' + +export function LiveOffline({onRetry}: {onRetry: () => void}) { + const {_} = useLingui() + return ( + + + This stream is offline + + + + ) +} diff --git a/src/features/streamplace/LivePlayer.tsx b/src/features/streamplace/LivePlayer.tsx new file mode 100644 index 000000000..523ba0a83 --- /dev/null +++ b/src/features/streamplace/LivePlayer.tsx @@ -0,0 +1,72 @@ +import {useEffect, useRef, useState} from 'react' +import {View} from 'react-native' +import {useVideoPlayer, VideoView} from 'expo-video' +import {useIsFocused} from '@react-navigation/native' + +import {atoms as a} from '#/alf' +import {LiveOffline} from './LiveOffline' +import {livePlaylistUrl} from './url' + +const RETRY_MS = 2000 +const OFFLINE_AFTER_MS = 10_000 + +export function LivePlayer({actor}: {actor: string}) { + const source = livePlaylistUrl(actor) + const player = useVideoPlayer(source, p => { + p.play() + }) + const failingSince = useRef(null) + const [offline, setOffline] = useState(false) + + const reload = () => { + failingSince.current = null + player.replace(source) + player.play() + } + + const isFocused = useIsFocused() + useEffect(() => { + if (isFocused) { + player.play() + } else { + player.pause() + } + }, [isFocused, player]) + + useEffect(() => { + let retry: ReturnType | undefined + const sub = player.addListener('statusChange', ({status}) => { + if (status === 'readyToPlay') { + failingSince.current = null + setOffline(false) + return + } + if (status !== 'error') return + if (failingSince.current === null) failingSince.current = Date.now() + setOffline(Date.now() - failingSince.current > OFFLINE_AFTER_MS) + clearTimeout(retry) + retry = setTimeout(() => { + player.replace(source) + player.play() + }, RETRY_MS) + }) + return () => { + sub.remove() + clearTimeout(retry) + } + }, [player, source]) + + return ( + + + {offline && } + + ) +} diff --git a/src/features/streamplace/LivePlayer.web.tsx b/src/features/streamplace/LivePlayer.web.tsx new file mode 100644 index 000000000..05fe05ec5 --- /dev/null +++ b/src/features/streamplace/LivePlayer.web.tsx @@ -0,0 +1,118 @@ +import {useCallback, useEffect, useRef, useState} from 'react' +import {View} from 'react-native' +import {useFocusEffect} from '@react-navigation/native' + +import {atoms as a} from '#/alf' +import {LiveOffline} from './LiveOffline' +import {livePlaylistUrl} from './url' + +const RETRY_MS = 2000 +const OFFLINE_AFTER_MS = 10_000 +const MAX_MEDIA_RECOVERIES = 2 + +export function LivePlayer({actor}: {actor: string}) { + const ref = useRef(null) + const [offline, setOffline] = useState(false) + const [attempt, setAttempt] = useState(0) + + useFocusEffect( + useCallback(() => { + const video = ref.current + if (video?.paused) void video.play().catch(() => undefined) + return () => video?.pause() + }, []), + ) + + useEffect(() => { + const video = ref.current + if (!video) return + const src = livePlaylistUrl(actor) + let disposed = false + let retry: ReturnType | undefined + let offlineTimer: ReturnType | undefined + let hls: {destroy: () => void} | undefined + let mediaRecoveries = 0 + setOffline(false) + + const onFailure = (reload: () => void) => { + if (!offlineTimer) { + offlineTimer = setTimeout(() => setOffline(true), OFFLINE_AFTER_MS) + } + clearTimeout(retry) + retry = setTimeout(() => { + if (!disposed) reload() + }, RETRY_MS) + } + const onPlaying = () => { + mediaRecoveries = 0 + clearTimeout(offlineTimer) + offlineTimer = undefined + setOffline(false) + } + video.addEventListener('playing', onPlaying) + + void import('hls.js') + .then(({default: Hls}) => { + if (disposed) return + if (Hls.isSupported()) { + const instance = new Hls({ + liveDurationInfinity: true, + backBufferLength: 10, + }) + instance.on(Hls.Events.ERROR, (_e, data) => { + if (!data.fatal) return + if ( + data.type === Hls.ErrorTypes.MEDIA_ERROR && + mediaRecoveries++ < MAX_MEDIA_RECOVERIES + ) { + instance.recoverMediaError() + return + } + onFailure(() => { + instance.loadSource(src) + instance.startLoad() + }) + }) + instance.attachMedia(video) + instance.loadSource(src) + hls = instance + } else { + const load = () => { + video.src = src + video.load() + void video.play().catch(() => undefined) + } + video.onerror = () => onFailure(load) + load() + } + }) + .catch(() => { + if (!disposed) setOffline(true) + }) + + return () => { + disposed = true + clearTimeout(retry) + clearTimeout(offlineTimer) + video.removeEventListener('playing', onPlaying) + video.onerror = null + hls?.destroy() + video.removeAttribute('src') + video.load() + } + }, [actor, attempt]) + + return ( + + + ) +} diff --git a/src/features/streamplace/__tests__/live-state.test.ts b/src/features/streamplace/__tests__/live-state.test.ts new file mode 100644 index 000000000..a239a8f02 --- /dev/null +++ b/src/features/streamplace/__tests__/live-state.test.ts @@ -0,0 +1,117 @@ +import { + EMPTY_LIVE_STATE, + isLiveAt, + type LiveState, + reduceLiveEvent, +} from '../live-state' + +const msg = (uri: string, did: string, text: string, createdAt: string) => ({ + $type: 'place.stream.chat.defs#messageView', + uri, + cid: 'bafy', + indexedAt: createdAt, + author: {did, handle: `${did}.test`}, + record: { + $type: 'place.stream.chat.message', + text, + createdAt, + streamer: 'did:plc:s', + }, +}) + +const apply = (events: unknown[], now = 1000): LiveState => + events.reduce( + (s, e) => reduceLiveEvent(s, e, now), + EMPTY_LIVE_STATE, + ) + +it('keeps messages oldest-first even when the burst arrives newest-first', () => { + const s = apply([ + msg('at://a/2', 'did:a', 'second', '2026-09-25T00:00:02Z'), + msg('at://a/1', 'did:a', 'first', '2026-09-25T00:00:01Z'), + ]) + expect(s.messages.map(m => m.text)).toEqual(['first', 'second']) +}) + +it('orders by server indexedAt, not the sender-controlled createdAt', () => { + const future = { + ...msg('at://a/1', 'did:a', 'spoofed', '2026-09-25T00:00:01Z'), + record: { + $type: 'place.stream.chat.message', + text: 'spoofed', + createdAt: '2099-01-01T00:00:00Z', + streamer: 'did:plc:s', + }, + } + const s = apply([ + future, + msg('at://a/2', 'did:a', 'later', '2026-09-25T00:00:02Z'), + ]) + expect(s.messages.map(m => m.text)).toEqual(['spoofed', 'later']) +}) + +it('dedupes by uri across reconnect bursts', () => { + const m = msg('at://a/1', 'did:a', 'hi', '2026-09-25T00:00:01Z') + expect(apply([m, m]).messages).toHaveLength(1) +}) + +it('removes deleted and gated messages', () => { + const m = msg('at://a/1', 'did:a', 'hi', '2026-09-25T00:00:01Z') + expect(apply([m, {...m, deleted: true}]).messages).toHaveLength(0) + expect( + apply([m, {$type: 'place.stream.chat.gate', hiddenMessage: 'at://a/1'}]) + .messages, + ).toHaveLength(0) +}) + +it('drops a blocked author, including later messages', () => { + const s = apply([ + msg('at://a/1', 'did:a', 'hi', '2026-09-25T00:00:01Z'), + {$type: 'place.stream.defs#blockView', record: {subject: 'did:a'}}, + msg('at://a/2', 'did:a', 'again', '2026-09-25T00:00:02Z'), + ]) + expect(s.messages).toHaveLength(0) +}) + +it('caps history at 200 messages', () => { + const events = Array.from({length: 250}, (_, i) => + msg(`at://a/${i}`, 'did:a', `m${i}`, new Date(i * 1000).toISOString()), + ) + const s = apply(events) + expect(s.messages).toHaveLength(200) + expect(s.messages[0].text).toBe('m50') +}) + +it('tracks livestream title, end, viewer count and liveness', () => { + const s = apply( + [ + { + $type: 'place.stream.livestream#livestreamView', + record: {title: 'Speedrun'}, + }, + {$type: 'place.stream.livestream#viewerCount', count: 12}, + {$type: 'place.stream.segment'}, + ], + 5000, + ) + expect(s.title).toBe('Speedrun') + expect(s.viewerCount).toBe(12) + expect(isLiveAt(s, 9000)).toBe(true) + expect(isLiveAt(s, 20000)).toBe(false) + const ended = reduceLiveEvent( + s, + { + $type: 'place.stream.livestream#livestreamView', + record: {title: 'Speedrun', endedAt: 'x'}, + }, + 5000, + ) + expect(isLiveAt(ended, 6000)).toBe(false) +}) + +it('returns the same state for unknown or malformed events', () => { + expect( + reduceLiveEvent(EMPTY_LIVE_STATE, {$type: 'place.stream.live.teleport'}, 0), + ).toBe(EMPTY_LIVE_STATE) + expect(reduceLiveEvent(EMPTY_LIVE_STATE, 'garbage', 0)).toBe(EMPTY_LIVE_STATE) +}) diff --git a/src/features/streamplace/__tests__/pending.test.ts b/src/features/streamplace/__tests__/pending.test.ts new file mode 100644 index 000000000..663fc02cf --- /dev/null +++ b/src/features/streamplace/__tests__/pending.test.ts @@ -0,0 +1,37 @@ +import {type PendingMessage, reconcilePending} from '../pending' + +const p = (over: Partial): PendingMessage => ({ + localId: '1', + text: 'hi', + sentAt: 0, + status: 'sending', + ...over, +}) + +it('drops pending messages once their uri shows up on the socket', () => { + expect( + reconcilePending( + [p({uri: 'at://me/1'})], + new Set(['at://me/1']), + 1000, + 10_000, + ), + ).toEqual([]) +}) + +it('marks sending messages failed after the timeout', () => { + expect( + reconcilePending([p({uri: 'at://me/1'})], new Set(), 10_001, 10_000)[0] + .status, + ).toBe('failed') +}) + +it('leaves recent sends alone', () => { + const list = [p({uri: 'at://me/1'})] + expect(reconcilePending(list, new Set(), 5000, 10_000)).toBe(list) +}) + +it('does not time out a send whose record has not been created yet', () => { + const list = [p({})] + expect(reconcilePending(list, new Set(), 60_000, 10_000)).toBe(list) +}) diff --git a/src/features/streamplace/__tests__/url.test.ts b/src/features/streamplace/__tests__/url.test.ts new file mode 100644 index 000000000..479ad63eb --- /dev/null +++ b/src/features/streamplace/__tests__/url.test.ts @@ -0,0 +1,40 @@ +import {livePlaylistUrl, liveSocketUrl, parseStreamplaceActor} from '../url' + +describe('parseStreamplaceActor', () => { + it.each([ + ['https://stream.place/alice.bsky.social', 'alice.bsky.social'], + ['https://stream.place/@Alice.Bsky.Social', 'alice.bsky.social'], + ['https://www.stream.place/alice.bsky.social/', 'alice.bsky.social'], + ['https://stream.place/embed/alice.bsky.social', 'alice.bsky.social'], + [ + 'https://stream.place/did:plc:7icioco6iksxt3nl2oxpkj2u', + 'did:plc:7icioco6iksxt3nl2oxpkj2u', + ], + ])('parses %s', (url, actor) => { + expect(parseStreamplaceActor(url)).toBe(actor) + }) + + it.each([ + 'https://stream.place/', + 'https://stream.place/about', + 'https://stream.place/docs', + 'https://stream.place/alice.bsky.social/video/3abc', + 'https://example.com/alice.bsky.social', + 'not a url', + 'https://stream.place/%', + 'https://stream.place/%E0%A4%A', + ])('rejects %s', url => { + expect(parseStreamplaceActor(url)).toBeUndefined() + }) +}) + +describe('urls', () => { + it('builds the playlist and socket urls', () => { + expect(livePlaylistUrl('did:plc:abc')).toBe( + 'https://stream.place/xrpc/place.stream.playback.getLivePlaylist?streamer=did:plc:abc', + ) + expect(liveSocketUrl('did:plc:abc')).toBe( + 'wss://stream.place/api/websocket/did:plc:abc', + ) + }) +}) diff --git a/src/features/streamplace/__tests__/useStreamplaceLive.test.ts b/src/features/streamplace/__tests__/useStreamplaceLive.test.ts new file mode 100644 index 000000000..27da871ac --- /dev/null +++ b/src/features/streamplace/__tests__/useStreamplaceLive.test.ts @@ -0,0 +1,49 @@ +import {act, renderHook} from '@testing-library/react-native' + +import {useStreamplaceLive} from '../useStreamplaceLive' + +class FakeSocket { + static instances: FakeSocket[] = [] + onopen?: () => void + onmessage?: (e: {data: string}) => void + onclose?: () => void + closed = false + constructor(public url: string) { + FakeSocket.instances.push(this) + } + close() { + this.closed = true + } +} + +beforeEach(() => { + FakeSocket.instances = [] + jest.useFakeTimers() + Object.assign(global, {WebSocket: FakeSocket}) +}) +afterEach(() => jest.useRealTimers()) + +it('connects by actor, applies frames, and reconnects after close', () => { + const {result, unmount} = renderHook(() => useStreamplaceLive('did:plc:s')) + const ws = FakeSocket.instances[0] + expect(ws.url).toBe('wss://stream.place/api/websocket/did:plc:s') + + act(() => { + ws.onmessage?.({ + data: JSON.stringify({ + $type: 'place.stream.livestream#viewerCount', + count: 7, + }), + }) + }) + expect(result.current.viewerCount).toBe(7) + + act(() => { + ws.onclose?.() + jest.advanceTimersByTime(1000) + }) + expect(FakeSocket.instances).toHaveLength(2) + + unmount() + expect(FakeSocket.instances[1].closed).toBe(true) +}) diff --git a/src/features/streamplace/__tests__/visible.test.ts b/src/features/streamplace/__tests__/visible.test.ts new file mode 100644 index 000000000..5d586dcd2 --- /dev/null +++ b/src/features/streamplace/__tests__/visible.test.ts @@ -0,0 +1,33 @@ +import {type ModerationOpts} from '@atproto/api' + +import {visibleMessages} from '../visible' + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + moderateProfile: (p: {did: string}) => ({ + ui: () => ({filter: p.did === 'did:muted', blur: p.did === 'did:warned'}), + }), +})) + +const m = (did: string) => ({ + uri: `at://${did}/1`, + authorDid: did, + handle: did, + text: 'x', + indexedAt: '', +}) +const profile = (did: string) => ({did, handle: did}) + +it('hides unknown, filtered and blurred authors', () => { + const profiles = new Map([ + ['did:ok', profile('did:ok')], + ['did:muted', profile('did:muted')], + ['did:warned', profile('did:warned')], + ]) + const out = visibleMessages( + [m('did:ok'), m('did:muted'), m('did:warned'), m('did:unknown')], + profiles, + {} as ModerationOpts, + ) + expect(out.map(x => x.message.authorDid)).toEqual(['did:ok']) +}) diff --git a/src/features/streamplace/live-state.ts b/src/features/streamplace/live-state.ts new file mode 100644 index 000000000..f370a95fa --- /dev/null +++ b/src/features/streamplace/live-state.ts @@ -0,0 +1,126 @@ +export type ChatMessage = { + uri: string + authorDid: string + handle: string + text: string + indexedAt: string +} + +export type LiveState = { + title?: string + endedAt?: string + viewerCount?: number + lastSegmentAt?: number + messages: ChatMessage[] + blockedDids: ReadonlySet +} + +export const EMPTY_LIVE_STATE: LiveState = { + messages: [], + blockedDids: new Set(), +} + +const MAX_MESSAGES = 200 +const SEGMENT_STALE_MS = 10_000 + +type Raw = Record + +function isRecord(value: unknown): value is Raw { + return typeof value === 'object' && value !== null +} + +export function reduceLiveEvent( + state: LiveState, + raw: unknown, + now: number, +): LiveState { + if (!raw || typeof raw !== 'object') return state + const e = raw as Raw + switch (e.$type) { + case 'place.stream.chat.defs#messageView': + return onMessage(state, e) + case 'place.stream.chat.gate': + return typeof e.hiddenMessage === 'string' + ? withMessages( + state, + state.messages.filter(m => m.uri !== e.hiddenMessage), + ) + : state + case 'place.stream.defs#blockView': { + const did = isRecord(e.record) ? e.record.subject : undefined + if (typeof did !== 'string') return state + const blockedDids = new Set(state.blockedDids).add(did) + return { + ...state, + blockedDids, + messages: state.messages.filter(m => m.authorDid !== did), + } + } + case 'place.stream.livestream#livestreamView': { + const record = isRecord(e.record) ? e.record : undefined + const viewerCount = isRecord(e.viewerCount) + ? e.viewerCount.count + : undefined + return { + ...state, + title: typeof record?.title === 'string' ? record.title : state.title, + endedAt: + typeof record?.endedAt === 'string' ? record.endedAt : undefined, + viewerCount: + typeof viewerCount === 'number' ? viewerCount : state.viewerCount, + } + } + case 'place.stream.livestream#viewerCount': + return typeof e.count === 'number' + ? {...state, viewerCount: e.count} + : state + case 'place.stream.segment': + return {...state, lastSegmentAt: now} + default: + return state + } +} + +export function isLiveAt(state: LiveState, now: number) { + return ( + !state.endedAt && + state.lastSegmentAt !== undefined && + now - state.lastSegmentAt < SEGMENT_STALE_MS + ) +} + +function onMessage(state: LiveState, e: Raw): LiveState { + if (typeof e.uri !== 'string') return state + if (e.deleted === true) { + return withMessages( + state, + state.messages.filter(m => m.uri !== e.uri), + ) + } + const author = isRecord(e.author) ? e.author : undefined + const record = isRecord(e.record) ? e.record : undefined + const authorDid = author?.did + const text = record?.text + const indexedAt = typeof e.indexedAt === 'string' ? e.indexedAt : '' + if (typeof authorDid !== 'string' || typeof text !== 'string') return state + if (state.blockedDids.has(authorDid)) return state + if (state.messages.some(m => m.uri === e.uri)) return state + const message: ChatMessage = { + uri: e.uri, + authorDid, + handle: typeof author?.handle === 'string' ? author.handle : authorDid, + text, + indexedAt, + } + const messages = [...state.messages, message].sort((x, y) => + x.indexedAt < y.indexedAt ? -1 : x.indexedAt > y.indexedAt ? 1 : 0, + ) + return withMessages(state, messages.slice(-MAX_MESSAGES)) +} + +function withMessages(state: LiveState, messages: ChatMessage[]): LiveState { + return messages.length === state.messages.length && + messages.every((m, i) => m === state.messages[i]) + ? state + : {...state, messages} +} diff --git a/src/features/streamplace/pending.ts b/src/features/streamplace/pending.ts new file mode 100644 index 000000000..a1e082e27 --- /dev/null +++ b/src/features/streamplace/pending.ts @@ -0,0 +1,30 @@ +export type PendingMessage = { + localId: string + text: string + sentAt: number + uri?: string + status: 'sending' | 'failed' +} + +export function reconcilePending( + pending: PendingMessage[], + seenUris: ReadonlySet, + now: number, + timeoutMs: number, +): PendingMessage[] { + let changed = false + const next: PendingMessage[] = [] + for (const m of pending) { + if (m.uri && seenUris.has(m.uri)) { + changed = true + continue + } + if (m.status === 'sending' && m.uri && now - m.sentAt > timeoutMs) { + changed = true + next.push({...m, status: 'failed'}) + continue + } + next.push(m) + } + return changed ? next : pending +} diff --git a/src/features/streamplace/url.ts b/src/features/streamplace/url.ts new file mode 100644 index 000000000..28154f6e1 --- /dev/null +++ b/src/features/streamplace/url.ts @@ -0,0 +1,34 @@ +export const STREAMPLACE_ORIGIN = 'https://stream.place' + +const HOSTS = new Set(['stream.place', 'www.stream.place']) +const ACTOR_RE = + /^(did:[a-z]+:[a-zA-Z0-9._:-]+|[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+)$/ + +export function parseStreamplaceActor(url: string): string | undefined { + let urlp: URL + try { + urlp = new URL(url) + } catch { + return undefined + } + if (!HOSTS.has(urlp.hostname)) return undefined + const parts = urlp.pathname.split('/').filter(Boolean) + if (parts[0] === 'embed') parts.shift() + if (parts.length !== 1) return undefined + let actor: string + try { + actor = decodeURIComponent(parts[0]).replace(/^@/, '') + } catch { + return undefined + } + if (!ACTOR_RE.test(actor)) return undefined + return actor.startsWith('did:') ? actor : actor.toLowerCase() +} + +export function livePlaylistUrl(actor: string) { + return `${STREAMPLACE_ORIGIN}/xrpc/place.stream.playback.getLivePlaylist?streamer=${actor}` +} + +export function liveSocketUrl(actor: string) { + return `wss://stream.place/api/websocket/${actor}` +} diff --git a/src/features/streamplace/useChatProfiles.ts b/src/features/streamplace/useChatProfiles.ts new file mode 100644 index 000000000..97c6dd03c --- /dev/null +++ b/src/features/streamplace/useChatProfiles.ts @@ -0,0 +1,37 @@ +import {useEffect, useRef, useState} from 'react' +import {type AppBskyActorDefs} from '@atproto/api' + +import {useAgent} from '#/state/session' + +const BATCH = 25 + +export function useChatProfiles(dids: string[]) { + const agent = useAgent() + const requested = useRef(new Set()) + const [profiles, setProfiles] = useState< + ReadonlyMap + >(new Map()) + + useEffect(() => { + const missing = [...new Set(dids)].filter(d => !requested.current.has(d)) + if (!missing.length) return + missing.forEach(d => requested.current.add(d)) + void (async () => { + for (let i = 0; i < missing.length; i += BATCH) { + const chunk = missing.slice(i, i + BATCH) + try { + const res = await agent.getProfiles({actors: chunk}) + setProfiles(prev => { + const next = new Map(prev) + for (const p of res.data.profiles) next.set(p.did, p) + return next + }) + } catch { + chunk.forEach(d => requested.current.delete(d)) + } + } + })() + }, [dids, agent]) + + return profiles +} diff --git a/src/features/streamplace/useSendChat.ts b/src/features/streamplace/useSendChat.ts new file mode 100644 index 000000000..09f416c21 --- /dev/null +++ b/src/features/streamplace/useSendChat.ts @@ -0,0 +1,98 @@ +import {useCallback, useEffect, useMemo, useRef, useState} from 'react' + +import {logger} from '#/logger' +import {useAgent} from '#/state/session' +import {type ChatMessage} from './live-state' +import {type PendingMessage, reconcilePending} from './pending' + +const COLLECTION = 'place.stream.chat.message' +export const CHAT_DELIVERY_TIMEOUT_MS = 10_000 + +export function useSendChat( + streamerDid: string | undefined, + messages: ChatMessage[], +) { + const agent = useAgent() + const [pending, setPending] = useState([]) + const retrying = useRef(new Set()) + const seenUris = useMemo(() => new Set(messages.map(m => m.uri)), [messages]) + + useEffect(() => { + const initial = setTimeout( + () => + setPending(prev => + reconcilePending( + prev, + seenUris, + Date.now(), + CHAT_DELIVERY_TIMEOUT_MS, + ), + ), + 0, + ) + const id = setInterval( + () => + setPending(prev => + reconcilePending( + prev, + seenUris, + Date.now(), + CHAT_DELIVERY_TIMEOUT_MS, + ), + ), + 2000, + ) + return () => { + clearTimeout(initial) + clearInterval(id) + } + }, [seenUris]) + + const send = useCallback( + async (text: string, replacing?: PendingMessage) => { + if (!streamerDid || !agent.session) return + if (replacing) { + if (retrying.current.has(replacing.localId)) return + retrying.current.add(replacing.localId) + } + const localId = `${Date.now()}-${Math.random()}` + setPending(prev => [ + ...prev.filter(m => m.localId !== replacing?.localId), + {localId, text, sentAt: Date.now(), status: 'sending'}, + ]) + try { + if (replacing?.uri) { + const rkey = replacing.uri.split('/').pop()! + await agent.com.atproto.repo + .deleteRecord({repo: agent.assertDid, collection: COLLECTION, rkey}) + .catch(() => undefined) + } + const res = await agent.com.atproto.repo.createRecord({ + repo: agent.assertDid, + collection: COLLECTION, + record: { + $type: COLLECTION, + text, + streamer: streamerDid, + createdAt: new Date().toISOString(), + }, + }) + setPending(prev => + prev.map(m => + m.localId === localId + ? {...m, uri: res.data.uri, sentAt: Date.now()} + : m, + ), + ) + } catch (err) { + logger.warn('streamplace: chat send failed', {safeMessage: err}) + setPending(prev => + prev.map(m => (m.localId === localId ? {...m, status: 'failed'} : m)), + ) + } + }, + [agent, streamerDid], + ) + + return {pending, send} +} diff --git a/src/features/streamplace/useStreamplaceLive.ts b/src/features/streamplace/useStreamplaceLive.ts new file mode 100644 index 000000000..3743e9f54 --- /dev/null +++ b/src/features/streamplace/useStreamplaceLive.ts @@ -0,0 +1,60 @@ +import {useEffect, useReducer, useState} from 'react' + +import {logger} from '#/logger' +import { + EMPTY_LIVE_STATE, + isLiveAt, + type LiveState, + reduceLiveEvent, +} from './live-state' +import {liveSocketUrl} from './url' + +type Action = {raw: unknown; now: number} + +const reducer = (s: LiveState, a: Action) => reduceLiveEvent(s, a.raw, a.now) + +export function useStreamplaceLive(actor: string | undefined) { + const [state, dispatch] = useReducer(reducer, EMPTY_LIVE_STATE) + const [now, setNow] = useState(() => Date.now()) + + useEffect(() => { + if (!actor) return + let ws: WebSocket | undefined + let retry: ReturnType | undefined + let attempt = 0 + let disposed = false + + const connect = () => { + ws = new WebSocket(liveSocketUrl(actor)) + ws.onopen = () => { + attempt = 0 + } + ws.onmessage = e => { + try { + dispatch({raw: JSON.parse(String(e.data)), now: Date.now()}) + } catch (err) { + logger.warn('streamplace: unparseable websocket frame', { + safeMessage: err, + }) + } + } + ws.onclose = () => { + if (disposed) return + retry = setTimeout(connect, Math.min(1000 * 2 ** attempt++, 10_000)) + } + } + connect() + return () => { + disposed = true + clearTimeout(retry) + ws?.close() + } + }, [actor]) + + useEffect(() => { + const id = setInterval(() => setNow(Date.now()), 5000) + return () => clearInterval(id) + }, []) + + return {...state, isLive: isLiveAt(state, now)} +} diff --git a/src/features/streamplace/visible.ts b/src/features/streamplace/visible.ts new file mode 100644 index 000000000..7a38ab294 --- /dev/null +++ b/src/features/streamplace/visible.ts @@ -0,0 +1,26 @@ +import { + type AppBskyActorDefs, + moderateProfile, + type ModerationOpts, +} from '@atproto/api' + +import {type ChatMessage} from './live-state' + +export function visibleMessages( + messages: ChatMessage[], + profiles: ReadonlyMap, + moderationOpts: ModerationOpts, +) { + const out: { + message: ChatMessage + profile: AppBskyActorDefs.ProfileViewDetailed + }[] = [] + for (const message of messages) { + const profile = profiles.get(message.authorDid) + if (!profile) continue + const ui = moderateProfile(profile, moderationOpts).ui('contentList') + if (ui.filter || ui.blur) continue + out.push({message, profile}) + } + return out +} diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index a22e33c70..3c57c0f9e 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -91,6 +91,7 @@ export type CommonNavigatorParams = { } StarterPackEdit: {rkey?: string} VideoFeed: VideoFeedSourceContext + StreamplaceWatch: {actor: string} Bookmarks: undefined FindContactsFlow: undefined } diff --git a/src/lib/strings/__tests__/embed-player-streamplace.test.ts b/src/lib/strings/__tests__/embed-player-streamplace.test.ts new file mode 100644 index 000000000..2cd6907e8 --- /dev/null +++ b/src/lib/strings/__tests__/embed-player-streamplace.test.ts @@ -0,0 +1,15 @@ +import {parseEmbedPlayerFromUrl} from '../embed-player' + +it('recognises stream.place channel links', () => { + expect( + parseEmbedPlayerFromUrl('https://stream.place/alice.bsky.social'), + ).toEqual({ + type: 'streamplace_stream', + source: 'streamplace', + playerUri: 'https://stream.place/embed/alice.bsky.social', + }) +}) + +it('ignores stream.place site pages', () => { + expect(parseEmbedPlayerFromUrl('https://stream.place/about')).toBeUndefined() +}) diff --git a/src/lib/strings/embed-player.ts b/src/lib/strings/embed-player.ts index ad8f585ef..53122cc02 100644 --- a/src/lib/strings/embed-player.ts +++ b/src/lib/strings/embed-player.ts @@ -1,6 +1,10 @@ import {Dimensions} from 'react-native' import {IS_WEB} from '#/env' +import { + parseStreamplaceActor, + STREAMPLACE_ORIGIN, +} from '#/features/streamplace/url' const {height: SCREEN_HEIGHT} = Dimensions.get('window') @@ -27,6 +31,7 @@ export const embedPlayerSources = [ 'flickr', 'assembly', 'bandcamp', + 'streamplace', ] as const export type EmbedPlayerSource = (typeof embedPlayerSources)[number] @@ -51,6 +56,7 @@ export type EmbedPlayerType = | 'assembly_conversation' | 'bandcamp_album' | 'bandcamp_track' + | 'streamplace_stream' export const externalEmbedLabels: Record = { youtube: 'YouTube', @@ -66,6 +72,7 @@ export const externalEmbedLabels: Record = { flickr: 'Flickr', assembly: "Blacksky People's Assembly", bandcamp: 'Bandcamp', + streamplace: 'Streamplace', } /** @@ -520,6 +527,15 @@ export function parseEmbedPlayerFromUrl( } } + const streamplaceActor = parseStreamplaceActor(url) + if (streamplaceActor) { + return { + type: 'streamplace_stream', + source: 'streamplace', + playerUri: `${STREAMPLACE_ORIGIN}/embed/${streamplaceActor}`, + } + } + const bandcampRegex = /^[a-z\d][a-z\d-]{2,}[a-z\d]\.bandcamp\.com$/i if (bandcampRegex.test(urlp.hostname)) { diff --git a/src/routes.ts b/src/routes.ts index 7a5912bee..d218fc06d 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -87,6 +87,7 @@ export const router = new Router({ StarterPackShort: '/starter-pack-short/:code', StarterPackWizard: '/starter-pack/create', VideoFeed: '/video-feed', + StreamplaceWatch: '/live/:actor', Bookmarks: '/saved', FindContactsFlow: '/find-contacts', }) diff --git a/src/screens/Settings/ExternalMediaPreferences.tsx b/src/screens/Settings/ExternalMediaPreferences.tsx index 98ce067fa..e0fde0e6b 100644 --- a/src/screens/Settings/ExternalMediaPreferences.tsx +++ b/src/screens/Settings/ExternalMediaPreferences.tsx @@ -19,6 +19,7 @@ import {atoms as a, native} from '#/alf' import {Admonition} from '#/components/Admonition' import * as Toggle from '#/components/forms/Toggle' import * as Layout from '#/components/Layout' +import {useAnalytics} from '#/analytics' import * as SettingsList from './components/SettingsList' type Props = NativeStackScreenProps< @@ -26,6 +27,10 @@ type Props = NativeStackScreenProps< 'PreferencesExternalEmbeds' > export function ExternalMediaPreferencesScreen({}: Props) { + const ax = useAnalytics() + const streamplaceEnabled = ax.features.enabled( + ax.features.StreamplaceWatchEnable, + ) return ( @@ -57,7 +62,8 @@ export function ExternalMediaPreferencesScreen({}: Props) { {Object.entries(externalEmbedLabels) .filter( ([key]) => - !exemptExternalEmbedSources.has(key as EmbedPlayerSource), + !exemptExternalEmbedSources.has(key as EmbedPlayerSource) && + (key !== 'streamplace' || streamplaceEnabled), ) .map(([key, label]) => ( diff --git a/src/screens/StreamplaceWatch/index.tsx b/src/screens/StreamplaceWatch/index.tsx new file mode 100644 index 000000000..c7e5eee61 --- /dev/null +++ b/src/screens/StreamplaceWatch/index.tsx @@ -0,0 +1,260 @@ +import {useEffect, useMemo} from 'react' +import {Pressable, View} from 'react-native' +import {KeyboardAvoidingView} from 'react-native-keyboard-controller' +import {moderateProfile} from '@atproto/api' +import {msg} from '@lingui/core/macro' +import {useLingui} from '@lingui/react' +import {Trans} from '@lingui/react/macro' +import {useNavigation} from '@react-navigation/native' + +import {useOpenLink} from '#/lib/hooks/useOpenLink' +import { + type CommonNavigatorParams, + type NativeStackScreenProps, + type NavigationProp, +} from '#/lib/routes/types' +import {useExternalEmbedsPrefs} from '#/state/preferences' +import {useModerationOpts} from '#/state/preferences/moderation-opts' +import {useProfileQuery} from '#/state/queries/profile' +import {UserAvatar} from '#/view/com/util/UserAvatar' +import {atoms as a, useTheme, web} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import {EmbedConsentDialog} from '#/components/dialogs/EmbedConsent' +import * as Layout from '#/components/Layout' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' +import {ChatComposer} from '#/features/streamplace/ChatComposer' +import {ChatList} from '#/features/streamplace/ChatList' +import {LivePlayer} from '#/features/streamplace/LivePlayer' +import {STREAMPLACE_ORIGIN} from '#/features/streamplace/url' +import {useChatProfiles} from '#/features/streamplace/useChatProfiles' +import {useSendChat} from '#/features/streamplace/useSendChat' +import {useStreamplaceLive} from '#/features/streamplace/useStreamplaceLive' +import {visibleMessages} from '#/features/streamplace/visible' + +type Props = NativeStackScreenProps + +export function StreamplaceWatchScreen({route}: Props) { + const {actor} = route.params + const ax = useAnalytics() + const prefs = useExternalEmbedsPrefs() + const pref = prefs?.streamplace + const enabled = ax.features.enabled(ax.features.StreamplaceWatchEnable) + + return ( + + + + + + Live + + + + + {!enabled ? ( + + ) : pref === 'show' ? ( + + ) : ( + + ) +} + +function Unavailable({actor}: {actor: string}) { + const {_} = useLingui() + const openLink = useOpenLink() + + return ( + + + Watching livestreams in Blacksky isn't available yet. + + + + ) +} + +function ConsentGate({hidden}: {hidden: boolean}) { + const {_} = useLingui() + const control = Dialog.useDialogControl() + + return ( + + undefined} + /> + + {hidden ? ( + + Streamplace media is turned off. Turn it on in Settings → Content + and media → External media. + + ) : ( + Watch Streamplace media inside Blacksky. + )} + + {!hidden && ( + + )} + + ) +} + +function Watch({actor}: {actor: string}) { + const t = useTheme() + const ax = useAnalytics() + const navigation = useNavigation() + const {data: profile} = useProfileQuery({did: actor}) + const did = actor.startsWith('did:') ? actor : profile?.did + const live = useStreamplaceLive(did) + const profiles = useChatProfiles( + live.messages.map(message => message.authorDid), + ) + const moderationOpts = useModerationOpts() + const visible = useMemo( + () => + moderationOpts + ? visibleMessages(live.messages, profiles, moderationOpts) + : [], + [live.messages, moderationOpts, profiles], + ) + const visibleChat = useMemo(() => visible.map(v => v.message), [visible]) + const {pending, send} = useSendChat(did, visibleChat) + + useEffect(() => { + ax.metric('live:watch:open', {subject: actor}) + }, [actor, ax]) + + const onSend = (text: string) => { + ax.metric('live:chat:send', {subject: actor}) + void send(text) + } + + const chat = moderationOpts ? ( + <> + void send(message.text, message)} + /> + + + ) : null + + return ( + + {did ? ( + + ) : ( + + )} + { + navigation.push('Profile', {name: profile?.did ?? actor}) + }} + /> + + Live chat + + + {chat} + + + ) +} + +function ProfileInfo({ + actor, + profile, + live, + onPress, +}: { + actor: string + profile: ReturnType['data'] + live: ReturnType + onPress: () => void +}) { + const {_} = useLingui() + const t = useTheme() + const moderationOpts = useModerationOpts() + const moderation = + profile && moderationOpts + ? moderateProfile(profile, moderationOpts) + : undefined + const viewerText = + live.viewerCount === undefined + ? undefined + : _(msg`${live.viewerCount} watching`) + + return ( + + {profile && ( + + )} + + {profile?.displayName || profile?.handle || actor} + {live.title && ( + {live.title} + )} + + {live.isLive && ( + + LIVE + + )} + {viewerText && ( + {viewerText} + )} + + ) +} diff --git a/src/state/persisted/schema.ts b/src/state/persisted/schema.ts index fef41cb96..be0c4d21b 100644 --- a/src/state/persisted/schema.ts +++ b/src/state/persisted/schema.ts @@ -118,6 +118,7 @@ const schema = z.object({ flickr: z.enum(externalEmbedOptions).optional(), assembly: z.enum(externalEmbedOptions).optional(), bandcamp: z.enum(externalEmbedOptions).optional(), + streamplace: z.enum(externalEmbedOptions).optional(), }) .optional(), invites: z.object({ -- knotmirror 0.0.1