feat: add travel album OTG import flow

This commit is contained in:
2026-07-08 09:24:51 +08:00
parent 00bda390e8
commit 92fcad7ac9
42 changed files with 6826 additions and 89 deletions

View File

@ -0,0 +1,61 @@
//
// SonyCameraDriver.swift
// otg_swift
//
// Created by hanqiu on 2026/7/2.
//
import Foundation
@preconcurrency import ImageCaptureCore
/// **MTP ** Driver
/// PC Remote `SonyRemoteCaptureService` + PTP Driver catalog
/// PC Remote catalog MTP AGENTS.md
final class SonyCameraDriver: CameraDriver {
private let device: ICCameraDevice
let platform: CameraPlatform = .sony
let deviceInfo: CameraDeviceInfo
init(device: ICCameraDevice, deviceInfo: CameraDeviceInfo) {
self.device = device
self.deviceInfo = deviceInfo
OTGLog.info(.sony, "initialized, device=\(deviceInfo.name)")
}
func connect() async throws {
OTGLog.debug(.sony, "connect called")
}
func disconnect() {
OTGLog.info(.sony, "driver released, device=\(deviceInfo.name)")
}
/// `mediaFiles` / `contents` PC Remote
func listObjects() async throws -> [CameraObject] {
let mediaFilesCount = device.mediaFiles?.count ?? 0
let contentsCount = device.contents?.count ?? 0
let files = ICCameraItemScanner.collectImageFiles(from: device)
OTGLog.info(.sony, "listObjects: mediaFiles=\(mediaFilesCount), contents=\(contentsCount), images=\(files.count)")
let results = await ICCameraItemScanner.cameraObjects(from: files)
.sorted { $0.capturedAt > $1.capturedAt }
OTGLog.info(.sony, "listObjects: image count=\(results.count)")
return results
}
func requestThumbnailData(for object: CameraObject, maxPixelSize: Int) async -> Data? {
await ICCameraThumbnailLoader.loadThumbnailData(for: object, from: device, maxPixelSize: maxPixelSize)
}
func downloadObject(_ object: CameraObject, to directory: URL) async throws -> URL {
guard let file = ICCameraItemScanner.findFile(matching: object, in: device) else {
OTGLog.error(.sony, "downloadObject file not found: \(object.filename)")
throw CameraError.deviceNotFound
}
let url = try await ICCameraFileDownloader.download(file, to: directory)
OTGLog.info(.sony, "downloadObject saved: \(url.lastPathComponent)")
return url
}
}

View File

@ -0,0 +1,51 @@
//
// SonyPTPCommands.swift
// otg_swift
//
// Created by hanqiu on 2026/7/3.
//
import Foundation
/// SDIO / SDIE PTP
enum SonyPTPCommand {
// MARK: - SDIO
/// SDIO Connect (0x9201)
static let sdioConnect: UInt16 = 0x9201
/// GetExtDeviceInfo (0x9202)
static let sdioGetExtDeviceInfo: UInt16 = 0x9202
/// SetExtDevicePropValue (0x9205)
static let sdioSetExtDevicePropValue: UInt16 = 0x9205
/// GetAllExtDevicePropInfo (0x9209) diff
static let sdioGetAllExtDevicePropInfo: UInt16 = 0x9209
// MARK: -
/// Position_Key_Setting (0xD25A) PC Remote
static let positionKeySetting: UInt16 = 0xD25A
/// Still_Image_Save_Destination (0xD222) Host PC
static let stillImageSaveDestination: UInt16 = 0xD222
/// Still_Image_Trans_Size (0xD268)0xFFFFFFFF =
static let stillImageTransSize: UInt16 = 0xD268
/// Shooting_File_Info (0xD215) > 0x8000 PC Remote
static let shootingFileInfo: UInt16 = 0xD215
/// PC Remote GetObjectInfo/GetObject Probe
static let shotObjectHandle: UInt32 = 0xFFFF_C001
/// Host PC
static let saveDestinationHostPC: UInt16 = 1
/// D215 shot buffer
static let shotBufferReadyThreshold: Int64 = 0x8000
// MARK: - PTP Events (Sony SDIE)
/// ObjectAdded (0xC201) catalog
static let sdieObjectAdded: UInt16 = 0xC201
/// ObjectRemoved (0xC202) catalog
static let sdieObjectRemoved: UInt16 = 0xC202
/// DevicePropChanged (0xC203)ZV-E10 D215/Probe
static let sdieDevicePropChanged: UInt16 = 0xC203
/// CapturedEvent (0xC206)
static let sdieCapturedEvent: UInt16 = 0xC206
}

