mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 12:24:39 +00:00
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:
@@ -61,6 +61,7 @@ import { dedupeSymlinksToTarget } from './symlink'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { shareActivityService } from '@shumai/core/src/share/share-activity'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
@@ -1964,7 +1965,7 @@ export class AssetService {
|
||||
*/
|
||||
async createComment(
|
||||
req: CreateCommentRequest,
|
||||
options: { triggerAgents?: boolean } = {},
|
||||
options: { triggerAgents?: boolean; shareLinkId?: string } = {},
|
||||
): Promise<CommentInfo> {
|
||||
const triggerAgents = options.triggerAgents ?? true
|
||||
let commentId = ''
|
||||
@@ -2020,6 +2021,14 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
if (options.shareLinkId) {
|
||||
await shareActivityService.recordEvent(
|
||||
options.shareLinkId,
|
||||
{ kind: 'comment_created', assetId: a.id, userId: req.userId },
|
||||
tx,
|
||||
)
|
||||
}
|
||||
|
||||
if (!triggerAgents) return
|
||||
|
||||
// Parse bot mentions
|
||||
@@ -3080,6 +3089,10 @@ export class AssetService {
|
||||
* that belong to an asset they have access to.
|
||||
*/
|
||||
async getDownloadUrl(assetId: string, key: string): Promise<string> {
|
||||
return (await this.getDownloadUrlWithAsset(assetId, key)).url
|
||||
}
|
||||
|
||||
async getDownloadUrlWithAsset(assetId: string, key: string) {
|
||||
const targetAssetId = await this.resolveLatestVersionId(assetId)
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: targetAssetId },
|
||||
@@ -3100,6 +3113,7 @@ export class AssetService {
|
||||
throw new Error('Key does not belong to this asset')
|
||||
}
|
||||
|
||||
let signedAssetId = asset.id
|
||||
let storageKey = asset.storageKey.key
|
||||
let assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
let targetName = asset.name
|
||||
@@ -3115,12 +3129,14 @@ export class AssetService {
|
||||
storageKey: { key: { startsWith: key.substring(0, key.lastIndexOf('/') + 1) } },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
status: true,
|
||||
storageKey: { select: { key: true, isArchived: true } },
|
||||
},
|
||||
})
|
||||
if (sibling?.storageKey?.key) {
|
||||
signedAssetId = sibling.id
|
||||
storageKey = sibling.storageKey.key
|
||||
assetDir = storageKey.substring(0, storageKey.lastIndexOf('/') + 1)
|
||||
targetStatus = sibling.status
|
||||
@@ -3176,7 +3192,14 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
return s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'GET', true, downloadFilename)
|
||||
const url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
key,
|
||||
'GET',
|
||||
true,
|
||||
downloadFilename,
|
||||
)
|
||||
return { url, assetId: signedAssetId }
|
||||
}
|
||||
|
||||
async archiveAssets(
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { shareActivityService } from './share-activity'
|
||||
import { shareService } from './share'
|
||||
|
||||
describe('Share activity', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let shareId: string
|
||||
let projectId: string
|
||||
let assetId: string
|
||||
let userId: string
|
||||
|
||||
beforeEach(async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Reviewer',
|
||||
email: 'reviewer@example.com',
|
||||
image: 'https://example.com/avatar',
|
||||
},
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Team' } })
|
||||
const project = await prisma.project.create({ data: { name: 'Project', teamId: team.id } })
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'Review Cut', projectId: project.id, type: 'file', status: 'processed' },
|
||||
})
|
||||
const share = await shareService.createShareLink(project.id, { name: 'Review' }, user.id)
|
||||
shareId = share.id
|
||||
projectId = project.id
|
||||
assetId = asset.id
|
||||
userId = user.id
|
||||
})
|
||||
|
||||
it('sets the last view and counts every visit, including a duplicate deep-link visit', async () => {
|
||||
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 0, lastViewedAt: null })
|
||||
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||
const first = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||
expect(first).toMatchObject({ views: 1, lastViewedAt: expect.any(Date) })
|
||||
|
||||
const prior = new Date('2020-01-01T00:00:00Z')
|
||||
await prisma.shareLink.update({ where: { id: shareId }, data: { lastViewedAt: prior } })
|
||||
await shareActivityService.recordView(shareId, { assetId, isShareEntry: true })
|
||||
|
||||
const share = await prisma.shareLink.findUniqueOrThrow({ where: { id: shareId } })
|
||||
expect(share.views).toBe(2)
|
||||
expect(share.lastViewedAt!.getTime()).toBeGreaterThan(prior.getTime())
|
||||
expect(await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'share_viewed', userId: null, assetId: null }),
|
||||
expect.objectContaining({ kind: 'asset_viewed', userId: null, assetId }),
|
||||
]),
|
||||
)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||
})
|
||||
|
||||
it('uses a rolling window from the last recorded event and permits a match after 30 minutes', async () => {
|
||||
const event = { kind: 'asset_downloaded', userId, assetId } as const
|
||||
const record = await prisma.shareActivity.create({
|
||||
data: {
|
||||
...event,
|
||||
shareLinkId: shareId,
|
||||
createdAt: new Date(Date.now() - 29 * 60_000),
|
||||
},
|
||||
})
|
||||
await shareActivityService.recordEvent(shareId, event)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(1)
|
||||
expect(await prisma.shareActivity.findUnique({ where: { id: record.id } })).toEqual(record)
|
||||
|
||||
await prisma.shareActivity.update({
|
||||
where: { id: record.id },
|
||||
data: { createdAt: new Date(Date.now() - 30 * 60_000) },
|
||||
})
|
||||
await shareActivityService.recordEvent(shareId, event)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(2)
|
||||
})
|
||||
|
||||
it('scopes the deduplication identity to the share, event kind, user and asset', async () => {
|
||||
const otherShare = await shareService.createShareLink(projectId, { name: 'Other' })
|
||||
const otherAsset = await prisma.asset.create({
|
||||
data: { name: 'Other Cut', projectId, type: 'file', status: 'processed' },
|
||||
})
|
||||
await shareActivityService.recordView(shareId, { assetId })
|
||||
await shareActivityService.recordView(shareId, { assetId, userId })
|
||||
await shareActivityService.recordView(shareId, { assetId: otherAsset.id, userId })
|
||||
await shareActivityService.recordView(otherShare.id, { assetId, userId })
|
||||
await shareActivityService.recordEvent(shareId, { kind: 'asset_downloaded', assetId, userId })
|
||||
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(4)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: otherShare.id } })).toBe(1)
|
||||
expect(await shareService.getShareLink(shareId)).toMatchObject({ views: 3 })
|
||||
})
|
||||
|
||||
it('records a share comment in its transaction while preserving every comment', async () => {
|
||||
const comment = { assetId, userId, message: 'Looks good', attachmentIds: [] }
|
||||
await assetService.createComment(comment, { shareLinkId: shareId })
|
||||
await assetService.createComment({ ...comment, message: 'Ready' }, { shareLinkId: shareId })
|
||||
await assetService.createComment({ ...comment, message: 'Workspace comment' })
|
||||
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||
const events = await prisma.shareActivity.findMany({ where: { shareLinkId: shareId } })
|
||||
expect(events).toMatchObject([{ kind: 'comment_created', assetId, userId }])
|
||||
|
||||
await expect(assetService.createComment(comment, { shareLinkId: 'missing' })).rejects.toThrow(
|
||||
'Share link not found',
|
||||
)
|
||||
expect(await prisma.assetComment.count({ where: { assetId } })).toBe(3)
|
||||
})
|
||||
|
||||
it('paginates the feed and resolves current names and missing assets', async () => {
|
||||
await shareActivityService.recordView(shareId, { assetId, userId, isShareEntry: true })
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { name: 'Renamed Cut' } })
|
||||
const first = await shareActivityService.list(shareId, { first: 1 })
|
||||
expect(first.pageInfo).toMatchObject({ total: 2, cursor: expect.any(String) })
|
||||
const second = await shareActivityService.list(shareId, {
|
||||
first: 1,
|
||||
after: first.pageInfo.cursor,
|
||||
})
|
||||
expect(first.data).toHaveLength(1)
|
||||
expect(second.data).toHaveLength(1)
|
||||
expect(first.data[0].id > second.data[0].id).toBe(true)
|
||||
expect([...first.data, ...second.data]).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: 'asset_viewed',
|
||||
user: { name: 'Reviewer', image: 'https://example.com/avatar' },
|
||||
asset: { id: assetId, name: 'Renamed Cut' },
|
||||
}),
|
||||
expect.objectContaining({ kind: 'share_viewed', asset: null }),
|
||||
]),
|
||||
)
|
||||
|
||||
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
|
||||
const getAssetEvent = async () =>
|
||||
(await shareActivityService.list(shareId, {})).data.find(
|
||||
(event) => event.kind === 'asset_viewed',
|
||||
)
|
||||
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||
await prisma.asset.delete({ where: { id: assetId } })
|
||||
expect((await getAssetEvent())?.asset).toEqual({ id: assetId, name: null })
|
||||
await shareService.deleteShareLink(shareId)
|
||||
expect(await prisma.shareActivity.count({ where: { shareLinkId: shareId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('checks that a share root is accessible before accepting a root view', async () => {
|
||||
const share = await shareService.getShareLink(shareId)
|
||||
await expect(shareService.verifyPublicAccess(shareId, undefined)).resolves.toMatchObject({
|
||||
id: shareId,
|
||||
})
|
||||
await prisma.asset.update({
|
||||
where: { id: share.rootFolderId },
|
||||
data: { isDeleted: true },
|
||||
})
|
||||
await expect(shareService.verifyPublicAccess(shareId, undefined)).rejects.toThrow(
|
||||
'Asset is not shared',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { prisma, type Prisma } from '@shumai/db'
|
||||
import type { ShareActivityInfo, ShareActivityKind } from '@shumai/dtos'
|
||||
import { paginateQuery, type PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { ShareLinkNotFoundError } from './errors'
|
||||
|
||||
const deduplicationWindowMs = 30 * 60 * 1000
|
||||
|
||||
type Activity = {
|
||||
kind: ShareActivityKind
|
||||
userId?: string
|
||||
assetId?: string
|
||||
}
|
||||
|
||||
class ShareActivityService {
|
||||
async recordView(
|
||||
shareLinkId: string,
|
||||
view: { userId?: string; assetId?: string; isShareEntry?: boolean },
|
||||
): Promise<void> {
|
||||
const events: Activity[] = []
|
||||
if (!view.assetId || view.isShareEntry) {
|
||||
events.push({ kind: 'share_viewed', userId: view.userId })
|
||||
}
|
||||
if (view.assetId) {
|
||||
events.push({ kind: 'asset_viewed', userId: view.userId, assetId: view.assetId })
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
const now = await this.lockShare(tx, shareLinkId)
|
||||
// A visit updates the counters independently of whether its events are duplicates.
|
||||
await tx.$executeRaw`
|
||||
UPDATE share_links
|
||||
SET views = views + 1,
|
||||
last_viewed_at = GREATEST(last_viewed_at, ${now.toISOString()}::timestamptz AT TIME ZONE 'UTC')
|
||||
WHERE id = ${shareLinkId}
|
||||
`
|
||||
for (const event of events) {
|
||||
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async recordEvent(
|
||||
shareLinkId: string,
|
||||
event: Activity,
|
||||
tx?: Prisma.TransactionClient,
|
||||
): Promise<void> {
|
||||
if (!tx) {
|
||||
await prisma.$transaction((client) => this.recordEvent(shareLinkId, event, client))
|
||||
return
|
||||
}
|
||||
|
||||
const now = await this.lockShare(tx, shareLinkId)
|
||||
await this.insertIfNew(tx, shareLinkId, event, now)
|
||||
}
|
||||
|
||||
async list(shareLinkId: string, params: PaginationParams) {
|
||||
const where = { shareLinkId }
|
||||
const page = await paginateQuery(
|
||||
(skip, take) => prisma.shareActivity.findMany({ where, orderBy: { id: 'desc' }, skip, take }),
|
||||
() => prisma.shareActivity.count({ where }),
|
||||
params,
|
||||
)
|
||||
const userIds = page.data.flatMap(({ userId }) => (userId ? [userId] : []))
|
||||
const assetIds = page.data.flatMap(({ assetId }) => (assetId ? [assetId] : []))
|
||||
const [users, assets] = await Promise.all([
|
||||
prisma.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, name: true, image: true },
|
||||
}),
|
||||
prisma.asset.findMany({
|
||||
where: { id: { in: assetIds }, isDeleted: false },
|
||||
select: { id: true, name: true },
|
||||
}),
|
||||
])
|
||||
const usersById = new Map(
|
||||
await Promise.all(
|
||||
users.map(
|
||||
async ({ id, name, image }) => [id, { name, image: await getAvatarUrl(image) }] as const,
|
||||
),
|
||||
),
|
||||
)
|
||||
const namesById = new Map(assets.map(({ id, name }) => [id, name]))
|
||||
const data: ShareActivityInfo[] = page.data.map((event) => ({
|
||||
id: event.id,
|
||||
kind: event.kind,
|
||||
createdAt: event.createdAt.toISOString(),
|
||||
user: event.userId ? (usersById.get(event.userId) ?? null) : null,
|
||||
asset: event.assetId
|
||||
? { id: event.assetId, name: namesById.get(event.assetId) ?? null }
|
||||
: null,
|
||||
}))
|
||||
return { data, pageInfo: page.pageInfo }
|
||||
}
|
||||
|
||||
private async lockShare(tx: Prisma.TransactionClient, shareLinkId: string) {
|
||||
const rows = await tx.$queryRaw<{ id: string }[]>`
|
||||
SELECT id FROM share_links WHERE id = ${shareLinkId} FOR UPDATE
|
||||
`
|
||||
if (rows.length === 0) throw new ShareLinkNotFoundError('Share link not found')
|
||||
// Read time after acquiring the lock so a queued request uses its actual write time.
|
||||
const [clock] = await tx.$queryRaw<{ now: Date }[]>`SELECT clock_timestamp() AS now`
|
||||
return clock.now
|
||||
}
|
||||
|
||||
private async insertIfNew(
|
||||
tx: Prisma.TransactionClient,
|
||||
shareLinkId: string,
|
||||
event: Activity,
|
||||
now: Date,
|
||||
) {
|
||||
const identity = {
|
||||
shareLinkId,
|
||||
kind: event.kind,
|
||||
userId: event.userId ?? null,
|
||||
assetId: event.assetId ?? null,
|
||||
}
|
||||
const recent = await tx.shareActivity.findFirst({
|
||||
where: {
|
||||
...identity,
|
||||
createdAt: { gt: new Date(now.getTime() - deduplicationWindowMs) },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
if (!recent) await tx.shareActivity.create({ data: { ...identity, createdAt: now } })
|
||||
}
|
||||
}
|
||||
|
||||
export const shareActivityService = new ShareActivityService()
|
||||
@@ -250,7 +250,7 @@ export class ShareService {
|
||||
|
||||
async verifyPublicAccess(
|
||||
shareLinkId: string,
|
||||
assetId: string,
|
||||
assetId: string | undefined,
|
||||
providedPassword?: string,
|
||||
): Promise<Prisma.ShareLinkGetPayload<true>> {
|
||||
const shareLink = await prisma.shareLink.findUnique({
|
||||
@@ -273,11 +273,13 @@ export class ShareService {
|
||||
throw new ShareLinkPasswordInvalidError('Invalid password for share link')
|
||||
}
|
||||
|
||||
const targetId = assetId ?? shareLink.rootFolderId
|
||||
|
||||
const rows = await prisma.$queryRaw<{ id: string }[]>`
|
||||
WITH RECURSIVE
|
||||
-- Trace ancestors in the real asset tree
|
||||
real_ancestors AS (
|
||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${assetId} AND is_deleted = false
|
||||
SELECT id, parent_id, type::text, target_id FROM assets WHERE id = ${targetId} AND is_deleted = false
|
||||
UNION ALL
|
||||
SELECT a.id, a.parent_id, a.type::text, a.target_id FROM assets a
|
||||
INNER JOIN real_ancestors ra ON ra.parent_id = a.id
|
||||
@@ -339,6 +341,8 @@ export class ShareService {
|
||||
rootFolderId: l.rootFolderId,
|
||||
projectId: l.projectId,
|
||||
isExpired,
|
||||
views: l.views,
|
||||
lastViewedAt: l.lastViewedAt?.toISOString() ?? null,
|
||||
watermarkConfigId: l.watermarkConfigId,
|
||||
watermarkStatus: l.watermarkStatus || 'disabled',
|
||||
watermarkConfig: watermarkConfig
|
||||
|
||||
Reference in New Issue
Block a user