fix(desktop): stop USB re-imports inventing -1/-2 copies (BIT-168) #168

Merged
spark merged 1 commits from task/BIT-168-usb-no-dup-copies into main 2026-11-03 21:30:44 +00:00
2 changed files with 85 additions and 35 deletions

No files matched your search

+50 -17
View File
@@ -165,6 +165,7 @@ static BOOL is_still(ICCameraItem *item) {
cam.openRequested = NO;
cam.state = @"idle";
self.cams[uuid] = cam;
[self loadFetchedInto:cam];
}
cam.device = (ICCameraDevice *)device;
cam.name = device.name ?: @"Câmara";
@@ -354,19 +355,31 @@ static BOOL is_still(ICCameraItem *item) {
if (cam.pendingDownloads == 0) [self closeWhenIdle:cam];
}
- (NSString *)uniqueName:(NSString *)original {
NSString *base = original.lastPathComponent ?: @"photo.JPG";
NSString *stem = base.stringByDeletingPathExtension;
NSString *ext = base.pathExtension;
NSString *candidate = base;
NSFileManager *fm = [NSFileManager defaultManager];
for (int n = 1; n < 1000; n++) {
if (![fm fileExistsAtPath:[self.dir stringByAppendingPathComponent:candidate]]) return candidate;
candidate = ext.length
? [NSString stringWithFormat:@"%@-%d.%@", stem, n, ext]
: [NSString stringWithFormat:@"%@-%d", stem, n];
- (NSString *)fetchedPath {
return self.dir.length ? [self.dir stringByAppendingPathComponent:@".fetched"] : nil;
}
- (void)rememberFetched:(NSString *)name cam:(PRCam *)cam {
if (!name.length || !cam) return;
[cam.fetched addObject:name];
NSString *path = [self fetchedPath];
if (!path.length) return;
NSMutableSet *all = [NSMutableSet setWithObject:name];
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
if (line.length) [all addObject:line];
}
NSArray *sorted = [[all allObjects] sortedArrayUsingSelector:@selector(compare:)];
[[sorted componentsJoinedByString:@"\n"] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (void)loadFetchedInto:(PRCam *)cam {
NSString *path = [self fetchedPath];
if (!path.length || !cam) return;
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
if (line.length) [cam.fetched addObject:line];
}
return candidate;
}
- (void)download:(ICCameraFile *)file cam:(PRCam *)cam {
@@ -374,15 +387,23 @@ static BOOL is_still(ICCameraItem *item) {
if ([cam.fetched containsObject:file.name]) return;
NSFileManager *fm = [NSFileManager defaultManager];
[fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
NSString *save = [self uniqueName:file.name];
// Keep the camera's name. A leftover ingest copy of the same shot must not become PSR1-1.JPG.
NSString *existing = [self.dir stringByAppendingPathComponent:file.name];
NSDictionary *attrs = [fm attributesOfItemAtPath:existing error:nil];
if (attrs && [attrs fileSize] > 0) {
[self rememberFetched:file.name cam:cam];
emit(@{@"kind": @"file", @"path": existing, @"name": file.name, @"size": @([attrs fileSize])});
return;
}
if (attrs) [fm removeItemAtPath:existing error:nil];
NSURL *url = [NSURL fileURLWithPath:self.dir isDirectory:YES];
if (!url) return;
[cam.fetched addObject:file.name];
[self rememberFetched:file.name cam:cam];
cam.pendingDownloads++;
NSDictionary *options = @{
ICDownloadsDirectoryURL: url,
ICSaveAsFilename: save,
ICOverwrite: @NO,
ICSaveAsFilename: file.name,
ICOverwrite: @YES,
ICDeleteAfterSuccessfulDownload: @NO,
};
#pragma clang diagnostic push
@@ -567,6 +588,15 @@ static BOOL is_still(ICCameraItem *item) {
if (error || self.dir.length == 0) {
if (cam && file.name) {
[cam.fetched removeObject:file.name];
NSString *path = [self fetchedPath];
if (path.length) {
NSMutableArray *keep = [NSMutableArray array];
NSString *prev = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [prev componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
if (line.length && ![line isEqualToString:file.name]) [keep addObject:line];
}
[[keep componentsJoinedByString:@"\n"] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
[self publishCatalog:cam];
}
if (cam) [self closeWhenIdle:cam];
@@ -614,7 +644,10 @@ void pr_camera_set_dir(const char *dir) {
NSString *path = dir ? [NSString stringWithUTF8String:dir] : @"";
on_main(^{
g_dir = [path copy];
g_hub.dir = g_dir;
if (g_hub) {
g_hub.dir = g_dir;
for (NSString *key in g_hub.cams) [g_hub loadFetchedInto:g_hub.cams[key]];
}
});
}
+35 -18
View File
@@ -700,36 +700,37 @@ impl FtpState {
.ok_or("bad_path")?
.to_string_lossy()
.into_owned();
let (stem, ext) = match name.rsplit_once('.') {
Some((s, e)) => (s.to_string(), format!(".{e}")),
None => (name.clone(), String::new()),
let stem = match name.rsplit_once('.') {
Some((s, _)) => s.to_string(),
None => name.clone(),
};
let mut target = dir.join(&name);
let mut n = 1;
while target.exists() {
target = dir.join(format!("{stem}-{n}{ext}"));
n += 1;
}
let target = dir.join(&name);
let sidecars = if is_photo(&p) {
raw_sidecars(&p)
} else {
Vec::new()
};
let paired = target
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| stem.clone());
// Same camera name already in the work folder (USB re-import / server duplicate): drop the
// ingest copy — never invent PSR1-1.JPG, PSR1-2.JPG beside the first filing.
if target.exists() {
let _ = std::fs::remove_file(&p);
for raw in &sidecars {
let _ = std::fs::remove_file(raw);
}
self.taken.lock().unwrap().remove(path);
return Ok(target.to_string_lossy().into_owned());
}
let paired = stem.clone();
move_file(&p, &target).map_err(|e| e.to_string())?;
for raw in sidecars {
let raw_ext = raw
.extension()
.map(|e| e.to_string_lossy().into_owned())
.unwrap_or_default();
let mut raw_target = dir.join(format!("{paired}.{raw_ext}"));
let mut k = 1;
while raw_target.exists() {
raw_target = dir.join(format!("{paired}-{k}.{raw_ext}"));
k += 1;
let raw_target = dir.join(format!("{paired}.{raw_ext}"));
if raw_target.exists() {
let _ = std::fs::remove_file(&raw);
continue;
}
let _ = move_file(&raw, &raw_target);
}
@@ -1092,6 +1093,22 @@ mod tests {
assert!(moved.with_extension("CR3").is_file());
assert!(!jpeg.exists());
assert!(!ingest.join("IMG_0001.CR3").exists());
// A second send of the same camera name (USB re-pull / server duplicate) must not invent -1 copies.
std::fs::write(ingest.join("IMG_0001.JPG"), [0xFFu8, 0xD8, 0xFF, 0xD9]).unwrap();
let again = state
.sent(
ingest.join("IMG_0001.JPG").to_str().unwrap(),
"POR x SUI",
"2026-11-04",
)
.unwrap();
assert_eq!(PathBuf::from(&again), moved);
assert!(!ingest.join("IMG_0001.JPG").exists());
assert!(!moved
.parent()
.unwrap()
.join("IMG_0001-1.JPG")
.exists());
let _ = std::fs::remove_dir_all(&dir);
}