team-ljyzipelo

공개
279줄9.8 KB
1use std::{cell::RefCell, collections::VecDeque, rc::Rc};
2use zipelo_ui_memory_app::archive_ui::*;
3
4#[derive(Default)]
5pub struct State {
6 pub requests: Vec<(u64, &'static str)>,
7 pub starts: Vec<Start>,
8 pub password_seen: bool,
9 pub expanded: bool,
10 pub resources: Vec<(u64, ResourceScope, bool)>,
11 pub conflict_replies: Vec<(u64, ConflictChoice, bool)>,
12 /// 마지막으로 받은 암호 원문. 화면에서 입력한 암호가 그대로 전달됐는지 확인할 때 씀.
13 pub password: Vec<u8>,
14 pub job: u64,
15 sequence: u64,
16 pub queue: VecDeque<HostEvent>,
17 pub manual: bool,
18 pub list_format: Option<Format>,
19 pub fail_start: bool,
20 pub dropped_connections: usize,
21 /// 풀기 출력으로 알릴 이름. 없으면 "읽어주세요.txt" 하나를 알림.
22 pub outputs: Option<Vec<String>>,
23 pause: bool,
24}
25#[derive(Default, Clone)]
26pub struct FakeFactory {
27 pub state: Rc<RefCell<State>>,
28}
29impl FakeFactory {
30 pub fn manual() -> Self {
31 let f = Self::default();
32 f.state.borrow_mut().manual = true;
33 f
34 }
35}
36impl State {
37 pub fn frame(&mut self, event: Event) {
38 let sequence = self.sequence;
39 self.sequence += 1;
40 self.queue.push_back(HostEvent::Frame {
41 job_id: self.job,
42 sequence,
43 event,
44 });
45 }
46 pub fn finish(&mut self, outcome: Outcome, publication: Publication) {
47 self.frame(Event::Terminal(Terminal {
48 outcome,
49 error: None,
50 publication,
51 created_count: if publication == Publication::Complete {
52 1
53 } else {
54 0
55 },
56 retained_partial_count: 0,
57 durability: Durability::Synced,
58 cleanup: Cleanup::Complete,
59 }));
60 self.queue.push_back(HostEvent::StdoutEof);
61 self.queue.push_back(HostEvent::StderrEof);
62 self.queue.push_back(HostEvent::Exited { success: true });
63 }
64 fn complete_action(&mut self) {
65 match self.starts.last().cloned().unwrap() {
66 Start::List { archive } => {
67 self.frame(Event::Entry(Entry {
68 id: 0,
69 name: "읽어주세요.txt".into(),
70 kind: Kind::File,
71 bytes: Some(31),
72 packed: Some(54),
73 encrypted: false,
74 }));
75 let format = self.list_format.unwrap_or_else(|| {
76 if archive.extension().is_some_and(|x| x == "gz") {
77 Format::Gzip
78 } else {
79 Format::Zip
80 }
81 });
82 self.frame(Event::ListEnd {
83 entry_count: 1,
84 list_id: ListId {
85 catalog_version: 1,
86 format,
87 source_object: SourceObject::Unix {
88 device: 1,
89 inode: 1,
90 },
91 archive_bytes: 54,
92 archive_sha256: [7; 32],
93 },
94 });
95 self.finish(Outcome::Completed, Publication::None);
96 }
97 Start::Preview { entry_id, .. } => {
98 use sha2::{Digest, Sha256};
99 let data = "미리보기 내용".as_bytes().to_vec();
100 self.frame(Event::PreviewBegin(PreviewInfo {
101 entry_id,
102 format: PreviewFormat::Utf8Text,
103 total_bytes: data.len() as u64,
104 width: 0,
105 height: 0,
106 }));
107 self.frame(Event::PreviewChunk {
108 entry_id,
109 offset: 0,
110 data: data.clone(),
111 });
112 self.frame(Event::PreviewEnd {
113 entry_id,
114 total_bytes: data.len() as u64,
115 sha256: Sha256::digest(&data).into(),
116 });
117 self.frame(Event::Terminal(Terminal {
118 outcome: Outcome::Completed,
119 error: None,
120 publication: Publication::None,
121 created_count: 0,
122 retained_partial_count: 0,
123 durability: Durability::NotApplicable,
124 cleanup: Cleanup::Complete,
125 }));
126 self.queue.push_back(HostEvent::StdoutEof);
127 self.queue.push_back(HostEvent::StderrEof);
128 self.queue.push_back(HostEvent::Exited { success: true });
129 }
130 _ => {
131 self.frame(Event::Progress {
132 stage: Stage::Write,
133 processed: 31,
134 total: Some(31),
135 completed_entries: 1,
136 });
137 let names = self
138 .outputs
139 .clone()
140 .unwrap_or_else(|| vec!["읽어주세요.txt".into()]);
141 for name in names {
142 self.frame(Event::Output {
143 entry_id: None,
144 relative_name: name,
145 disposition: Disposition::Created,
146 });
147 }
148 self.finish(Outcome::Completed, Publication::Complete);
149 }
150 }
151 }
152}
153struct FakeConnection {
154 state: Rc<RefCell<State>>,
155}
156impl Drop for FakeConnection {
157 fn drop(&mut self) {
158 self.state.borrow_mut().dropped_connections += 1;
159 }
160}
161impl Factory for FakeFactory {
162 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
163 let mut s = self.state.borrow_mut();
164 s.job = job;
165 s.sequence = 0;
166 s.queue.clear();
167 s.pause = false;
168 Ok(Box::new(FakeConnection {
169 state: self.state.clone(),
170 }))
171 }
172}
173impl Connection for FakeConnection {
174 fn send(&mut self, request: Request) -> Result<(), String> {
175 let mut s = self.state.borrow_mut();
176 assert_eq!(s.job, request.job_id);
177 if matches!(&request.command, Command::StartExpanded(_)) {
178 s.expanded = true;
179 }
180 match request.command {
181 Command::Start(start) | Command::StartExpanded(start) => {
182 if let Start::Extract {
183 list_id,
184 gzip_output_name,
185 ..
186 } = &start
187 {
188 let valid = match list_id.format {
189 Format::Gzip => gzip_output_name.as_deref().is_some_and(valid_leaf),
190 _ => gzip_output_name.is_none(),
191 };
192 if !valid {
193 return Err("형식에 맞지 않는 GZIP 출력명".into());
194 }
195 }
196 s.requests.push((request.sequence, "start"));
197 s.starts.push(start.clone());
198 if s.fail_start {
199 return Err("Start 전송 실패".into());
200 }
201 if !s.manual {
202 s.frame(Event::Accepted { encryption: false });
203 s.frame(Event::Progress {
204 stage: Stage::Scan,
205 processed: 0,
206 total: None,
207 completed_entries: 0,
208 });
209 if matches!(&start,Start::List {archive} if archive.file_name().is_some_and(|n|n.to_string_lossy().contains("locked")))
210 {
211 s.frame(Event::PasswordRequired {
212 challenge_id: 17,
213 attempt: 1,
214 encrypt: false,
215 });
216 } else {
217 s.complete_action();
218 }
219 }
220 }
221 Command::Password {
222 challenge_id,
223 secret,
224 } => {
225 assert_eq!(challenge_id, 17);
226 assert!(!secret.as_bytes().is_empty());
227 s.password_seen = true;
228 s.password = secret.as_bytes().to_vec();
229 s.requests.push((request.sequence, "password"));
230 if !s.manual {
231 s.complete_action();
232 }
233 }
234 Command::ResourceReply {
235 challenge_id,
236 scope,
237 allow,
238 } => {
239 s.resources.push((challenge_id, scope, allow));
240 }
241 Command::ConflictReply {
242 challenge_id,
243 choice,
244 apply_to_remaining,
245 } => {
246 s.requests.push((request.sequence, "conflict"));
247 s.conflict_replies
248 .push((challenge_id, choice, apply_to_remaining));
249 }
250 Command::Cancel => {
251 s.requests.push((request.sequence, "cancel"));
252 if !s.manual {
253 let consumed = s
254 .queue
255 .iter()
256 .filter(|e| matches!(e, HostEvent::Frame { .. }))
257 .count() as u64;
258 s.sequence -= consumed;
259 s.queue.clear();
260 s.frame(Event::CancelAck {
261 request_sequence: request.sequence,
262 status: CancelStatus::Requested,
263 });
264 s.finish(Outcome::Cancelled, Publication::None);
265 }
266 }
267 }
268 Ok(())
269 }
270 fn poll(&mut self) -> Option<HostEvent> {
271 let mut s = self.state.borrow_mut();
272 if s.pause {
273 s.pause = false;
274 return None;
275 }
276 s.pause = true;
277 s.queue.pop_front()
278 }
279}