team-ljyzipelo

공개
424줄14 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::Integrity => "압축파일이 손상됐습니다",
23 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
24 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
25 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
26 ErrorCode::UnsafePath => "파일 경로의 안전성을 확인할 수 없어 중단했습니다",
27 ErrorCode::Conflict => "같은 이름의 파일이 이미 있습니다. 다른 폴더를 선택하세요",
28 ErrorCode::Limit => "처리 한도를 초과했습니다",
29 ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요",
30 ErrorCode::DiskFull => "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
31 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
32 ErrorCode::InvalidRequest => "풀 위치와 선택한 항목을 확인하세요",
33 ErrorCode::Protocol | ErrorCode::Internal => INTERNAL,
34 }
35}
36
37pub fn progress_text(stage: Stage, creating: bool) -> &'static str {
38 match stage {
39 Stage::Scan | Stage::Read => "압축파일을 읽는 중",
40 Stage::Decode if creating => "압축하는 중",
41 Stage::Decode => "압축을 푸는 중",
42 Stage::Write => "파일을 저장하는 중",
43 Stage::Verify => "확인하는 중",
44 Stage::Commit => "마무리하는 중",
45 }
46}
47
48pub fn bytes_text(bytes: u64) -> String {
49 for (unit, size) in [("GB", 1_u64 << 30), ("MB", 1 << 20), ("KB", 1 << 10)] {
50 if bytes >= size {
51 return format!("{:.1} {unit}", bytes as f64 / size as f64);
52 }
53 }
54 format!("{bytes} B")
55}
56
57pub fn middle_text(text: &str, max_chars: usize) -> String {
58 let chars = text.chars().collect::<Vec<_>>();
59 if chars.len() <= max_chars || max_chars < 5 {
60 return text.into();
61 }
62 let left = (max_chars - 1) / 2;
63 chars[..left]
64 .iter()
65 .chain(std::iter::once(&'…'))
66 .chain(chars[chars.len() - (max_chars - left - 1)..].iter())
67 .collect()
68}
69
70pub fn default_destination(archive: &Path) -> PathBuf {
71 let name = archive.file_name().unwrap_or_default().to_string_lossy();
72 let lower = name.to_ascii_lowercase();
73 let stem = if lower.ends_with(".tar.gz") {
74 &name[..name.len() - 7]
75 } else {
76 name.rsplit_once('.')
77 .map_or(name.as_ref(), |(stem, _)| stem)
78 };
79 archive.with_file_name(if stem.is_empty() {
80 "압축 해제"
81 } else {
82 stem
83 })
84}
85
86pub fn prepare_destination(path: &Path, automatic: bool) -> io::Result<bool> {
87 match fs::symlink_metadata(path) {
88 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(false),
89 Ok(_) => Err(io::Error::other(FOLDER_ERROR)),
90 Err(error) if error.kind() == io::ErrorKind::NotFound && automatic => {
91 let mut builder = fs::DirBuilder::new();
92 #[cfg(unix)]
93 {
94 use std::os::unix::fs::DirBuilderExt;
95 builder.mode(0o700);
96 }
97 builder.create(path)?;
98 Ok(true)
99 }
100 Err(error) => Err(error),
101 }
102}
103
104pub fn remove_owned_empty(path: &Path) {
105 // 이번 요청에서 만든 폴더만 호출하며 비어 있지 않으면 보존함.
106 let _ = fs::remove_dir(path);
107}
108
109fn requested(entry: &Entry, selection: &Selection) -> bool {
110 match selection {
111 Selection::All => true,
112 Selection::EntryIds(ids) => ids.contains(&entry.id),
113 }
114}
115
116pub fn target_files(
117 entries: &[Entry],
118 selection: &Selection,
119 gzip: Option<&str>,
120) -> Option<BTreeSet<String>> {
121 let mut names = BTreeSet::new();
122 for entry in entries
123 .iter()
124 .filter(|entry| entry.kind == Kind::File && requested(entry, selection))
125 {
126 if !names.insert(gzip.unwrap_or(&entry.name).replace('\\', "/")) {
127 return None;
128 }
129 }
130 Some(names)
131}
132
133pub fn resolved_targets(
134 targets: Option<&BTreeSet<String>>,
135 entries: &[Entry],
136 gzip: Option<&str>,
137 resolutions: &[Resolution],
138) -> Option<BTreeSet<String>> {
139 let mut names = targets?.clone();
140 let entries: BTreeMap<_, _> = entries.iter().map(|entry| (entry.id, entry)).collect();
141 for resolution in resolutions {
142 let entry = entries.get(&resolution.entry_id)?;
143 let original = gzip.unwrap_or(&entry.name).replace('\\', "/");
144 if !names.remove(&original) {
145 return None;
146 }
147 }
148 for resolution in resolutions {
149 if resolution.choice != ConflictChoice::Skip
150 && !names.insert(resolution.relative_name.replace('\\', "/"))
151 {
152 return None;
153 }
154 }
155 Some(names)
156}
157
158pub fn target_directories(entries: &[Entry], selection: &Selection) -> BTreeSet<String> {
159 let mut directories = BTreeSet::new();
160 for entry in entries.iter().filter(|entry| {
161 matches!(entry.kind, Kind::File | Kind::Directory) && requested(entry, selection)
162 }) {
163 let normalized = entry.name.replace('\\', "/");
164 let name = normalized.trim_end_matches('/');
165 if entry.kind == Kind::Directory {
166 directories.insert(name.to_owned());
167 }
168 let mut parent = name;
169 while let Some((directory, _)) = parent.rsplit_once('/') {
170 directories.insert(directory.to_owned());
171 parent = directory;
172 }
173 }
174 directories
175}
176
177pub fn durability_warning(durability: Durability) -> Option<&'static str> {
178 match durability {
179 Durability::Failed => Some(SYNC_FAILED),
180 Durability::Unconfirmed => Some(SYNC_WARNING),
181 _ => None,
182 }
183}
184
185pub fn warnings(
186 terminal: Option<&Terminal>,
187 confirmed: bool,
188 targets: Option<&BTreeSet<String>>,
189 directories: &BTreeSet<String>,
190 outputs: &[(String, Disposition)],
191) -> Vec<&'static str> {
192 let mut result = publication_warnings(terminal, confirmed, targets, directories, outputs);
193 if let Some(warning) = terminal
194 .filter(|_| confirmed)
195 .and_then(|t| durability_warning(t.durability))
196 {
197 result.push(warning);
198 }
199 result
200}
201
202pub fn publication_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 Some(t) = terminal.filter(|_| confirmed) else {
210 return vec![UNCERTAIN];
211 };
212 let created = outputs
213 .iter()
214 .filter(|(_, state)| *state == Disposition::Created)
215 .map(|(name, _)| name.replace('\\', "/"))
216 .collect::<BTreeSet<_>>();
217 let created_reports = outputs
218 .iter()
219 .filter(|(_, state)| *state == Disposition::Created)
220 .count();
221 let uncertain = t.publication == Publication::Uncertain
222 || outputs
223 .iter()
224 .any(|(_, state)| *state == Disposition::CommitUncertain)
225 || created.len() != created_reports
226 || created_reports as u64 != t.created_count
227 || (t.publication == Publication::None && !created.is_empty());
228 let retained = t.retained_partial_count > 0
229 || outputs
230 .iter()
231 .any(|(_, state)| *state == Disposition::PartialRetained);
232 let mut result = Vec::new();
233 let mut all_saved_with_leftovers = false;
234 if uncertain {
235 result.push(UNCERTAIN);
236 } else if let Some(targets) = targets {
237 let files = created
238 .difference(directories)
239 .cloned()
240 .collect::<BTreeSet<_>>();
241 let saved = targets.intersection(&files).count();
242 let unknown = !targets.is_disjoint(directories)
243 || created
244 .iter()
245 .any(|name| !targets.contains(name) && !directories.contains(name));
246 if unknown {
247 result.push(UNCERTAIN);
248 } else if !targets.is_empty() && saved == targets.len() && retained {
249 result.push(LEFTOVERS);
250 all_saved_with_leftovers = true;
251 } else if saved > 0 && saved < targets.len() && t.outcome != Outcome::Completed {
252 result.push(PARTIAL);
253 } else if (saved == 0 && !files.is_empty())
254 || (retained && saved == 0)
255 || (t.outcome == Outcome::Completed && saved != targets.len())
256 {
257 result.push(UNCERTAIN);
258 }
259 } else {
260 result.push(UNCERTAIN);
261 }
262 if (retained || t.cleanup != Cleanup::Complete) && !all_saved_with_leftovers {
263 result.push(CLEANUP_WARNING);
264 }
265 result
266}
267
268pub fn definitely_unsaved(
269 t: Option<&Terminal>,
270 confirmed: bool,
271 outputs: &[(String, Disposition)],
272) -> bool {
273 t.is_some_and(|t| {
274 confirmed
275 && t.publication == Publication::None
276 && t.created_count == 0
277 && t.retained_partial_count == 0
278 && t.cleanup == Cleanup::Complete
279 && outputs
280 .iter()
281 .all(|(_, state)| *state == Disposition::Removed)
282 })
283}
284
285#[derive(Clone)]
286pub struct BrowserEntry {
287 pub path: PathBuf,
288 pub name: String,
289 pub directory: bool,
290 pub link: bool,
291}
292
293pub fn directory_entries(path: &Path) -> io::Result<Vec<BrowserEntry>> {
294 if fs::symlink_metadata(path)?.file_type().is_symlink() {
295 return Err(io::Error::other("링크 폴더는 탐색하지 않음"));
296 }
297 let mut entries = Vec::new();
298 for item in fs::read_dir(path)? {
299 let item = item?;
300 let kind = item.file_type()?;
301 entries.push(BrowserEntry {
302 path: item.path(),
303 name: item.file_name().to_string_lossy().into(),
304 directory: kind.is_dir(),
305 link: kind.is_symlink(),
306 });
307 }
308 entries.sort_by(|a, b| {
309 b.directory
310 .cmp(&a.directory)
311 .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
312 });
313 Ok(entries)
314}
315
316pub fn home_directory() -> PathBuf {
317 std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
318 .map(PathBuf::from)
319 .filter(|p| p.is_absolute())
320 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/")))
321}
322
323pub fn shortcuts() -> Vec<(String, PathBuf)> {
324 let home = home_directory();
325 let mut paths = vec![("홈".into(), home.clone())];
326 for (label, candidates) in [
327 ("바탕 화면", ["Desktop", "바탕화면"]),
328 ("문서", ["Documents", "문서"]),
329 ("다운로드", ["Downloads", "다운로드"]),
330 ] {
331 if let Some(path) = candidates
332 .iter()
333 .map(|name| home.join(name))
334 .find(|p| p.is_dir())
335 {
336 paths.push((label.into(), path));
337 }
338 }
339 #[cfg(windows)]
340 for drive in b'A'..=b'Z' {
341 let path = PathBuf::from(format!("{}:\\", drive as char));
342 if path.is_dir() {
343 paths.push((format!("{}:", drive as char), path));
344 }
345 }
346 paths
347}
348
349pub fn folder_command(path: &Path) -> std::process::Command {
350 let mut command = std::process::Command::new(if cfg!(windows) {
351 "explorer"
352 } else {
353 "xdg-open"
354 });
355 command.arg(path);
356 command
357}
358
359pub const UNCONFIRMED_FINISH: &str =
360 "작업이 정상적으로 끝났는지 확인하지 못했습니다. 풀 위치 폴더를 확인하세요";
361
362pub fn client_error_text(error: &str) -> &'static str {
363 if error.starts_with("작업자 종료 결과를 확인할 수 없습니다") {
364 UNCONFIRMED_FINISH
365 } else {
366 INTERNAL
367 }
368}
369
370pub fn activity_text(model: &Model, creating: bool) -> &'static str {
371 if model.terminal.is_some()
372 || matches!(
373 model.cancel,
374 Some(CancelStatus::TooLate | CancelStatus::Finished)
375 )
376 {
377 "마무리하는 중"
378 } else if model.cancellation_requested() || model.cancel.is_some() {
379 "취소하는 중..."
380 } else if model.conflict.is_some() {
381 "파일 충돌 선택 대기 중"
382 } else if model.challenge.is_some() {
383 "암호를 입력하세요"
384 } else {
385 model
386 .progress
387 .map_or("압축파일을 읽는 중", |(stage, _, _, _)| {
388 progress_text(stage, creating)
389 })
390 }
391}
392
393pub fn valid_output_leaf(name: &str) -> bool {
394 valid_leaf(name) && worker_protocol::archive::valid_name(name, false).is_ok()
395}
396
397pub fn gzip_output_name(archive: &Path) -> String {
398 let file_name = archive
399 .file_name()
400 .and_then(|name| name.to_str())
401 .unwrap_or("");
402 let candidate = file_name
403 .rsplit_once('.')
404 .filter(|(_, suffix)| suffix.eq_ignore_ascii_case("gz"))
405 .map_or(file_name, |(stem, _)| stem);
406 if valid_output_leaf(candidate) {
407 candidate.to_owned()
408 } else {
409 "압축 해제 파일".into()
410 }
411}
412
413pub fn operation_text(text: &str, creating: bool) -> String {
414 if creating {
415 text.replace("풀 위치", "저장 위치")
416 .replace("선택한 항목", "추가한 항목")
417 .replace(
418 "일부 파일만 풀렸습니다. 풀린 파일은",
419 "ZIP 파일이 일부만 저장됐습니다. 저장된 파일은",
420 )
421 } else {
422 text.to_owned()
423 }
424}