team-ljyzipelo

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