team-ljyzipelo

공개
829줄30 KB
1use crate::archive_ui::*;
2use std::{
3 collections::{BTreeMap, BTreeSet},
4 fs, io,
5 path::{Path, PathBuf},
6};
7
8pub const UNCERTAIN: &str = "저장이 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요.";
9pub const PARTIAL: &str = "일부 파일만 풀렸습니다. 풀린 파일은 풀 위치 폴더에 남아 있습니다.";
10pub const LEFTOVERS: &str =
11 "선택한 파일은 모두 저장했지만 임시 파일을 지우지 못했습니다. 풀 위치 폴더를 확인하세요.";
12pub const SYNC_FAILED: &str =
13 "파일을 디스크에 완전히 저장하지 못했습니다. 풀 위치 폴더를 확인하세요.";
14pub const SYNC_WARNING: &str = "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다.";
15pub const CLEANUP_WARNING: &str =
16 "임시 파일을 지우지 못했습니다. 풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다.";
17pub const INTERNAL: &str = "내부 오류가 발생했습니다. 프로그램을 다시 시작해 주세요";
18pub const FOLDER_ERROR: &str = "풀 위치 폴더를 만들 수 없습니다. 접근 권한을 확인하세요";
19
20pub fn error_text(code: ErrorCode) -> &'static str {
21 match code {
22 ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다. 복구본과 경고를 확인하세요.",
23 ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다.",
24 ErrorCode::MissingVolume => {
25 "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요"
26 }
27 ErrorCode::Integrity => "압축파일이 손상됐습니다",
28 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
29 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
30 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
31 ErrorCode::UnsafePath => "파일 경로의 안전성을 확인할 수 없어 중단했습니다",
32 ErrorCode::Conflict => "같은 이름의 파일이 이미 있습니다. 다른 폴더를 선택하세요",
33 ErrorCode::Limit => "처리 한도를 초과했습니다",
34 ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요",
35 ErrorCode::DiskFull => "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
36 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
37 ErrorCode::InvalidRequest => "풀 위치와 선택한 항목을 확인하세요",
38 ErrorCode::Protocol | ErrorCode::Internal => INTERNAL,
39 }
40}
41
42pub fn progress_text(stage: Stage, creating: bool) -> &'static str {
43 match stage {
44 Stage::Scan | Stage::Read => "압축파일을 읽는 중",
45 Stage::Decode if creating => "압축하는 중",
46 Stage::Decode => "압축을 푸는 중",
47 Stage::Write => "파일을 저장하는 중",
48 Stage::Verify => "확인하는 중",
49 Stage::Commit => "마무리하는 중",
50 }
51}
52
53pub fn bytes_text(bytes: u64) -> String {
54 for (unit, size) in [("GB", 1_u64 << 30), ("MB", 1 << 20), ("KB", 1 << 10)] {
55 if bytes >= size {
56 return format!("{:.1} {unit}", bytes as f64 / size as f64);
57 }
58 }
59 format!("{bytes} B")
60}
61
62/// 자원 상한 표시. u64::MAX는 상한이 없다는 뜻임.
63pub fn limit_text(bytes: u64) -> String {
64 if bytes == u64::MAX {
65 "제한 없음".into()
66 } else {
67 bytes_text(bytes)
68 }
69}
70
71pub fn middle_text(text: &str, max_chars: usize) -> String {
72 let chars = text.chars().collect::<Vec<_>>();
73 if chars.len() <= max_chars || max_chars < 5 {
74 return text.into();
75 }
76 let left = (max_chars - 1) / 2;
77 chars[..left]
78 .iter()
79 .chain(std::iter::once(&'…'))
80 .chain(chars[chars.len() - (max_chars - left - 1)..].iter())
81 .collect()
82}
83
84pub fn default_destination(archive: &Path) -> PathBuf {
85 let name = archive.file_name().unwrap_or_default().to_string_lossy();
86 let lower = name.to_ascii_lowercase();
87 let compound = [".tar.bz2", ".tar.gz", ".tar.xz"]
88 .into_iter()
89 .find(|suffix| lower.ends_with(suffix));
90 let stem = if let Some(suffix) = compound {
91 &name[..name.len() - suffix.len()]
92 } else {
93 name.rsplit_once('.')
94 .map_or(name.as_ref(), |(stem, _)| stem)
95 };
96 archive.with_file_name(if stem.is_empty() {
97 "압축 해제"
98 } else {
99 stem
100 })
101}
102
103pub fn prepare_destination(path: &Path, automatic: bool) -> io::Result<bool> {
104 match fs::symlink_metadata(path) {
105 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(false),
106 Ok(_) => Err(io::Error::other(FOLDER_ERROR)),
107 Err(error) if error.kind() == io::ErrorKind::NotFound && automatic => {
108 let mut builder = fs::DirBuilder::new();
109 #[cfg(unix)]
110 {
111 use std::os::unix::fs::DirBuilderExt;
112 builder.mode(0o700);
113 }
114 builder.create(path)?;
115 Ok(true)
116 }
117 Err(error) => Err(error),
118 }
119}
120
121pub fn remove_owned_empty(path: &Path) {
122 // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함.
123 let _ = fs::remove_dir(path);
124}
125
126fn requested(entry: &Entry, selection: &Selection) -> bool {
127 match selection {
128 Selection::All => true,
129 Selection::EntryIds(ids) => ids.contains(&entry.id),
130 }
131}
132
133pub fn target_files(
134 entries: &[Entry],
135 selection: &Selection,
136 gzip: Option<&str>,
137) -> Option<BTreeSet<String>> {
138 let mut names = BTreeSet::new();
139 for entry in entries
140 .iter()
141 .filter(|entry| entry.kind == Kind::File && requested(entry, selection))
142 {
143 if !names.insert(gzip.unwrap_or(&entry.name).replace('\\', "/")) {
144 return None;
145 }
146 }
147 Some(names)
148}
149
150pub fn resolved_targets(
151 targets: Option<&BTreeSet<String>>,
152 entries: &[Entry],
153 gzip: Option<&str>,
154 resolutions: &[Resolution],
155) -> Option<BTreeSet<String>> {
156 let mut names = targets?.clone();
157 let entries: BTreeMap<_, _> = entries.iter().map(|entry| (entry.id, entry)).collect();
158 for resolution in resolutions {
159 let entry = entries.get(&resolution.entry_id)?;
160 let original = gzip.unwrap_or(&entry.name).replace('\\', "/");
161 if !names.remove(&original) {
162 return None;
163 }
164 }
165 for resolution in resolutions {
166 if resolution.choice != ConflictChoice::Skip
167 && !names.insert(resolution.relative_name.replace('\\', "/"))
168 {
169 return None;
170 }
171 }
172 Some(names)
173}
174
175pub fn target_directories(entries: &[Entry], selection: &Selection) -> BTreeSet<String> {
176 let mut directories = BTreeSet::new();
177 for entry in entries.iter().filter(|entry| {
178 matches!(entry.kind, Kind::File | Kind::Directory) && requested(entry, selection)
179 }) {
180 let normalized = entry.name.replace('\\', "/");
181 let name = normalized.trim_end_matches('/');
182 if entry.kind == Kind::Directory {
183 directories.insert(name.to_owned());
184 }
185 let mut parent = name;
186 while let Some((directory, _)) = parent.rsplit_once('/') {
187 directories.insert(directory.to_owned());
188 parent = directory;
189 }
190 }
191 directories
192}
193
194pub fn durability_warning(durability: Durability) -> Option<&'static str> {
195 match durability {
196 Durability::Failed => Some(SYNC_FAILED),
197 Durability::Unconfirmed => Some(SYNC_WARNING),
198 _ => None,
199 }
200}
201
202pub fn warnings(
203 terminal: Option<&Terminal>,
204 confirmed: bool,
205 targets: Option<&BTreeSet<String>>,
206 directories: &BTreeSet<String>,
207 outputs: &[(String, Disposition)],
208) -> Vec<&'static str> {
209 let mut result = publication_warnings(terminal, confirmed, targets, directories, outputs);
210 if let Some(warning) = terminal
211 .filter(|_| confirmed)
212 .and_then(|t| durability_warning(t.durability))
213 {
214 result.push(warning);
215 }
216 result
217}
218
219pub fn publication_warnings(
220 terminal: Option<&Terminal>,
221 confirmed: bool,
222 targets: Option<&BTreeSet<String>>,
223 directories: &BTreeSet<String>,
224 outputs: &[(String, Disposition)],
225) -> Vec<&'static str> {
226 let Some(t) = terminal.filter(|_| confirmed) else {
227 return vec![UNCERTAIN];
228 };
229 let created = outputs
230 .iter()
231 .filter(|(_, state)| *state == Disposition::Created)
232 .map(|(name, _)| name.replace('\\', "/"))
233 .collect::<BTreeSet<_>>();
234 let created_reports = outputs
235 .iter()
236 .filter(|(_, state)| *state == Disposition::Created)
237 .count();
238 let uncertain = t.publication == Publication::Uncertain
239 || outputs
240 .iter()
241 .any(|(_, state)| *state == Disposition::CommitUncertain)
242 || created.len() != created_reports
243 || created_reports as u64 != t.created_count
244 || (t.publication == Publication::None && !created.is_empty());
245 let retained = t.retained_partial_count > 0
246 || outputs
247 .iter()
248 .any(|(_, state)| *state == Disposition::PartialRetained);
249 let mut result = Vec::new();
250 let mut all_saved_with_leftovers = false;
251 if uncertain {
252 result.push(UNCERTAIN);
253 } else if let Some(targets) = targets {
254 let files = created
255 .difference(directories)
256 .cloned()
257 .collect::<BTreeSet<_>>();
258 let saved = targets.intersection(&files).count();
259 let unknown = !targets.is_disjoint(directories)
260 || created
261 .iter()
262 .any(|name| !targets.contains(name) && !directories.contains(name));
263 if unknown {
264 result.push(UNCERTAIN);
265 } else if !targets.is_empty() && saved == targets.len() && retained {
266 result.push(LEFTOVERS);
267 all_saved_with_leftovers = true;
268 } else if saved > 0 && saved < targets.len() && t.outcome != Outcome::Completed {
269 result.push(PARTIAL);
270 } else if (saved == 0 && !files.is_empty())
271 || (retained && saved == 0)
272 || (t.outcome == Outcome::Completed && saved != targets.len())
273 {
274 result.push(UNCERTAIN);
275 }
276 } else {
277 result.push(UNCERTAIN);
278 }
279 if (retained || t.cleanup != Cleanup::Complete) && !all_saved_with_leftovers {
280 result.push(CLEANUP_WARNING);
281 }
282 result
283}
284
285pub fn definitely_unsaved(
286 t: Option<&Terminal>,
287 confirmed: bool,
288 outputs: &[(String, Disposition)],
289) -> bool {
290 t.is_some_and(|t| {
291 confirmed
292 && t.publication == Publication::None
293 && t.created_count == 0
294 && t.retained_partial_count == 0
295 && t.cleanup == Cleanup::Complete
296 && outputs
297 .iter()
298 .all(|(_, state)| *state == Disposition::Removed)
299 })
300}
301
302#[derive(Clone)]
303pub struct BrowserEntry {
304 pub path: PathBuf,
305 pub name: String,
306 pub directory: bool,
307 pub link: bool,
308}
309
310pub fn directory_entries(path: &Path) -> io::Result<Vec<BrowserEntry>> {
311 if fs::symlink_metadata(path)?.file_type().is_symlink() {
312 return Err(io::Error::other("링크 폴더는 탐색하지 않음"));
313 }
314 let mut entries = Vec::new();
315 for item in fs::read_dir(path)? {
316 let item = item?;
317 let kind = item.file_type()?;
318 entries.push(BrowserEntry {
319 path: item.path(),
320 name: item.file_name().to_string_lossy().into(),
321 directory: kind.is_dir(),
322 link: kind.is_symlink(),
323 });
324 }
325 entries.sort_by(|a, b| {
326 b.directory
327 .cmp(&a.directory)
328 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
329 });
330 Ok(entries)
331}
332
333pub fn home_directory() -> PathBuf {
334 std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
335 .map(PathBuf::from)
336 .filter(|p| p.is_absolute())
337 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")))
338}
339
340pub fn shortcuts() -> Vec<(String, PathBuf)> {
341 let home = home_directory();
342 let mut paths = vec![("홈".into(), home.clone())];
343 for (label, candidates) in [
344 ("바탕 화면", ["Desktop", "바탕화면"]),
345 ("문서", ["Documents", "문서"]),
346 ("다운로드", ["Downloads", "다운로드"]),
347 ] {
348 if let Some(path) = candidates
349 .iter()
350 .map(|name| home.join(name))
351 .find(|p| p.is_dir())
352 {
353 paths.push((label.into(), path));
354 }
355 }
356 #[cfg(windows)]
357 for drive in b'A'..=b'Z' {
358 let path = PathBuf::from(format!("{}:\\", drive as char));
359 if path.is_dir() {
360 paths.push((format!("{}:", drive as char), path));
361 }
362 }
363 paths
364}
365
366pub fn folder_command(path: &Path) -> std::process::Command {
367 let mut command = std::process::Command::new(if cfg!(windows) {
368 "explorer"
369 } else {
370 "xdg-open"
371 });
372 command.arg(path);
373 command
374}
375
376pub const UNCONFIRMED_FINISH: &str =
377 "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요";
378
379pub fn client_error_text(error: &str) -> &'static str {
380 if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") {
381 UNCONFIRMED_FINISH
382 } else {
383 INTERNAL
384 }
385}
386
387pub fn activity_text(model: &Model, creating: bool) -> &'static str {
388 if model.terminal.is_some()
389 || matches!(
390 model.cancel,
391 Some(CancelStatus::TooLate | CancelStatus::Finished)
392 )
393 {
394 "마무리하는 중"
395 } else if model.cancellation_requested() || model.cancel.is_some() {
396 "취소하는 중..."
397 } else if model.conflict.is_some() {
398 "파일 충돌 선택 대기 중"
399 } else if model.challenge.is_some() {
400 "암호를 입력하세요"
401 } else {
402 model
403 .progress
404 .map_or("압축파일을 읽는 중", |(stage, _, _, _)| {
405 progress_text(stage, creating)
406 })
407 }
408}
409
410pub fn valid_output_leaf(name: &str) -> bool {
411 valid_leaf(name) && worker_protocol::archive::valid_name(name, false).is_ok()
412}
413
414pub fn gzip_output_name(archive: &Path) -> String {
415 let file_name = archive
416 .file_name()
417 .and_then(|name| name.to_str())
418 .unwrap_or("");
419 let candidate = file_name
420 .rsplit_once('.')
421 .filter(|(_, suffix)| suffix.eq_ignore_ascii_case("gz"))
422 .map_or(file_name, |(stem, _)| stem);
423 if valid_output_leaf(candidate) {
424 candidate.to_owned()
425 } else {
426 "압축 해제 파일".into()
427 }
428}
429
430pub fn operation_text(text: &str, creating: bool) -> String {
431 if creating {
432 text.replace("풀 위치", "저장 위치")
433 .replace("선택한 항목", "추가한 항목")
434 .replace(
435 "일부 파일만 풀렸습니다. 풀린 파일은",
436 "ZIP 파일이 일부만 저장됐습니다. 저장된 파일은",
437 )
438 } else {
439 text.to_owned()
440 }
441}
442
443pub fn volume_problem_text(problem: &VolumeProblem) -> String {
444 fn visible(c: char) -> String {
445 if c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') {
446 c.escape_unicode().to_string()
447 } else {
448 c.to_string()
449 }
450 }
451 let name = match &problem.volume {
452 NativePath::Unix(bytes) => bytes
453 .utf8_chunks()
454 .map(|chunk| {
455 let mut text = chunk.valid().chars().map(visible).collect::<String>();
456 for byte in chunk.invalid() {
457 text.push_str(&format!("\\x{byte:02x}"));
458 }
459 text
460 })
461 .collect::<String>(),
462 NativePath::Windows(units) => char::decode_utf16(units.iter().copied())
463 .map(|c| {
464 c.map(visible)
465 .unwrap_or_else(|e| format!("\\u{{{:04x}}}", e.unpaired_surrogate()))
466 })
467 .collect::<String>(),
468 };
469 match problem.reason {
470 VolumeProblemReason::FirstVolumeRequired => format!("첫 조각 {name}을 선택해 다시 여세요."),
471 VolumeProblemReason::MissingVolume => {
472 format!("{name} 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 .001을 다시 여세요.")
473 }
474 VolumeProblemReason::IncompleteSet => format!(
475 "{name}의 분할 묶음이 불완전하거나 손상됐습니다. 모든 조각의 존재와 손상을 확인한 뒤 .001을 다시 여세요."
476 ),
477 }
478}
479
480pub const SPLIT_SUPPORT: &str =
481 "분할 7z는 .7z.001부터 열 수 있습니다. 분할 ZIP과 RAR는 지원하지 않습니다.";
482
483/// 7z 분할 볼륨 크기 단위. 크기 표시(bytes_text)와 같이 1 MB = 1,048,576바이트.
484#[derive(Clone, Copy, Debug, PartialEq, Eq)]
485pub enum VolumeUnit {
486 Mb,
487 Gb,
488}
489impl VolumeUnit {
490 pub fn label(self) -> &'static str {
491 match self {
492 Self::Mb => "MB",
493 Self::Gb => "GB",
494 }
495 }
496 fn bytes(self) -> u64 {
497 match self {
498 Self::Mb => 1 << 20,
499 Self::Gb => 1 << 30,
500 }
501 }
502}
503/// 분할 7z 볼륨 수 상한. 분할 읽기는 `.001`부터 `.999`까지만 찾음.
504pub const MAX_VOLUMES: u64 = worker_protocol::protocol::MAX_SEVEN_ZIP_VOLUMES;
505pub const VOLUME_SIZE_ERROR: &str = "쪼갤 용량은 1 이상의 정수로 입력하세요";
506pub const VOLUME_LIMIT_ERROR: &str =
507 "볼륨이 999개를 넘거나 처리 한도를 넘었습니다. 쪼갤 용량을 늘려 다시 만드세요";
508
509/// 입력한 숫자와 단위를 볼륨 바이트 수로 바꿈. 최소 1 MB이고 정수만 받음.
510pub fn volume_size(amount: &str, unit: VolumeUnit) -> Result<u64, &'static str> {
511 let amount = amount.trim();
512 if amount.is_empty() || amount.len() > 9 || !amount.bytes().all(|b| b.is_ascii_digit()) {
513 return Err(VOLUME_SIZE_ERROR);
514 }
515 amount
516 .parse::<u64>()
517 .ok()
518 .and_then(|value| value.checked_mul(unit.bytes()))
519 .filter(|bytes| *bytes >= worker_protocol::protocol::MIN_SEVEN_ZIP_VOLUME_BYTES)
520 .ok_or(VOLUME_SIZE_ERROR)
521}
522
523/// 분할 7z의 `index`번째 볼륨 경로 (`이름.7z.001` 형식).
524pub fn volume_path(output: &Path, index: u64) -> PathBuf {
525 let mut name = output.as_os_str().to_owned();
526 name.push(format!(".{index:03}"));
527 PathBuf::from(name)
528}
529
530/// 같은 폴더에 분할 읽기가 한 묶음으로 볼 `이름.7z.<숫자>`가 이미 있으면 그 이름.
531pub fn existing_volume(output: &Path) -> Option<String> {
532 let parent = output.parent()?;
533 let prefix = format!("{}.", output.file_name()?.to_str()?);
534 let fold = |value: &str| {
535 if cfg!(windows) {
536 value.to_lowercase()
537 } else {
538 value.to_owned()
539 }
540 };
541 let prefix = fold(&prefix);
542 fs::read_dir(parent).ok()?.flatten().find_map(|entry| {
543 let name = entry.file_name().to_string_lossy().into_owned();
544 let suffix = fold(&name).strip_prefix(&prefix)?.to_owned();
545 (!suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit())).then_some(name)
546 })
547}
548
549pub fn excluded_split(path: &Path) -> bool {
550 let name = path
551 .file_name()
552 .unwrap_or_default()
553 .to_string_lossy()
554 .to_ascii_lowercase();
555 name.ends_with(".zip.001") || name.ends_with(".z01") || name.ends_with(".rar")
556}
557
558/// 같은 이름이 이미 있으면 `이름 (1)`, `이름 (2)`처럼 비어 있는 이름을 찾음.
559pub fn unique_folder(base: &Path) -> PathBuf {
560 let taken = |path: &Path| fs::symlink_metadata(path).is_ok();
561 if !taken(base) {
562 return base.to_path_buf();
563 }
564 let name = base.file_name().unwrap_or_default().to_string_lossy();
565 (1..)
566 .map(|n| base.with_file_name(format!("{name} ({n})")))
567 .find(|path| !taken(path))
568 .unwrap()
569}
570
571fn private_dir(path: &Path) -> io::Result<()> {
572 let mut builder = fs::DirBuilder::new();
573 #[cfg(unix)]
574 {
575 use std::os::unix::fs::DirBuilderExt;
576 builder.mode(0o700);
577 }
578 builder.create(path)
579}
580
581pub struct OpenRoot {
582 path: PathBuf,
583 handle: fs::File,
584 identity: worker_protocol::protocol::SourceObject,
585}
586
587impl OpenRoot {
588 fn capture(path: PathBuf) -> io::Result<Self> {
589 let handle = open_root_handle(&path)?;
590 // 만든 직후에는 비어 있어야 함. 만든 뒤 핸들을 잡기 전에 다른 폴더로 바뀌었다면
591 // 사용자 데이터가 들어 있을 수 있으므로 원본으로 기록하지 않음.
592 if !worker_protocol::tree_remove::is_empty(&handle, &path)? {
593 return Err(io::Error::other("만든 임시 폴더가 아님"));
594 }
595 let identity = worker_protocol::filesystem::object(&handle)
596 .map_err(|_| io::Error::other("임시 폴더 식별 실패"))?;
597 Ok(Self {
598 path,
599 handle,
600 identity,
601 })
602 }
603
604 pub fn path(&self) -> &Path {
605 &self.path
606 }
607
608 pub fn is_current(&self) -> bool {
609 // 원본 핸들을 유지해 삭제된 inode가 재사용되어도 같다고 판정하지 않음.
610 self.handle.metadata().is_ok()
611 && open_root_handle(&self.path)
612 .ok()
613 .and_then(|file| worker_protocol::filesystem::object(&file).ok())
614 .is_some_and(|identity| identity == self.identity)
615 }
616}
617
618fn open_root_handle(path: &Path) -> io::Result<fs::File> {
619 let mut options = fs::OpenOptions::new();
620 options.read(true);
621 #[cfg(target_os = "linux")]
622 {
623 use std::os::unix::fs::OpenOptionsExt;
624 options.custom_flags(0x20000); // 심볼릭 링크를 따라가지 않음.
625 }
626 #[cfg(windows)]
627 {
628 use std::os::windows::fs::OpenOptionsExt;
629 // 폴더 자체를 열며 재분석 지점을 따라가지 않음.
630 // 삭제 공유를 허용하지 않아 열어 둔 동안 폴더 이름을 바꾸거나 지울 수 없게 함.
631 options.share_mode(1 | 2).custom_flags(0x02000000 | 0x00200000);
632 }
633 let file = options.open(path)?;
634 let metadata = file.metadata()?;
635 if !metadata.is_dir() || fs::symlink_metadata(path)?.file_type().is_symlink() {
636 return Err(io::Error::other("임시 폴더가 아님"));
637 }
638 #[cfg(windows)]
639 {
640 use std::os::windows::fs::MetadataExt;
641 if metadata.file_attributes() & 0x400 != 0 {
642 return Err(io::Error::other("재분석 지점은 임시 폴더로 쓰지 않음"));
643 }
644 }
645 Ok(file)
646}
647
648/// 압축파일 안 파일을 기본 프로그램으로 열 때 쓸 임시 폴더를 만듦.
649/// 압축파일과 같은 폴더에 만들고, 그곳에 만들 수 없으면 시스템 임시 폴더를 씀.
650/// 숨김 폴더로 만들지 않음. snap으로 설치한 Firefox 등은 홈 바로 아래 숨김 폴더와
651/// 시스템 임시 폴더의 파일을 읽지 못해 열기 요청을 조용히 무시함.
652pub fn create_open_root(archive: &Path) -> io::Result<OpenRoot> {
653 create_open_root_with(archive, |_| {})
654}
655
656/// `create_open_root`와 같고, 폴더를 만든 직후 핸들을 잡기 전에 `after_create`를 실행함.
657/// 만든 뒤 경로가 바뀌는 경우를 시험하려고 둠.
658/// 폴더를 만든 뒤 핸들을 잡기까지의 틈에 경로가 바뀌어도, 핸들로 확인한 폴더가 비어 있지
659/// 않으면 원본으로 쓰지 않고 다른 이름으로 다시 만듦. 바뀐 폴더는 건드리지 않음.
660pub fn create_open_root_with(
661 archive: &Path,
662 mut after_create: impl FnMut(&Path),
663) -> io::Result<OpenRoot> {
664 let name = archive.file_name().unwrap_or_default().to_string_lossy();
665 let mut error = None;
666 // Windows는 점으로 숨겨지지 않으므로 숨김 속성을 줌.
667 if let Some(parent) = archive.parent().filter(|p| !p.as_os_str().is_empty()) {
668 let base = parent.join(open_root_name_in(parent, &name));
669 for _ in 0..8 {
670 let path = unique_folder(&base);
671 match private_dir(&path) {
672 Ok(()) => {
673 #[cfg(windows)]
674 hide_folder(&path);
675 after_create(&path);
676 match OpenRoot::capture(path.clone()) {
677 Ok(root) => return Ok(root),
678 Err(e) => {
679 // 비어 있는 폴더만 지워지므로 바뀐 폴더의 내용은 남음.
680 let _ = fs::remove_dir(&path);
681 error = Some(e);
682 continue;
683 }
684 }
685 }
686 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
687 Err(e) => {
688 error = Some(e);
689 break;
690 }
691 }
692 }
693 }
694 let base = std::env::temp_dir().join(format!("zipelo-{}-{name}", std::process::id()));
695 let path = unique_folder(&base);
696 private_dir(&path).map_err(|e| error.unwrap_or(e))?;
697 after_create(&path);
698 OpenRoot::capture(path.clone()).inspect_err(|_| {
699 let _ = fs::remove_dir(&path);
700 })
701}
702
703/// Windows 탐색기에서 임시 폴더가 압축파일 옆에 보이지 않도록 숨김 속성을 줌.
704/// 실패해도 폴더는 그대로 씀. unsafe 없이 시스템의 attrib.exe를 창 없이 실행함.
705#[cfg(windows)]
706pub fn hide_folder(path: &Path) {
707 use std::os::windows::process::CommandExt;
708 let Some(system) = std::env::var_os("SystemRoot").map(PathBuf::from) else {
709 return;
710 };
711 let _ = std::process::Command::new(system.join("System32").join("attrib.exe"))
712 .arg("+h")
713 .arg(path)
714 .creation_flags(0x0800_0000)
715 .stdin(std::process::Stdio::null())
716 .stdout(std::process::Stdio::null())
717 .stderr(std::process::Stdio::null())
718 .status();
719}
720
721/// 열기와 끌어 놓기용 임시 폴더 이름. 예: `.자료.zip (Zipelo 임시)`.
722/// 파일 관리자에서 압축파일 옆에 풀린 것처럼 보이지 않도록 Unix 계열에서는 숨김
723/// 이름(앞에 '.')을 씀. Windows는 점으로 숨겨지지 않으므로 원래 이름에 숨김 속성을 줌.
724pub fn open_root_name(archive_name: &str) -> String {
725 if cfg!(windows) {
726 format!("{archive_name} (Zipelo 임시)")
727 } else {
728 format!(".{archive_name} (Zipelo 임시)")
729 }
730}
731
732/// `parent` 폴더에 만들 임시 폴더 이름. snap 앱(Firefox 등)은 홈 폴더 바로 아래의
733/// 숨김 항목을 읽지 못하므로, 압축파일이 홈 폴더 바로 아래에 있으면 숨기지 않음.
734/// 그보다 아래 폴더의 숨김 항목은 snap 앱도 읽을 수 있음.
735pub fn open_root_name_in(parent: &Path, archive_name: &str) -> String {
736 let home = home_directory();
737 let same = |a: &Path, b: &Path| {
738 a == b || a.canonicalize().ok().zip(b.canonicalize().ok()).is_some_and(|(a, b)| a == b)
739 };
740 if cfg!(windows) || same(parent, &home) {
741 format!("{archive_name} (Zipelo 임시)")
742 } else {
743 open_root_name(archive_name)
744 }
745}
746
747/// 이 앱이 만든 열기용 폴더를 지움. 다른 프로그램이 파일을 쓰고 있으면 남을 수 있음.
748pub fn remove_open_root(root: OpenRoot) {
749 remove_open_root_with(root, || {});
750}
751
752/// `remove_open_root`와 같고, 정체를 확인한 직후 삭제 전에 `after_check`를 실행함.
753/// 확인과 삭제 사이에 경로가 바뀌는 경우를 시험하려고 둠.
754/// 내용은 만들 때 열어 둔 폴더 핸들에 묶어 지우므로 경로가 바뀌어도 다른 폴더는 건드리지 않음.
755pub fn remove_open_root_with(root: OpenRoot, after_check: impl FnOnce()) {
756 if !root.is_current() {
757 return;
758 }
759 after_check();
760 let OpenRoot { path, handle, .. } = root;
761 let _ = worker_protocol::tree_remove::remove_contents(&handle, &path);
762 // Windows는 핸들을 닫아야 폴더를 지울 수 있음.
763 drop(handle);
764 // 비어 있지 않거나 링크로 바뀐 경로는 지워지지 않으므로 다른 내용이 사라지지 않음.
765 let _ = fs::remove_dir(&path);
766}
767
768/// 기본 프로그램으로 열면 실행될 수 있는 파일은 바로 열지 않음.
769/// Windows는 스크립트도 연결 프로그램이 바로 실행하므로 범위가 넓고,
770/// Linux는 스크립트를 편집기로 열므로 실행·설치 파일만 막음.
771pub fn blocked_open(name: &str) -> bool {
772 #[cfg(windows)]
773 const EXECUTABLE: &[&str] = &[
774 "exe", "com", "bat", "cmd", "scr", "pif", "msi", "msp", "msc", "ps1", "psm1", "vbs",
775 "vbe", "js", "jse", "wsf", "wsh", "hta", "cpl", "lnk", "url", "reg", "jar", "inf", "scf",
776 "chm", "dll", "sys", "appref-ms", "application", "gadget", "settingcontent-ms",
777 ];
778 #[cfg(not(windows))]
779 const EXECUTABLE: &[&str] = &[
780 "desktop", "appimage", "run", "bin", "jar", "deb", "rpm", "snap", "flatpakref",
781 "flatpak", "exe", "msi",
782 ];
783 open_extension(name).is_some_and(|ext| EXECUTABLE.contains(&ext.to_ascii_lowercase().as_str()))
784}
785
786fn open_extension(name: &str) -> Option<&str> {
787 let leaf = name.rsplit(['/', '\\']).next().unwrap_or(name);
788 leaf.rsplit_once('.')
789 .map(|(_, ext)| ext)
790 .filter(|ext| !ext.is_empty())
791}
792
793/// 실행 파일이라 열지 않았다는 짧은 안내. 압축은 풀지 않음.
794pub fn open_blocked_text(name: &str) -> String {
795 match open_extension(name) {
796 Some(ext) => format!("실행 파일(.{ext})은 안전을 위해 바로 열 수 없습니다"),
797 None => "실행 파일은 안전을 위해 바로 열 수 없습니다".into(),
798 }
799}
800
801pub const OPEN_FAILED: &str = "파일을 열 프로그램을 실행하지 못했습니다";
802pub const OPEN_MISSING: &str = "풀린 파일을 찾지 못해 열지 못했습니다";
803
804
805/// 운영체제에 설정된 기본 프로그램으로 파일을 엶.
806pub fn open_with_default(path: &Path) -> Result<(), String> {
807 #[cfg(windows)]
808 let mut command = {
809 let mut command = std::process::Command::new("explorer.exe");
810 command.arg(path);
811 command
812 };
813 #[cfg(not(windows))]
814 let mut command = {
815 let mut command = std::process::Command::new("xdg-open");
816 command.arg(path);
817 command
818 };
819 command
820 .stdin(std::process::Stdio::null())
821 .stdout(std::process::Stdio::null())
822 .stderr(std::process::Stdio::null());
823 let mut child = command.spawn().map_err(|_| OPEN_FAILED.to_owned())?;
824 // 끝난 자식 프로세스를 거둬 좀비로 남지 않게 함.
825 std::thread::spawn(move || {
826 let _ = child.wait();
827 });
828 Ok(())
829}