2026-09-19 10:40:49 +08:00
import { cancelWorkflowTask , prisma } from '@shumai/db'
2026-05-19 16:05:09 +08:00
import {
2026-05-25 23:51:37 +08:00
AncestorFolder ,
2026-11-03 20:31:56 +08:00
ArchiveAssetsResponse ,
2026-05-25 23:51:37 +08:00
AssetInfo ,
AttachmentInfo ,
ChildPreview ,
CommentInfo ,
2026-09-14 15:01:36 +08:00
CommentReactionCount ,
2026-05-25 23:51:37 +08:00
CopyAssetsRequest ,
CreateAssetRequest ,
CreateCommentRequest ,
FieldValueInfo ,
GetAssetRequest ,
ListChildrenRequest ,
PreviewInfo ,
ReparentAssetsRequest ,
2026-11-03 20:31:56 +08:00
RestoreArchivedAssetsResponse ,
2026-05-25 23:51:37 +08:00
UpdateAssetNameRequest ,
UpdateAssetOrderRequest ,
2026-06-01 23:08:58 +08:00
AssetUserInfo ,
2026-08-25 18:51:24 +08:00
ListRecentsRequest ,
2026-09-13 14:48:41 +08:00
CommentExportFormat ,
2026-09-17 11:51:03 +08:00
PreviewFormat ,
2026-09-19 11:36:14 +08:00
TRASH_RETENTION_DAYS ,
2026-11-05 09:57:34 +08:00
GetStoragePathsResponse ,
StoragePathItem ,
2026-06-01 23:08:58 +08:00
} from '@shumai/dtos'
2026-09-13 14:48:41 +08:00
import {
exportCommentsToFormat ,
type ExportAssetMetadata ,
type ExportCommentItem ,
type ExportOptions ,
type ExportResult ,
} from './comments-export'
2026-09-19 10:40:49 +08:00
import {
type Asset ,
AssetStatus ,
AssetType ,
Prisma ,
type StorageKey ,
WorkflowTaskStatus ,
WorkflowTaskType ,
} from '@shumai/db'
2026-07-16 09:55:05 +08:00
import { HTTPException } from 'hono/http-exception'
2026-06-01 23:35:00 +08:00
import { logger } from '@shumai/core/src/logger'
2026-06-01 23:16:22 +08:00
import { PaginatedData , paginateQuery , PaginationParams } from '@shumai/core/src/pagination'
2026-11-05 09:57:34 +08:00
import { s3Service , getStorageBackend } from '@shumai/core/src/s3/s3'
2026-11-03 20:31:56 +08:00
import {
getArchiveStorageService ,
isArchiveStorageEnabled ,
2026-11-05 09:57:34 +08:00
getArchiveStoragePath ,
2026-11-03 20:31:56 +08:00
} from '@shumai/core/src/s3/archive-storage'
import { assetArchiveService } from './asset-archive'
2026-09-17 11:51:03 +08:00
import {
ensureJpegInStorage ,
getJpegKeyForWebp ,
isWebpKey ,
} from '@shumai/core/src/s3/preview-converter'
2026-08-15 15:37:17 +08:00
import { dedupeSymlinksToTarget } from './symlink'
2026-08-07 21:36:20 +08:00
import { watermarkService } from '@shumai/core/src/watermark/watermark'
2026-05-19 16:05:09 +08:00
import { generateKeyBetween } from 'jittered-fractional-indexing'
2026-06-03 19:56:07 +08:00
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
2026-08-16 11:16:14 +08:00
import { getAgentRequiredLevel , getRoleLevel } from '@shumai/core/src/agent/permissions'
2026-08-16 15:44:45 +08:00
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
2026-08-29 15:19:08 +08:00
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { uploadService } from '@shumai/core/src/upload/upload'
2026-09-18 23:14:54 +08:00
import path from 'path'
2026-11-18 15:58:57 +08:00
import { decodeTime } from 'ulid'
2026-09-18 23:14:54 +08:00
import { stemFromKey } from '@shumai/core/src/utils/filename'
2026-09-30 16:31:40 +08:00
import { rewriteM3u8WithPresignedUrls } from '@shumai/core/src/transcode/transcode'
2026-05-19 16:05:09 +08:00
2026-08-25 18:51:24 +08:00
export const assetInclude = {
creator : true ,
2026-09-04 11:27:52 +08:00
agent : { include : { user : true } },
2026-08-25 18:51:24 +08:00
metadataValues : true ,
storageKey : true ,
target : {
include : {
creator : true ,
2026-09-04 11:27:52 +08:00
agent : { include : { user : true } },
2026-08-25 18:51:24 +08:00
metadataValues : true ,
storageKey : true ,
children : {
2026-09-04 11:27:52 +08:00
where : { isDeleted : false },
include : {
creator : true ,
agent : { include : { user : true } },
metadataValues : true ,
storageKey : true ,
},
take : 3 ,
orderBy : { sortIndex : 'asc' },
2026-08-25 18:51:24 +08:00
},
},
},
children : {
2026-09-04 11:27:52 +08:00
where : { isDeleted : false },
include : {
creator : true ,
agent : { include : { user : true } },
metadataValues : true ,
storageKey : true ,
},
take : 3 ,
orderBy : { sortIndex : 'asc' },
2026-08-25 18:51:24 +08:00
},
} as const
export type AssetWithIncludes = Prisma . AssetGetPayload < {
include : typeof assetInclude
2026-05-19 16:05:09 +08:00
} >
2026-09-19 11:36:14 +08:00
/**
* Same shape as {@link assetInclude}, but keeps soft-deleted children.
*
* The "Recently Deleted" view needs this because deleting a folder soft-deletes
* all of its descendants by cascade, so filtering out deleted children leaves
* the folder card with no previews of what was inside it.
*/
export const assetIncludeIncludingDeletedChildren = {
... assetInclude ,
target : {
... assetInclude . target ,
include : {
... assetInclude . target . include ,
children : {
... assetInclude . target . include . children ,
where : {},
},
},
},
children : {
... assetInclude . children ,
where : {},
},
} as const
2026-05-19 16:05:09 +08:00
type CommentWithIncludes = Prisma . AssetCommentGetPayload < {
include : {
creator : true
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true
2026-05-25 00:52:45 +08:00
attachments : { include : { asset : { include : { storageKey : true } } } }
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true ; name : true } }
}
}
2026-05-19 16:05:09 +08:00
replies : {
include : {
creator : true
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true
2026-05-25 00:52:45 +08:00
attachments : { include : { asset : { include : { storageKey : true } } } }
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true ; name : true } }
}
}
2026-05-19 16:05:09 +08:00
}
}
}
} >
type AssetWithProjectTeam = Prisma . AssetGetPayload < {
include : { project : { include : { team : true } } }
} >
function generateSortIndex ( previous? : string | null ) : string {
if ( ! previous ) return generateKeyBetween ( null , null )
return generateKeyBetween ( null , previous )
}
export class AssetService {
constructor ( private readonly prismaClient : typeof prisma = prisma ) {}
async getDescendantFolderIds ( folderId : string ) : Promise < string [] > {
const rows = await this . prismaClient . $queryRaw < { id : string }[] > `
WITH RECURSIVE descendant AS (
2026-11-23 16:40:12 +08:00
SELECT id, parent_id
FROM assets
WHERE parent_id = ${ folderId }
AND type = 'folder'::"AssetType"
AND is_deleted = false
2026-05-19 16:05:09 +08:00
UNION ALL
2026-11-23 16:40:12 +08:00
SELECT a.id, a.parent_id
FROM assets a
2026-05-19 16:05:09 +08:00
INNER JOIN descendant d ON a.parent_id = d.id
2026-11-23 16:40:12 +08:00
WHERE a.type = 'folder'::"AssetType"
AND a.is_deleted = false
2026-05-19 16:05:09 +08:00
)
SELECT id FROM descendant;
`
const ids = rows . map (( r ) => r . id )
return [ folderId , ... ids ]
}
2026-09-17 11:51:03 +08:00
async listAssetsByIds ( ids : string [], previewFormat? : PreviewFormat ) : Promise < AssetInfo [] > {
2026-05-19 16:05:09 +08:00
if ( ids . length === 0 ) return []
const assets = await this . prismaClient . asset . findMany ({
where : { id : { in : ids } },
2026-09-04 11:27:52 +08:00
include : assetInclude ,
2026-05-19 16:05:09 +08:00
})
const assetMap = new Map ( assets . map (( a ) => [ a . id , a ]))
2026-05-22 15:39:46 +08:00
const orderedAssets = ids
. map (( id ) => assetMap . get ( id ))
. filter (( a ) : a is AssetWithIncludes => !! a )
2026-09-17 11:51:03 +08:00
const orderedInfos = await this . toAssetInfos ( orderedAssets , previewFormat )
2026-05-19 16:05:09 +08:00
return orderedInfos
}
2026-07-29 20:14:23 +08:00
async updateAncestorsSize (
tx : Prisma.TransactionClient ,
startNodeId : string ,
sizeDelta : number | bigint ,
) {
if ( sizeDelta === 0 || sizeDelta === 0 n ) return
2026-05-19 16:05:09 +08:00
const rows = await tx . $queryRaw < { id : string }[] > `
WITH RECURSIVE ancestor AS (
SELECT id, parent_id FROM assets WHERE id = ${ startNodeId }
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN ancestor d ON a.id = d.parent_id
)
SELECT id FROM ancestor;
`
const ancestorIds = rows . map (( r ) => r . id )
if ( ancestorIds . length > 0 ) {
await tx . asset . updateMany ({
where : { id : { in : ancestorIds } },
data : { sizeByte : { increment : sizeDelta } },
})
}
}
async dissolveStackIfEmpty ( tx : Prisma.TransactionClient , stack : Asset ) {
if ( stack . type !== AssetType . version_stack ) return
const count = await tx . asset . count ({ where : { parentId : stack.id } })
if ( count === 0 ) {
2026-08-15 15:37:17 +08:00
await tx . asset . deleteMany ({
where : { targetId : stack.id , type : AssetType . symlink },
})
2026-05-19 16:05:09 +08:00
if ( stack . parentId ) {
await tx . asset . update ({
where : { id : stack.parentId },
data : { fileCount : { decrement : 1 } },
})
}
await tx . asset . delete ({ where : { id : stack.id } })
} else if ( count === 1 ) {
const lastChild = await tx . asset . findFirst ({
where : { parentId : stack.id },
})
if ( ! lastChild ) return
if ( ! stack . parentId ) throw new Error ( 'Stack has no parent' )
2026-08-15 15:37:17 +08:00
await tx . asset . updateMany ({
where : { targetId : stack.id , type : AssetType . symlink },
data : { targetId : lastChild.id , name : lastChild.name },
})
2026-05-19 16:05:09 +08:00
await tx . asset . update ({
where : { id : lastChild.id },
2026-08-15 15:37:17 +08:00
data : { parentId : stack.parentId , sortIndex : stack.sortIndex },
2026-05-19 16:05:09 +08:00
})
await tx . asset . delete ({ where : { id : stack.id } })
}
}
2026-06-09 08:10:33 +08:00
async reparentAssets ( req : ReparentAssetsRequest , tx? : Prisma.TransactionClient ) : Promise < void > {
const runInTx = async ( tx : Prisma.TransactionClient ) => {
2026-05-19 16:05:09 +08:00
const newParent = await tx . asset . findUnique ({
where : { id : req.newParentId },
include : { project : { include : { team : true } } },
})
if ( ! newParent ) throw new Error ( 'New parent not found' )
if ( ! newParent . project ) throw new Error ( 'New parent folder is not associated with a project' )
if ( newParent . type === AssetType . file ) {
return this . reparentFileToFile ( tx , newParent , req . assetIds , req . creatorId )
}
2026-08-29 16:09:36 +08:00
if ( newParent . type === AssetType . version_stack ) {
if ( req . assetIds . length !== 1 ) {
throw new Error ( 'Can only move one file at a time into a version stack' )
}
}
2026-05-19 16:05:09 +08:00
const assetsToMove = await tx . asset . findMany ({
where : { id : { in : req . assetIds } },
include : { project : { include : { team : true } } },
})
if ( assetsToMove . length !== req . assetIds . length ) {
throw new Error ( 'Not all assets to be moved were found' )
}
if ( assetsToMove . length === 0 ) return
2026-09-06 17:15:58 +08:00
// Check if newParentId is equal to or a descendant of any asset being moved
const ancestors = await tx . $queryRaw < { id : string }[] > `
WITH RECURSIVE ancestor AS (
SELECT id, parent_id FROM assets WHERE id = ${ newParent . id }
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN ancestor d ON a.id = d.parent_id
)
SELECT id FROM ancestor WHERE id IN ( ${ Prisma . join ( req . assetIds ) } ) LIMIT 1;
`
if ( ancestors . length > 0 ) {
throw new Error ( 'Cannot move an asset into itself or its own descendant' )
}
2026-08-29 16:09:36 +08:00
if ( newParent . type === AssetType . version_stack ) {
for ( const a of assetsToMove ) {
if ( a . type !== AssetType . file ) {
throw new Error ( `Cannot move ${ a . type } asset into a version stack` )
}
}
}
2026-05-19 16:05:09 +08:00
let totalSize = 0
const oldParentId = assetsToMove [ 0 ]. parentId
if ( ! oldParentId ) {
throw new Error ( `Asset ${ assetsToMove [ 0 ]. id } has no parent` )
}
for ( const a of assetsToMove ) {
if ( ! a . project || ! a . project . team ) {
throw new Error ( `Asset ${ a . id } is not associated with a team` )
}
if ( ! newParent . project . team ) {
throw new Error ( 'New parent folder is not associated with a team' )
}
if ( a . project . team . id !== newParent . project . team . id ) {
throw new Error ( `Cannot move asset ${ a . id } to a different team` )
}
if ( a . parentId !== oldParentId ) {
throw new Error ( 'All assets must be moved from the same parent folder' )
}
2026-07-29 20:14:23 +08:00
totalSize += Number ( a . sizeByte )
2026-05-19 16:05:09 +08:00
}
const totalCount = assetsToMove . length
// Sibling folder move
if ( newParent . parentId && oldParentId === newParent . parentId ) {
await tx . asset . update ({
where : { id : oldParentId },
data : { fileCount : { decrement : totalCount } },
})
await tx . asset . update ({
where : { id : newParent.id },
data : {
fileCount : { increment : totalCount },
sizeByte : { increment : totalSize },
},
})
} else {
await tx . asset . update ({
where : { id : oldParentId },
data : { fileCount : { decrement : totalCount } },
})
await this . updateAncestorsSize ( tx , oldParentId , - totalSize )
await tx . asset . update ({
where : { id : newParent.id },
data : { fileCount : { increment : totalCount } },
})
await this . updateAncestorsSize ( tx , newParent . id , totalSize )
}
const firstFile = await tx . asset . findFirst ({
where : { parentId : newParent.id },
orderBy : { sortIndex : 'asc' },
})
let firstSortIndex = firstFile ? . sortIndex || null
for ( let i = req . assetIds . length - 1 ; i >= 0 ; i -- ) {
const assetId = req . assetIds [ i ]
const newSortIndex = generateSortIndex ( firstSortIndex )
await tx . asset . update ({
where : { id : assetId },
data : { parentId : newParent.id , sortIndex : newSortIndex },
})
firstSortIndex = newSortIndex
}
2026-08-15 15:37:17 +08:00
if ( newParent . type === AssetType . version_stack ) {
await dedupeSymlinksToTarget ( tx , {
targetIds : req.assetIds ,
newTargetId : newParent.id ,
name : '' ,
})
}
2026-05-19 16:05:09 +08:00
const oldParent = await tx . asset . findUnique ({
where : { id : oldParentId },
})
if ( oldParent ) {
await this . dissolveStackIfEmpty ( tx , oldParent )
}
2026-06-09 08:10:33 +08:00
}
if ( tx ) {
await runInTx ( tx )
} else {
await this . prismaClient . $transaction ( runInTx )
}
2026-05-19 16:05:09 +08:00
}
2026-10-27 14:37:26 +08:00
/** Copies assets into a folder. Returns the IDs of the copies, in the order of `assetIds`. */
async copyAssets ( req : CopyAssetsRequest ) : Promise < string [] > {
return this . prismaClient . $transaction ( async ( tx ) => {
2026-05-24 20:15:55 +08:00
const newParent = await tx . asset . findUnique ({
where : { id : req.newParentId },
include : { project : { include : { team : true } } },
})
if ( ! newParent ) throw new Error ( 'New parent not found' )
if ( ! newParent . project ) throw new Error ( 'New parent folder is not associated with a project' )
const assetsToCopy = await tx . asset . findMany ({
where : { id : { in : req . assetIds } },
2026-11-03 20:31:56 +08:00
include : { project : { include : { team : true } }, storageKey : true },
2026-05-24 20:15:55 +08:00
})
if ( assetsToCopy . length !== req . assetIds . length ) {
throw new Error ( 'Not all assets to be copied were found' )
}
2026-05-25 10:45:10 +08:00
// Check if newParentId is a descendant of any asset being copied
const ancestors = await tx . $queryRaw < { id : string }[] > `
WITH RECURSIVE ancestor AS (
SELECT id, parent_id FROM assets WHERE id = ${ newParent . id }
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN ancestor d ON a.id = d.parent_id
)
SELECT id FROM ancestor WHERE id IN ( ${ Prisma . join ( req . assetIds ) } ) LIMIT 1;
`
if ( ancestors . length > 0 ) {
throw new Error ( 'Cannot copy a folder into its own descendant' )
}
2026-05-24 20:15:55 +08:00
for ( const a of assetsToCopy ) {
if ( ! a . project || ! a . project . team ) {
throw new Error ( `Asset ${ a . id } is not associated with a team` )
}
if ( ! newParent . project . team ) {
throw new Error ( 'New parent folder is not associated with a team' )
}
if ( a . project . team . id !== newParent . project . team . id ) {
throw new Error ( `Cannot copy asset ${ a . id } to a different team` )
}
}
const firstFile = await tx . asset . findFirst ({
where : { parentId : newParent.id },
orderBy : { sortIndex : 'asc' },
})
let firstSortIndex = firstFile ? . sortIndex || null
let totalSize = 0
2026-10-27 14:37:26 +08:00
const copiedIds : string [] = new Array ( req . assetIds . length )
2026-05-24 20:15:55 +08:00
for ( let i = req . assetIds . length - 1 ; i >= 0 ; i -- ) {
const assetId = req . assetIds [ i ]
const asset = assetsToCopy . find (( a ) => a . id === assetId ) !
const newSortIndex = generateSortIndex ( firstSortIndex )
const copiedAsset = await this . copyAssetRecursive (
tx ,
asset ,
newParent . id ,
newParent . projectId ! ,
newSortIndex ,
req . creatorId ,
req . withComments ,
)
2026-10-27 14:37:26 +08:00
copiedIds [ i ] = copiedAsset . id
2026-07-29 20:14:23 +08:00
totalSize += Number ( copiedAsset . sizeByte )
2026-05-24 20:15:55 +08:00
firstSortIndex = newSortIndex
}
await tx . asset . update ({
where : { id : newParent.id },
data : {
fileCount : { increment : assetsToCopy.length },
},
})
await this . updateAncestorsSize ( tx , newParent . id , totalSize )
2026-10-27 14:37:26 +08:00
return copiedIds
2026-05-24 20:15:55 +08:00
})
}
private async copyAssetRecursive (
tx : Prisma.TransactionClient ,
2026-05-25 00:52:45 +08:00
asset : Asset & { storageKey? : StorageKey | null },
2026-05-24 20:15:55 +08:00
newParentId : string | null ,
projectId : string | null ,
sortIndex : string | null ,
creatorId? : string ,
withComments : boolean = false ,
) : Promise < Asset > {
2026-11-03 20:31:56 +08:00
if ( asset . status === AssetStatus . archiving || asset . status === AssetStatus . restoring ) {
throw new HTTPException ( 409 , {
message : 'Cannot copy an asset while it is being archived or restored' ,
})
}
const copiedStatus =
asset . type === AssetType . file && asset . storageKey ? . isArchived
? AssetStatus.archived
: asset.status
2026-05-24 20:15:55 +08:00
const newAsset = await tx . asset . create ({
data : {
name : asset.name ,
nameNgram : asset.nameNgram ,
type : asset . type ,
mediaType : asset.mediaType ,
fileCount : asset.fileCount ,
sizeByte : asset.sizeByte ,
2026-11-03 20:31:56 +08:00
status : copiedStatus ,
2026-05-24 20:15:55 +08:00
transcodeTaskId : asset.transcodeTaskId ,
2026-05-25 10:45:10 +08:00
media : asset.media || undefined ,
2026-05-24 20:15:55 +08:00
isDeleted : asset.isDeleted ,
deletedAt : asset.deletedAt ,
sortIndex : sortIndex ,
parentId : newParentId ,
projectId : projectId ,
creatorId : creatorId || asset . creatorId ,
taskId : asset.taskId ,
2026-05-25 10:45:10 +08:00
targetId : asset.targetId ,
2026-05-25 00:52:45 +08:00
storageKeyId : asset.storageKeyId ,
2026-05-24 20:15:55 +08:00
},
})
if ( withComments ) {
2026-05-25 10:45:10 +08:00
await this . copyComments ( tx , asset . id , newAsset . id , projectId , creatorId )
2026-05-24 20:15:55 +08:00
}
2026-11-03 20:31:56 +08:00
if ( asset . type === AssetType . folder || asset . type === AssetType . version_stack ) {
2026-05-24 20:15:55 +08:00
const children = await tx . asset . findMany ({
where : { parentId : asset.id },
2026-11-03 20:31:56 +08:00
include : { storageKey : true },
2026-05-24 20:15:55 +08:00
orderBy : { sortIndex : 'asc' },
})
for ( const child of children ) {
await this . copyAssetRecursive (
tx ,
child ,
newAsset . id ,
projectId ,
child . sortIndex ,
creatorId ,
withComments ,
)
}
}
return newAsset
}
private async copyComments (
tx : Prisma.TransactionClient ,
oldAssetId : string ,
newAssetId : string ,
2026-05-25 10:45:10 +08:00
projectId : string | null ,
2026-05-24 20:15:55 +08:00
creatorId? : string ,
) {
const comments = await tx . assetComment . findMany ({
where : { assetId : oldAssetId , replyToId : null },
include : {
attachments : { include : { asset : true } },
replies : {
include : {
attachments : { include : { asset : true } },
},
},
},
})
for ( const comment of comments ) {
2026-05-25 10:45:10 +08:00
await this . copyCommentRecursive ( tx , comment , newAssetId , null , projectId , creatorId )
2026-05-24 20:15:55 +08:00
}
}
private async copyCommentRecursive (
tx : Prisma.TransactionClient ,
comment : any , // eslint-disable-line @typescript-eslint/no-explicit-any
newAssetId : string ,
newReplyToId : string | null ,
2026-05-25 10:45:10 +08:00
projectId : string | null ,
2026-05-24 20:15:55 +08:00
creatorId? : string ,
) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { id , createdAt , updatedAt , assetId , replyToId , attachments , replies , ... data } = comment
const newComment = await tx . assetComment . create ({
data : {
... data ,
assetId : newAssetId ,
replyToId : newReplyToId ,
creatorId : creatorId || comment . creatorId ,
},
})
if ( attachments ) {
for ( const attachment of attachments ) {
// Deep copy attachment asset
const copiedAttachmentAsset = await this . copyAssetRecursive (
tx ,
attachment . asset ,
null , // attachment usually has no parent
2026-05-25 10:45:10 +08:00
projectId ,
2026-05-24 20:15:55 +08:00
attachment . asset . sortIndex ,
creatorId ,
false ,
)
await tx . assetCommentAttachment . create ({
data : {
commentId : newComment.id ,
assetId : copiedAttachmentAsset.id ,
},
})
}
}
if ( replies ) {
for ( const reply of replies ) {
2026-05-25 10:45:10 +08:00
await this . copyCommentRecursive ( tx , reply , newAssetId , newComment . id , projectId , creatorId )
2026-05-24 20:15:55 +08:00
}
}
}
2026-05-19 16:05:09 +08:00
private async reparentFileToFile (
tx : Prisma.TransactionClient ,
destFile : AssetWithProjectTeam ,
assetIds : string [],
creatorId? : string ,
) {
2026-08-29 16:09:36 +08:00
if ( destFile . type !== AssetType . file ) {
throw new Error ( 'Destination asset must be a file' )
}
2026-05-19 16:05:09 +08:00
if ( assetIds . length !== 1 ) {
throw new Error ( 'Can only reparent one file to another file' )
}
const sourceId = assetIds [ 0 ]
if ( sourceId === destFile . id ) {
throw new Error ( 'Cannot reparent a file to itself' )
}
const sourceAsset = await tx . asset . findUnique ({
where : { id : sourceId },
include : { project : { include : { team : true } } },
})
if ( ! sourceAsset ) throw new Error ( 'Source asset not found' )
2026-08-29 16:09:36 +08:00
if ( sourceAsset . type !== AssetType . file ) {
throw new Error ( 'Source asset must be a file to create a version stack' )
}
2026-05-19 16:05:09 +08:00
if ( ! sourceAsset . project || ! sourceAsset . project . team ) {
throw new Error ( `Asset ${ sourceAsset . id } is not associated with a team` )
}
if ( ! destFile . project || ! destFile . project . team ) {
throw new Error ( 'Destination file is not associated with a team' )
}
if ( sourceAsset . project . team . id !== destFile . project . team . id ) {
throw new Error ( `Cannot move asset ${ sourceAsset . id } to a different team` )
}
const oldParentId = sourceAsset . parentId
if ( ! oldParentId ) {
throw new Error ( `Asset ${ sourceAsset . id } has no parent` )
}
const stackParentId = destFile . parentId
if ( ! stackParentId ) {
throw new Error ( `Destination file ${ destFile . id } has no parent` )
}
const stack = await tx . asset . create ({
data : {
type : AssetType . version_stack ,
status : 'uploaded' ,
projectId : destFile.project.id ,
parentId : stackParentId ,
creatorId : creatorId ,
name : '' ,
2026-06-15 20:38:46 +08:00
sortIndex : destFile.sortIndex ,
2026-05-19 16:05:09 +08:00
},
})
2026-05-24 16:55:08 +08:00
const isUploading = sourceAsset . status === 'uploading'
if ( ! isUploading ) {
await tx . asset . update ({
where : { id : oldParentId },
data : { fileCount : { decrement : 1 } },
})
2026-07-29 20:14:23 +08:00
await this . updateAncestorsSize ( tx , oldParentId , - Number ( sourceAsset . sizeByte ))
await this . updateAncestorsSize ( tx , stackParentId , Number ( sourceAsset . sizeByte ))
2026-05-24 16:55:08 +08:00
}
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
const firstIndex = generateKeyBetween ( null , null )
const secondIndex = generateKeyBetween ( firstIndex , null )
2026-05-19 16:05:09 +08:00
await tx . asset . update ({
where : { id : destFile.id },
2026-05-22 15:39:46 +08:00
data : { parentId : stack.id , sortIndex : secondIndex },
2026-05-19 16:05:09 +08:00
})
await tx . asset . update ({
where : { id : sourceAsset.id },
2026-05-22 15:39:46 +08:00
data : { parentId : stack.id , sortIndex : firstIndex },
2026-05-19 16:05:09 +08:00
})
await tx . asset . update ({
where : { id : stack.id },
data : {
2026-05-24 16:55:08 +08:00
fileCount : isUploading ? 1 : 2 ,
sizeByte : isUploading ? destFile.sizeByte : destFile.sizeByte + sourceAsset . sizeByte ,
2026-05-19 16:05:09 +08:00
},
})
2026-08-15 15:37:17 +08:00
// Update existing symlinks pointing to destFile or sourceAsset
await dedupeSymlinksToTarget ( tx , {
targetIds : [ destFile . id , sourceAsset . id ],
newTargetId : stack.id ,
})
2026-05-19 16:05:09 +08:00
const oldParent = await tx . asset . findUnique ({ where : { id : oldParentId } })
if ( oldParent ) {
await this . dissolveStackIfEmpty ( tx , oldParent )
}
}
async listChildren ( req : ListChildrenRequest ) : Promise < PaginatedData < AssetInfo [] >> {
2026-08-29 15:19:08 +08:00
let typesToQuery : AssetType []
if ( req . assetType === 'file' ) {
typesToQuery = [ AssetType . file , AssetType . version_stack ]
} else if ( req . assetType === 'folder' ) {
typesToQuery = [ AssetType . folder ]
} else {
typesToQuery = [ AssetType . file , AssetType . folder , AssetType . version_stack ]
2026-05-19 16:05:09 +08:00
}
let where : Prisma.AssetWhereInput = {}
2026-05-23 23:26:43 +08:00
if ( req . showDeleted ) {
2026-05-19 16:05:09 +08:00
if ( ! req . projectId ) {
2026-05-23 23:26:43 +08:00
throw new Error ( 'ProjectID is required when ShowDeleted is true' )
2026-05-19 16:05:09 +08:00
}
const thirtyDaysAgo = new Date ()
2026-09-19 11:36:14 +08:00
thirtyDaysAgo . setDate ( thirtyDaysAgo . getDate () - TRASH_RETENTION_DAYS )
2026-05-19 16:05:09 +08:00
where = {
projectId : req.projectId ,
2026-05-23 23:26:43 +08:00
isDeleted : true ,
2026-05-19 16:05:09 +08:00
deletedAt : { gte : thirtyDaysAgo },
2026-08-26 21:04:38 +08:00
type : { in : typesToQuery },
2026-05-19 16:05:09 +08:00
}
} else {
if ( ! req . assetId ) {
2026-05-23 23:26:43 +08:00
throw new Error ( 'AssetId is required when ShowDeleted is false' )
2026-05-19 16:05:09 +08:00
}
let parentId = req . assetId
const asset = await this . prismaClient . asset . findUnique ({
where : { id : parentId },
})
if ( asset ? . type === AssetType . symlink && asset . targetId ) {
parentId = asset . targetId
}
where = {
parentId ,
2026-05-23 23:26:43 +08:00
isDeleted : false ,
2026-05-19 16:05:09 +08:00
OR : [
{ type : { in : typesToQuery } },
2026-08-26 21:04:38 +08:00
{ type : AssetType . symlink , target : { isDeleted : false , type : { in : typesToQuery } } },
2026-05-19 16:05:09 +08:00
],
}
}
if ( req . prefix ) {
where . name = { startsWith : req.prefix }
}
let orderBy : Prisma.AssetOrderByWithRelationInput = {}
const dir = req . order === 'desc' ? 'desc' : 'asc'
switch ( req . sort ) {
case 'createdAt' :
orderBy = { id : dir }
break
case 'name' :
orderBy = { name : dir }
break
case 'size' :
orderBy = { sizeByte : dir }
break
case 'index' :
default :
orderBy = { sortIndex : 'asc' }
break
}
2026-09-19 11:36:14 +08:00
const include = req . showDeleted ? assetIncludeIncludingDeletedChildren : assetInclude
2026-05-19 16:05:09 +08:00
const { data : assets , pageInfo } = await paginateQuery (
async ( skip , take ) => {
return this . prismaClient . asset . findMany ({
where ,
2026-09-19 11:36:14 +08:00
include ,
2026-05-19 16:05:09 +08:00
orderBy ,
skip ,
take ,
})
},
async () => this . prismaClient . asset . count ({ where }),
req ,
)
2026-09-19 11:36:14 +08:00
const infos = await this . toAssetInfos ( assets , undefined , {
includeDeletedChildren : req.showDeleted ,
})
2026-05-19 16:05:09 +08:00
return { data : infos , pageInfo }
}
2026-08-29 15:19:08 +08:00
async createAsset (
req : CreateAssetRequest ,
txClient? : Prisma.TransactionClient ,
) : Promise < AssetInfo > {
const db = txClient ?? this . prismaClient
2026-05-19 16:05:09 +08:00
let projectId = req . projectId
let parent : Prisma.AssetGetPayload < { include : { project : true } } > | null = null
if ( req . parentId ) {
2026-08-29 15:19:08 +08:00
parent = await db . asset . findUnique ({
2026-05-19 16:05:09 +08:00
where : { id : req.parentId },
include : { project : true },
})
if ( ! parent ) throw new Error ( 'Parent not found' )
projectId = parent . projectId ?? undefined
}
if ( ! projectId ) throw new Error ( 'projectId is empty' )
let sortIndex : string | null = null
if ( parent ) {
2026-08-29 15:19:08 +08:00
const firstFile = await db . asset . findFirst ({
2026-05-19 16:05:09 +08:00
where : { parentId : parent.id },
orderBy : { sortIndex : 'asc' },
})
sortIndex = generateSortIndex ( firstFile ? . sortIndex )
}
const data : Prisma.AssetCreateInput = {
name : req.name ,
type : req . type as AssetType ,
status : 'uploaded' ,
project : { connect : { id : projectId } },
}
if ( parent ) data . parent = { connect : { id : parent.id } }
if ( sortIndex ) data . sortIndex = sortIndex
2026-05-25 00:52:45 +08:00
if ( req . key ) {
2026-05-25 10:14:22 +08:00
data . storageKey = {
2026-05-25 00:52:45 +08:00
connectOrCreate : {
where : { key : req.key },
create : { key : req.key },
},
}
}
2026-05-19 16:05:09 +08:00
if ( req . sizeByte ) data . sizeByte = req . sizeByte
if ( req . contentType ) data . mediaType = req . contentType
if ( req . creatorId ) data . creator = { connect : { id : req.creatorId } }
2026-09-04 11:27:52 +08:00
if ( req . agentId ) data . agent = { connect : { id : req.agentId } }
2026-05-19 16:05:09 +08:00
2026-08-29 15:19:08 +08:00
const executeInTx = async ( tx : Prisma.TransactionClient ) => {
2026-06-09 08:10:33 +08:00
const createdAsset = await tx . asset . create ({
data ,
include : {
creator : true ,
2026-09-04 11:27:52 +08:00
agent : { include : { user : true } },
2026-06-09 08:10:33 +08:00
metadataValues : true ,
storageKey : true ,
target : {
include : {
creator : true ,
2026-09-04 11:27:52 +08:00
agent : { include : { user : true } },
2026-06-09 08:10:33 +08:00
metadataValues : true ,
storageKey : true ,
children : {
2026-07-21 11:19:20 +08:00
where : { isDeleted : false },
2026-09-04 11:27:52 +08:00
include : {
creator : true ,
agent : { include : { user : true } },
metadataValues : true ,
storageKey : true ,
},
2026-06-09 08:10:33 +08:00
take : 3 ,
orderBy : { sortIndex : 'asc' },
},
2026-05-19 16:05:09 +08:00
},
},
2026-06-09 08:10:33 +08:00
children : {
2026-07-21 11:19:20 +08:00
where : { isDeleted : false },
2026-09-04 11:27:52 +08:00
include : {
creator : true ,
agent : { include : { user : true } },
metadataValues : true ,
storageKey : true ,
},
2026-06-09 08:10:33 +08:00
take : 3 ,
orderBy : { sortIndex : 'asc' },
},
2026-05-19 16:05:09 +08:00
},
2026-06-09 08:10:33 +08:00
})
if ( parent ) {
await tx . asset . update ({
where : { id : parent.id },
data : { fileCount : { increment : 1 } },
})
}
return createdAsset
2026-08-29 15:19:08 +08:00
}
const asset = txClient
? await executeInTx ( txClient )
: await this . prismaClient . $transaction ( executeInTx )
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
const infos = await this . toAssetInfos ([ asset ])
return infos [ 0 ]
2026-05-19 16:05:09 +08:00
}
2026-08-29 15:19:08 +08:00
async createFile ( params : {
parentId : string
name : string
key : string
sizeByte : number
contentType : string
creatorId : string
2026-09-04 11:27:52 +08:00
agentId? : string
2026-08-29 15:19:08 +08:00
metadata? : Record < string , unknown >
}) : Promise < AssetInfo > {
2026-09-04 11:27:52 +08:00
const { parentId , name , key , sizeByte , contentType , creatorId , agentId , metadata } = params
2026-08-29 15:19:08 +08:00
const parentAsset = await this . prismaClient . asset . findUnique ({
where : { id : parentId },
include : { project : true },
})
if ( ! parentAsset || ! parentAsset . projectId || ! parentAsset . project ? . teamId ) {
throw new Error ( `Parent folder ${ parentId } is invalid or has no project associated` )
}
if ( metadata ) {
await metadataService . validateCreationContextMetadata (
creatorId ,
parentAsset . projectId ,
metadata ,
)
}
let newFileId = ''
await this . prismaClient . $transaction ( async ( tx ) => {
const newFile = await this . createAsset (
{
name ,
type : 'file' ,
parentId ,
key ,
sizeByte ,
contentType ,
creatorId ,
2026-09-04 11:27:52 +08:00
agentId ,
2026-08-29 15:19:08 +08:00
},
tx ,
)
newFileId = newFile . id
await this . updateAncestorsSize ( tx , parentId , sizeByte )
if ( metadata ) {
const metadataUpdates = Object . entries ( metadata )
. filter (([, value ]) => value !== null )
. map (([ k , v ]) => ({ key : k , value : v }))
if ( metadataUpdates . length > 0 ) {
await metadataService . updateAssetMetadataInTx ( tx , newFile . id , metadataUpdates )
}
}
await uploadService . triggerPostUploadWorkflows (
tx ,
newFile . id ,
parentAsset . project ! . teamId ,
parentAsset . projectId ! ,
)
})
return this . getAsset ({ assetId : newFileId })
}
async createVersion ( params : {
parentId : string
name : string
key : string
sizeByte : number
contentType : string
creatorId : string
2026-09-04 11:27:52 +08:00
agentId? : string
2026-08-29 15:19:08 +08:00
metadata? : Record < string , unknown >
}) : Promise < AssetInfo > {
2026-09-04 11:27:52 +08:00
const { parentId , name , key , sizeByte , contentType , creatorId , agentId , metadata } = params
2026-08-29 15:19:08 +08:00
const targetAsset = await this . prismaClient . asset . findUnique ({
where : { id : parentId },
include : { project : true , parent : true },
})
if ( ! targetAsset || ! targetAsset . projectId || ! targetAsset . project ? . teamId ) {
throw new Error ( `Target file ${ parentId } is invalid or has no project associated` )
}
if ( metadata ) {
await metadataService . validateCreationContextMetadata (
creatorId ,
targetAsset . projectId ,
metadata ,
)
}
let targetFolderId : string
let reparentTargetId : string
if ( targetAsset . type === AssetType . version_stack ) {
targetFolderId = targetAsset . parentId !
reparentTargetId = targetAsset . id
} else if ( targetAsset . parent ? . type === AssetType . version_stack ) {
targetFolderId = targetAsset . parent . parentId !
reparentTargetId = targetAsset . parentId !
} else {
targetFolderId = targetAsset . parentId !
reparentTargetId = targetAsset . id
}
let newFileId = ''
await this . prismaClient . $transaction ( async ( tx ) => {
const newFile = await this . createAsset (
{
name ,
type : 'file' ,
parentId : targetFolderId ,
key ,
sizeByte ,
contentType ,
creatorId ,
2026-09-04 11:27:52 +08:00
agentId ,
2026-08-29 15:19:08 +08:00
},
tx ,
)
newFileId = newFile . id
await this . reparentAssets (
{
assetIds : [ newFile . id ],
newParentId : reparentTargetId ,
creatorId ,
},
tx ,
)
if ( metadata ) {
const metadataUpdates = Object . entries ( metadata )
. filter (([, value ]) => value !== null )
. map (([ k , v ]) => ({ key : k , value : v }))
if ( metadataUpdates . length > 0 ) {
await metadataService . updateAssetMetadataInTx ( tx , newFile . id , metadataUpdates )
}
}
await uploadService . triggerPostUploadWorkflows (
tx ,
newFile . id ,
targetAsset . project ! . teamId ,
targetAsset . projectId ! ,
)
})
return this . getAsset ({ assetId : newFileId })
}
2026-05-19 16:05:09 +08:00
async findAsset ( parentId : string , name : string ) : Promise < AssetInfo | null > {
const asset = await this . prismaClient . asset . findFirst ({
where : { parentId , name },
})
if ( ! asset ) return null
return this . getAsset ({ assetId : asset.id })
}
async getAsset ( req : GetAssetRequest ) : Promise < AssetInfo > {
const a = await this . prismaClient . asset . findUnique ({
where : { id : req.assetId },
2026-09-04 11:27:52 +08:00
include : assetInclude ,
2026-05-19 16:05:09 +08:00
})
if ( ! a ) throw new Error ( 'Asset not found' )
const rows = await this . prismaClient . $queryRaw < { id : string ; name : string ; type : string }[] > `
WITH RECURSIVE ancestor AS (
SELECT id, parent_id, name, type::text FROM assets WHERE id = ${ a . id }
UNION ALL
SELECT a.id, a.parent_id, a.name, a.type::text FROM assets a
INNER JOIN ancestor d ON d.parent_id = a.id
)
SELECT id, name, type FROM ancestor;
`
const afs : AncestorFolder [] = []
for ( const row of rows ) {
2026-05-23 10:02:51 +08:00
if ( row . id === a . id || row . type === 'root' || row . type === 'version_stack' ) continue
2026-05-19 16:05:09 +08:00
afs . push ({ id : row.id , name : row.name })
}
2026-05-22 15:39:46 +08:00
const infos = await this . toAssetInfos ([ a ])
const info = infos [ 0 ]
2026-05-19 16:05:09 +08:00
info . ancestorFolders = afs
if ( info . media ) {
if ( info . media . imageTranscodes ) {
for ( const t of info . media . imageTranscodes ) {
t . url = await s3Service . presign ( process . env . S3_BUCKET || 'shumai' , t . key , 'GET' )
}
}
if ( info . media . videoTranscodes ) {
for ( const t of info . media . videoTranscodes ) {
t . url = await s3Service . presign ( process . env . S3_BUCKET || 'shumai' , t . key , 'GET' )
}
}
}
return info
}
2026-08-01 11:21:56 +08:00
async getAssetContext ( assetId : string ) : Promise < { teamId : string ; projectId? : string } > {
2026-05-25 23:51:37 +08:00
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
select : {
projectId : true ,
project : { select : { teamId : true } },
teamRootFolder : { select : { id : true } },
},
})
2026-08-01 11:21:56 +08:00
if ( ! asset ) {
throw new Error ( `Asset not found: ${ assetId } ` )
}
2026-05-25 23:51:37 +08:00
if ( asset . project ) {
return { teamId : asset.project.teamId , projectId : asset.projectId ?? undefined }
}
if ( asset . teamRootFolder ) {
return { teamId : asset.teamRootFolder.id }
}
2026-08-01 11:21:56 +08:00
throw new Error ( `Asset has no team context: ${ assetId } ` )
2026-05-25 23:51:37 +08:00
}
2026-10-27 08:09:09 +08:00
/**
* Lightweight lookup of an asset's type and team/project, without building a full AssetInfo
* (no presigned URLs). Use it to capture context before a mutation such as a delete.
*/
2026-10-27 14:37:26 +08:00
async getAssetMeta ( assetId : string ) : Promise < {
id : string
name : string
type : AssetType
parentId : string | null
teamId : string
projectId? : string
} > {
2026-10-27 08:09:09 +08:00
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
2026-10-27 14:37:26 +08:00
select : { id : true , name : true , type : true , parentId : true },
2026-10-27 08:09:09 +08:00
})
if ( ! asset ) {
throw new HTTPException ( 404 , { message : 'Asset not found' })
}
const { teamId , projectId } = await this . getAssetContext ( assetId )
return { ... asset , teamId , projectId }
}
2026-10-27 14:37:26 +08:00
/**
* The asset whose file is stored under `key`, with its creator. Used to make finishing an
* upload idempotent: the same uploaded object is never attached to two assets.
*/
async findAssetByStorageKey (
key : string ,
) : Promise < { id : string ; creatorId : string | null } | null > {
return this . prismaClient . asset . findFirst ({
where : { storageKey : { key } },
select : { id : true , creatorId : true },
orderBy : { id : 'asc' },
})
}
2026-05-19 16:05:09 +08:00
async resolveTargetAssetId ( assetId : string ) : Promise < string > {
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
select : { type : true , targetId : true },
})
if ( asset ? . type === AssetType . symlink && asset . targetId ) {
return asset . targetId
}
return assetId
}
2026-05-22 15:39:46 +08:00
async resolveLatestVersionId ( assetId : string ) : Promise < string > {
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
select : { id : true , type : true , targetId : true },
})
if ( ! asset ) return assetId
let currentId = asset . id
let currentType = asset . type
if ( asset . type === AssetType . symlink && asset . targetId ) {
const target = await this . prismaClient . asset . findUnique ({
where : { id : asset.targetId },
select : { id : true , type : true },
})
if ( target ) {
currentId = target . id
currentType = target . type
}
}
if ( currentType === AssetType . version_stack ) {
const latestChild = await this . prismaClient . asset . findFirst ({
2026-05-23 23:26:43 +08:00
where : { parentId : currentId , isDeleted : false },
2026-07-04 20:56:31 +08:00
orderBy : { sortIndex : 'asc' },
2026-05-22 15:39:46 +08:00
select : { id : true },
})
if ( latestChild ) {
return latestChild . id
}
}
return currentId
}
2026-11-05 09:57:34 +08:00
async resolveLatestVersionIds ( assetIds : string []) : Promise < string [] > {
if ( assetIds . length === 0 ) return []
const initialAssets = await this . prismaClient . asset . findMany ({
where : { id : { in : assetIds }, isDeleted : false },
select : { id : true , type : true , targetId : true },
})
const assetMap = new Map ( initialAssets . map (( a ) => [ a . id , a ]))
// Find symlinks to resolve
const symlinks = initialAssets . filter (( a ) => a . type === AssetType . symlink && a . targetId )
const targetIds = Array . from ( new Set ( symlinks . map (( s ) => s . targetId ! )))
const symlinkTargetMap = new Map < string , { id : string ; type : AssetType }>()
if ( targetIds . length > 0 ) {
const targets = await this . prismaClient . asset . findMany ({
where : { id : { in : targetIds }, isDeleted : false },
select : { id : true , type : true },
})
for ( const t of targets ) {
symlinkTargetMap . set ( t . id , t )
}
}
// Determine current ID and type for each input ID
const intermediate = assetIds . map (( id ) => {
const asset = assetMap . get ( id )
if ( ! asset ) return { originalId : id , currentId : id , type : null }
if ( asset . type === AssetType . symlink && asset . targetId ) {
const target = symlinkTargetMap . get ( asset . targetId )
if ( target ) {
return { originalId : id , currentId : target.id , type : target . type }
}
}
return { originalId : id , currentId : asset.id , type : asset . type }
})
// Find version stacks to resolve to their latest child
const versionStackIds = Array . from (
new Set (
intermediate
. filter (( item ) => item . type === AssetType . version_stack )
. map (( item ) => item . currentId ),
),
)
const latestChildByParent = new Map < string , string >()
if ( versionStackIds . length > 0 ) {
const children = await this . prismaClient . asset . findMany ({
where : { parentId : { in : versionStackIds }, isDeleted : false },
select : { id : true , parentId : true , sortIndex : true },
orderBy : { sortIndex : 'asc' },
})
for ( const child of children ) {
if ( child . parentId && ! latestChildByParent . has ( child . parentId )) {
latestChildByParent . set ( child . parentId , child . id )
}
}
}
return intermediate . map (( item ) => {
if ( item . type === AssetType . version_stack ) {
const childId = latestChildByParent . get ( item . currentId )
if ( childId ) return childId
}
return item . currentId
})
}
2026-05-19 16:05:09 +08:00
async updateAssetName ( req : UpdateAssetNameRequest ) : Promise < AssetInfo > {
2026-08-15 16:18:11 +08:00
const existing = await this . prismaClient . asset . findUnique ({
where : { id : req.id },
include : { target : true },
})
if ( ! existing ) throw new Error ( 'Asset not found' )
let targetType = existing . type
let targetId = existing . id
if ( existing . type === AssetType . symlink && existing . target ) {
targetType = existing . target . type
targetId = existing . target . id
}
if ( targetType === AssetType . version_stack ) {
const latestChild = await this . prismaClient . asset . findFirst ({
where : { parentId : targetId , isDeleted : false },
orderBy : { sortIndex : 'asc' },
select : { id : true },
})
if ( ! latestChild ) {
throw new Error ( 'No active version found in stack to rename' )
}
await this . prismaClient . asset . update ({
where : { id : latestChild.id },
data : { name : req.name },
})
} else {
await this . prismaClient . asset . update ({
where : { id : req.id },
data : { name : req.name },
})
}
const asset = await this . prismaClient . asset . findUnique ({
2026-05-19 16:05:09 +08:00
where : { id : req.id },
include : {
creator : true ,
metadataValues : true ,
target : {
include : {
creator : true ,
metadataValues : true ,
2026-05-25 00:52:45 +08:00
storageKey : true ,
2026-05-19 16:05:09 +08:00
children : {
2026-07-21 11:19:20 +08:00
where : { isDeleted : false },
2026-05-25 00:52:45 +08:00
include : { creator : true , metadataValues : true , storageKey : true },
2026-05-19 16:05:09 +08:00
take : 3 ,
orderBy : { sortIndex : 'asc' },
},
},
},
children : {
2026-07-21 11:19:20 +08:00
where : { isDeleted : false },
2026-05-25 00:52:45 +08:00
include : { creator : true , metadataValues : true , storageKey : true },
2026-05-19 16:05:09 +08:00
take : 3 ,
orderBy : { sortIndex : 'asc' },
},
2026-05-25 00:52:45 +08:00
storageKey : true ,
2026-05-19 16:05:09 +08:00
},
})
2026-08-15 16:18:11 +08:00
if ( ! asset ) throw new Error ( 'Asset not found' )
2026-05-25 10:14:22 +08:00
const infos = await this . toAssetInfos ([ asset as unknown as AssetWithIncludes ])
2026-05-22 15:39:46 +08:00
return infos [ 0 ]
2026-05-19 16:05:09 +08:00
}
async updateAssetOrder ( id : string , req : UpdateAssetOrderRequest ) : Promise < AssetInfo > {
const asset = await this . prismaClient . asset . findUnique ({
where : { id },
})
if ( ! asset ) throw new Error ( 'Asset not found' )
let afterSortIndex : string | null = null
let beforeSortIndex : string | null = null
if ( req . beforeIndex ) {
beforeSortIndex = req . beforeIndex
const prevAsset = await this . prismaClient . asset . findFirst ({
where : {
parentId : asset.parentId ,
sortIndex : { lt : req.beforeIndex },
id : { not : id },
},
orderBy : { sortIndex : 'desc' },
})
afterSortIndex = prevAsset ? . sortIndex || null
} else if ( req . afterIndex ) {
afterSortIndex = req . afterIndex
2026-06-15 20:25:49 +08:00
const nextAsset = await this . prismaClient . asset . findFirst ({
where : {
parentId : asset.parentId ,
sortIndex : { gt : req.afterIndex },
id : { not : id },
},
orderBy : { sortIndex : 'asc' },
})
beforeSortIndex = nextAsset ? . sortIndex || null
2026-05-19 16:05:09 +08:00
}
const newSortIndex = generateKeyBetween ( afterSortIndex , beforeSortIndex )
await this . prismaClient . asset . update ({
where : { id },
data : { sortIndex : newSortIndex },
})
return this . getAsset ({ assetId : id })
}
async deleteAssets ( ids : string []) : Promise < void > {
for ( const id of ids ) {
await this . prismaClient . $transaction ( async ( tx ) => {
const a = await tx . asset . findUnique ({
where : { id },
include : { project : { include : { team : true } } },
})
if ( ! a ) throw new Error ( 'Asset not found' )
if ( ! a . parentId ) throw new Error ( 'Asset has no parent' )
await tx . asset . update ({
where : { id : a.parentId },
data : { fileCount : { decrement : 1 } },
})
const rows = await tx . $queryRaw < { id : string }[] > `
WITH RECURSIVE descendant AS (
SELECT id, parent_id FROM assets WHERE parent_id = ${ a . id }
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
SELECT id FROM descendant;
`
const descendantIds = rows . map (( r ) => r . id )
if ( descendantIds . length > 0 ) {
await tx . asset . updateMany ({
where : { id : { in : descendantIds } },
2026-05-23 23:26:43 +08:00
data : { isDeleted : true },
2026-05-19 16:05:09 +08:00
})
}
2026-08-26 21:04:38 +08:00
const allDeletedIds = [ a . id , ... descendantIds ]
const symlinks = await tx . asset . findMany ({
where : {
targetId : { in : allDeletedIds },
isDeleted : false ,
type : AssetType . symlink ,
},
})
if ( symlinks . length > 0 ) {
await tx . asset . updateMany ({
where : { id : { in : symlinks . map (( s ) => s . id ) } },
data : {
isDeleted : true ,
status : AssetStatus.trashed ,
deletedAt : new Date (),
},
})
const parentCounts = new Map < string , number >()
for ( const s of symlinks ) {
if ( s . parentId ) {
parentCounts . set ( s . parentId , ( parentCounts . get ( s . parentId ) || 0 ) + 1 )
}
}
for ( const [ parentId , count ] of parentCounts . entries ()) {
await tx . asset . update ({
where : { id : parentId },
data : { fileCount : { decrement : count } },
})
}
}
2026-05-19 16:05:09 +08:00
await tx . asset . update ({
where : { id : a.id },
2026-05-23 23:26:43 +08:00
data : {
isDeleted : true ,
status : 'trashed' ,
deletedAt : new Date (),
},
2026-05-19 16:05:09 +08:00
})
2026-07-29 20:14:23 +08:00
await this . updateAncestorsSize ( tx , a . parentId , - Number ( a . sizeByte ))
2026-05-19 16:05:09 +08:00
})
}
}
2026-06-11 16:40:21 +08:00
private async cascadeStatusToPendingPurge ( rootIds : string []) : Promise < void > {
if ( rootIds . length === 0 ) return
2026-09-19 10:40:49 +08:00
const rows = await this . prismaClient . $queryRaw < { id : string }[] > `
2026-06-11 16:40:21 +08:00
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ANY( ${ rootIds } )
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
2026-08-26 21:04:38 +08:00
),
all_purging_targets AS (
SELECT id FROM descendant
),
all_affected_symlinks AS (
SELECT s.id FROM assets s
WHERE s.type = 'symlink' AND s.target_id IN (SELECT id FROM all_purging_targets)
2026-06-11 16:40:21 +08:00
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
2026-09-19 10:40:49 +08:00
WHERE id IN (SELECT id FROM all_purging_targets) OR id IN (SELECT id FROM all_affected_symlinks)
RETURNING id;
2026-06-11 16:40:21 +08:00
`
2026-09-19 10:40:49 +08:00
const affectedIds = rows . map (( r ) => r . id )
if ( affectedIds . length > 0 ) {
const inFlightTasks = await this . prismaClient . workflowTask . findMany ({
where : {
assetId : { in : affectedIds },
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
},
select : { id : true },
})
for ( const task of inFlightTasks ) {
try {
logger . info ({ taskId : task.id }, 'Cancelling in-flight workflow task for purging asset' )
await cancelWorkflowTask ( task . id )
} catch ( err ) {
logger . warn ({ taskId : task.id , err }, 'Failed to cancel workflow task during purge' )
}
}
2026-10-23 16:44:52 +08:00
await this . prismaClient . workflowTask . updateMany ({
where : {
assetId : { in : affectedIds },
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
},
data : {
status : WorkflowTaskStatus.failed ,
output : { error : 'Asset was purged' },
},
})
2026-09-19 10:40:49 +08:00
}
2026-06-11 16:40:21 +08:00
}
2026-06-11 16:19:35 +08:00
async emptyTrash ( projectId : string ) : Promise < void > {
const trashedRoots = await this . prismaClient . asset . findMany ({
where : {
projectId ,
isDeleted : true ,
},
select : { id : true },
})
2026-06-11 16:40:21 +08:00
const rootIds = trashedRoots . map (( r ) => r . id )
await this . cascadeStatusToPendingPurge ( rootIds )
2026-06-11 16:19:35 +08:00
await this . purgePendingAssets ()
await this . purgeUnreferencedStorageKeys ()
}
2026-05-23 23:57:46 +08:00
private cleanupJobsRunning = false
2026-05-25 09:57:46 +08:00
async startCleanupJob() {
2026-11-18 15:58:57 +08:00
if ( this . cleanupJobsRunning ) return
2026-05-23 23:57:46 +08:00
this . cleanupJobsRunning = true
2026-11-18 15:58:57 +08:00
let nextGeneratedCleanupAt = 0
2026-05-23 23:57:46 +08:00
2026-05-25 09:57:46 +08:00
const runCleanup = async () => {
2026-05-23 23:57:46 +08:00
if ( ! this . cleanupJobsRunning ) return
2026-05-25 09:57:46 +08:00
2026-05-23 18:09:30 +08:00
try {
2026-05-23 23:26:43 +08:00
await this . expireTrashedAssets ()
await this . purgePendingAssets ()
2026-05-25 00:52:45 +08:00
await this . purgeUnreferencedStorageKeys ()
2026-08-07 21:36:20 +08:00
await watermarkService . purgeOrphanWatermarkConfigs ()
2026-11-18 15:58:57 +08:00
const now = Date . now ()
if ( now >= nextGeneratedCleanupAt ) {
nextGeneratedCleanupAt = now + 60 * 60 * 1000
await this . purgeExpiredGeneratedFiles ()
}
2026-05-25 00:52:45 +08:00
} catch ( e : unknown ) {
2026-05-25 09:57:46 +08:00
console . error ( 'Error in asset cleanup job:' , e )
}
if ( this . cleanupJobsRunning ) {
setTimeout ( runCleanup , 5000 ) // Run every 5 seconds after previous run completion
2026-05-25 00:52:45 +08:00
}
}
2026-05-25 09:57:46 +08:00
runCleanup ()
2026-05-23 18:09:30 +08:00
}
2026-05-23 23:57:46 +08:00
stopCleanupJob() {
this . cleanupJobsRunning = false
}
2026-05-23 23:26:43 +08:00
/**
* Stage 1: Find root assets that have been in the trash for > 30 days.
* Cascade the 'pending_purge' status to all their descendants.
*/
private async expireTrashedAssets() {
2026-09-19 11:36:14 +08:00
const thirtyDaysAgo = new Date ( Date . now () - TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000 )
2026-05-23 18:09:30 +08:00
2026-05-23 23:57:46 +08:00
// Find up to 100 expired roots, ordered by oldest first to avoid starvation
2026-05-23 23:26:43 +08:00
const expiredRoots = await this . prismaClient . asset . findMany ({
where : {
isDeleted : true ,
2026-09-19 10:40:49 +08:00
status : { not : AssetStatus.pending_purge },
deletedAt : { lt : thirtyDaysAgo },
2026-05-23 23:26:43 +08:00
},
2026-05-23 23:57:46 +08:00
orderBy : { deletedAt : 'asc' },
2026-05-23 23:26:43 +08:00
select : { id : true },
take : 100 ,
})
2026-06-11 16:40:21 +08:00
const rootIds = expiredRoots . map (( r ) => r . id )
await this . cascadeStatusToPendingPurge ( rootIds )
2026-05-23 23:26:43 +08:00
}
/**
2026-05-25 09:57:46 +08:00
* Stage 2: Delete DB records for assets marked as 'pending_purge'.
2026-05-23 23:26:43 +08:00
*/
private async purgePendingAssets() {
2026-09-19 10:40:49 +08:00
const pendingAssets = await this . prismaClient . asset . findMany ({
where : { status : AssetStatus.pending_purge },
select : { id : true },
})
const pendingAssetIds = pendingAssets . map (( a ) => a . id )
if ( pendingAssetIds . length > 0 ) {
const inFlightTasks = await this . prismaClient . workflowTask . findMany ({
where : {
assetId : { in : pendingAssetIds },
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
},
select : { id : true },
})
for ( const task of inFlightTasks ) {
try {
logger . info ({ taskId : task.id }, 'Cancelling in-flight workflow task before purge' )
await cancelWorkflowTask ( task . id )
} catch ( err ) {
logger . warn ({ taskId : task.id , err }, 'Failed to cancel workflow task during purge' )
}
}
2026-10-23 16:44:52 +08:00
await this . prismaClient . workflowTask . updateMany ({
where : {
assetId : { in : pendingAssetIds },
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
},
data : {
status : WorkflowTaskStatus.failed ,
output : { error : 'Asset was purged' },
},
2026-09-19 10:40:49 +08:00
})
}
2026-05-25 09:57:46 +08:00
const { count } = await this . prismaClient . asset . deleteMany ({
where : { status : AssetStatus.pending_purge },
})
2026-05-24 09:24:44 +08:00
2026-05-25 09:57:46 +08:00
if ( count > 0 ) {
2026-05-24 09:24:44 +08:00
logger . info (
2026-05-24 09:40:53 +08:00
{
2026-05-25 09:57:46 +08:00
purgedCount : count ,
2026-05-24 09:40:53 +08:00
},
2026-05-25 09:57:46 +08:00
` ${ count } assets purged from database` ,
2026-05-25 00:52:45 +08:00
)
}
}
/**
* Stage 3: Garbage Collection - Physically delete files and StorageKey records
* that have no associated logical assets.
*/
private async purgeUnreferencedStorageKeys() {
const bucket = process . env . S3_BUCKET || 'shumai'
// 1. Find storage keys with no associated assets and older than 24 hours
2026-05-25 09:57:46 +08:00
// using FOR UPDATE SKIP LOCKED to ensure multiple servers don't pick up the same keys.
2026-11-03 20:31:56 +08:00
const lockedKeys = await this . prismaClient . $queryRaw <
{ id : string ; key : string ; isArchived : boolean }[]
> `
2026-05-25 09:57:46 +08:00
WITH to_purge AS (
2026-05-25 10:04:32 +08:00
SELECT id FROM storage_keys sk
WHERE NOT EXISTS (SELECT 1 FROM assets a WHERE a.storage_key_id = sk.id)
2026-05-25 22:22:08 +08:00
AND sk.created_at < NOW() - INTERVAL '20 seconds'
2026-05-25 09:57:46 +08:00
AND (sk.status = 'active' OR (sk.status = 'purging' AND sk.updated_at < NOW() - INTERVAL '1 hour'))
LIMIT 100
FOR UPDATE SKIP LOCKED
)
UPDATE storage_keys SET status = 'purging', updated_at = NOW()
WHERE id IN (SELECT id FROM to_purge)
2026-11-03 20:31:56 +08:00
RETURNING id, key, is_archived AS "isArchived";
2026-05-25 09:57:46 +08:00
`
2026-05-25 00:52:45 +08:00
2026-05-25 09:57:46 +08:00
if ( lockedKeys . length === 0 ) return
2026-05-25 00:52:45 +08:00
2026-05-25 09:57:46 +08:00
let physicalFilesDeleted = 0
let purgedCount = 0
2026-11-03 20:31:56 +08:00
const archiveEnabled = isArchiveStorageEnabled ()
2026-05-25 09:57:46 +08:00
for ( const sk of lockedKeys ) {
2026-05-25 00:52:45 +08:00
try {
2026-11-03 20:31:56 +08:00
if ( sk . isArchived && ! archiveEnabled ) {
logger . warn (
{ storageKeyId : sk.id , key : sk.key },
'Skipping purge of archived storage key because archive storage is not configured' ,
)
await this . prismaClient . storageKey . update ({
where : { id : sk.id },
data : { status : 'active' },
})
continue
}
// Physically delete proxies (and unarchived original) from main storage
2026-05-25 00:52:45 +08:00
const parts = sk . key . split ( '/' )
if ( parts . length > 2 ) {
const prefix = parts . slice ( 0 , parts . length - 1 ). join ( '/' ) + '/'
const count = await s3Service . deletePrefix ( bucket , prefix )
physicalFilesDeleted += count
} else {
const count = await s3Service . deleteObject ( bucket , sk . key )
physicalFilesDeleted += count
}
2026-11-03 20:31:56 +08:00
// Also delete original raw file from archive storage when archive storage is separate
if ( archiveEnabled ) {
const archiveStorage = getArchiveStorageService ()
if ( ! archiveStorage . isSameS3Target ) {
const archiveDeleted = await archiveStorage . deleteObject ( sk . key )
physicalFilesDeleted += archiveDeleted
}
}
2026-05-25 00:52:45 +08:00
// Delete from database
await this . prismaClient . storageKey . delete ({
where : { id : sk.id },
})
purgedCount ++
} catch ( e : unknown ) {
logger . error (
{ key : sk.key , error : e instanceof Error ? e.message : String ( e ) },
'Failed to purge unreferenced storage key' ,
)
}
}
if ( purgedCount > 0 ) {
logger . info (
{ purgedCount , physicalFilesDeleted },
`Garbage collection: purged ${ purgedCount } storage keys and ${ physicalFilesDeleted } physical files` ,
2026-05-24 09:24:44 +08:00
)
2026-05-23 19:06:23 +08:00
}
2026-05-23 18:09:30 +08:00
}
2026-11-18 15:58:57 +08:00
private async purgeExpiredGeneratedFiles ( retentionMs = 24 * 60 * 60 * 1000 ) {
const bucket = process . env . S3_BUCKET || 'shumai'
const keys = await s3Service . listObjects ( bucket , 'temp/generated/' )
if ( keys . length === 0 ) return
const now = Date . now ()
for ( const key of keys ) {
try {
const parts = key . split ( '/' )
const idSegment = parts [ 2 ]
let createdAtMs : number | null = null
if ( idSegment && /^[0-9A-HJKMNP-TV-Z]{26}$/i . test ( idSegment )) {
try {
createdAtMs = decodeTime ( idSegment . toUpperCase ())
} catch {
createdAtMs = null
}
}
if ( createdAtMs === null ) {
const info = await s3Service . headObject ( bucket , key )
createdAtMs = info . lastModified . getTime ()
}
if ( now - createdAtMs > retentionMs ) {
await s3Service . deleteObject ( bucket , key )
}
} catch ( err ) {
logger . warn ({ err , key }, 'Failed to purge expired generated file' )
}
}
}
2026-05-19 16:05:09 +08:00
async restoreAssets ( ids : string []) : Promise < void > {
for ( const id of ids ) {
await this . prismaClient . $transaction ( async ( tx ) => {
const a = await tx . asset . findUnique ({
where : { id },
2026-11-03 20:31:56 +08:00
include : { project : { include : { team : true } }, storageKey : true },
2026-05-19 16:05:09 +08:00
})
if ( ! a ) throw new Error ( 'Asset not found' )
if ( ! a . parentId ) throw new Error ( 'Asset has no parent' )
await tx . asset . update ({
where : { id : a.parentId },
data : { fileCount : { increment : 1 } },
})
const rows = await tx . $queryRaw < { id : string }[] > `
WITH RECURSIVE descendant AS (
SELECT id, parent_id FROM assets WHERE parent_id = ${ a . id }
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
SELECT id FROM descendant;
`
const descendantIds = rows . map (( r ) => r . id )
if ( descendantIds . length > 0 ) {
await tx . asset . updateMany ({
where : { id : { in : descendantIds } },
2026-11-03 20:31:56 +08:00
data : { isDeleted : false , deletedAt : null },
})
await tx . asset . updateMany ({
where : {
id : { in : descendantIds },
type : AssetType . file ,
status : AssetStatus.trashed ,
storageKey : { isArchived : true },
},
data : { status : AssetStatus.archived },
})
await tx . asset . updateMany ({
where : {
id : { in : descendantIds },
type : AssetType . file ,
status : AssetStatus.trashed ,
storageKey : { isArchived : false },
},
data : { status : AssetStatus.processed },
2026-05-19 16:05:09 +08:00
})
}
2026-08-26 21:04:38 +08:00
const allRestoredIds = [ a . id , ... descendantIds ]
const symlinks = await tx . asset . findMany ({
where : {
targetId : { in : allRestoredIds },
isDeleted : true ,
type : AssetType . symlink ,
},
})
if ( symlinks . length > 0 ) {
await tx . asset . updateMany ({
where : { id : { in : symlinks . map (( s ) => s . id ) } },
data : {
isDeleted : false ,
status : AssetStatus.processed ,
deletedAt : null ,
},
})
const parentCounts = new Map < string , number >()
for ( const s of symlinks ) {
if ( s . parentId ) {
parentCounts . set ( s . parentId , ( parentCounts . get ( s . parentId ) || 0 ) + 1 )
}
}
for ( const [ parentId , count ] of parentCounts . entries ()) {
await tx . asset . update ({
where : { id : parentId },
data : { fileCount : { increment : count } },
})
}
}
2026-11-03 20:31:56 +08:00
const activeArchiveTask = await tx . workflowTask . findFirst ({
where : {
assetId : a.id ,
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
type : {
in : [ WorkflowTaskType . archive_asset , WorkflowTaskType . restore_asset ],
},
},
})
2026-09-19 10:40:49 +08:00
const activeTask = await tx . workflowTask . findFirst ({
where : {
assetId : a.id ,
status : { in : [ WorkflowTaskStatus . pending , WorkflowTaskStatus . processing ] },
type : {
in : [
WorkflowTaskType . transcode ,
WorkflowTaskType . transcode_video ,
WorkflowTaskType . transcode_image ,
WorkflowTaskType . transcode_pdf ,
WorkflowTaskType . transcode_pdf_pages ,
WorkflowTaskType . transcode_screenshot ,
WorkflowTaskType . transcode_image_annotation ,
WorkflowTaskType . transcode_watermark ,
],
},
},
})
2026-11-03 20:31:56 +08:00
let restoredStatus : AssetStatus = AssetStatus . processed
if ( activeArchiveTask ? . type === WorkflowTaskType . archive_asset ) {
restoredStatus = AssetStatus . archiving
} else if ( activeArchiveTask ? . type === WorkflowTaskType . restore_asset ) {
restoredStatus = AssetStatus . restoring
} else if ( activeTask ) {
restoredStatus = AssetStatus . processing
} else if ( a . type === AssetType . file && a . storageKey ? . isArchived ) {
restoredStatus = AssetStatus . archived
}
2026-05-19 16:05:09 +08:00
await tx . asset . update ({
where : { id : a.id },
2026-05-23 23:26:43 +08:00
data : {
isDeleted : false ,
2026-11-03 20:31:56 +08:00
status : restoredStatus ,
2026-05-23 23:26:43 +08:00
deletedAt : null ,
},
2026-05-19 16:05:09 +08:00
})
2026-07-29 20:14:23 +08:00
await this . updateAncestorsSize ( tx , a . parentId , Number ( a . sizeByte ))
2026-05-19 16:05:09 +08:00
})
}
}
2026-10-27 14:37:26 +08:00
/**
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
* further agent runs.
*/
async createComment (
req : CreateCommentRequest ,
options : { triggerAgents? : boolean } = {},
) : Promise < CommentInfo > {
const triggerAgents = options . triggerAgents ?? true
2026-05-19 16:05:09 +08:00
let commentId = ''
2026-05-22 15:39:46 +08:00
const resolvedAssetId = await this . resolveLatestVersionId ( req . assetId )
2026-05-19 16:05:09 +08:00
await this . prismaClient . $transaction ( async ( tx ) => {
const a = await tx . asset . findUnique ({
2026-05-22 15:39:46 +08:00
where : { id : resolvedAssetId },
2026-05-19 16:05:09 +08:00
include : { project : { include : { team : true } } },
})
if ( ! a ) throw new Error ( 'Asset not found' )
2026-05-22 10:57:55 +08:00
let actualReplyToId = req . replyToId
let parentComment = null
if ( req . replyToId ) {
parentComment = await tx . assetComment . findUnique ({
where : { id : req.replyToId },
include : { creator : true },
})
if ( parentComment ? . replyToId ) {
actualReplyToId = parentComment . replyToId
}
}
2026-05-19 16:05:09 +08:00
const comment = await tx . assetComment . create ({
data : {
assetId : a.id ,
creatorId : req.userId ,
message : req.message ,
annotation : req.annotations ,
second : req.second ,
2026-05-22 10:57:55 +08:00
replyToId : actualReplyToId ,
2026-05-19 16:05:09 +08:00
},
})
commentId = comment . id
for ( const attachmentId of req . attachmentIds ) {
const attachmentAsset = await tx . asset . findUnique ({
where : { id : attachmentId },
})
2026-11-05 20:49:38 +08:00
if (
attachmentAsset &&
( attachmentAsset . type === AssetType . attachment ||
attachmentAsset . type === AssetType . file ) &&
attachmentAsset . projectId === a . projectId
) {
2026-05-19 16:05:09 +08:00
await tx . assetCommentAttachment . create ({
data : {
assetId : attachmentAsset.id ,
commentId : comment.id ,
},
})
}
}
2026-10-27 14:37:26 +08:00
if ( ! triggerAgents ) return
2026-05-21 22:51:40 +08:00
// Parse bot mentions
const botMentionMatches = [... req . message . matchAll ( /<@([^>]+)>/g )]
const mentionedAgentIds = new Set ( botMentionMatches . map (( match ) => match [ 1 ]))
const handledAgentIds = new Set < string >()
2026-05-19 16:05:09 +08:00
2026-08-16 15:44:45 +08:00
// Effective role for the project context (project override wins; project-
// scoped members without project access resolve to null and are denied).
const effectiveRole = a . project ? . team
? await resolveEffectiveRole ( a . project . team . id , a . project . id , req . userId , tx )
2026-08-16 11:16:14 +08:00
: null
2026-08-16 15:44:45 +08:00
const userLevel = getRoleLevel ( effectiveRole )
2026-08-16 11:16:14 +08:00
2026-05-22 10:57:55 +08:00
if ( parentComment && a . project ) {
const rootSessionId = parentComment . sessionId
const isRootAgent = !! rootSessionId || parentComment . creator ? . type === 'agent'
const rootAgentId = parentComment . creatorId
2026-05-21 22:51:40 +08:00
2026-07-27 14:49:41 +08:00
if ( isRootAgent && rootAgentId && mentionedAgentIds . has ( rootAgentId )) {
2026-08-16 11:16:14 +08:00
const rootAgent = await tx . agent . findUnique ({ where : { id : rootAgentId } })
const requiredLevel = getAgentRequiredLevel ( rootAgent ? . permission )
if ( userLevel >= requiredLevel ) {
await tx . workflowTask . create ({
data : {
assetId : a.id ,
type : 'chat' ,
status : 'pending' ,
teamId : a.project.team.id ,
2026-05-21 22:51:40 +08:00
projectId : a.project.id ,
2026-08-16 11:16:14 +08:00
payload : {
projectId : a.project.id ,
agent : {
userCommentId : comment.id ,
agentId : rootAgentId ,
sessionId : rootSessionId || undefined ,
userId : req.userId ,
},
2026-05-28 09:48:05 +08:00
},
2026-05-21 22:51:40 +08:00
},
2026-08-16 11:16:14 +08:00
})
}
2026-05-21 22:51:40 +08:00
handledAgentIds . add ( rootAgentId )
}
}
// Handle any other explicitly mentioned agents
for ( const agentId of mentionedAgentIds ) {
if ( handledAgentIds . has ( agentId )) continue
let foundAgent = false
2026-05-19 16:05:09 +08:00
if ( agentId === 'default' ) {
foundAgent = true
} else {
const agent = await tx . agent . findUnique ({ where : { id : agentId } })
2026-08-16 11:16:14 +08:00
if ( agent ) {
const requiredLevel = getAgentRequiredLevel ( agent . permission )
if ( userLevel >= requiredLevel ) {
foundAgent = true
}
}
2026-05-19 16:05:09 +08:00
}
if ( foundAgent && a . project ) {
await tx . workflowTask . create ({
data : {
assetId : a.id ,
type : 'chat' ,
status : 'pending' ,
teamId : a.project.team.id ,
projectId : a.project.id ,
payload : {
projectId : a.project.id ,
2026-05-28 09:48:05 +08:00
agent : {
userCommentId : comment.id ,
agentId : agentId ,
2026-05-30 18:42:55 +08:00
userId : req.userId ,
2026-05-28 09:48:05 +08:00
},
2026-05-19 16:05:09 +08:00
},
},
})
2026-05-21 22:51:40 +08:00
handledAgentIds . add ( agentId )
2026-05-19 16:05:09 +08:00
}
}
})
2026-09-14 15:01:36 +08:00
return this . getComment ( commentId , req . userId )
2026-05-19 16:05:09 +08:00
}
2026-09-14 15:01:36 +08:00
async getComment ( commentId : string , requestingUserId? : string ) : Promise < CommentInfo > {
2026-05-19 16:05:09 +08:00
const c = await this . prismaClient . assetComment . findUnique ({
where : { id : commentId },
include : {
creator : true ,
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true ,
2026-05-25 00:52:45 +08:00
asset : { include : { storageKey : true } },
attachments : { include : { asset : { include : { storageKey : true } } } },
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true , name : true } },
},
orderBy : { createdAt : 'asc' },
},
2026-05-19 16:05:09 +08:00
replies : {
include : {
creator : true ,
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true ,
2026-05-25 00:52:45 +08:00
attachments : { include : { asset : { include : { storageKey : true } } } },
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true , name : true } },
},
orderBy : { createdAt : 'asc' },
},
2026-05-19 16:05:09 +08:00
},
orderBy : { id : 'asc' },
},
},
})
if ( ! c ) throw new Error ( 'Comment not found' )
2026-09-14 15:01:36 +08:00
return this . toCommentInfo ( c , requestingUserId )
}
async addCommentReaction ( commentId : string , userId : string , code : string ) : Promise < void > {
const comment = await this . prismaClient . assetComment . findUnique ({
where : { id : commentId },
select : { id : true },
})
if ( ! comment ) throw new Error ( 'Comment not found' )
await this . prismaClient . assetCommentReaction . upsert ({
where : {
// eslint-disable-next-line @typescript-eslint/naming-convention
commentId_userId_code : {
commentId ,
userId ,
code ,
},
},
create : {
commentId ,
userId ,
code ,
},
update : {},
})
}
async removeCommentReaction ( commentId : string , userId : string , code : string ) : Promise < void > {
await this . prismaClient . assetCommentReaction . deleteMany ({
where : {
commentId ,
userId ,
code ,
},
})
2026-05-19 16:05:09 +08:00
}
2026-07-06 12:24:40 +08:00
async completeComment (
commentId : string ,
isCompleted : boolean ,
userId : string ,
) : Promise < CommentInfo > {
await this . prismaClient . assetComment . update ({
where : { id : commentId },
data : {
isCompleted ,
completionLastChangedById : userId ,
},
})
2026-09-14 15:01:36 +08:00
return this . getComment ( commentId , userId )
2026-07-06 12:24:40 +08:00
}
2026-07-16 09:55:05 +08:00
async deleteComment ({ commentId , userId } : { commentId : string ; userId : string }) : Promise < void > {
const comment = await this . prismaClient . assetComment . findUnique ({
where : { id : commentId },
include : {
2026-07-16 10:17:32 +08:00
attachments : {
include : {
asset : {
include : {
storageKey : true ,
},
},
},
},
2026-07-16 09:55:05 +08:00
asset : {
select : {
project : { select : { id : true , teamId : true } },
},
},
},
})
if ( ! comment ) {
throw new HTTPException ( 404 , { message : 'Comment not found' })
}
2026-07-16 10:17:32 +08:00
const teamId = comment . asset . project ? . teamId
2026-07-16 09:55:05 +08:00
if ( ! teamId ) {
2026-07-16 10:23:47 +08:00
throw new HTTPException ( 400 , {
message : 'Data corruption: Comment asset is not associated with a project' ,
})
2026-07-16 09:55:05 +08:00
}
const member = await this . prismaClient . teamMember . findUnique ({
where : {
teamIdUserId : {
teamId ,
userId ,
},
},
})
if ( ! member ) {
throw new HTTPException ( 403 , { message : 'User is not a member of the team' })
}
const isOwner = member . role === 'owner'
const isCreator = comment . creatorId === userId
if ( ! isOwner && ! isCreator ) {
throw new HTTPException ( 403 , { message : 'You do not have permission to delete this comment' })
}
2026-07-16 10:17:32 +08:00
// Clean up attachment files from S3/storage and delete their DB records
const bucket = process . env . S3_BUCKET || 'shumai'
for ( const att of comment . attachments ) {
const asset = att . asset
if ( asset . storageKey ) {
try {
2026-07-16 10:31:34 +08:00
await s3Service . deleteObject ( bucket , asset . storageKey . key )
2026-07-16 10:17:32 +08:00
} catch ( err ) {
logger . error ({ err , assetId : asset.id }, 'Failed to delete attachment file from S3' )
}
}
await this . prismaClient . asset . delete ({
where : { id : asset.id },
})
if ( asset . storageKey ) {
2026-07-16 10:23:47 +08:00
await this . prismaClient . storageKey
. delete ({
where : { id : asset.storageKey.id },
})
. catch (() => {
// Silently ignore if already deleted
})
2026-07-16 10:17:32 +08:00
}
}
2026-07-16 09:55:05 +08:00
await this . prismaClient . assetComment . delete ({
where : { id : commentId },
})
}
2026-05-19 16:05:09 +08:00
async listComments (
assetId : string ,
params : PaginationParams ,
2026-09-14 15:01:36 +08:00
requestingUserId? : string ,
2026-05-19 16:05:09 +08:00
) : Promise < PaginatedData < CommentInfo [] >> {
2026-05-22 15:39:46 +08:00
const resolvedAssetId = await this . resolveLatestVersionId ( assetId )
2026-05-19 16:05:09 +08:00
const { data : comments , pageInfo } = await paginateQuery (
async ( skip , take ) => {
return this . prismaClient . assetComment . findMany ({
2026-05-22 15:39:46 +08:00
where : { assetId : resolvedAssetId , replyToId : null },
2026-05-19 16:05:09 +08:00
include : {
creator : true ,
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true ,
2026-05-25 00:52:45 +08:00
asset : { include : { storageKey : true } },
attachments : { include : { asset : { include : { storageKey : true } } } },
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true , name : true } },
},
orderBy : { createdAt : 'asc' },
},
2026-05-19 16:05:09 +08:00
replies : {
include : {
creator : true ,
2026-07-06 12:24:40 +08:00
completionLastChangedBy : true ,
2026-05-25 00:52:45 +08:00
attachments : { include : { asset : { include : { storageKey : true } } } },
2026-09-14 15:01:36 +08:00
reactions : {
include : {
user : { select : { id : true , name : true } },
},
orderBy : { createdAt : 'asc' },
},
2026-05-19 16:05:09 +08:00
},
orderBy : { id : 'asc' },
},
},
skip ,
take ,
orderBy : { id : 'asc' },
})
},
2026-10-27 14:37:26 +08:00
async () =>
this . prismaClient . assetComment . count ({
where : { assetId : resolvedAssetId , replyToId : null },
}),
2026-05-19 16:05:09 +08:00
params ,
)
2026-09-14 15:01:36 +08:00
const infos = await Promise . all ( comments . map (( c ) => this . toCommentInfo ( c , requestingUserId )))
2026-05-19 16:05:09 +08:00
return { data : infos , pageInfo }
}
2026-09-13 14:48:41 +08:00
async exportComments (
assetId : string ,
format : CommentExportFormat ,
options? : ExportOptions ,
) : Promise < ExportResult > {
const resolvedAssetId = await this . resolveLatestVersionId ( assetId )
const asset = await this . prismaClient . asset . findUnique ({
where : { id : resolvedAssetId },
include : {
creator : true ,
},
})
if ( ! asset ) {
throw new HTTPException ( 404 , { message : 'Asset not found' })
}
const rawComments = await this . prismaClient . assetComment . findMany ({
where : { assetId : resolvedAssetId , replyToId : null },
include : {
creator : true ,
replies : {
include : {
creator : true ,
},
orderBy : { id : 'asc' },
},
},
orderBy : { id : 'asc' },
})
const comments : ExportCommentItem [] = await Promise . all (
rawComments . map ( async ( c ) => {
const creatorImage = c . creator ? await getAvatarUrl ( c . creator . image ) : null
const replies : ExportCommentItem [] = await Promise . all (
( c . replies || []). map ( async ( r ) => {
const replyCreatorImage = r . creator ? await getAvatarUrl ( r . creator . image ) : null
return {
id : r.id ,
message : r.message ,
second : r.second ,
createdAt : r.createdAt ,
isCompleted : r.isCompleted ,
creator : {
id : r.creator?.id || '' ,
name : r.creator?.name || 'Anonymous' ,
image : replyCreatorImage || null ,
},
annotations : r.annotation ,
}
}),
)
return {
id : c.id ,
message : c.message ,
second : c.second ,
createdAt : c.createdAt ,
isCompleted : c.isCompleted ,
creator : {
id : c.creator?.id || '' ,
name : c.creator?.name || 'Anonymous' ,
image : creatorImage || null ,
},
annotations : c.annotation ,
replies ,
}
}),
)
const media = asset . media as PrismaJson . MediaInfo | null
const fps = media ? . metadata ? . frameRate || 24
const duration = media ? . metadata ? . duration || 0
const totalFrames =
media ? . metadata ? . totalFrames || media ? . frames || Math . round ( duration * fps ) || 0
const width = media ? . metadata ? . originalWidth || 1920
const height = media ? . metadata ? . originalHeight || 1080
const startTimecode = media ? . metadata ? . startTimecode || null
const metadata : ExportAssetMetadata = {
id : asset.id ,
name : asset.name ,
fps ,
duration ,
totalFrames ,
width ,
height ,
startTimecode ,
rawMedia : media ,
}
return exportCommentsToFormat ( metadata , comments , format , options )
}
2026-09-17 11:51:03 +08:00
async toAssetInfos (
assets : AssetWithIncludes [],
previewFormat? : PreviewFormat ,
2026-09-19 11:36:14 +08:00
options ?: { includeDeletedChildren? : boolean },
2026-09-17 11:51:03 +08:00
) : Promise < AssetInfo [] > {
2026-09-19 11:36:14 +08:00
const includeDeletedChildren = options ? . includeDeletedChildren ?? false
2026-05-22 15:39:46 +08:00
const stackIds = new Set < string >()
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
for ( const a of assets ) {
if (
a . type === AssetType . version_stack ||
( a . type === AssetType . symlink && a . target ? . type === AssetType . version_stack )
) {
stackIds . add ( a . type === AssetType . symlink ? a . targetId ! : a . id )
2026-05-19 16:05:09 +08:00
}
2026-05-22 15:39:46 +08:00
const folderForPreview =
a . type === AssetType . symlink && a . target ? . type === AssetType . folder ? a.target : a
if (
( folderForPreview . type === AssetType . folder ||
folderForPreview . type === AssetType . share_root ||
folderForPreview . type === AssetType . share ) &&
'children' in folderForPreview &&
folderForPreview . children
) {
for ( const child of folderForPreview . children ) {
if ( child . type === AssetType . version_stack ) {
stackIds . add ( child . id )
2026-05-19 16:05:09 +08:00
}
}
}
}
2026-05-22 15:39:46 +08:00
const versionsMap = new Map < string , AssetWithIncludes [ 'children' ][ 0 ][] >()
if ( stackIds . size > 0 ) {
const allVersions = await this . prismaClient . asset . findMany ({
2026-09-19 11:36:14 +08:00
where : {
parentId : { in : Array . from ( stackIds ) },
...( includeDeletedChildren ? {} : { isDeleted : false }),
},
2026-09-04 11:27:52 +08:00
include : {
creator : true ,
agent : { include : { user : true } },
metadataValues : true ,
storageKey : true ,
},
2026-05-22 15:39:46 +08:00
})
for ( const v of allVersions ) {
const list = versionsMap . get ( v . parentId ! ) || []
list . push ( v )
versionsMap . set ( v . parentId ! , list )
2026-05-19 16:05:09 +08:00
}
2026-05-23 10:02:51 +08:00
for ( const list of versionsMap . values ()) {
list . sort (( x , y ) => {
if ( ! x . sortIndex || ! y . sortIndex ) return 0
return x . sortIndex < y . sortIndex ? - 1 : x.sortIndex > y . sortIndex ? 1 : 0
})
}
2026-05-19 16:05:09 +08:00
}
2026-08-15 10:25:46 +08:00
const agentMdRecords =
assets . length > 0
? await this . prismaClient . assetAgentMd . findMany ({
where : { assetId : { in : assets . map (( a ) => a . id ) } },
select : { assetId : true },
})
: []
const hasAgentMdSet = new Set ( agentMdRecords . map (( r ) => r . assetId ))
2026-09-13 21:12:21 +08:00
const commentTargetIds = new Set < string >()
for ( const a of assets ) {
if (
a . type === AssetType . version_stack ||
( a . type === AssetType . symlink && a . target ? . type === AssetType . version_stack )
) {
const stackId = a . type === AssetType . symlink ? a . targetId ! : a . id
const versions = versionsMap . get ( stackId ) || []
if ( versions . length > 0 ) {
commentTargetIds . add ( versions [ 0 ]. id )
} else {
commentTargetIds . add ( stackId )
}
} else if ( a . type === AssetType . symlink && a . target ) {
commentTargetIds . add ( a . target . id )
} else {
commentTargetIds . add ( a . id )
}
}
const commentCounts =
commentTargetIds . size > 0
? await this . prismaClient . assetComment . groupBy ({
by : [ 'assetId' ],
where : {
assetId : { in : Array . from ( commentTargetIds ) },
},
_count : { _all : true },
})
: []
const commentCountMap = new Map ( commentCounts . map (( c ) => [ c . assetId , c . _count . _all ]))
2026-05-22 15:39:46 +08:00
const result : AssetInfo [] = []
for ( const a of assets ) {
let latestVersion :
| AssetWithIncludes
| AssetWithIncludes [ 'children' ][ 0 ]
| NonNullable < AssetWithIncludes [ 'target' ] > = a
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
let versionStack : AssetInfo [ 'versionStack' ] = null
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
if (
a . type === AssetType . version_stack ||
( a . type === AssetType . symlink && a . target ? . type === AssetType . version_stack )
) {
const stackId = a . type === AssetType . symlink ? a . targetId ! : a . id
const versions = versionsMap . get ( stackId ) || []
if ( versions . length > 0 ) {
2026-05-23 10:02:51 +08:00
latestVersion = versions [ 0 ]
2026-05-22 15:39:46 +08:00
versionStack = {
id : stackId ,
2026-05-23 10:02:51 +08:00
versions : await Promise . all (
versions . map ( async ( v , i ) => {
2026-09-17 11:51:03 +08:00
const preview = await this . toPreviewInfo ( v as Asset , previewFormat )
2026-05-23 10:02:51 +08:00
return {
version : versions.length - i ,
current : i === 0 ,
id : v.id ,
name : v.name ,
2026-11-03 20:31:56 +08:00
status : v.status ,
2026-05-23 10:02:51 +08:00
previewUrl : preview?.thumbnailUrl || null ,
2026-08-15 15:37:17 +08:00
createdAt : v.createdAt.toISOString (),
2026-06-03 19:56:07 +08:00
creator : v.creator
? {
id : v.creator.id ,
name : v.creator.name ,
image : await getAvatarUrl ( v . creator . image ),
}
: null ,
2026-09-04 11:27:52 +08:00
agent : v.agent
? {
id : v.agent.id ,
name : v.agent.user.name ,
}
: null ,
2026-05-23 10:02:51 +08:00
}
}),
),
2026-05-22 15:39:46 +08:00
}
}
} else if ( a . type === AssetType . symlink ) {
if ( a . target ) {
latestVersion = a . target
2026-05-19 16:05:09 +08:00
}
}
2026-05-22 15:39:46 +08:00
const latestChildren : ChildPreview [] = []
const folderForPreview =
a . type === AssetType . symlink && a . target ? . type === AssetType . folder ? a.target : a
if (
( folderForPreview . type === AssetType . folder ||
folderForPreview . type === AssetType . share_root ||
folderForPreview . type === AssetType . share ) &&
'children' in folderForPreview &&
folderForPreview . children
) {
for ( const child of folderForPreview . children ) {
2026-09-19 11:36:14 +08:00
if ( ! includeDeletedChildren && child . isDeleted ) continue
2026-05-22 15:39:46 +08:00
let previewAsset = child as Asset
let mediaType = child . mediaType
2026-05-19 16:05:09 +08:00
2026-05-22 15:39:46 +08:00
if ( child . type === AssetType . version_stack ) {
const versions = versionsMap . get ( child . id ) || []
if ( versions . length > 0 ) {
2026-05-23 10:02:51 +08:00
const latestChild = versions [ 0 ]
2026-05-22 15:39:46 +08:00
previewAsset = latestChild as Asset
mediaType = latestChild . mediaType
}
}
latestChildren . push ({
type : mediaType ,
2026-09-17 11:51:03 +08:00
preview : await this . toPreviewInfo ( previewAsset , previewFormat ),
2026-05-22 15:39:46 +08:00
})
}
}
2026-09-17 11:51:03 +08:00
const preview = await this . toPreviewInfo ( latestVersion as Asset , previewFormat )
2026-05-22 15:39:46 +08:00
const creator = latestVersion . creator
2026-06-03 19:56:07 +08:00
? {
id : latestVersion.creator.id ,
name : latestVersion.creator.name ,
image : await getAvatarUrl ( latestVersion . creator . image ),
}
2026-05-22 15:39:46 +08:00
: null
2026-09-04 11:27:52 +08:00
const agent = latestVersion . agent
? {
id : latestVersion.agent.id ,
name : latestVersion.agent.user.name ,
}
: null
2026-05-22 15:39:46 +08:00
const fieldValues : FieldValueInfo [] = []
if ( 'metadataValues' in latestVersion && latestVersion . metadataValues ) {
for ( const mv of latestVersion . metadataValues ) {
let value : unknown = null
if ( mv . jsonValue !== null ) {
value = mv . jsonValue
} else if ( mv . dateValue !== null ) {
value = mv . dateValue . toISOString ()
} else if ( mv . stringValue !== null ) {
value = mv . stringValue
} else if ( mv . numberValue !== null ) {
value = mv . numberValue
} else if ( mv . booleanValue !== null ) {
value = mv . booleanValue
}
2026-05-28 12:24:38 +08:00
fieldValues . push ({ fieldId : mv.fieldKey , value })
2026-05-22 15:39:46 +08:00
}
}
2026-11-03 20:31:56 +08:00
const isOriginalUnavailable =
latestVersion . status === AssetStatus . archiving ||
latestVersion . status === AssetStatus . archived ||
latestVersion . status === AssetStatus . restoring ||
Boolean ( latestVersion . storageKey ? . isArchived )
let media = latestVersion . media
? ( structuredClone ( latestVersion . media ) as PrismaJson . MediaInfo )
: null
2026-05-22 15:39:46 +08:00
if ( media && media . videoPreview ? . key ) {
media . videoPreview . url = await s3Service . presign (
process . env . S3_BUCKET || 'shumai' ,
media . videoPreview . key ,
'GET' ,
)
}
2026-07-19 21:19:43 +08:00
if ( media && media . pdfTranscode ? . key ) {
2026-11-03 20:31:56 +08:00
if ( isOriginalUnavailable && media . pdfTranscode . key === latestVersion . storageKey ? . key ) {
delete media . pdfTranscode . url
} else {
media . pdfTranscode . url = await s3Service . presign (
process . env . S3_BUCKET || 'shumai' ,
media . pdfTranscode . key ,
'GET' ,
)
}
2026-07-19 21:19:43 +08:00
}
2026-09-30 16:31:40 +08:00
if ( media && media . isHls && media . hls ? . key ) {
media . hls . url = `/api/files/ ${ latestVersion . id } /m3u8/master.m3u8`
}
2026-05-22 15:39:46 +08:00
2026-05-25 00:52:45 +08:00
const key = latestVersion . storageKey ? . key
2026-07-02 15:26:10 +08:00
if ( key ) {
if ( ! media ) {
media = {
original : null ,
videoTranscodes : [],
imageTranscodes : [],
} as unknown as PrismaJson . MediaInfo
}
2026-05-25 00:52:45 +08:00
media . original = {
key ,
2026-07-29 20:14:23 +08:00
filesizeInBytes : Number ( latestVersion . sizeByte ),
2026-07-02 15:26:10 +08:00
codec : '' ,
2026-05-25 00:52:45 +08:00
}
}
2026-10-11 21:32:28 +08:00
const proxyType = ( media ? . proxyType || null ) as
2026-10-22 20:25:54 +08:00
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
2026-07-19 21:19:43 +08:00
2026-05-22 15:39:46 +08:00
result . push ({
id : a.id ,
name :
2026-08-15 15:37:17 +08:00
a.type === AssetType . version_stack ||
( a . type === AssetType . symlink && a . target ? . type === AssetType . version_stack )
2026-05-22 15:39:46 +08:00
? latestVersion.name
2026-08-15 15:37:17 +08:00
: a.type === AssetType . symlink
? a . name || latestVersion . name || a . target ? . name || ''
: a . name ,
2026-07-29 20:14:23 +08:00
sizeByte : Number ( latestVersion . sizeByte ),
2026-05-22 15:39:46 +08:00
fileCount : latestVersion.fileCount ,
type : a . type ,
targetType : a.type === AssetType . symlink ? a.target?.type : null ,
status : latestVersion.status ,
2026-07-19 21:19:43 +08:00
proxyType ,
2026-05-22 15:39:46 +08:00
latestChildren ,
preview ,
2026-11-23 16:40:12 +08:00
createdAt : latestVersion.createdAt.toISOString (),
updatedAt : latestVersion.updatedAt.toISOString (),
2026-05-22 15:39:46 +08:00
deletedAt : a.deletedAt ? a . deletedAt . toISOString () : null ,
2026-06-21 12:35:12 +08:00
projectId : a.projectId ,
2026-05-22 15:39:46 +08:00
creator ,
2026-09-04 11:27:52 +08:00
agentId : latestVersion.agentId ?? null ,
agent ,
2026-05-22 15:39:46 +08:00
fieldValues ,
sortIndex : a.sortIndex ,
2026-08-15 10:25:46 +08:00
hasAgentsMd : hasAgentMdSet.has ( a . id ),
2026-09-13 21:12:21 +08:00
commentsCount : commentCountMap.get ( latestVersion . id ) ?? 0 ,
2026-05-22 15:39:46 +08:00
media : media as unknown as AssetInfo [ 'media' ],
versionStack ,
})
2026-05-19 16:05:09 +08:00
}
2026-05-22 15:39:46 +08:00
return result
2026-05-19 16:05:09 +08:00
}
2026-05-23 10:02:51 +08:00
async getStackVersions ( stackId : string ) : Promise <
Array < {
id : string
version : number
name : string
2026-11-03 20:31:56 +08:00
status : AssetStatus
2026-05-23 10:02:51 +08:00
previewUrl : string | null
2026-08-15 15:37:17 +08:00
createdAt : string
creator : { id : string ; name : string | null ; image? : string | null } | null
2026-09-04 11:27:52 +08:00
agent ?: { id : string ; name : string } | null
2026-05-23 10:02:51 +08:00
} >
> {
const versions = await this . prismaClient . asset . findMany ({
2026-05-23 23:26:43 +08:00
where : { parentId : stackId , isDeleted : false },
2026-09-04 11:27:52 +08:00
include : { creator : true , agent : { include : { user : true } } },
2026-05-23 10:02:51 +08:00
})
versions . sort (( x , y ) => {
if ( ! x . sortIndex || ! y . sortIndex ) return 0
return x . sortIndex < y . sortIndex ? - 1 : x.sortIndex > y . sortIndex ? 1 : 0
})
return await Promise . all (
versions . map ( async ( v , i ) => {
const preview = await this . toPreviewInfo ( v )
return {
id : v.id ,
version : versions.length - i ,
name : v.name ,
2026-11-03 20:31:56 +08:00
status : v.status ,
2026-05-23 10:02:51 +08:00
previewUrl : preview?.thumbnailUrl || null ,
2026-08-15 15:37:17 +08:00
createdAt : v.createdAt.toISOString (),
2026-06-03 19:56:07 +08:00
creator : v.creator
? {
id : v.creator.id ,
name : v.creator.name ,
image : await getAvatarUrl ( v . creator . image ),
}
: null ,
2026-09-04 11:27:52 +08:00
agent : v.agent
? {
id : v.agent.id ,
name : v.agent.user.name ,
}
: null ,
2026-05-23 10:02:51 +08:00
}
}),
)
}
2026-06-11 13:08:29 +08:00
async getProjectIds ( assetIds : string []) : Promise < string [] > {
2026-06-11 13:06:01 +08:00
if ( assetIds . length === 0 ) {
2026-06-11 13:08:29 +08:00
return []
2026-06-11 13:06:01 +08:00
}
const assets = await this . prismaClient . asset . findMany ({
where : { id : { in : assetIds }, isDeleted : false },
select : {
2026-09-17 11:51:03 +08:00
id : true ,
2026-06-11 13:06:01 +08:00
projectId : true ,
type : true ,
target : { select : { projectId : true } },
},
})
const projectIds = new Set < string >()
for ( const asset of assets ) {
let projId = asset . projectId
if ( asset . type === 'symlink' && asset . target ? . projectId ) {
projId = asset . target . projectId
}
2026-09-17 11:51:03 +08:00
if ( ! projId ) {
try {
const ctx = await this . getAssetContext ( asset . id )
if ( ctx . projectId ) {
projId = ctx . projectId
}
} catch {
// ignore if no team/project context
}
}
2026-06-11 13:06:01 +08:00
if ( projId ) {
projectIds . add ( projId )
}
}
2026-06-11 13:08:29 +08:00
return Array . from ( projectIds )
2026-06-11 13:06:01 +08:00
}
2026-11-03 20:31:56 +08:00
async getDownloadLinks ( ids : string []) : Promise < {
files : Array < { id : string ; name : string ; url : string } >
skippedArchivedCount : number
} > {
if ( ids . length === 0 ) return { files : [], skippedArchivedCount : 0 }
2026-06-11 13:08:29 +08:00
// Resolve starting IDs (dereference top-level symlinks)
const assets = await this . prismaClient . asset . findMany ({
where : { id : { in : ids }, isDeleted : false },
select : {
id : true ,
type : true ,
targetId : true ,
},
})
const startingIds = assets . map (( asset ) => {
if ( asset . type === 'symlink' && asset . targetId ) {
return asset . targetId
}
return asset . id
})
2026-11-03 20:31:56 +08:00
if ( startingIds . length === 0 ) return { files : [], skippedArchivedCount : 0 }
2026-06-11 11:44:26 +08:00
const descendants = await this . prismaClient . $queryRaw <
Array < {
id : string
name : string
type : string
2026-11-03 20:31:56 +08:00
status : string
2026-06-11 11:44:26 +08:00
parentId : string | null
storageKeyId : string | null
sortIndex : string | null
targetId : string | null
} >
> `
WITH RECURSIVE descendant AS (
2026-11-03 20:31:56 +08:00
SELECT id, name, type, status::text AS status, parent_id, storage_key_id, sort_index, target_id, is_deleted
2026-06-11 11:44:26 +08:00
FROM assets
WHERE id IN ( ${ Prisma . join ( startingIds ) } ) AND is_deleted = false
UNION ALL
2026-11-03 20:31:56 +08:00
SELECT a.id, a.name, a.type, a.status::text AS status, a.parent_id, a.storage_key_id, a.sort_index, a.target_id, a.is_deleted
2026-06-11 11:44:26 +08:00
FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
WHERE a.is_deleted = false
)
2026-11-03 20:31:56 +08:00
SELECT id, name, type, status, parent_id AS "parentId", storage_key_id AS "storageKeyId", sort_index AS "sortIndex", target_id AS "targetId" FROM descendant;
2026-06-11 11:44:26 +08:00
`
// Find any symlink in the descendants and resolve its target.
const symlinks = descendants . filter (( d ) => d . type === 'symlink' )
let resolvedTargets : Array < {
id : string
name : string
type : string
2026-11-03 20:31:56 +08:00
status : string
2026-06-11 11:44:26 +08:00
parentId : string | null
storageKeyId : string | null
sortIndex : string | null
targetId : string | null
} > = []
if ( symlinks . length > 0 ) {
const targetIds = symlinks . map (( s ) => s . targetId ). filter (( id ) : id is string => !! id )
if ( targetIds . length > 0 ) {
const dbTargets = await this . prismaClient . asset . findMany ({
where : { id : { in : targetIds }, isDeleted : false },
})
resolvedTargets = dbTargets . map (( t ) => ({
id : t.id ,
name : t.name ,
type : t . type ,
2026-11-03 20:31:56 +08:00
status : t.status ,
2026-06-11 11:44:26 +08:00
parentId : t.parentId ,
storageKeyId : t.storageKeyId ,
sortIndex : t.sortIndex ,
targetId : t.targetId ,
}))
}
}
const allAssets = [... descendants . filter (( d ) => d . type !== 'symlink' ), ... resolvedTargets ]
const nonFolderAssets = allAssets . filter (
( a ) =>
a . type !== 'folder' && a . type !== 'root' && a . type !== 'share_root' && a . type !== 'share' ,
)
// Separate version stacks and other files
const versionStackIds = new Set (
nonFolderAssets . filter (( a ) => a . type === 'version_stack' ). map (( a ) => a . id ),
)
const versionAssetsByStack = new Map < string , typeof nonFolderAssets >()
const otherAssets : typeof nonFolderAssets = []
for ( const asset of nonFolderAssets ) {
if ( asset . type === 'version_stack' ) {
continue
}
if ( asset . parentId && versionStackIds . has ( asset . parentId )) {
const list = versionAssetsByStack . get ( asset . parentId ) || []
list . push ( asset )
versionAssetsByStack . set ( asset . parentId , list )
} else {
otherAssets . push ( asset )
}
}
// Pick the latest version for each version stack (ascending sortIndex: 'asc' means first version is latest)
const latestVersions : typeof nonFolderAssets = []
for ( const versions of versionAssetsByStack . values ()) {
versions . sort (( x , y ) => {
if ( ! x . sortIndex || ! y . sortIndex ) return 0
return x . sortIndex < y . sortIndex ? - 1 : x.sortIndex > y . sortIndex ? 1 : 0
})
if ( versions . length > 0 ) {
latestVersions . push ( versions [ 0 ])
}
}
const finalFiles = [... otherAssets , ... latestVersions ]
// Deduplicate files by id
const uniqueFilesMap = new Map < string , ( typeof finalFiles )[ 0 ] >()
for ( const file of finalFiles ) {
uniqueFilesMap . set ( file . id , file )
}
const deduplicatedFiles = Array . from ( uniqueFilesMap . values ())
// Fetch storage keys
const storageKeyIds = deduplicatedFiles
. map (( f ) => f . storageKeyId )
. filter (( id ) : id is string => !! id )
const storageKeys = await this . prismaClient . storageKey . findMany ({
where : { id : { in : storageKeyIds } },
})
2026-11-03 20:31:56 +08:00
const storageKeyMap = new Map ( storageKeys . map (( k ) => [ k . id , k ]))
let skippedArchivedCount = 0
2026-06-11 11:44:26 +08:00
const downloadLinks = await Promise . all (
deduplicatedFiles . map ( async ( file ) => {
2026-11-03 20:31:56 +08:00
const sk = file . storageKeyId ? storageKeyMap . get ( file . storageKeyId ) : null
if ( ! sk ? . key ) return null
const isArchivedOrTransitioning =
file . status === AssetStatus . archiving ||
file . status === AssetStatus . archived ||
file . status === AssetStatus . restoring ||
sk . isArchived
if ( isArchivedOrTransitioning ) {
skippedArchivedCount ++
return null
}
2026-06-11 11:44:26 +08:00
2026-08-09 16:39:15 +08:00
const url = await s3Service . presign (
process . env . S3_BUCKET || 'shumai' ,
2026-11-03 20:31:56 +08:00
sk . key ,
2026-08-09 16:39:15 +08:00
'GET' ,
true ,
file . name ,
)
2026-06-11 11:44:26 +08:00
return {
id : file.id ,
name : file.name ,
url ,
}
}),
)
2026-11-03 20:31:56 +08:00
const filteredLinks = downloadLinks . filter (
( link ) : link is { id : string ; name : string ; url : string } => !! link ,
)
return {
files : filteredLinks ,
skippedArchivedCount ,
}
2026-06-11 11:44:26 +08:00
}
2026-11-05 09:57:34 +08:00
async getStoragePaths ( ids : string []) : Promise < GetStoragePathsResponse > {
if ( ids . length === 0 ) return { paths : [] }
const targetAssetIds = await this . resolveLatestVersionIds ( ids )
const uniqueTargetIds = Array . from ( new Set ( targetAssetIds ))
const assets = await this . prismaClient . asset . findMany ({
where : {
id : { in : uniqueTargetIds },
isDeleted : false ,
type : {
notIn : [ AssetType . folder , AssetType . root , AssetType . share_root , AssetType . share ],
},
},
select : {
id : true ,
name : true ,
status : true ,
storageKey : {
select : {
key : true ,
isArchived : true ,
},
},
},
})
const defaultBackend = getStorageBackend ()
const mainBucket = process . env . S3_BUCKET || 'shumai'
const paths : StoragePathItem [] = []
for ( const asset of assets ) {
const sk = asset . storageKey
if ( ! sk ? . key ) continue
const isArchived =
asset . status === AssetStatus . archived ||
asset . status === AssetStatus . archiving ||
asset . status === AssetStatus . restoring ||
sk . isArchived
const archivePathInfo = isArchived ? getArchiveStoragePath ( sk . key ) : null
if ( archivePathInfo ) {
paths . push ({
id : asset.id ,
name : asset.name ,
path : archivePathInfo.path ,
backend : archivePathInfo.backend ,
isArchived : true ,
})
} else {
const storagePath = s3Service . getStoragePath ( mainBucket , sk . key )
paths . push ({
id : asset.id ,
name : asset.name ,
path : storagePath ,
backend : defaultBackend ,
isArchived ,
})
}
}
return { paths }
}
2026-07-02 15:26:10 +08:00
/**
* Generate a presigned download URL for a given key, verifying it belongs to the asset's
* storage directory. This ensures users can only download files (original, transcodes, etc.)
* that belong to an asset they have access to.
*/
async getDownloadUrl ( assetId : string , key : string ) : Promise < string > {
2026-08-07 23:24:24 +08:00
const targetAssetId = await this . resolveLatestVersionId ( assetId )
2026-07-02 15:26:10 +08:00
const asset = await this . prismaClient . asset . findUnique ({
2026-08-07 23:24:24 +08:00
where : { id : targetAssetId },
2026-11-03 20:31:56 +08:00
select : {
id : true ,
name : true ,
status : true ,
parentId : true ,
storageKey : { select : { key : true , isArchived : true } },
},
2026-07-02 15:26:10 +08:00
})
if ( ! asset ? . storageKey ? . key ) {
throw new Error ( 'Asset not found or has no storage key' )
}
2026-08-07 23:24:24 +08:00
if ( key . includes ( '..' )) {
throw new Error ( 'Key does not belong to this asset' )
}
let storageKey = asset . storageKey . key
let assetDir = storageKey . substring ( 0 , storageKey . lastIndexOf ( '/' ) + 1 )
2026-09-18 23:14:54 +08:00
let targetName = asset . name
2026-11-03 20:31:56 +08:00
let targetStatus = asset . status
let targetIsArchived = asset . storageKey . isArchived
2026-08-07 23:24:24 +08:00
if ( ! key . startsWith ( assetDir ) && asset . parentId ) {
// Check if requested key belongs to another version in the same version stack
const sibling = await this . prismaClient . asset . findFirst ({
where : {
parentId : asset.parentId ,
isDeleted : false ,
storageKey : { key : { startsWith : key.substring ( 0 , key . lastIndexOf ( '/' ) + 1 ) } },
},
2026-11-03 20:31:56 +08:00
select : {
name : true ,
status : true ,
storageKey : { select : { key : true , isArchived : true } },
},
2026-08-07 23:24:24 +08:00
})
if ( sibling ? . storageKey ? . key ) {
storageKey = sibling . storageKey . key
assetDir = storageKey . substring ( 0 , storageKey . lastIndexOf ( '/' ) + 1 )
2026-11-03 20:31:56 +08:00
targetStatus = sibling . status
targetIsArchived = sibling . storageKey . isArchived
2026-09-18 23:14:54 +08:00
if ( sibling . name ) {
targetName = sibling . name
}
2026-08-07 23:24:24 +08:00
}
}
if ( ! key . startsWith ( assetDir )) {
2026-07-02 15:26:10 +08:00
throw new Error ( 'Key does not belong to this asset' )
}
2026-11-03 20:31:56 +08:00
if ( key === storageKey ) {
if (
targetStatus === AssetStatus . archiving ||
targetStatus === AssetStatus . archived ||
targetStatus === AssetStatus . restoring ||
targetIsArchived
) {
throw new HTTPException ( 409 , {
message : 'Original file is archived. Restore the asset to download the original file.' ,
})
}
}
2026-09-18 23:14:54 +08:00
let downloadFilename : string | undefined
if ( key === storageKey ) {
downloadFilename = targetName ?? undefined
} else {
const keyBasename = path . posix . basename ( key )
const originalStem = stemFromKey ( storageKey )
const assetStem = targetName ? stemFromKey ( targetName ) : originalStem
if (
originalStem &&
assetStem &&
originalStem !== assetStem &&
keyBasename . startsWith ( originalStem + '-' )
) {
downloadFilename = assetStem + keyBasename . slice ( originalStem . length )
} else if (
originalStem &&
assetStem &&
originalStem !== assetStem &&
keyBasename . startsWith ( 'watermark-' + originalStem + '-' )
) {
downloadFilename =
'watermark-' + assetStem + keyBasename . slice (( 'watermark-' + originalStem ). length )
} else {
downloadFilename = keyBasename
}
}
return s3Service . presign ( process . env . S3_BUCKET || 'shumai' , key , 'GET' , true , downloadFilename )
2026-07-02 15:26:10 +08:00
}
2026-11-04 14:40:44 +08:00
async archiveAssets (
assetIds : string [],
options ?: {
suppressBusyErrors? : boolean
autoArchivePolicy ?: {
method : 'not_updated' | 'after_created'
cutoffDate : Date
restoreCutoffDate : Date
}
},
) : Promise < ArchiveAssetsResponse > {
return assetArchiveService . archiveAssets ( assetIds , options )
2026-11-03 20:31:56 +08:00
}
async restoreArchivedAssets ( assetIds : string []) : Promise < RestoreArchivedAssetsResponse > {
return assetArchiveService . restoreArchivedAssets ( assetIds )
}
2026-09-17 11:51:03 +08:00
async toPreviewInfo (
asset : Asset | AssetWithIncludes ,
previewFormat? : PreviewFormat ,
) : Promise < PreviewInfo | null > {
2026-05-19 16:05:09 +08:00
if ( ! asset . media ) return null
2026-10-11 21:32:28 +08:00
const proxyType = ( asset . media ? . proxyType || null ) as
2026-10-22 20:25:54 +08:00
'image' | 'video' | 'audio' | 'pdf' | '3d' | null
2026-07-20 10:22:36 +08:00
2026-09-17 11:51:03 +08:00
let rawThumbKey : string | undefined
2026-07-20 10:22:36 +08:00
if ( proxyType === 'image' && asset . media . thumbnail ? . key ) {
2026-09-17 11:51:03 +08:00
rawThumbKey = asset . media . thumbnail . key
2026-07-18 10:41:28 +08:00
} else if ( asset . media . poster ? . key ) {
2026-09-17 11:51:03 +08:00
rawThumbKey = asset . media . poster . key
}
let thumbnailUrl = undefined
if ( rawThumbKey ) {
const bucket = process . env . S3_BUCKET || 'shumai'
let finalKey = rawThumbKey
if ( previewFormat === 'jpeg' && isWebpKey ( rawThumbKey )) {
const targetJpegKey = getJpegKeyForWebp ( rawThumbKey )
if ( asset . hasJpegPreview ) {
finalKey = targetJpegKey
} else {
try {
await ensureJpegInStorage ( bucket , rawThumbKey , targetJpegKey )
await this . prismaClient . asset . update ({
where : { id : asset.id },
data : { hasJpegPreview : true },
})
asset . hasJpegPreview = true
finalKey = targetJpegKey
} catch ( err ) {
logger . warn (
{ err , assetId : asset.id , rawThumbKey },
'Failed to ensure JPEG preview for asset, falling back to WebP' ,
)
finalKey = rawThumbKey
}
}
}
thumbnailUrl = await s3Service . presign ( bucket , finalKey , 'GET' )
2026-05-19 16:05:09 +08:00
}
let spriteUrl = undefined
if ( asset . media . sprite ? . key ) {
spriteUrl = await s3Service . presign (
process . env . S3_BUCKET || 'shumai' ,
asset . media . sprite . key ,
'GET' ,
)
}
return {
2026-07-19 21:19:43 +08:00
proxyType ,
2026-05-19 16:05:09 +08:00
thumbnailUrl ,
originalHeight : asset.media.metadata?.originalHeight ,
originalWidth : asset.media.metadata?.originalWidth ,
spriteUrl ,
2026-10-11 21:32:28 +08:00
duration : proxyType === '3d' ? undefined : asset . media . metadata ? . duration ,
2026-07-18 10:32:38 +08:00
pageCount : asset.media.metadata?.totalFrames ,
2026-05-19 16:05:09 +08:00
}
}
private async toCommentInfo (
c : CommentWithIncludes | CommentWithIncludes [ 'replies' ][ 0 ],
2026-09-14 15:01:36 +08:00
requestingUserId? : string ,
2026-05-19 16:05:09 +08:00
) : Promise < CommentInfo > {
const replies : CommentInfo [] = []
if ( 'replies' in c && c . replies ) {
for ( const r of c . replies ) {
2026-09-14 15:01:36 +08:00
replies . push ( await this . toCommentInfo ( r , requestingUserId ))
2026-05-19 16:05:09 +08:00
}
}
const attachments : AttachmentInfo [] = []
if ( c . attachments ) {
for ( const a of c . attachments ) {
2026-05-25 00:52:45 +08:00
if ( a . asset ? . storageKey ? . key ) {
const url = await s3Service . presign (
process . env . S3_BUCKET || 'shumai' ,
a . asset . storageKey . key ,
'GET' ,
)
2026-07-20 10:22:36 +08:00
const attachmentProxyType = ( a . asset . media ? . proxyType || null ) as
2026-10-22 20:25:54 +08:00
'image' | 'video' | 'audio' | 'pdf' | null
2026-05-19 16:05:09 +08:00
attachments . push ({
id : a.id ,
assetId : a.asset.id ,
url ,
2026-07-20 10:22:36 +08:00
proxyType : attachmentProxyType ,
2026-05-19 16:05:09 +08:00
})
}
}
}
2026-06-01 23:08:58 +08:00
const mentions : AssetUserInfo [] = []
2026-05-19 16:05:09 +08:00
const botMentionMatch = ( c . message || '' ). match ( /<@([^>]+)>/g )
if ( botMentionMatch ) {
const userIds = botMentionMatch . map (( m : string ) => m . replace ( '<@' , '' ). replace ( '>' , '' ))
const users = await this . prismaClient . user . findMany ({
where : { id : { in : userIds } },
})
for ( const u of users ) {
2026-06-03 19:56:07 +08:00
mentions . push ({
id : u.id ,
name : u.name ,
image : await getAvatarUrl ( u . image ),
})
2026-05-19 16:05:09 +08:00
}
}
2026-06-01 23:08:58 +08:00
const creator : AssetUserInfo = { id : '' , name : '' }
2026-05-21 14:58:31 +08:00
if ( c . sessionId ) {
2026-05-19 16:05:09 +08:00
creator . id = c . creatorId || ''
creator . name = c . creator ? . name || 'Ai Bot'
2026-06-03 19:56:07 +08:00
creator . image = await getAvatarUrl ( c . creator ? . image )
2026-05-19 16:05:09 +08:00
} else if ( c . creator ) {
creator . id = c . creator . id
creator . name = c . creator . name
2026-06-03 19:56:07 +08:00
creator . image = await getAvatarUrl ( c . creator . image )
2026-05-19 16:05:09 +08:00
}
2026-07-06 12:24:40 +08:00
const completionLastChangedBy : AssetUserInfo | null = c . completionLastChangedBy
? {
id : c.completionLastChangedBy.id ,
name : c.completionLastChangedBy.name ,
image : await getAvatarUrl ( c . completionLastChangedBy . image ),
}
: null
2026-09-14 15:01:36 +08:00
const reactionsMap = new Map <
string ,
{
count : number
requestingUserReacted : boolean
creatorNames : string []
firstCreatedAt : Date
}
> ()
if ( 'reactions' in c && c . reactions ) {
for ( const reaction of c . reactions ) {
let entry = reactionsMap . get ( reaction . code )
if ( ! entry ) {
entry = {
count : 0 ,
requestingUserReacted : false ,
creatorNames : [],
firstCreatedAt : reaction.createdAt ,
}
reactionsMap . set ( reaction . code , entry )
}
entry . count ++
if ( requestingUserId && reaction . userId === requestingUserId ) {
entry . requestingUserReacted = true
} else {
const userName = reaction . user ? . name || 'User'
if ( ! entry . creatorNames . includes ( userName )) {
entry . creatorNames . push ( userName )
}
}
}
}
const reactionCounts : CommentReactionCount [] = Array . from ( reactionsMap . entries ())
. sort (( a , b ) => a [ 1 ]. firstCreatedAt . getTime () - b [ 1 ]. firstCreatedAt . getTime ())
. map (([ code , data ]) => ({
code ,
count : data.count ,
requestingUserReacted : data.requestingUserReacted ,
creatorNames : data.creatorNames ,
}))
2026-05-19 16:05:09 +08:00
return {
id : c.id ,
assetId : c.assetId ,
message : c.message ,
annotations : c.annotation ,
2026-05-27 11:17:56 +08:00
second : c.second ,
2026-05-19 16:05:09 +08:00
creator ,
replies ,
attachments ,
mentions ,
createdAt : c.createdAt.toISOString (),
updatedAt : c.updatedAt.toISOString (),
2026-05-21 14:58:31 +08:00
sessionId : c.sessionId ,
2026-07-06 12:24:40 +08:00
isCompleted : c.isCompleted ,
completionLastChangedBy ,
2026-09-14 15:01:36 +08:00
reactionCounts ,
2026-05-19 16:05:09 +08:00
}
}
2026-08-15 10:25:46 +08:00
async getAgentsMd ( assetId : string ) : Promise < string | null > {
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
select : { type : true },
})
if ( ! asset ) throw new Error ( 'Asset not found' )
if ( asset . type !== AssetType . folder && asset . type !== AssetType . root ) {
throw new Error ( 'AGENTS.md can only be stored on folders' )
}
const record = await this . prismaClient . assetAgentMd . findUnique ({
where : { assetId },
select : { content : true },
})
return record ? . content ?? null
}
async updateAgentsMd ( assetId : string , content : string ) : Promise < { content : string } > {
const asset = await this . prismaClient . asset . findUnique ({
where : { id : assetId },
select : { id : true , type : true },
})
if ( ! asset ) throw new Error ( 'Asset not found' )
if ( asset . type !== AssetType . folder && asset . type !== AssetType . root ) {
throw new Error ( 'AGENTS.md can only be stored on folders' )
}
const trimmed = content . trim ()
if ( trimmed . length === 0 ) {
await this . prismaClient . assetAgentMd . deleteMany ({
where : { assetId },
})
return { content : '' }
}
const record = await this . prismaClient . assetAgentMd . upsert ({
where : { assetId },
create : { assetId , content },
update : { content },
select : { content : true },
})
return { content : record.content }
}
async getNestedAgentsMd ( assetId : string ) : Promise < Array < { path : string ; content : string }> > {
let currentId : string | null = assetId
const nodes : Array < {
id : string
name : string
type : AssetType
parentId : string | null
} > = []
while ( currentId ) {
const node : {
id : string
name : string
type : AssetType
parentId : string | null
} | null = await this . prismaClient . asset . findUnique ({
where : { id : currentId },
select : { id : true , name : true , type : true , parentId : true },
})
if ( ! node ) break
nodes . unshift ( node )
currentId = node . parentId
}
if ( nodes . length === 0 ) return []
const agentMds = await this . prismaClient . assetAgentMd . findMany ({
where : { assetId : { in : nodes . map (( n ) => n . id ) } },
select : { assetId : true , content : true },
})
const agentMdMap = new Map ( agentMds . map (( m ) => [ m . assetId , m . content ]))
const results : Array < { path : string ; content : string } > = []
let currentFolderPath = ''
for ( let i = 0 ; i < nodes . length ; i ++ ) {
const node = nodes [ i ]
let virtualPath : string
if ( node . type === AssetType . root || i === 0 ) {
currentFolderPath = ''
virtualPath = '/AGENTS.md'
} else {
currentFolderPath = currentFolderPath
? ` ${ currentFolderPath } / ${ node . name } `
: `/ ${ node . name } `
virtualPath = ` ${ currentFolderPath } /AGENTS.md`
}
const content = agentMdMap . get ( node . id )
if ( content && content . trim (). length > 0 ) {
results . push ({
path : virtualPath ,
content : content.trim (),
})
}
}
return results
}
2026-08-25 18:51:24 +08:00
/**
* Record a file view by user in project.
* If the asset is a child file in a version stack, resolves to the version stack.
* Enforces a maximum cap of 100 recent file items per (userId, projectId).
*/
async recordRecentView ( userId : string , projectId : string , assetId : string ) : Promise < void > {
const asset = await this . prismaClient . asset . findFirst ({
where : { id : assetId , projectId },
select : {
id : true ,
type : true ,
parentId : true ,
isDeleted : true ,
target : { select : { type : true , projectId : true , isDeleted : true } },
},
})
if ( ! asset || asset . isDeleted ) return
const isFileAsset =
asset . type === AssetType . file ||
asset . type === AssetType . version_stack ||
( asset . type === AssetType . symlink &&
asset . target !== null &&
( asset . target . type === AssetType . file || asset . target . type === AssetType . version_stack ) &&
asset . target . projectId === projectId &&
! asset . target . isDeleted )
if ( ! isFileAsset ) return
let targetAssetId = asset . id
// If it's a file inside a version stack, record the version stack instead
if ( asset . type === AssetType . file && asset . parentId ) {
const parent = await this . prismaClient . asset . findFirst ({
where : { id : asset.parentId , projectId , type : AssetType . version_stack , isDeleted : false },
select : { id : true },
})
if ( parent ) {
targetAssetId = parent . id
}
}
const now = new Date ()
// Upsert into recent_file_items
await this . prismaClient . recentFileItem . upsert ({
where : {
userIdProjectIdAssetId : {
userId ,
projectId ,
assetId : targetAssetId ,
},
},
update : {
viewedAt : now ,
},
create : {
userId ,
projectId ,
assetId : targetAssetId ,
viewedAt : now ,
},
})
// Prune if more than 100 items for this (userId, projectId)
const count = await this . prismaClient . recentFileItem . count ({
where : { userId , projectId },
})
if ( count > 100 ) {
const itemsToKeep = await this . prismaClient . recentFileItem . findMany ({
where : { userId , projectId },
orderBy : [{ viewedAt : 'desc' }, { id : 'desc' }],
take : 100 ,
select : { id : true },
})
const keepIds = itemsToKeep . map (( item ) => item . id )
await this . prismaClient . recentFileItem . deleteMany ({
where : {
userId ,
projectId ,
id : { notIn : keepIds },
},
})
}
}
/**
* List recent files for user in project, paginated up to 100 total items.
*/
async listRecents (
userId : string ,
projectId : string ,
req : ListRecentsRequest ,
) : Promise < PaginatedData < AssetInfo [] >> {
const where = {
userId ,
projectId ,
asset : {
isDeleted : false ,
projectId ,
},
}
return paginateQuery (
async ( skip , take ) => {
if ( skip >= 100 ) return []
const effectiveTake = Math . min ( take , 100 - skip )
if ( effectiveTake <= 0 ) return []
const recents = await this . prismaClient . recentFileItem . findMany ({
where ,
orderBy : [{ viewedAt : 'desc' }, { id : 'desc' }],
skip ,
take : effectiveTake ,
include : {
asset : {
include : assetInclude ,
},
},
})
const assets = recents . map (( r ) => r . asset ). filter (( a ) : a is AssetWithIncludes => !! a )
return await this . toAssetInfos ( assets )
},
async () => {
const total = await this . prismaClient . recentFileItem . count ({ where })
return Math . min ( total , 100 )
},
req ,
)
}
2026-09-30 16:31:40 +08:00
async getHlsMasterPlaylist ( params : {
assetId : string
watermarkConfigId? : string | null
}) : Promise < string > {
const bucket = process . env . S3_BUCKET || 'shumai'
const targetAssetId = await this . resolveLatestVersionId ( params . assetId )
if ( params . watermarkConfigId ) {
const wf = await this . prismaClient . watermarkFile . findUnique ({
where : {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId : {
assetId : targetAssetId ,
watermarkConfigId : params.watermarkConfigId ,
},
},
})
const media = wf ? . media as PrismaJson . MediaInfo | null
if ( ! media ? . isHls || ! media . hls ? . key ) {
throw new HTTPException ( 404 , { message : 'HLS playlist not found' })
}
const obj = await s3Service . getObject ( bucket , media . hls . key )
return obj . buffer . toString ( 'utf-8' )
}
const asset = await this . prismaClient . asset . findUnique ({
where : { id : targetAssetId },
})
if ( ! asset ) {
throw new HTTPException ( 404 , { message : 'Asset not found' })
}
const media = asset . media as PrismaJson . MediaInfo | null
if ( ! media ? . isHls || ! media . hls ? . key ) {
throw new HTTPException ( 404 , { message : 'HLS playlist not found' })
}
const obj = await s3Service . getObject ( bucket , media . hls . key )
return obj . buffer . toString ( 'utf-8' )
}
async getHlsVariantPlaylist ( params : {
assetId : string
resolution : string
watermarkConfigId? : string | null
}) : Promise < string > {
const bucket = process . env . S3_BUCKET || 'shumai'
if ( ! /^\d+p$/ . test ( params . resolution )) {
throw new HTTPException ( 400 , { message : 'Invalid resolution format' })
}
const targetAssetId = await this . resolveLatestVersionId ( params . assetId )
let media : PrismaJson.MediaInfo | null
if ( params . watermarkConfigId ) {
const wf = await this . prismaClient . watermarkFile . findUnique ({
where : {
// eslint-disable-next-line @typescript-eslint/naming-convention
assetId_watermarkConfigId : {
assetId : targetAssetId ,
watermarkConfigId : params.watermarkConfigId ,
},
},
})
media = ( wf ? . media as PrismaJson . MediaInfo | null ) ?? null
} else {
const asset = await this . prismaClient . asset . findUnique ({
where : { id : targetAssetId },
})
if ( ! asset ) {
throw new HTTPException ( 404 , { message : 'Asset not found' })
}
media = ( asset . media as PrismaJson . MediaInfo | null ) ?? null
}
if ( ! media ? . isHls || ! media . hls ? . key ) {
throw new HTTPException ( 404 , { message : 'HLS playlist not found' })
}
const matchedRes = media . hls . resolutions ? . find (( r ) => r . resolution === params . resolution )
const variantKey =
matchedRes ? . key ||
path . posix . join ( path . posix . dirname ( media . hls . key ), params . resolution , 'index.m3u8' )
const obj = await s3Service . getObject ( bucket , variantKey )
const rawM3u8 = obj . buffer . toString ( 'utf-8' )
const s3Prefix = path . posix . dirname ( variantKey )
return await rewriteM3u8WithPresignedUrls ( rawM3u8 , s3Prefix , bucket )
}
2026-05-19 16:05:09 +08:00
}
export const assetService = new AssetService ()