View File

@ -0,0 +1,422 @@
//
// SonyPTPHelper.swift
// otg_swift
//
// Created by hanqiu on 2026/7/3.
//
import Foundation
@preconcurrency import ImageCaptureCore
/// PC RemoteSDIO Probe PTP
enum SonyPTPHelper {
/// SDIO `nextTransactionID` PTP 使
struct RemoteSessionResult {
let success: Bool
let nextTransactionID: UInt32
}
private static func sendCommand(
on camera: ICCameraDevice,
code: UInt16,
transactionID: inout UInt32,
parameters: [UInt32],
outData: Data?,
label: String
) async -> PTPHelper.CommandResult {
await PTPHelper.sendCommand(
on: camera,
code: code,
transactionID: &transactionID,
parameters: parameters,
outData: outData,
label: label
)
}
private static func setDeviceProperty(
on camera: ICCameraDevice,
propertyCode: UInt16,
value: UInt16,
transactionID: inout UInt32,
label: String
) async -> Bool {
var payload = Data()
PTPHelper.appendUInt16LE(value, to: &payload)
return await sendCommand(
on: camera,
code: SonyPTPCommand.sdioSetExtDevicePropValue,
transactionID: &transactionID,
parameters: [UInt32(propertyCode), 1],
outData: payload,
label: label
).success
}
private static func setDevicePropertyUInt32(
on camera: ICCameraDevice,
propertyCode: UInt16,
value: UInt32,
transactionID: inout UInt32,
label: String
) async -> Bool {
var payload = Data()
PTPHelper.appendUInt32LE(value, to: &payload)
return await sendCommand(
on: camera,
code: SonyPTPCommand.sdioSetExtDevicePropValue,
transactionID: &transactionID,
parameters: [UInt32(propertyCode), 1],
outData: payload,
label: label
).success
}
/// PC Remote D25A / D222 / D268
private static func configureRemoteCapture(
on camera: ICCameraDevice,
transactionID: inout UInt32
) async -> Bool {
guard await setDeviceProperty(
on: camera,
propertyCode: SonyPTPCommand.positionKeySetting,
value: 1,
transactionID: &transactionID,
label: "Position_Key_Setting=PC Remote"
) else { return false }
guard await setDeviceProperty(
on: camera,
propertyCode: SonyPTPCommand.stillImageSaveDestination,
value: SonyPTPCommand.saveDestinationHostPC,
transactionID: &transactionID,
label: "Still_Image_Save_Destination=Host PC"
) else { return false }
return await setDevicePropertyUInt32(
on: camera,
propertyCode: SonyPTPCommand.stillImageTransSize,
value: 0xFFFF_FFFF,
transactionID: &transactionID,
label: "Still_Image_Trans_Size=Full"
)
}
/// SDIO Connect×3 GetExtDeviceInfo GetAllExtDevicePropInfo
static func initializeRemoteSession(
on camera: ICCameraDevice,
startingTransactionID: UInt32
) async -> RemoteSessionResult {
var transactionID = startingTransactionID
OTGLog.info(.sony, "SDIO handshake starting (phase 1: steps 1-5)")
// Phase 1 SDIO libgphoto2 / my_otg
let steps: [(UInt16, [UInt32], String)] = [
(SonyPTPCommand.sdioConnect, [1, 0, 0], "SDIO Connect(1)"),
(SonyPTPCommand.sdioConnect, [2, 0, 0], "SDIO Connect(2)"),
(SonyPTPCommand.sdioGetExtDeviceInfo, [0x012C, 1], "SDIO GetExtDeviceInfo"),
(SonyPTPCommand.sdioConnect, [3, 0, 0], "SDIO Connect(3)"),
(SonyPTPCommand.sdioGetAllExtDevicePropInfo, [1], "SDIO GetAllExtDevicePropInfo"),
]
for (code, parameters, label) in steps {
let result = await sendCommand(
on: camera,
code: code,
transactionID: &transactionID,
parameters: parameters,
outData: nil,
label: label
)
guard result.success else {
OTGLog.error(.sony, "SDIO failed at: \(label)")
return RemoteSessionResult(success: false, nextTransactionID: transactionID)
}
}
OTGLog.info(.sony, "SDIO phase 1 OK, nextTransactionID=\(transactionID)")
let configured = await configureRemoteCapture(on: camera, transactionID: &transactionID)
if configured {
OTGLog.info(.sony, "SDIO handshake completed, nextTransactionID=\(transactionID)")
} else {
OTGLog.error(.sony, "SDIO handshake failed at remote capture configuration")
}
return RemoteSessionResult(success: configured, nextTransactionID: transactionID)
}
// MARK: - PTP Events
static func describeEvent(_ eventData: Data) -> String {
guard let code = PTPHelper.parseEventCode(from: eventData) else {
return "unknown, hex=\(PTPHelper.hexString(eventData.prefix(16)))"
}
let name: String
switch code {
case SonyPTPCommand.sdieObjectAdded:
name = "ObjectAdded"
case SonyPTPCommand.sdieObjectRemoved:
name = "ObjectRemoved"
case SonyPTPCommand.sdieDevicePropChanged:
name = "DevicePropChanged"
case SonyPTPCommand.sdieCapturedEvent:
name = "CapturedEvent"
default:
name = "Other"
}
if let container = try? PTPHelper.parseContainer(eventData), !container.params.isEmpty {
let params = container.params
.map { String(format: "0x%08X", $0) }
.joined(separator: ", ")
return "\(name) (0x\(String(format: "%04X", code))), params=[\(params)]"
}
return "\(name) (0x\(String(format: "%04X", code)))"
}
// MARK: - Shot detection
/// Probe GetObject
struct PendingShot {
let filename: String
let size: UInt32
let handle: UInt32
}
/// GetObjectInfo CompressedSize
static func probeShotObject(
on camera: ICCameraDevice,
handle: UInt32 = SonyPTPCommand.shotObjectHandle,
transactionID: inout UInt32
) async -> PendingShot? {
let infoResult = await sendCommand(
on: camera,
code: PTPStandardCommand.getObjectInfo,
transactionID: &transactionID,
parameters: [handle],
outData: nil,
label: "ProbeObjectInfo(0x\(String(format: "%08X", handle)))"
)
guard infoResult.success else { return nil }
guard let size = PTPHelper.parseObjectCompressedSize(infoResult.inData), size > 0 else {
return nil
}
let filename = PTPHelper.parseObjectInfoFilename(infoResult.inData)
?? "DSC_\(Int(Date().timeIntervalSince1970)).JPG"
return PendingShot(filename: filename, size: size, handle: handle)
}
/// GetObject
struct DownloadedShot {
let filename: String
let data: Data
let handle: UInt32
}
/// GetObject JPEG/RAW Probe `skipObjectInfo` GetObjectInfo
static func downloadShotObject(
on camera: ICCameraDevice,
handle: UInt32 = SonyPTPCommand.shotObjectHandle,
transactionID: inout UInt32,
knownFilename: String? = nil,
skipObjectInfo: Bool = false
) async -> DownloadedShot? {
var filename = PTPHelper.sanitizeFilename(
knownFilename ?? "DSC_\(Int(Date().timeIntervalSince1970)).JPG"
)
if !skipObjectInfo {
let infoResult = await sendCommand(
on: camera,
code: PTPStandardCommand.getObjectInfo,
transactionID: &transactionID,
parameters: [handle],
outData: nil,
label: "GetObjectInfo(0x\(String(format: "%08X", handle)))"
)
if infoResult.success, let parsedName = PTPHelper.parseObjectInfoFilename(infoResult.inData) {
filename = parsedName
}
}
let objectResult = await sendCommand(
on: camera,
code: PTPStandardCommand.getObject,
transactionID: &transactionID,
parameters: [handle],
outData: nil,
label: "GetObject(0x\(String(format: "%08X", handle)))"
)
guard objectResult.success, PTPHelper.isLikelyImageData(objectResult.inData) else {
return nil
}
return DownloadedShot(filename: filename, data: objectResult.inData, handle: handle)
}
/// SDIO `onlyDiff=true`
static func fetchExtDeviceProperties(
on camera: ICCameraDevice,
transactionID: inout UInt32,
onlyDiff: Bool = true
) async -> [UInt16: Int64] {
let result = await sendCommand(
on: camera,
code: SonyPTPCommand.sdioGetAllExtDevicePropInfo,
transactionID: &transactionID,
parameters: [onlyDiff ? 1 : 0],
outData: nil,
label: "GetAllExtDevicePropInfo(\(onlyDiff ? "diff" : "all"))"
)
guard result.success else { return [:] }
return parseExtDeviceProperties(result.inData)
}
/// GetAllExtDevicePropInfo
static func parseExtDeviceProperties(_ data: Data) -> [UInt16: Int64] {
guard data.count >= 8 else { return [:] }
var properties: [UInt16: Int64] = [:]
var offset = 8 //
while offset + 6 <= data.count {
let propertyCode = PTPHelper.readUInt16LE(data, offset: offset)
offset += 2
let dataType = PTPHelper.readUInt16LE(data, offset: offset)
offset += 2
offset += 2 // GetSet
guard skipVariableValue(dataType: dataType, data: data, offset: &offset) else { break }
guard let currentValue = readVariableValue(dataType: dataType, data: data, offset: &offset) else { break }
properties[propertyCode] = currentValue
guard offset < data.count else { break }
let formFlag = data[offset]
offset += 1
// formFlag: 0=, 1=Range, 2=Enumeration
guard skipFormPayload(formFlag: formFlag, dataType: dataType, data: data, offset: &offset) else { break }
}
return properties
}
/// D215Shooting_File_Info
static func isShotBufferReady(_ shootingFileInfo: Int64?) -> Bool {
guard let shootingFileInfo else { return false }
return shootingFileInfo > SonyPTPCommand.shotBufferReadyThreshold
}
static func shotObjectSignature(filename: String, size: UInt32) -> String {
PTPHelper.objectSignature(filename: filename, size: size)
}
/// PTP parseExtDeviceProperties
private enum PTPDataType: UInt16 {
/// 8
case int8 = 0x0001
/// 8
case uint8 = 0x0002
/// 16
case int16 = 0x0003
/// 16
case uint16 = 0x0004
/// 32
case int32 = 0x0005
/// 32
case uint32 = 0x0006
/// 64 8
case int64 = 0x0007
/// 64 8
case uint64 = 0x0008
/// UTF-16LE map
case string = 0xFFFF
}
private static func readVariableValue(dataType: UInt16, data: Data, offset: inout Int) -> Int64? {
guard let type = PTPDataType(rawValue: dataType) else { return nil }
switch type {
case .int8:
guard offset < data.count else { return nil }
let value = Int64(Int8(bitPattern: data[offset]))
offset += 1
return value
case .uint8:
guard offset < data.count else { return nil }
let value = Int64(data[offset])
offset += 1
return value
case .int16:
guard offset + 1 < data.count else { return nil }
let value = Int64(Int16(bitPattern: PTPHelper.readUInt16LE(data, offset: offset)))
offset += 2
return value
case .uint16:
guard offset + 1 < data.count else { return nil }
let value = Int64(PTPHelper.readUInt16LE(data, offset: offset))
offset += 2
return value
case .int32:
guard offset + 3 < data.count else { return nil }
let value = Int64(Int32(bitPattern: PTPHelper.readUInt32LE(data, offset: offset)))
offset += 4
return value
case .uint32:
guard offset + 3 < data.count else { return nil }
let value = Int64(PTPHelper.readUInt32LE(data, offset: offset))
offset += 4
return value
case .int64, .uint64:
guard offset + 7 < data.count else { return nil }
offset += 8
return 0
case .string:
guard offset < data.count else { return nil }
let length = Int(data[offset])
offset += 1 + length * 2
return 0
}
}
private static func skipVariableValue(dataType: UInt16, data: Data, offset: inout Int) -> Bool {
readVariableValue(dataType: dataType, data: data, offset: &offset) != nil
}
private static func skipFormPayload(formFlag: UInt8, dataType: UInt16, data: Data, offset: inout Int) -> Bool {
switch formFlag {
case 0:
return true
case 1:
for _ in 0..<3 {
guard skipVariableValue(dataType: dataType, data: data, offset: &offset) else { return false }
}
return true
case 2:
guard offset + 1 < data.count else { return false }
var enumCount = Int(PTPHelper.readUInt16LE(data, offset: offset))
offset += 2
for _ in 0..<enumCount {
guard skipVariableValue(dataType: dataType, data: data, offset: &offset) else { return false }
}
guard offset + 1 < data.count else { return false }
enumCount = Int(PTPHelper.readUInt16LE(data, offset: offset))
offset += 2
for _ in 0..<enumCount {
guard skipVariableValue(dataType: dataType, data: data, offset: &offset) else { return false }
}
return true
default:
return true
}
}
}

