Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 86 additions & 29 deletions worker/src/db/queries/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,26 +153,45 @@ export async function checkFileNameConflict(
prefix: string,
userId: number,
folderId: string | null,
name: string
name: string,
excludeFileId?: string
): Promise<boolean> {
const statement =
folderId === null
? db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE
LIMIT 1`
)
.bind(userId, name)
: db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE
LIMIT 1`
)
.bind(userId, folderId, name)
? excludeFileId
? db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE AND id != ?
LIMIT 1`
)
.bind(userId, name, excludeFileId)
: db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id IS NULL AND name = ? COLLATE NOCASE
LIMIT 1`
)
.bind(userId, name)
: excludeFileId
? db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE AND id != ?
LIMIT 1`
)
.bind(userId, folderId, name, excludeFileId)
: db
.prepare(
`SELECT 1 AS exists_row
FROM ${filesTable(prefix)}
WHERE user_id = ? AND folder_id = ? AND name = ? COLLATE NOCASE
LIMIT 1`
)
.bind(userId, folderId, name)

const row = await statement.first<{ exists_row: number }>()
return row !== null
Expand Down Expand Up @@ -258,37 +277,75 @@ export async function deleteFileRecord(
return result.meta.changes > 0
}

export async function updateFileExpiration(
export interface UpdateFileInput {
name?: string
folderId?: string | null
expiresAt?: string | null
}

export async function updateFileRecord(
db: D1Database,
prefix: string,
userId: number,
fileId: string,
newExpiresAt: string | null
patch: UpdateFileInput
): Promise<FileRow | null> {
const file = await findFileById(db, prefix, userId, fileId)
if (!file) return null

await db
.prepare(
`UPDATE ${filesTable(prefix)}
SET expires_at = ?
WHERE id = ? AND user_id = ?`
)
.bind(newExpiresAt, fileId, userId)
.run()
const assignments: string[] = []
const values: Array<string | number | null> = []

if (patch.name !== undefined) {
assignments.push("name = ?")
values.push(patch.name)
}

if (patch.folderId !== undefined) {
assignments.push("folder_id = ?")
values.push(patch.folderId)
}

if (patch.expiresAt !== undefined) {
assignments.push("expires_at = ?")
values.push(patch.expiresAt)
}

if (assignments.length > 0) {
await db
.prepare(
`UPDATE ${filesTable(prefix)}
SET ${assignments.join(", ")}
WHERE id = ? AND user_id = ?`
)
.bind(...values, fileId, userId)
.run()
}

// 若缩短了过期时间,同步截断越过新到期时间的分享行(规格 §5.4 / §6)
if (newExpiresAt !== null) {
if (patch.expiresAt !== undefined && patch.expiresAt !== null) {
await db
.prepare(
`UPDATE ${sharesTable(prefix)}
SET expires_at = ?
WHERE file_id = ?
AND (expires_at IS NULL OR expires_at > ?)`
)
.bind(newExpiresAt, fileId, newExpiresAt)
.bind(patch.expiresAt, fileId, patch.expiresAt)
.run()
}

return await findFileById(db, prefix, userId, fileId)
}

export async function updateFileExpiration(
db: D1Database,
prefix: string,
userId: number,
fileId: string,
newExpiresAt: string | null
): Promise<FileRow | null> {
return await updateFileRecord(db, prefix, userId, fileId, {
expiresAt: newExpiresAt
})
}
142 changes: 119 additions & 23 deletions worker/src/routes/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import {
isFileExpired,
isValidExpiresInPreset,
toFileView,
updateFileExpiration
updateFileRecord
} from "../db/queries/files"
import { findFolderById } from "../db/queries/folders"
import { findFolderById, isValidFolderName } from "../db/queries/folders"
import { createShareRecord, listSharesByFile } from "../db/queries/shares"
import {
completeFileUpload,
Expand Down Expand Up @@ -526,45 +526,141 @@ fileRoutes.patch("/:id", async (c) => {
const prefix = getTablePrefix(c.env)
const fileId = c.req.param("id")?.trim()

const body = await readJsonBody<{ expiresIn?: unknown }>(c)
if (!fileId) {
return apiError(c, 404, "FILE_NOT_FOUND", "File not found")
}

const body = await readJsonBody<{
name?: unknown
folderId?: unknown
expiresIn?: unknown
}>(c)
if (!body) {
return apiError(c, 400, "INVALID_REQUEST", "Invalid request body")
}

let preset: string | null = null
if (typeof body.expiresIn === "string") {
if (
body.expiresIn !== "" &&
body.expiresIn !== "never" &&
!isValidExpiresInPreset(body.expiresIn)
) {
const hasName = body.name !== undefined
const hasFolderId = body.folderId !== undefined
const hasExpiresIn = body.expiresIn !== undefined

if (!hasName && !hasFolderId && !hasExpiresIn) {
return apiError(
c,
400,
"INVALID_REQUEST",
"At least one field (name, folderId, expiresIn) is required"
)
}

const file = await findFileById(c.env.DB, prefix, userId, fileId)
if (!file) {
return apiError(c, 404, "FILE_NOT_FOUND", "File not found")
}

let targetFolderId: string | null = file.folder_id
if (hasFolderId) {
if (body.folderId === null) {
targetFolderId = null
} else if (typeof body.folderId === "string") {
const trimmedFolderId = body.folderId.trim()
if (!trimmedFolderId) {
targetFolderId = null
} else {
const folder = await findFolderById(
c.env.DB,
prefix,
userId,
trimmedFolderId
)
if (!folder) {
return apiError(c, 404, "FOLDER_NOT_FOUND", "Folder not found")
}
targetFolderId = trimmedFolderId
}
} else {
return apiError(
c,
400,
"INVALID_REQUEST",
"folderId must be a string or null"
)
}
}

let targetName = file.name
if (hasName) {
if (typeof body.name !== "string" || !isValidFolderName(body.name)) {
return apiError(
c,
400,
"INVALID_FILENAME",
"File name must be between 1 and 255 characters and cannot contain slashes"
)
}
targetName = body.name.trim()
}

if (hasName || hasFolderId) {
const isConflict = await checkFileNameConflict(
c.env.DB,
prefix,
userId,
targetFolderId,
targetName,
file.id
)
if (isConflict) {
return apiError(
c,
409,
"FILE_NAME_CONFLICT",
"A file with the same name already exists in this folder"
)
}
}

let newExpiresAt: string | null | undefined
if (hasExpiresIn) {
let preset: string | null = null
if (typeof body.expiresIn === "string") {
const trimmed = body.expiresIn.trim()
if (
trimmed !== "" &&
trimmed !== "never" &&
!isValidExpiresInPreset(trimmed)
) {
return apiError(
c,
400,
"INVALID_EXPIRES_IN",
"Invalid expiration preset (allowed: never, 1h, 24h, 7d, 30d)"
)
}
preset = trimmed === "" ? null : trimmed
} else if (body.expiresIn === null) {
preset = null
} else {
return apiError(
c,
400,
"INVALID_EXPIRES_IN",
"Invalid expiration preset (allowed: never, 1h, 24h, 7d, 30d)"
)
}
preset = body.expiresIn
newExpiresAt = calculateExpiresAt(preset)
}

const newExpiresAt = calculateExpiresAt(preset)
const updated = await updateFileExpiration(
c.env.DB,
prefix,
userId,
fileId,
newExpiresAt
)
const updated = await updateFileRecord(c.env.DB, prefix, userId, fileId, {
...(hasName ? { name: targetName } : {}),
...(hasFolderId ? { folderId: targetFolderId } : {}),
...(hasExpiresIn ? { expiresAt: newExpiresAt } : {})
})

if (!updated) {
return apiError(c, 404, "FILE_NOT_FOUND", "File not found")
}

return c.json({
id: updated.id,
expiresAt: updated.expires_at
})
return c.json(toFileView(updated))
})

fileRoutes.post("/:id/shares", async (c) => {
Expand Down
Loading