feat(ios): 支持位置拍照、相册上传和照片清理
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-26 20:47:51 +08:00
parent 39cf539e86
commit 3cf0728b81
18 changed files with 370 additions and 120 deletions

View File

@ -6,6 +6,8 @@
<string>$(ATLAS_API_BASE_URL)</string> <string>$(ATLAS_API_BASE_URL)</string>
<key>AtlasOIDCIssuer</key> <key>AtlasOIDCIssuer</key>
<string>$(ATLAS_OIDC_ISSUER)</string> <string>$(ATLAS_OIDC_ISSUER)</string>
<key>NSCameraUsageDescription</key>
<string>用于拍摄物品和位置照片,裁剪确认后上传到当前空间。</string>
<key>NSMicrophoneUsageDescription</key> <key>NSMicrophoneUsageDescription</key>
<string>用于录入物品时接收你说的话。</string> <string>用于录入物品时接收你说的话。</string>
<key>NSSpeechRecognitionUsageDescription</key> <key>NSSpeechRecognitionUsageDescription</key>

View File

@ -117,7 +117,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10; CURRENT_PROJECT_VERSION = 11;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";
@ -138,7 +138,7 @@
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 10; CURRENT_PROJECT_VERSION = 11;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com"; ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";

View File

@ -148,7 +148,7 @@ struct ItemEditor: View {
Button("移除待上传照片", role: .destructive) { self.photo = nil }.disabled(busy) Button("移除待上传照片", role: .destructive) { self.photo = nil }.disabled(busy)
} }
} else if let existing, let cover = existing.coverPhotoId { } else if let existing, let cover = existing.coverPhotoId {
PhotoImage(store: store, item: existing.id, photo: cover, thumbnail: true) PhotoImage(store: store, target: .item(existing.id), photo: cover, thumbnail: true)
.frame(width: 82, height: 82).clipShape(.rect(cornerRadius: 10)) .frame(width: 82, height: 82).clipShape(.rect(cornerRadius: 10))
} }
if savedItem == nil { if savedItem == nil {
@ -180,7 +180,7 @@ struct ItemEditor: View {
item = try await store.save(input, id: existing?.id, idempotencyKey: existing == nil ? createKey : nil) item = try await store.save(input, id: existing?.id, idempotencyKey: existing == nil ? createKey : nil)
savedItem = item savedItem = item
} }
if let photo { try await store.upload(photo, item: item.id, idempotencyKey: photoKey) } if let photo { try await store.upload(photo, target: .item(item.id), idempotencyKey: photoKey) }
dismiss() dismiss()
} catch { self.error = error.localizedDescription } } catch { self.error = error.localizedDescription }
} }

View File