View File

@ -0,0 +1,334 @@
//
// SonyRemoteCaptureService.swift
// otg_swift
//
import Foundation
@preconcurrency import ImageCaptureCore
/// Sony PC Remote Step 5+ GetObject Step 6
final class SonyRemoteCaptureService {
private weak var camera: ICCameraDevice?
private var transactionID: UInt32 = 1
private(set) var isReady = false
private var albumID: Int?
private let photoRepository: PhotoRepositoryProtocol
/// ConnectionManager ViewModel
var onShotSaved: ((String) -> Void)?
private var pollTimer: Timer?
private var propertyCheckTask: Task<Void, Never>?
private var isEvaluatingShotBuffer = false
private var propertyCheckCoalesceScheduled = false
private var isDownloading = false
private var lastDownloadedShotSignature: String?
private var detectedShotCount = 0
private var savedShotCount = 0
private let idlePollInterval: TimeInterval = 1.0
/// D215
private let activePollInterval: TimeInterval = 0.25
/// C203
private let propertyCheckDelay: TimeInterval = 0.12
init(photoRepository: PhotoRepositoryProtocol = TravelAlbumOTGPhotoRepository()) {
self.photoRepository = photoRepository
}
// MARK: - Lifecycle
/// SDIO `albumID` nil
func start(
camera: ICCameraDevice,
startingTransactionID: UInt32,
albumID: Int?
) {
stop()
self.camera = camera
self.transactionID = startingTransactionID
self.albumID = albumID
self.isReady = true
self.lastDownloadedShotSignature = nil
self.detectedShotCount = 0
self.savedShotCount = 0
OTGLog.info(.sony, "Remote capture service started, transactionID=\(startingTransactionID), album=\(albumID.map(String.init) ?? "nil")")
startD215Polling()
}
func stop() {
isReady = false
stopD215Polling()
propertyCheckTask?.cancel()
propertyCheckTask = nil
isEvaluatingShotBuffer = false
propertyCheckCoalesceScheduled = false
isDownloading = false
albumID = nil
camera = nil
}
// MARK: - PTP Events
/// Sony SDIE C201/C206 C203 D215/Probe
func handlePTPEvent(_ eventData: Data) {
guard isReady else { return }
guard let code = PTPHelper.parseEventCode(from: eventData) else { return }
switch code {
case SonyPTPCommand.sdieObjectAdded:
let handle = (try? PTPHelper.parseContainer(eventData))?.params.first
?? SonyPTPCommand.shotObjectHandle
OTGLog.info(.sony, "Shot signal: ObjectAdded handle=0x\(String(format: "%08X", handle))")
schedulePropertyBasedShotCheck(reason: "ObjectAdded")
case SonyPTPCommand.sdieCapturedEvent:
OTGLog.info(.sony, "Shot signal: CapturedEvent")
schedulePropertyBasedShotCheck(reason: "CapturedEvent")
case SonyPTPCommand.sdieDevicePropChanged:
OTGLog.debug(.sony, "PTP event: DevicePropChanged (0xC203)")
schedulePropertyBasedShotCheck(reason: "DevicePropChanged")
case SonyPTPCommand.sdieObjectRemoved:
OTGLog.debug(.sony, "PTP event: ObjectRemoved (0xC202)")
default:
OTGLog.debug(.sony, "PTP event: \(SonyPTPHelper.describeEvent(eventData))")
}
}
// MARK: - D215 Polling
private func startD215Polling() {
stopD215Polling()
OTGLog.info(.sony, "D215 polling started (idle=\(idlePollInterval)s)")
schedulePollTimer(interval: idlePollInterval)
}
private func stopD215Polling() {
pollTimer?.invalidate()
pollTimer = nil
}
private func schedulePollTimer(interval: TimeInterval) {
stopD215Polling()
pollTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
self?.schedulePropertyBasedShotCheck(reason: "D215Poll", delay: 0)
}
}
private func refreshPollInterval() {
guard isReady else { return }
let interval = savedShotCount > 0 ? activePollInterval : idlePollInterval
if pollTimer?.timeInterval != interval {
schedulePollTimer(interval: interval)
}
}
// MARK: - Property check + Probe + Download
private func schedulePropertyBasedShotCheck(reason: String, delay: TimeInterval? = nil) {
// PTP
if isEvaluatingShotBuffer {
propertyCheckCoalesceScheduled = true
return
}
propertyCheckTask?.cancel()
let wait = delay ?? propertyCheckDelay
propertyCheckTask = Task { [weak self] in
if wait > 0 {
try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
}
guard !Task.isCancelled else { return }
await self?.runPropertyBasedShotCheck(reason: reason)
}
}
private func runPropertyBasedShotCheck(reason: String) async {
if isEvaluatingShotBuffer {
propertyCheckCoalesceScheduled = true
return
}
isEvaluatingShotBuffer = true
defer {
isEvaluatingShotBuffer = false
if propertyCheckCoalesceScheduled {
propertyCheckCoalesceScheduled = false
schedulePropertyBasedShotCheck(reason: "Coalesced", delay: 0.08)
}
}
await evaluateShotBuffer(reason: reason)
}
/// D215 Probe GetObject
private func evaluateShotBuffer(reason: String) async {
guard isReady, let camera else { return }
var localTransactionID = transactionID
var properties = await SonyPTPHelper.fetchExtDeviceProperties(
on: camera,
transactionID: &localTransactionID,
onlyDiff: true
)
transactionID = localTransactionID
var shootingFileInfo = properties[SonyPTPCommand.shootingFileInfo]
if shootingFileInfo == nil, shouldFallbackFullPropertyFetch(for: reason) {
properties = await SonyPTPHelper.fetchExtDeviceProperties(
on: camera,
transactionID: &localTransactionID,
onlyDiff: false
)
transactionID = localTransactionID
shootingFileInfo = properties[SonyPTPCommand.shootingFileInfo]
OTGLog.debug(.sony, "\(reason): diff had no D215, fetched full property set")
}
if let shootingFileInfo {
OTGLog.debug(
.sony,
"\(reason): D215=0x\(String(format: "%04X", shootingFileInfo))"
)
}
if SonyPTPHelper.isShotBufferReady(shootingFileInfo) {
_ = await attemptFetchPendingShot(reason: "\(reason)-D215")
refreshPollInterval()
return
}
// ZV-E10 C203 D215 Probe
if shouldProbeWithoutD215(for: reason) {
_ = await attemptFetchPendingShot(reason: "\(reason)-Probe")
}
refreshPollInterval()
}
/// Probe GetObject Core Data
@discardableResult
private func attemptFetchPendingShot(reason: String) async -> Bool {
guard isReady, let camera else { return false }
var localTransactionID = transactionID
guard let probe = await SonyPTPHelper.probeShotObject(
on: camera,
transactionID: &localTransactionID
) else {
return false
}
transactionID = localTransactionID
let signature = SonyPTPHelper.shotObjectSignature(
filename: probe.filename,
size: probe.size
)
if signature == lastDownloadedShotSignature {
OTGLog.debug(.sony, "\(reason): already downloaded signature=\(signature)")
return false
}
detectedShotCount += 1
OTGLog.info(
.sony,
"New shot detected (#\(detectedShotCount)): \(probe.filename), size=\(probe.size), reason=\(reason)"
)
guard await downloadAndSave(probe: probe, reason: reason) else {
return false
}
lastDownloadedShotSignature = signature
savedShotCount += 1
return true
}
/// 3
private func downloadAndSave(probe: SonyPTPHelper.PendingShot, reason: String) async -> Bool {
guard isReady, let camera else { return false }
guard let albumID else {
OTGLog.warning(.sony, "\(reason): live transfer album not configured, skip save")
return false
}
if isDownloading {
OTGLog.debug(.sony, "\(reason): download already in progress, skip")
return false
}
isDownloading = true
defer { isDownloading = false }
var localTransactionID = transactionID
for attempt in 1...3 {
if attempt > 1 {
try? await Task.sleep(nanoseconds: UInt64(attempt) * 350_000_000)
}
guard let downloaded = await SonyPTPHelper.downloadShotObject(
on: camera,
handle: probe.handle,
transactionID: &localTransactionID,
knownFilename: probe.filename,
skipObjectInfo: true
) else {
if attempt == 3 {
OTGLog.error(.sony, "\(reason): GetObject failed after \(attempt) attempts")
}
continue
}
transactionID = localTransactionID
do {
let fileURL = try AlbumPhotoStorage.writeImage(
downloaded.data,
filename: downloaded.filename,
albumID: albumID
)
try photoRepository.addPhoto(
albumID: albumID,
localPath: fileURL.path,
createdAt: Date()
)
OTGLog.info(
.sony,
"Live shot saved (#\(savedShotCount + 1)): \(downloaded.filename), bytes=\(downloaded.data.count), path=\(fileURL.lastPathComponent)"
)
onShotSaved?(downloaded.filename)
return true
} catch {
OTGLog.error(.sony, "\(reason): save failed: \(error.localizedDescription)")
return false
}
}
return false
}
private func shouldFallbackFullPropertyFetch(for reason: String) -> Bool {
reason.contains("DevicePropChanged")
|| reason.hasPrefix("D215Poll")
|| reason.hasPrefix("Coalesced")
}
private func shouldProbeWithoutD215(for reason: String) -> Bool {
reason.contains("DevicePropChanged")
|| reason.hasPrefix("D215Poll")
|| reason.hasPrefix("Coalesced")
|| reason.contains("ObjectAdded")
|| reason.contains("CapturedEvent")
}
}