feat(share): record and display share activity (#549)

* feat(share): record and display share activity

* style(share): remove activity entry borders

* docs(share): explain share link activity
This commit is contained in:
Yiling-J
2026-11-25 12:23:11 +08:00
committed by GitHub
parent 9c8eb16259
commit e32445684f
51 changed files with 3208 additions and 227 deletions
@@ -419,6 +419,8 @@ describe('BreadcrumbNav component', () => {
rootFolderId: 'rf-1',
projectId: 'proj-1',
isExpired: false,
views: 0,
lastViewedAt: null,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
},
+2 -4
View File
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import {
@@ -206,10 +207,7 @@ export function BreadcrumbNav({
if (!fileId) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId },
json: { key },
})
? await requestShareDownload(shareId, fileId, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: fileId },
})
@@ -1,6 +1,7 @@
'use client'
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import type { AssetInfo } from '@shumai/dtos'
import { toast } from 'sonner'
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
@@ -39,18 +40,7 @@ export function useCopyActions({
if (transcode?.url) return transcode.url
if (transcode?.key && item.id) {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
{
param: { shareId, fileId: item.id },
json: { key: transcode.key },
},
{
headers: {
'x-share-password': password,
},
},
)
const res = await requestShareDownload(shareId, item.id, transcode.key, 'clipboard')
if (res.ok) {
const { url } = await res.json()
return url
@@ -1,6 +1,7 @@
'use client'
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import type { AssetInfo } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
@@ -20,6 +21,18 @@ interface UseFileActionsProps {
shareId?: string
}
async function requestShareDownloadUrl(
shareId: string,
fileId: string,
key: string,
purpose: 'prepare' | 'download',
) {
const response = await requestShareDownload(shareId, fileId, key, purpose)
if (response.ok) return (await response.json()).url
}
type DownloadFile = { id: string; name: string; url: string; shareDownloadKey?: string }
export function useFileActions({
teamId,
projectId,
@@ -35,9 +48,7 @@ export function useFileActions({
const [itemsToDelete, setItemsToDelete] = useState<AssetInfo[]>([])
const [isDownloadDialogOpen, setIsDownloadDialogOpen] = useState(false)
const [isLoadingLinks, setIsLoadingLinks] = useState(false)
const [resolvedFiles, setResolvedFiles] = useState<
Array<{ id: string; name: string; url: string }>
>([])
const [resolvedFiles, setResolvedFiles] = useState<DownloadFile[]>([])
const [skippedArchivedCount, setSkippedArchivedCount] = useState(0)
const [archiveConfirmState, setArchiveConfirmState] = useState<{
open: boolean
@@ -257,8 +268,7 @@ export function useFileActions({
setSkippedArchivedCount(0)
try {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const links: Array<{ id: string; name: string; url: string }> = []
const links: DownloadFile[] = []
let skipped = 0
for (const item of items) {
if (
@@ -271,20 +281,9 @@ export function useFileActions({
}
const key = item.media?.original?.key
if (!key || !item.id) continue
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
{
param: { shareId, fileId: item.id },
json: { key },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.ok) {
const { url } = await res.json()
links.push({ id: item.id, name: item.name || 'download', url })
const url = await requestShareDownloadUrl(shareId, item.id, key, 'prepare')
if (url) {
links.push({ id: item.id, name: item.name || 'download', url, shareDownloadKey: key })
}
}
setSkippedArchivedCount(skipped)
@@ -407,9 +406,21 @@ export function useFileActions({
const runQueue = async () => {
const batchSize = 5
let failed = 0
for (let i = 0; i < files.length; i += batchSize) {
const chunk = files.slice(i, i + batchSize)
for (const file of chunk) {
const urls = await Promise.allSettled(
chunk.map((file) =>
shareId && file.shareDownloadKey
? requestShareDownloadUrl(shareId, file.id, file.shareDownloadKey, 'download')
: file.url,
),
)
for (const result of urls) {
if (result.status !== 'fulfilled' || !result.value) {
failed++
continue
}
// Use a hidden iframe instead of an anchor with target="_blank".
// Download URLs respond with Content-Disposition: attachment, so the
// browser starts the download in the background: no flash of a tab
@@ -417,7 +428,7 @@ export function useFileActions({
// the hidden iframe instead of navigating the SPA tab away.
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = file.url
iframe.src = result.value
document.body.appendChild(iframe)
// Remove the iframe once the download has had time to start.
window.setTimeout(() => iframe.remove(), 60_000)
@@ -426,7 +437,8 @@ export function useFileActions({
await delay(600)
}
}
toast.success('All downloads initiated successfully')
if (failed > 0) toast.error(m.share_download_start_failed())
else toast.success('All downloads initiated successfully')
}
runQueue().catch((err) => {
@@ -238,6 +238,8 @@ describe('MobileFileHeader', () => {
rootFolderId: 'rf-1',
projectId: 'proj-1',
isExpired: false,
views: 0,
lastViewedAt: null,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
},
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import { Badge } from '@/ui/components/ui/badge'
import { Button } from '@/ui/components/ui/button'
import {
@@ -113,10 +114,7 @@ export function MobileFileHeader({
try {
const res =
isPublic && shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: activeFileId },
json: { key },
})
? await requestShareDownload(shareId, activeFileId, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: activeFileId },
})
@@ -6,6 +6,7 @@ import { m } from '@/ui/paraglide/messages.js'
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
import { useEffect, useState, useMemo, useRef } from 'react'
import { useIsMobile } from '@/ui/hooks/use-mobile'
import { usePublicShareView } from '@/ui/hooks/use-public-share-view'
import { TopNav } from './top-nav'
import { FileBrowser } from './file-browser/file-browser'
import { MobileFileBrowser } from './file-browser/mobile-file-browser'
@@ -127,6 +128,7 @@ export function PublicShareManager({
},
)
if (res.status === 401) throw new Error('Unauthorized')
if (!res.ok) throw new Error('Failed to fetch shared asset')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!shareInfo && !!currentFolderId,
@@ -258,6 +260,7 @@ export function PublicShareManager({
},
)
if (res.status === 401) throw new Error('Unauthorized')
if (!res.ok) throw new Error('Failed to fetch shared asset')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!viewingFileId && !!shareInfo,
@@ -277,6 +280,7 @@ export function PublicShareManager({
},
)
if (res.status === 401) throw new Error('Unauthorized')
if (!res.ok) throw new Error('Failed to fetch shared asset')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!versionId && !!shareInfo,
@@ -286,6 +290,12 @@ export function PublicShareManager({
// or the stack itself) is what we actually display.
const viewingFileData = versionId ? versionFileData : stackFileData
const isViewingFileLoading = isStackFileLoading || (!!versionId && isVersionFileLoading)
usePublicShareView({
shareId,
assetId: activeFileId ?? initialFolderId,
password,
ready: !!shareInfo && (viewingFileId ? !!viewingFileData : !initialFolderId || !!folderInfo),
})
useEffect(() => {
if (foldersError?.message === 'Unauthorized') {
@@ -0,0 +1,123 @@
import type { ShareActivityKind } from '@shumai/dtos'
import { useInfiniteQuery } from '@tanstack/react-query'
import { isToday, isYesterday } from 'date-fns'
import { CircleUserRound } from 'lucide-react'
import { useEffect } from 'react'
import { useInView } from 'react-intersection-observer'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { getLocale } from '@/ui/paraglide/runtime.js'
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
import { Button } from './ui/button'
import { ScrollArea } from './ui/scroll-area'
function activityLabel(kind: ShareActivityKind) {
switch (kind) {
case 'share_viewed':
return m.share_activity_opened_share_link()
case 'asset_viewed':
return m.share_activity_viewed_asset()
case 'asset_downloaded':
return m.share_activity_downloaded()
case 'comment_created':
return m.share_activity_commented()
}
}
function formatDay(date: Date) {
if (isToday(date)) return m.today()
if (isYesterday(date)) return m.yesterday()
return date.toLocaleDateString(getLocale(), { dateStyle: 'medium' })
}
export function ShareActivityList({ shareId }: { shareId: string }) {
const query = useInfiniteQuery({
queryKey: ['share-activities', shareId],
queryFn: async ({ pageParam, signal }) => {
const response = await client.api.shares[':shareId'].activities.$get(
{ param: { shareId }, query: { first: '20', after: pageParam } },
{ init: { signal } },
)
if (!response.ok) throw new Error(m.share_activity_load_failed())
return response.json()
},
initialPageParam: '',
getNextPageParam: (page) => page.pageInfo.cursor || undefined,
})
const { ref, inView } = useInView()
const { fetchNextPage, hasNextPage, isFetching, isError } = query
useEffect(() => {
if (inView && hasNextPage && !isFetching && !isError) void fetchNextPage()
}, [fetchNextPage, hasNextPage, inView, isError, isFetching])
const events = new Map(
query.data?.pages.flatMap((page) => page.data.map((event) => [event.id, event] as const)),
)
const days = Map.groupBy(events.values(), (event) => new Date(event.createdAt).toDateString())
return (
<ScrollArea className="min-h-0 flex-1">
<div className="space-y-4 p-3">
{query.isPending && <p className="text-sm text-muted-foreground">{m.loading()}</p>}
{query.isSuccess && events.size === 0 && (
<p className="text-sm text-muted-foreground">{m.no_activity_yet()}</p>
)}
{[...days].map(([day, entries]) => (
<section key={day} className="space-y-2">
<h3 className="text-xs font-medium text-muted-foreground">
{formatDay(new Date(entries[0].createdAt))}
</h3>
<ul className="space-y-2">
{entries.map((event) => (
<li
key={event.id}
className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 px-2 py-2"
>
{event.user ? (
<Avatar className="size-8">
<AvatarImage src={event.user.image} alt="" />
<AvatarFallback>{event.user.name.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
) : (
<CircleUserRound aria-hidden="true" className="size-8 text-muted-foreground" />
)}
<div className="min-w-0">
<div className="truncate text-sm font-medium">
{event.user?.name || m.someone()}
</div>
<div className="flex items-baseline gap-x-2 text-xs text-muted-foreground">
{event.asset && (
<span className="min-w-0 truncate" title={event.asset.name ?? undefined}>
{event.asset.name ?? m.share_activity_deleted_asset()}
</span>
)}
<time dateTime={event.createdAt} className="shrink-0 whitespace-nowrap">
{new Date(event.createdAt).toLocaleTimeString(getLocale(), {
timeStyle: 'short',
})}
</time>
</div>
</div>
<span className="max-w-24 text-right text-xs">{activityLabel(event.kind)}</span>
</li>
))}
</ul>
</section>
))}
{query.isError && (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">{m.share_activity_load_failed()}</p>
<Button
size="sm"
variant="outline"
onClick={() => void (query.isFetchNextPageError ? fetchNextPage() : query.refetch())}
>
{m.retry()}
</Button>
</div>
)}
{hasNextPage && <div ref={ref}>{query.isFetchingNextPage && m.loading()}</div>}
</div>
</ScrollArea>
)
}
@@ -52,6 +52,8 @@ const sampleShare: ShareLinkInfo = {
rootFolderId: 'folder-share-1',
projectId: 'proj-1',
isExpired: false,
views: 0,
lastViewedAt: null,
watermarkConfigId: null,
watermarkStatus: 'disabled',
watermarkConfig: null,
+26 -7
View File
@@ -9,6 +9,8 @@ import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tansta
import { useEffect, useState, useMemo } from 'react'
import { FileBrowser } from './file-browser/file-browser'
import { ShareSettingsSidebar } from './share-settings-sidebar'
import { ShareActivityList } from './share-activity-list'
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs'
import { FolderTree } from './folder-tree'
import { ResizeHandle } from './resize-handle'
import { useFileSystemDnd } from './use-file-system-dnd'
@@ -354,13 +356,30 @@ export default function ShareManager({
}
/>
<div style={{ width: rightSidebarWidth }} className="flex-shrink-0 h-full">
<ShareSettingsSidebar
shareLink={shareLink}
viewMode={displayStyle}
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
defaultSortOrder={defaultSortOrder}
onSortOrderChange={(sortOrder) => updateShare({ defaultSortOrder: sortOrder })}
/>
<Tabs defaultValue="settings" className="flex h-full min-h-0 flex-col px-2 py-1">
<TabsList className="w-full shrink-0">
<TabsTrigger value="settings" className="flex-1">
{m.settings()}
</TabsTrigger>
<TabsTrigger value="activity" className="flex-1">
{m.activity()}
</TabsTrigger>
</TabsList>
<TabsContent value="settings" className="min-h-0 flex-1 overflow-hidden">
<ShareSettingsSidebar
shareLink={shareLink}
viewMode={displayStyle}
onViewModeChange={(mode) => updateShare({ viewMode: mode })}
defaultSortOrder={defaultSortOrder}
onSortOrderChange={(sortOrder) =>
updateShare({ defaultSortOrder: sortOrder })
}
/>
</TabsContent>
<TabsContent value="activity" className="flex min-h-0 flex-1 flex-col">
<ShareActivityList shareId={shareId} />
</TabsContent>
</Tabs>
</div>
</>
)}
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import { m } from '@/ui/paraglide/messages.js'
import { Download, AlertCircle } from 'lucide-react'
import React, { useImperativeHandle } from 'react'
@@ -18,10 +19,7 @@ export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
? await requestShareDownload(shareId, file.id, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { getBestTranscode } from '@/ui/lib/media'
@@ -118,10 +119,7 @@ export const CompareImagePane = forwardRef<ComparePaneHandle, CompareImagePanePr
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
? await requestShareDownload(shareId, file.id, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
@@ -1,5 +1,6 @@
import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import { getBestTranscode } from '@/ui/lib/media'
import { copyImageToClipboard } from '@/ui/lib/clipboard'
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react'
@@ -106,10 +107,7 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
? await requestShareDownload(shareId, file.id, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useImperativeHandle, useRef, useState }
import { AlertCircle, Loader2 } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { FileViewerProps, MediaController } from '../types'
@@ -65,10 +66,7 @@ export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
if (!key || !data.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: data.id },
json: { key },
})
? await requestShareDownload(shareId, data.id, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: data.id },
})
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { m } from '@/ui/paraglide/messages.js'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
@@ -383,10 +384,7 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
? await requestShareDownload(shareId, file.id, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { cn } from '@/ui/lib/utils'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
@@ -452,10 +453,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
if (!dlKey || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key: dlKey },
})
? await requestShareDownload(shareId, file.id, dlKey)
: await client.api.files['download-url'].$post({
json: { key: dlKey, assetId: file.id },
})
@@ -1,4 +1,5 @@
import { client } from '@/ui/api/client'
import { requestShareDownload } from '@/ui/api/share-download'
import { m } from '@/ui/paraglide/messages.js'
import { cn } from '@/ui/lib/utils'
import { Play, AudioLines, Loader2, AlertCircle } from 'lucide-react'
@@ -901,10 +902,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const handleDownload = async (key: string) => {
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: data.id! },
json: { key },
})
? await requestShareDownload(shareId, data.id!, key)
: await client.api.files['download-url'].$post({
json: { key, assetId: data.id! },
})