@ -14,6 +14,7 @@ struct Place: Decodable, Identifiable {
let name: String let name: String
let path: String let path: String
var icon: String? = nil var icon: String? = nil
var coverPhotoId: UUID? = nil
} }
struct Item: Decodable, Identifiable { struct Item: Decodable, Identifiable {
@ -72,6 +73,25 @@ struct ItemDetail: Decodable {
struct Photo: Decodable, Identifiable { let id: UUID } struct Photo: Decodable, Identifiable { let id: UUID }
enum PhotoTarget: Hashable {
case item(UUID)
case location(UUID)
var path: String {
switch self {
case let .item(id): "/items/\(id)/photos"
case let .location(id): "/locations/\(id)/photos"
}
}
var title: String {
switch self {
case .item: "物品照片"
case .location: "位置照片"
}
}
}
@MainActor @MainActor
@Observable @Observable
final class InventoryStore { final class InventoryStore {
@ -88,7 +108,9 @@ final class InventoryStore {
} }
func refreshLocations() async throws { func refreshLocations() async throws {
locations = try await get(root + "/locations") let updated: [Place] = try await get(root + "/locations")
try Task.checkCancellation()
locations = updated
} }
func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0) async throws -> [Item] { func search(_ query: String, favorites: Bool, location: UUID? = nil, offset: Int = 0) async throws -> [Item] {
@ -137,19 +159,19 @@ final class InventoryStore {
root + "/items" + (id.map { "/\($0)" } ?? "") root + "/items" + (id.map { "/\($0)" } ?? "")
} }
func upload(_ image: Data, item: UUID, idempotencyKey: UUID? = nil) async throws { func upload(_ image: Data, target: PhotoTarget, idempotencyKey: UUID? = nil) async throws {
guard image.count <= 5 * 1024 * 1024 else { throw AtlasError("图片不能超过 5 MiB。") } guard image.count <= 5 * 1024 * 1024 else { throw AtlasError("图片不能超过 5 MiB。") }
let boundary = UUID().uuidString let boundary = UUID().uuidString
var payload = Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"image\"; filename=\"photo.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n".utf8) var payload = Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"image\"; filename=\"photo.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n".utf8)
payload.append(image) payload.append(image)
payload.append(Data("\r\n--\(boundary)--\r\n".utf8)) payload.append(Data("\r\n--\(boundary)--\r\n".utf8))
_ = try await account.request(itemPath(item) + "/photos", method: "POST", data: payload, _ = try await account.request(root + target.path, method: "POST", data: payload,
contentType: "multipart/form-data; boundary=\(boundary)", idempotencyKey: idempotencyKey) contentType: "multipart/form-data; boundary=\(boundary)", idempotencyKey: idempotencyKey)
changed() changed()
} }
func image(item: UUID, photo: UUID, thumbnail: Bool) async throws -> Data { func image(target: PhotoTarget, photo: UUID, thumbnail: Bool) async throws -> Data {
try await account.request(itemPath(item) + "/photos/\(photo)?thumbnail=\(thumbnail)") try await account.request(root + target.path + "/\(photo)?thumbnail=\(thumbnail)")
} }
func delete(_ path: String) async throws { func delete(_ path: String) async throws {

View File

@ -199,7 +199,7 @@ struct ItemsSection: View {
ForEach(results.rows) { item in ForEach(results.rows) { item in
NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: { NavigationLink { ItemDetailView(store: store, itemID: item.id) } label: {
HStack(spacing: 12) { HStack(spacing: 12) {
PhotoImage(store: store, item: item.id, photo: item.coverPhotoId, thumbnail: true, PhotoImage(store: store, target: .item(item.id), photo: item.coverPhotoId, thumbnail: true,
placeholderSymbol: InventorySymbol.item(item.icon).image) placeholderSymbol: InventorySymbol.item(item.icon).image)
.frame(width: 46, height: 46).clipShape(.rect(cornerRadius: 8)).accessibilityHidden(true) .frame(width: 46, height: 46).clipShape(.rect(cornerRadius: 8)).accessibilityHidden(true)
VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading, spacing: 3) {
@ -267,7 +267,7 @@ struct ItemDetailView: View {
if !detail.item.aliases.isEmpty { LabeledContent("别名", value: detail.item.aliases.joined(separator: "、")) } if !detail.item.aliases.isEmpty { LabeledContent("别名", value: detail.item.aliases.joined(separator: "、")) }
if !detail.item.notes.isEmpty { Text(detail.item.notes) } if !detail.item.notes.isEmpty { Text(detail.item.notes) }
} }
ItemPhotos(store: store, item: itemID) PhotoGallery(store: store, target: .item(itemID))
Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) } Section("我的评价") { PreferenceEditor(store: store, detail: detail, saved: { self.detail = $0 }) }
if !detail.relations.isEmpty { if !detail.relations.isEmpty {
Section("关联物品") { Section("关联物品") {

View File

@ -1,3 +1,4 @@
import AVFoundation
import ImageIO import ImageIO
import PhotosUI import PhotosUI
import SwiftUI import SwiftUI
@ -5,10 +6,11 @@ import UniformTypeIdentifiers
struct PhotoImage: View { struct PhotoImage: View {
let store: InventoryStore let store: InventoryStore
let item: UUID let target: PhotoTarget
let photo: UUID? let photo: UUID?
let thumbnail: Bool let thumbnail: Bool
var placeholderSymbol = "shippingbox.fill" var placeholderSymbol = "shippingbox.fill"
var placeholderTint: Color = .teal
@State private var image: UIImage? @State private var image: UIImage?
@State private var error = false @State private var error = false
@State private var retry = 0 @State private var retry = 0
@ -27,7 +29,7 @@ struct PhotoImage: View {
Button("重新加载图片") { retry += 1 } Button("重新加载图片") { retry += 1 }
} else { } else {
Image(systemName: error ? "photo" : placeholderSymbol) Image(systemName: error ? "photo" : placeholderSymbol)
.foregroundStyle(error ? Color.secondary : Color.teal) .foregroundStyle(error ? Color.secondary : placeholderTint)
} }
} }
.frame(width: geometry.size.width, height: geometry.size.height) .frame(width: geometry.size.width, height: geometry.size.height)
@ -38,7 +40,7 @@ struct PhotoImage: View {
error = false error = false
guard let photo else { return } guard let photo else { return }
do { do {
let bytes = try await store.image(item: item, photo: photo, thumbnail: thumbnail) let bytes = try await store.image(target: target, photo: photo, thumbnail: thumbnail)
try Task.checkCancellation() try Task.checkCancellation()
image = UIImage(data: bytes) image = UIImage(data: bytes)
error = image == nil error = image == nil
@ -48,76 +50,174 @@ struct PhotoImage: View {
} }
} }
struct ItemPhotos: View { struct PhotoGallery: View {
let store: InventoryStore let store: InventoryStore
let item: UUID let target: PhotoTarget
@State private var photos: [Photo] = [] @State private var photos: [Photo] = []
@State private var picker: PhotosPickerItem? @State private var picker: PhotosPickerItem?
@State private var crop: CropSource? @State private var crop: CropSource?
@State private var cameraCrop: CropSource?
@State private var showingCamera = false
@State private var preview: Photo? @State private var preview: Photo?
@State private var busy = false @State private var busy = false
@State private var error: String? @State private var error: String?
var body: some View { var body: some View {
Section("照片") { Section(target.title) {
if !photos.isEmpty { VStack(alignment: .leading, spacing: 14) {
ScrollView(.horizontal) { if !photos.isEmpty {
HStack { ScrollView(.horizontal) {
ForEach(photos) { photo in HStack {
Button { preview = photo } label: { ForEach(photos) { photo in
PhotoImage(store: store, item: item, photo: photo.id, thumbnail: true) Button { preview = photo } label: {
.frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9)) PhotoImage(store: store, target: target, photo: photo.id, thumbnail: true)
.frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9))
}
.buttonStyle(.plain)
.accessibilityLabel("查看照片")
} }
.buttonStyle(.plain)
.accessibilityLabel("查看照片")
} }
} }
.scrollIndicators(.hidden)
} else { Text("暂无照片").foregroundStyle(.secondary) }
if store.canWrite && photos.count < 6 {
HStack(spacing: 20) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
Button { Task { await openCamera() } } label: {
Label("拍照", systemImage: "camera")
}
.buttonStyle(.borderless)
}
PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) {
Label("从相册选", systemImage: "photo.badge.plus")
}
.buttonStyle(.borderless)
}
.disabled(busy)
} }
.scrollIndicators(.hidden) if busy { ProgressView() }
} else { Text("暂无照片").foregroundStyle(.secondary) } if let error { Text(error).foregroundStyle(.red).font(.footnote) }
if store.canWrite && photos.count < 6 { if error != nil {
PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) { Button("刷新照片") { Task { await load() } }.buttonStyle(.borderless)
Label("添加照片", systemImage: "photo.badge.plus")
}.disabled(busy)
}
if busy { ProgressView() }
if let error { Text(error).foregroundStyle(.red); Button("刷新照片") { Task { await load() } } }
}
.task(id: store.revision) { await load() }
.task(id: picker) {
guard let picker else { return }
busy = true
defer { busy = false; self.picker = nil }
do {
guard let source = try await picker.loadTransferable(type: CropSource.self) else {
throw AtlasError("这张图片无法读取,请重新选择。")
} }
try Task.checkCancellation()
error = nil
crop = source
} catch { self.error = error.localizedDescription }
}
.sheet(item: $crop) { source in
CropEditor(source: source) { image in
try await store.upload(image, item: item)
} }
} .padding(.vertical, 4)
.sheet(item: $preview) { photo in .task(id: store.revision) { await load() }
PhotoPreview(store: store, item: item, photo: photo) .task(id: picker) {
guard let selection = picker else { return }
busy = true
defer {
if picker == selection {
busy = false
picker = nil
}
}
do {
guard let source = try await selection.loadTransferable(type: CropSource.self) else {
throw AtlasError("这张图片无法读取,请重新选择。")
}
try Task.checkCancellation()
error = nil
crop = source
} catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
.fullScreenCover(isPresented: $showingCamera, onDismiss: {
crop = cameraCrop
cameraCrop = nil
}) {
CameraPicker { image in
if let image {
cameraCrop = CropSource.cameraImage(image)
if cameraCrop == nil { error = "照片无法读取,请重新拍摄。" }
}
showingCamera = false
}
.ignoresSafeArea()
}
.sheet(item: $crop) { source in
CropEditor(source: source) { image in
try await store.upload(image, target: target, idempotencyKey: source.id)
}
}
.sheet(item: $preview) { photo in
PhotoPreview(store: store, target: target, photo: photo)
}
} }
} }
private func openCamera() async {
guard !busy, UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
busy = true
defer { busy = false }
guard await AVCaptureDevice.requestAccess(for: .video) else {
error = "相机权限未开启。可以在系统设置中开启,或从相册选图。"
return
}
error = nil
showingCamera = true
}
private func load() async { private func load() async {
do { photos = try await store.get(store.itemPath(item) + "/photos"); error = nil } do {
catch where !Task.isCancelled { self.error = error.localizedDescription } let updated: [Photo] = try await store.get(store.root + target.path)
try Task.checkCancellation()
photos = updated
error = nil
} catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {} catch {}
} }
} }
private struct CameraPicker: UIViewControllerRepresentable {
let complete: (UIImage?) -> Void
func makeCoordinator() -> Coordinator { Coordinator(complete: complete) }
func makeUIViewController(context: Context) -> UIImagePickerController {
let camera = UIImagePickerController()
camera.sourceType = .camera
camera.cameraCaptureMode = .photo
camera.delegate = context.coordinator
return camera
}
func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let complete: (UIImage?) -> Void
init(complete: @escaping (UIImage?) -> Void) { self.complete = complete }
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { complete(nil) }
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
complete(info[.originalImage] as? UIImage)
}
}
}
struct CropSource: Transferable, Identifiable { struct CropSource: Transferable, Identifiable {
let id = UUID() let id = UUID()
let image: CGImage let image: CGImage
@MainActor
static func cameraImage(_ photo: UIImage) -> CropSource? {
let longest = max(photo.size.width, photo.size.height)
guard longest.isFinite, longest > 0 else { return nil }
let factor = min(1, 2400 / longest)
let size = CGSize(width: photo.size.width * factor, height: photo.size.height * factor)
guard size.width > 0, size.height > 0 else { return nil }
let format = UIGraphicsImageRendererFormat()
format.scale = 1
format.opaque = true
let rendered = UIGraphicsImageRenderer(size: size, format: format).image { _ in
photo.draw(in: CGRect(origin: .zero, size: size))
}
return rendered.cgImage.map { CropSource(image: $0) }
}
static var transferRepresentation: some TransferRepresentation { static var transferRepresentation: some TransferRepresentation {
FileRepresentation(importedContentType: .image) { source in FileRepresentation(importedContentType: .image) { source in
let size = try source.file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 let size = try source.file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
@ -223,7 +323,7 @@ struct CropEditor: View {
private struct PhotoPreview: View { private struct PhotoPreview: View {
let store: InventoryStore let store: InventoryStore
let item: UUID let target: PhotoTarget
let photo: Photo let photo: Photo
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
@State private var confirm = false @State private var confirm = false
@ -233,10 +333,10 @@ private struct PhotoPreview: View {
var body: some View { var body: some View {
NavigationStack { NavigationStack {
VStack { VStack {
PhotoImage(store: store, item: item, photo: photo.id, thumbnail: false) PhotoImage(store: store, target: target, photo: photo.id, thumbnail: false)
if let error { Text(error).foregroundStyle(.red) } if let error { Text(error).foregroundStyle(.red) }
} }
.navigationTitle("物品照片") .navigationTitle(target.title)
.navigationBarTitleDisplayMode(.inline) .navigationBarTitleDisplayMode(.inline)
.toolbar { .toolbar {
ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) } ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) }
@ -256,7 +356,7 @@ private struct PhotoPreview: View {
private func delete() async { private func delete() async {
busy = true busy = true
defer { busy = false } defer { busy = false }
do { try await store.delete(store.itemPath(item) + "/photos/\(photo.id)"); dismiss() } do { try await store.delete(store.root + target.path + "/\(photo.id)"); dismiss() }
catch { self.error = error.localizedDescription } catch { self.error = error.localizedDescription }
} }
} }

View File

@ -29,12 +29,23 @@ private struct LocationContents: View {
if let location { if let location {
Label(location.path, systemImage: InventorySymbol.location(location.icon).image) Label(location.path, systemImage: InventorySymbol.location(location.icon).image)
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
PhotoGallery(store: store, target: .location(location.id))
} }
Section(location == nil ? "房间和区域" : "子位置") { Section(location == nil ? "房间和区域" : "子位置") {
ForEach(store.locations.filter { $0.parentId == location?.id }) { child in ForEach(store.locations.filter { $0.parentId == location?.id }) { child in
NavigationLink { LocationContents(store: store, initialLocation: child) } label: { NavigationLink { LocationContents(store: store, initialLocation: child) } label: {
Label(child.name, systemImage: InventorySymbol.location(child.icon).image) HStack(spacing: 12) {
.labelStyle(.titleAndIcon) Label(child.name, systemImage: InventorySymbol.location(child.icon).image)
if let cover = child.coverPhotoId {
Spacer(minLength: 0)
PhotoImage(store: store, target: .location(child.id), photo: cover, thumbnail: true,
placeholderSymbol: InventorySymbol.location(child.icon).image,
placeholderTint: .atlasBlue)
.frame(width: 38, height: 38)
.clipShape(.rect(cornerRadius: 7))
.accessibilityHidden(true)
}
}
} }
} }
if store.canWrite { if store.canWrite {
@ -61,9 +72,10 @@ private struct LocationContents: View {
.task(id: items.loadID(query: "", revision: store.revision)) { .task(id: items.loadID(query: "", revision: store.revision)) {
if let location { await items.load(store: store, location: location.id) } if let location { await items.load(store: store, location: location.id) }
} }
.task(id: retry) { .task(id: "\(retry):\(store.revision)") {
do { try await store.refreshLocations(); error = nil } do { try await store.refreshLocations(); error = nil }
catch { self.error = error.localizedDescription } catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
} }
.sheet(isPresented: $addingLocation) { .sheet(isPresented: $addingLocation) {
PlaceEditor(store: store, parent: location?.id) { _ in } PlaceEditor(store: store, parent: location?.id) { _ in }
@ -86,7 +98,7 @@ private struct LocationContents: View {
} catch { self.error = error.localizedDescription } } catch { self.error = error.localizedDescription }
} }
} }
} message: { Text("有物品或子位置的位置需要先清空。") } } message: { Text("请先清空物品和子位置。删除这个位置时,里面的照片会一起删除。") }
} }
} }

View File

@ -24,12 +24,12 @@ spring:
- Path=/api/model-providers,/api/households/{householdId}/drafts,/api/households/{householdId}/drafts/**,/api/households/{householdId}/operations/** - Path=/api/model-providers,/api/households/{householdId}/drafts,/api/households/{householdId}/drafts/**,/api/households/{householdId}/operations/**
filters: filters:
- RequestSize=64KB - RequestSize=64KB
- id: item-photo-upload - id: photo-upload
order: -5 order: -5
uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
predicates: predicates:
- Method=POST - Method=POST
- Path=/api/households/{householdId}/items/{itemId}/photos - Path=/api/households/{householdId}/items/{itemId}/photos,/api/households/{householdId}/locations/{locationId}/photos
filters: filters:
- RequestSize=6MB - RequestSize=6MB
- id: inventory - id: inventory

View File

@ -44,7 +44,8 @@ class HouseholdService {
ManagedSpace managedSpace(UUID household) { ManagedSpace managedSpace(UUID household) {
return db.sql(""" return db.sql("""
SELECT h.id,h.name,(SELECT count(*) FROM item WHERE household_id=h.id AND archived_at IS NULL), SELECT h.id,h.name,(SELECT count(*) FROM item WHERE household_id=h.id AND archived_at IS NULL),
(SELECT count(*) FROM item_photo WHERE household_id=h.id) (SELECT count(*) FROM item_photo WHERE household_id=h.id) +
(SELECT count(*) FROM location_photo WHERE household_id=h.id)
FROM household h WHERE h.id=:id FROM household h WHERE h.id=:id
""").param("id", household).query((rs, row) -> new ManagedSpace(rs.getObject(1, UUID.class), """).param("id", household).query((rs, row) -> new ManagedSpace(rs.getObject(1, UUID.class),
rs.getString(2), rs.getLong(3), rs.getLong(4))).optional().orElseThrow(HouseholdAccess::missing); rs.getString(2), rs.getLong(3), rs.getLong(4))).optional().orElseThrow(HouseholdAccess::missing);

View File

@ -15,7 +15,7 @@ final class InventoryDtos {
enum LocationIcon { FOLDER, HOME, DESK, CABINET, DRAWER, BASKET } enum LocationIcon { FOLDER, HOME, DESK, CABINET, DRAWER, BASKET }
enum ItemIcon { BOX, CABLE, BOOK, TOOL, CLOTHING, KEY } enum ItemIcon { BOX, CABLE, BOOK, TOOL, CLOTHING, KEY }
record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon) {} record Location(UUID id, UUID parentId, String name, String path, LocationIcon icon, UUID coverPhotoId) {}
record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId, LocationIcon icon) {} record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId, LocationIcon icon) {}
record Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_999_999_999L) Long priceCents) {} record Appearance(@NotNull ItemIcon icon, @Min(0) @Max(9_999_999_999L) Long priceCents) {}
record Item(UUID id, String name, int quantity, String notes, UUID locationId, record Item(UUID id, String name, int quantity, String notes, UUID locationId,

View File

@ -19,7 +19,8 @@ import org.springframework.web.server.ResponseStatusException;
class InventoryService { class InventoryService {
private static final RowMapper<Location> LOCATION = (rs, row) -> new Location( private static final RowMapper<Location> LOCATION = (rs, row) -> new Location(
rs.getObject("id", UUID.class), rs.getObject("parent_id", UUID.class), rs.getObject("id", UUID.class), rs.getObject("parent_id", UUID.class),
rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon"))); rs.getString("name"), rs.getString("path"), LocationIcon.valueOf(rs.getString("icon")),
rs.getObject("cover_photo_id", UUID.class));
private static final RowMapper<Item> ITEM = (rs, row) -> new Item( private static final RowMapper<Item> ITEM = (rs, row) -> new Item(
rs.getObject("id", UUID.class), rs.getString("name"), rs.getInt("quantity"), rs.getObject("id", UUID.class), rs.getString("name"), rs.getInt("quantity"),
rs.getString("notes"), rs.getObject("location_id", UUID.class), rs.getString("path"), rs.getString("notes"), rs.getObject("location_id", UUID.class), rs.getString("path"),
@ -27,7 +28,11 @@ class InventoryService {
rs.getObject("cover_photo_id", UUID.class), ItemIcon.valueOf(rs.getString("icon")), rs.getObject("cover_photo_id", UUID.class), ItemIcon.valueOf(rs.getString("icon")),
rs.getObject("price_cents", Long.class)); rs.getObject("price_cents", Long.class));
private static final String SELECT_LOCATIONS = """ private static final String SELECT_LOCATIONS = """
SELECT p.*,l.icon FROM location_paths(:household) p SELECT p.*,l.icon,
(SELECT photo.id FROM location_photo photo
WHERE (photo.household_id,photo.location_id)=(p.household_id,p.id)
ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id
FROM location_paths(:household) p
JOIN location l ON (l.household_id,l.id)=(p.household_id,p.id) JOIN location l ON (l.household_id,l.id)=(p.household_id,p.id)
"""; """;
private static final String SCOPED_PATHS = "WITH paths AS (SELECT * FROM location_paths(:household))\n"; private static final String SCOPED_PATHS = "WITH paths AS (SELECT * FROM location_paths(:household))\n";

View File

@ -1,5 +1,7 @@
package com.tutudog.itematlas.inventory; package com.tutudog.itematlas.inventory;
import static com.tutudog.itematlas.inventory.PhotoService.Target.fromCollection;
import java.security.Principal; import java.security.Principal;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -10,35 +12,35 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@RestController @RestController
@RequestMapping("/api/households/{household}/items/{item}/photos") @RequestMapping("/api/households/{household}/{collection:items|locations}/{entity}/photos")
class PhotoController { class PhotoController {
private final PhotoService service; private final PhotoService service;
PhotoController(PhotoService service) { this.service = service; } PhotoController(PhotoService service) { this.service = service; }
@GetMapping @GetMapping
List<PhotoService.Photo> list(@PathVariable UUID household, @PathVariable UUID item, Principal user) { List<PhotoService.Photo> list(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, Principal user) {
return service.list(household, item, user.getName()); return service.list(household, fromCollection(collection), entity, user.getName());
} }
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<PhotoService.Photo> upload(@PathVariable UUID household, @PathVariable UUID item, ResponseEntity<PhotoService.Photo> upload(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity,
Principal user, @RequestPart("image") MultipartFile image, Principal user, @RequestPart("image") MultipartFile image,
@RequestHeader(value = "Idempotency-Key", required = false) UUID requestKey) { @RequestHeader(value = "Idempotency-Key", required = false) UUID requestKey) {
return ResponseEntity.status(201).body(service.upload(household, item, user.getName(), image, requestKey)); return ResponseEntity.status(201).body(service.upload(household, fromCollection(collection), entity, user.getName(), image, requestKey));
} }
@GetMapping("/{id}") @GetMapping("/{id}")
ResponseEntity<byte[]> image(@PathVariable UUID household, @PathVariable UUID item, @PathVariable UUID id, ResponseEntity<byte[]> image(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, @PathVariable UUID id,
Principal user, @RequestParam(defaultValue = "false") boolean thumbnail) { Principal user, @RequestParam(defaultValue = "false") boolean thumbnail) {
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).cacheControl(CacheControl.noStore()) return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).cacheControl(CacheControl.noStore())
.body(service.image(household, item, id, user.getName(), thumbnail)); .body(service.image(household, fromCollection(collection), entity, id, user.getName(), thumbnail));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
ResponseEntity<Void> delete(@PathVariable UUID household, @PathVariable UUID item, @PathVariable UUID id, ResponseEntity<Void> delete(@PathVariable UUID household, @PathVariable String collection, @PathVariable UUID entity, @PathVariable UUID id,
Principal user) { Principal user) {
service.delete(household, item, id, user.getName()); service.delete(household, fromCollection(collection), entity, id, user.getName());
return ResponseEntity.accepted().build(); return ResponseEntity.accepted().build();
} }
} }

View File

@ -43,27 +43,58 @@ class PhotoService {
record Photo(UUID id) {} record Photo(UUID id) {}
private record Cleanup(String prefix, int attempts) {} private record Cleanup(String prefix, int attempts) {}
List<Photo> list(UUID household, UUID item, String actor) { enum Target {
access.role(household, actor); ITEM("items", "item", "item_photo", "item_id", "物品"),
requireItem(household, item); LOCATION("locations", "location", "location_photo", "location_id", "位置");
return db.sql("SELECT id FROM item_photo WHERE household_id=:house AND item_id=:item ORDER BY created_at,id")
.param("house", household).param("item", item).query(UUID.class).list().stream().map(Photo::new).toList(); final String collection;
final String entityTable;
final String photoTable;
final String foreignKey;
final String label;
Target(String collection, String entityTable, String photoTable, String foreignKey, String label) {
this.collection = collection;
this.entityTable = entityTable;
this.photoTable = photoTable;
this.foreignKey = foreignKey;
this.label = label;
}
static Target fromCollection(String collection) {
return switch (collection) {
case "items" -> ITEM;
case "locations" -> LOCATION;
default -> throw new ResponseStatusException(NOT_FOUND);
};
}
String photosWhere() {
return " FROM " + photoTable + " WHERE household_id=:house AND " + foreignKey + "=:entity";
}
} }
Photo upload(UUID household, UUID item, String actor, MultipartFile file, UUID requestKey) { List<Photo> list(UUID household, Target target, UUID entity, String actor) {
access.role(household, actor);
requireEntity(household, target, entity);
return db.sql("SELECT id" + target.photosWhere() + " ORDER BY created_at,id")
.param("house", household).param("entity", entity).query(UUID.class).list().stream().map(Photo::new).toList();
}
Photo upload(UUID household, Target target, UUID entity, String actor, MultipartFile file, UUID requestKey) {
if ("VIEWER".equals(access.role(household, actor))) { if ("VIEWER".equals(access.role(household, actor))) {
throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限"); throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限");
} }
requireItem(household, item); requireEntity(household, target, entity);
var existing = uploaded(household, item, actor, requestKey); var existing = uploaded(household, target, entity, actor, requestKey);
if (existing.isPresent()) { return existing.get(); } if (existing.isPresent()) { return existing.get(); }
requireStorage(); requireStorage();
var images = PhotoImages.encode(file); var images = PhotoImages.encode(file);
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
String prefix = "households/" + household + "/items/" + item + "/" + id; String prefix = "households/" + household + "/" + target.collection + "/" + entity + "/" + id;
transaction.executeWithoutResult(status -> { transaction.executeWithoutResult(status -> {
access.requireWrite(household, actor); access.requireWrite(household, actor);
requireItem(household, item); requireEntity(household, target, entity);
db.sql("INSERT INTO media_cleanup(object_prefix,due_at) VALUES (:prefix, now()+interval '1 hour')") db.sql("INSERT INTO media_cleanup(object_prefix,due_at) VALUES (:prefix, now()+interval '1 hour')")
.param("prefix", prefix).update(); .param("prefix", prefix).update();
}); });
@ -71,20 +102,21 @@ class PhotoService {
try { try {
return transaction.execute(status -> { return transaction.execute(status -> {
access.requireWrite(household, actor); access.requireWrite(household, actor);
requireItem(household, item); requireEntity(household, target, entity);
int reserved = db.sql("DELETE FROM media_cleanup WHERE object_prefix=:prefix AND due_at>now()") int reserved = db.sql("DELETE FROM media_cleanup WHERE object_prefix=:prefix AND due_at>now()")
.param("prefix", prefix).update(); .param("prefix", prefix).update();
if (reserved == 0) { throw new ResponseStatusException(CONFLICT, "上传已超时,请重试"); } if (reserved == 0) { throw new ResponseStatusException(CONFLICT, "上传已超时,请重试"); }
var previous = uploaded(household, item, actor, requestKey); var previous = uploaded(household, target, entity, actor, requestKey);
if (previous.isPresent()) { return previous.get(); } if (previous.isPresent()) { return previous.get(); }
long count = db.sql("SELECT count(*) FROM item_photo WHERE household_id=:house AND item_id=:item") long count = db.sql("SELECT count(*)" + target.photosWhere())
.param("house", household).param("item", item).query(Long.class).single(); .param("house", household).param("entity", entity).query(Long.class).single();
if (count >= 6) { throw new ResponseStatusException(CONFLICT, "一件物品最多上传 6 张图片"); } if (count >= 6) { throw new ResponseStatusException(CONFLICT, "最多上传 6 张图片"); }
storage.store(prefix, images); storage.store(prefix, images);
db.sql(""" db.sql("""
INSERT INTO item_photo(household_id,item_id,id,object_prefix,upload_subject,upload_key) INSERT INTO %s(household_id,%s,id,object_prefix,upload_subject,upload_key)
VALUES (:house,:item,:id,:prefix,:actor,:key) VALUES (:house,:entity,:id,:prefix,:actor,:key)
""").param("house", household).param("item", item).param("id", id).param("prefix", prefix) """.formatted(target.photoTable, target.foreignKey))
.param("house", household).param("entity", entity).param("id", id).param("prefix", prefix)
.param("actor", requestKey == null ? null : actor, Types.VARCHAR) .param("actor", requestKey == null ? null : actor, Types.VARCHAR)
.param("key", requestKey, Types.OTHER).update(); .param("key", requestKey, Types.OTHER).update();
return new Photo(id); return new Photo(id);
@ -98,18 +130,17 @@ class PhotoService {
} }
} }
private Optional<Photo> uploaded(UUID household, UUID item, String actor, UUID requestKey) { private Optional<Photo> uploaded(UUID household, Target target, UUID entity, String actor, UUID requestKey) {
if (requestKey == null) { return Optional.empty(); } if (requestKey == null) { return Optional.empty(); }
return db.sql(""" return db.sql("SELECT id" + target.photosWhere() + " AND upload_subject=:actor AND upload_key=:key")
SELECT id FROM item_photo WHERE household_id=:house AND item_id=:item AND upload_subject=:actor AND upload_key=:key .param("house", household).param("entity", entity).param("actor", actor).param("key", requestKey)
""").param("house", household).param("item", item).param("actor", actor).param("key", requestKey)
.query(UUID.class).optional().map(Photo::new); .query(UUID.class).optional().map(Photo::new);
} }
byte[] image(UUID household, UUID item, UUID id, String actor, boolean thumbnail) { byte[] image(UUID household, Target target, UUID entity, UUID id, String actor, boolean thumbnail) {
access.role(household, actor); access.role(household, actor);
String prefix = db.sql("SELECT object_prefix FROM item_photo WHERE household_id=:house AND item_id=:item AND id=:id") String prefix = db.sql("SELECT object_prefix" + target.photosWhere() + " AND id=:id")
.param("house", household).param("item", item).param("id", id).query(String.class).optional() .param("house", household).param("entity", entity).param("id", id).query(String.class).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "图片不存在")); .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "图片不存在"));
requireStorage(); requireStorage();
try { return storage.get(prefix, thumbnail); } try { return storage.get(prefix, thumbnail); }
@ -117,11 +148,11 @@ class PhotoService {
} }
@Transactional @Transactional
void delete(UUID household, UUID item, UUID id, String actor) { void delete(UUID household, Target target, UUID entity, UUID id, String actor) {
access.requireWrite(household, actor); access.requireWrite(household, actor);
requireItem(household, item); requireEntity(household, target, entity);
db.sql("DELETE FROM item_photo WHERE household_id=:house AND item_id=:item AND id=:id") db.sql("DELETE" + target.photosWhere() + " AND id=:id")
.param("house", household).param("item", item).param("id", id).update(); .param("house", household).param("entity", entity).param("id", id).update();
} }
@Scheduled(fixedDelay = 2000) @Scheduled(fixedDelay = 2000)
@ -154,10 +185,10 @@ class PhotoService {
return true; return true;
} }
private void requireItem(UUID household, UUID item) { private void requireEntity(UUID household, Target target, UUID entity) {
db.sql("SELECT id FROM item WHERE household_id=:house AND id=:item AND archived_at IS NULL") db.sql("SELECT id FROM " + target.entityTable + " WHERE household_id=:house AND id=:entity AND archived_at IS NULL")
.param("house", household).param("item", item).query(UUID.class).optional() .param("house", household).param("entity", entity).query(UUID.class).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在")); .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, target.label + "不存在"));
} }
private void requireStorage() { if (storage == null) { throw unavailable(); } } private void requireStorage() { if (storage == null) { throw unavailable(); } }

View File

@ -0,0 +1,29 @@
CREATE TABLE location_photo (
household_id uuid NOT NULL,
location_id uuid NOT NULL,
id uuid PRIMARY KEY,
object_prefix text NOT NULL UNIQUE,
created_at timestamptz NOT NULL DEFAULT now(),
upload_key uuid,
upload_subject text,
FOREIGN KEY (household_id, location_id) REFERENCES location(household_id, id) ON DELETE CASCADE,
CHECK ((upload_key IS NULL) = (upload_subject IS NULL))
);
CREATE INDEX location_photo_location ON location_photo(household_id, location_id, created_at, id);
CREATE UNIQUE INDEX location_photo_upload_request ON location_photo(household_id, location_id, upload_subject, upload_key)
WHERE upload_key IS NOT NULL;
CREATE TRIGGER location_photo_cleanup AFTER DELETE ON location_photo
FOR EACH ROW EXECUTE FUNCTION enqueue_photo_cleanup();
CREATE FUNCTION detach_archived_location_photos() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
DELETE FROM location_photo WHERE household_id=NEW.household_id AND location_id=NEW.id;
RETURN NEW;
END;
$$;
CREATE TRIGGER location_archive_photo_cleanup AFTER UPDATE OF archived_at ON location
FOR EACH ROW WHEN (OLD.archived_at IS NULL AND NEW.archived_at IS NOT NULL)
EXECUTE FUNCTION detach_archived_location_photos();

View File

@ -41,13 +41,13 @@ def response(request, status):
return body return body
def storage_status(house, item, photo, filename): def storage_status(house, item, photo, filename, collection="items"):
endpoint = os.environ["ATLAS_MEDIA_ENDPOINT"].rstrip("/") endpoint = os.environ["ATLAS_MEDIA_ENDPOINT"].rstrip("/")
region = os.environ["ATLAS_MEDIA_REGION"] region = os.environ["ATLAS_MEDIA_REGION"]
bucket = os.environ["ATLAS_MEDIA_BUCKET"] bucket = os.environ["ATLAS_MEDIA_BUCKET"]
key = os.environ["ATLAS_MEDIA_ACCESS_KEY"] key = os.environ["ATLAS_MEDIA_ACCESS_KEY"]
secret = os.environ["ATLAS_MEDIA_SECRET_KEY"] secret = os.environ["ATLAS_MEDIA_SECRET_KEY"]
url = f"{endpoint}/{bucket}/households/{house}/items/{item}/{photo}/{filename}" url = f"{endpoint}/{bucket}/households/{house}/{collection}/{item}/{photo}/{filename}"
credentials = f'user = {key}:{secret}\n' credentials = f'user = {key}:{secret}\n'
result = subprocess.run(["curl", "-sS", "--max-time", "5", "-o", os.devnull, "-w", "%{http_code}", result = subprocess.run(["curl", "-sS", "--max-time", "5", "-o", os.devnull, "-w", "%{http_code}",
"--aws-sigv4", f"aws:amz:{region}:s3", "--config", "-", url], "--aws-sigv4", f"aws:amz:{region}:s3", "--config", "-", url],
@ -55,14 +55,51 @@ def storage_status(house, item, photo, filename):
return result.stdout.strip() if result.returncode == 0 else "000" return result.stdout.strip() if result.returncode == 0 else "000"
def await_absence(house, item, photo): def await_absence(house, item, photo, collection="items"):
for _ in range(25): for _ in range(25):
if all(storage_status(house, item, photo, variant) == "404" for variant in ("image.jpg", "thumb.jpg")): if all(storage_status(house, item, photo, variant, collection) == "404"
for variant in ("image.jpg", "thumb.jpg")):
return return
time.sleep(1) time.sleep(1)
raise AssertionError(f"Storage keys for {photo} still exist") raise AssertionError(f"Storage keys for {photo} still exist")
def verify_location_photos(house, space, jpeg):
import json
room = call("POST", space + "/locations", {"name": "带照片的房间"}, status=201)["id"]
child = call("POST", space + "/locations", {"name": "收纳柜", "parentId": room}, status=201)["id"]
location = f"{space}/locations/{child}"
photos = location + "/photos"
assert call("GET", photos) == [] and call("GET", location)["coverPhotoId"] is None
upload(photos, jpeg, user="viewer", status=403)
call("GET", photos, user="other", status=404)
upload(photos, b"x" * (6 * 1024 * 1024), status=413)
key = uuid.uuid4()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
receipts = list(pool.map(lambda _: json.loads(upload(photos, jpeg, request_key=key)), range(2)))
assert receipts[0] == receipts[1] and call("GET", photos) == [receipts[0]]
first = receipts[0]["id"]
second = json.loads(upload(photos, jpeg))["id"]
assert call("GET", location)["coverPhotoId"] == first
asset = f"{photos}/{first}"
full = response(make_request("GET", asset, None, "owner"), 200)
thumb = response(make_request("GET", asset + "?thumbnail=true", None, "viewer"), 200)
assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb)
assert all(storage_status(house, child, first, variant, "locations") == "200"
for variant in ("image.jpg", "thumb.jpg"))
call("DELETE", asset, user="viewer", status=403)
call("DELETE", asset, status=202)
await_absence(house, child, first, "locations")
assert call("GET", location)["coverPhotoId"] == second
call("DELETE", location, status=204)
call("GET", photos, status=404)
await_absence(house, child, second, "locations")
room_photo = json.loads(upload(f"{space}/locations/{room}/photos", jpeg))["id"]
print("PASS location photo routing, cover, permissions, retry and location cleanup", flush=True)
return room, room_photo
def main(): def main():
import json import json
@ -106,11 +143,13 @@ def main():
await_absence(house, item["id"], archived) await_absence(house, item["id"], archived)
second = call("POST", space + "/items", {"name": "相册", "quantity": 1, "locationId": location}, status=201) second = call("POST", space + "/items", {"name": "相册", "quantity": 1, "locationId": location}, status=201)
remaining = json.loads(upload(f"{space}/items/{second['id']}/photos", jpeg))["id"] remaining = json.loads(upload(f"{space}/items/{second['id']}/photos", jpeg))["id"]
room, room_photo = verify_location_photos(house, space, jpeg)
call("DELETE", space, user="viewer", status=403) call("DELETE", space, user="viewer", status=403)
call("DELETE", f"/api/admin/households/{house}", status=403) call("DELETE", f"/api/admin/households/{house}", status=403)
call("DELETE", space, status=202) call("DELETE", space, status=202)
call("GET", space, status=404) call("GET", space, status=404)
await_absence(house, second["id"], remaining) await_absence(house, second["id"], remaining)
await_absence(house, room, room_photo, "locations")
print("PASS upload limits, retry deduplication, thumbnail, authorization, favorites and OSS cleanup") print("PASS upload limits, retry deduplication, thumbnail, authorization, favorites and OSS cleanup")
if os.environ.get("ATLAS_SMOKE_ADMIN_TOKEN"): if os.environ.get("ATLAS_SMOKE_ADMIN_TOKEN"):
from smoke import TOKENS from smoke import TOKENS
@ -121,10 +160,12 @@ def main():
place = call("POST", api + "/locations", {"name": "盒子"}, status=201)["id"] place = call("POST", api + "/locations", {"name": "盒子"}, status=201)["id"]
second = call("POST", api + "/items", {"name": "纸盒", "quantity": 1, "locationId": place}, status=201) second = call("POST", api + "/items", {"name": "纸盒", "quantity": 1, "locationId": place}, status=201)
attached = json.loads(upload(f"{api}/items/{second['id']}/photos", jpeg))["id"] attached = json.loads(upload(f"{api}/items/{second['id']}/photos", jpeg))["id"]
assert call("GET", admin, user="admin")["photos"] == 1 place_photo = json.loads(upload(f"{api}/locations/{place}/photos", jpeg))["id"]
assert call("GET", admin, user="admin")["photos"] == 2
call("DELETE", admin, user="admin", status=202) call("DELETE", admin, user="admin", status=202)
call("GET", api, status=404) call("GET", api, status=404)
await_absence(another, second["id"], attached) await_absence(another, second["id"], attached)
await_absence(another, place, place_photo, "locations")
print("PASS dedicated OIDC admin client, role, audited deletion and both OSS objects") print("PASS dedicated OIDC admin client, role, audited deletion and both OSS objects")
finally: finally:
try: try:

View File

@ -53,6 +53,8 @@ curl -sS -o /dev/null -w '%{http_code}\n' "https://$host/api/households"
## 对象存储 ## 对象存储
Flyway V10 新增 `location_photo`,以空间和位置 ID 组成的外键约束归属。物理删除位置时外键级联删除照片记录,软删除位置时由归档触发器删除记录。这两条路径都会进入已有的清理队列,旧版物品服务回退后删除空间也受数据库约束保护。位置和物品照片共用 5 MiB 文件上限,网关为两条上传路由提供 6 MB 请求上限。
物品服务使用 AWS SDK for Java 2.x 的 S3 接口。Helm 从物品服务已有的 Secret 注入配置。提前创建独立私有桶,服务账号只有这个桶的指定前缀读、写和删除权限。Garage 本地环境把 `metadata_dir`、`data_dir` 和宿主容器运行数据都放在外置 SSD 上。生产实例的备份需同时考虑 PostgreSQL 和对象存储。 物品服务使用 AWS SDK for Java 2.x 的 S3 接口。Helm 从物品服务已有的 Secret 注入配置。提前创建独立私有桶,服务账号只有这个桶的指定前缀读、写和删除权限。Garage 本地环境把 `metadata_dir`、`data_dir` 和宿主容器运行数据都放在外置 SSD 上。生产实例的备份需同时考虑 PostgreSQL 和对象存储。
| 环境变量 | 用途 | | 环境变量 | 用途 |
@ -65,7 +67,7 @@ curl -sS -o /dev/null -w '%{http_code}\n' "https://$host/api/households"
Bucket 关闭匿名访问,当前清理语义要求关闭版本保留和对象锁。开启这些能力前须另行定义版本删除及保留策略。Nginx 上传大小设为 `6m`,网关及 multipart 总上限 6 MiB,单图上限 5 MiB。后端按解码器校验 JPEG 和像素,最长边上限为 2048,重新编码时去掉图片元数据。每张图以独立 UUID 保存两份对象。读取经 API 校验当前成员身份,列表可以只请求最长边 320 像素的 `thumbnail=true` 响应。 Bucket 关闭匿名访问,当前清理语义要求关闭版本保留和对象锁。开启这些能力前须另行定义版本删除及保留策略。Nginx 上传大小设为 `6m`,网关及 multipart 总上限 6 MiB,单图上限 5 MiB。后端按解码器校验 JPEG 和像素,最长边上限为 2048,重新编码时去掉图片元数据。每张图以独立 UUID 保存两份对象。读取经 API 校验当前成员身份,列表可以只请求最长边 320 像素的 `thumbnail=true` 响应。
对象键为 `households/{空间}/items/{物品}/{图片}/image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交图片和取消预留。图片删除、物品归档、空间删除使用同一数据库触发器登记清理。空间删除立即撤销访问并移除物品数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。 物品照片使用 `households/{空间}/items/{物品}/{图片}/`,位置照片使用 `households/{空间}/locations/{位置}/{图片}/`。每张照片存 `image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交照片并取消预留。照片删除、物品归档、位置归档和空间删除由数据库触发器登记清理。空间删除立即撤销访问并移除空间数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。
清理任务在物品服务领取,利用 `FOR UPDATE SKIP LOCKED` 避免多个 Pod 重复领取,同一个对象可安全重删。丢失响应或 OSS 暂时不可用时,任务会退避后重试。观察 `atlas_media_cleanup_pending` 和 `atlas_media_cleanup_attempts_total{result="retry"}` 判断是否积压。网关和图片接口返回 `202` 表示删除已受理,核对物理删除请检查清理队列和两个对象键。 清理任务在物品服务领取,利用 `FOR UPDATE SKIP LOCKED` 避免多个 Pod 重复领取,同一个对象可安全重删。丢失响应或 OSS 暂时不可用时,任务会退避后重试。观察 `atlas_media_cleanup_pending` 和 `atlas_media_cleanup_attempts_total{result="retry"}` 判断是否积压。网关和图片接口返回 `202` 表示删除已受理,核对物理删除请检查清理队列和两个对象键。

View File

@ -24,6 +24,8 @@
打开房间、区域或子位置,点右上角「编辑」即可修改名称和图标。新建时也能选图标,位置列表和选位置页面会同步显示。 打开房间、区域或子位置,点右上角「编辑」即可修改名称和图标。新建时也能选图标,位置列表和选位置页面会同步显示。
位置详情的「位置照片」可以拍照或从相册选图,裁剪确认后上传。已有照片可点开查看和删除,列表用第一张照片做缩略图。删除位置时,其照片随位置清理。
添加或编辑物品时,可以填写可选的购入单价、选择物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。 添加或编辑物品时,可以填写可选的购入单价、选择物品图标、从相册选照片并裁剪。点「保存」后先保存物品,再上传照片。照片上传失败时,可以点「重试上传」,也可以稍后从详情添加。没有封面照片时,物品列表显示所选物品图标。已有照片可在物品详情继续查看、添加和删除。
## 选存放位置 ## 选存放位置

View File

@ -37,5 +37,6 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前
| TC-31 分级选位置 | R02 | 建两个带同名收纳盒的分支,其中一个有三级。从录音草稿、添加物品和移位分别打开位置选择,逐级找一次,再用完整路径搜索。 | 叶子和上级节点都能选。搜索显示完整路径,选好后返回原表单,取消时保留原选择。 | | TC-31 分级选位置 | R02 | 建两个带同名收纳盒的分支,其中一个有三级。从录音草稿、添加物品和移位分别打开位置选择,逐级找一次,再用完整路径搜索。 | 叶子和上级节点都能选。搜索显示完整路径,选好后返回原表单,取消时保留原选择。 |
| TC-32 编辑位置与物品图标 | R02 | 为房间和子位置选择图标,再编辑子位置名称。新建物品并选择另一套物品图标。 | 位置层级保持正确,列表和选择页显示最新图标。无封面照片的物品显示物品图标。 | | TC-32 编辑位置与物品图标 | R02 | 为房间和子位置选择图标,再编辑子位置名称。新建物品并选择另一套物品图标。 | 位置层级保持正确,列表和选择页显示最新图标。无封面照片的物品显示物品图标。 |
| TC-33 购入单价与新建照片 | R09 | 添加物品,输入 39.99 元并选相册照片裁剪。模拟上传中断后重试。随后清空购入单价。 | 价格按分精确保存。照片可单独重试,只保留一件物品和一张照片,详情可读取原图和缩略图。清空后详情收起价格项。 | | TC-33 购入单价与新建照片 | R09 | 添加物品,输入 39.99 元并选相册照片裁剪。模拟上传中断后重试。随后清空购入单价。 | 价格按分精确保存。照片可单独重试,只保留一件物品和一张照片,详情可读取原图和缩略图。清空后详情收起价格项。 |
| TC-34 位置照片与清理 | R09 | 进入房间和子位置,分别拍照和选相册图,裁剪后上传。查看原图和缩略图,删除首图、归档空位置,再删除整个空间。 | 图标保留,缩略图随首图更新。查看者可看,编辑者可上传。删除相应记录后,两份对象都从桶中清理。 |
[测试与演示计划](plan.md) [测试与演示计划](plan.md)