team-ljyzipelo

공개
238줄8.1 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 pause: bool,
22}
23#[derive(Default, Clone)]
24pub struct FakeFactory {
25 pub state: Rc<RefCell<State>>,
26}
27impl FakeFactory {
28 pub fn manual() -> Self {
29 let f = Self::default();
30 f.state.borrow_mut().manual = true;
31 f
32 }
33}
34impl State {
35 pub fn frame(&mut self, event: Event) {
36 let sequence = self.sequence;
37 self.sequence += 1;
38 self.queue.push_back(HostEvent::Frame {
39 job_id: self.job,
40 sequence,
41 event,
42 });
43 }
44 pub fn finish(&mut self, outcome: Outcome, publication: Publication) {
45 self.frame(Event::Terminal(Terminal {
46 outcome,
47 error: None,
48 publication,
49 created_count: if publication == Publication::Complete {
50 1
51 } else {
52 0
53 },
54 retained_partial_count: 0,
55 durability: Durability::Synced,
56 cleanup: Cleanup::Complete,
57 }));
58 self.queue.push_back(HostEvent::StdoutEof);
59 self.queue.push_back(HostEvent::StderrEof);
60 self.queue.push_back(HostEvent::Exited { success: true });
61 }
62 fn complete_action(&mut self) {
63 match self.starts.last().cloned().unwrap() {
64 Start::List { archive } => {
65 self.frame(Event::Entry(Entry {
66 id: 0,
67 name: "읽어주세요.txt".into(),
68 kind: Kind::File,
69 bytes: Some(31),
70 packed: Some(54),
71 encrypted: false,
72 }));
73 let format = self.list_format.unwrap_or_else(|| {
74 if archive.extension().is_some_and(|x| x == "gz") {
75 Format::Gzip
76 } else {
77 Format::Zip
78 }
79 });
80 self.frame(Event::ListEnd {
81 entry_count: 1,
82 list_id: ListId {
83 catalog_version: 1,
84 format,
85 source_object: SourceObject::Unix {
86 device: 1,
87 inode: 1,
88 },
89 archive_bytes: 54,
90 archive_sha256: [7; 32],
91 },
92 });
93 self.finish(Outcome::Completed, Publication::None);
94 }
95 _ => {
96 self.frame(Event::Progress {
97 stage: Stage::Write,
98 processed: 31,
99 total: Some(31),
100 completed_entries: 1,
101 });
102 self.frame(Event::Output {
103 entry_id: Some(0),
104 relative_name: "읽어주세요.txt".into(),
105 disposition: Disposition::Created,
106 });
107 self.finish(Outcome::Completed, Publication::Complete);
108 }
109 }
110 }
111}
112struct FakeConnection {
113 state: Rc<RefCell<State>>,
114}
115impl Drop for FakeConnection {
116 fn drop(&mut self) {
117 self.state.borrow_mut().dropped_connections += 1;
118 }
119}
120impl Factory for FakeFactory {
121 fn connect(&mut self, job: u64) -> Result<Box<dyn Connection>, String> {
122 let mut s = self.state.borrow_mut();
123 s.job = job;
124 s.sequence = 0;
125 s.queue.clear();
126 s.pause = false;
127 Ok(Box::new(FakeConnection {
128 state: self.state.clone(),
129 }))
130 }
131}
132impl Connection for FakeConnection {
133 fn send(&mut self, request: Request) -> Result<(), String> {
134 let mut s = self.state.borrow_mut();
135 assert_eq!(s.job, request.job_id);
136 if matches!(&request.command, Command::StartExpanded(_)) {
137 s.expanded = true;
138 }
139 match request.command {
140 Command::Start(start) | Command::StartExpanded(start) => {
141 if let Start::Extract {
142 list_id,
143 gzip_output_name,
144 ..
145 } = &start
146 {
147 let valid = match list_id.format {
148 Format::Gzip => gzip_output_name.as_deref().is_some_and(valid_leaf),
149 _ => gzip_output_name.is_none(),
150 };
151 if !valid {
152 return Err("형식에 맞지 않는 GZIP 출력명".into());
153 }
154 }
155 s.requests.push((request.sequence, "start"));
156 s.starts.push(start.clone());
157 if s.fail_start {
158 return Err("Start 전송 실패".into());
159 }
160 if !s.manual {
161 s.frame(Event::Accepted { encryption: false });
162 s.frame(Event::Progress {
163 stage: Stage::Scan,
164 processed: 0,
165 total: None,
166 completed_entries: 0,
167 });
168 if matches!(&start,Start::List {archive} if archive.file_name().is_some_and(|n|n.to_string_lossy().contains("locked")))
169 {
170 s.frame(Event::PasswordRequired {
171 challenge_id: 17,
172 attempt: 1,
173 encrypt: false,
174 });
175 } else {
176 s.complete_action();
177 }
178 }
179 }
180 Command::Password {
181 challenge_id,
182 secret,
183 } => {
184 assert_eq!(challenge_id, 17);
185 assert!(!secret.as_bytes().is_empty());
186 s.password_seen = true;
187 s.password = secret.as_bytes().to_vec();
188 s.requests.push((request.sequence, "password"));
189 if !s.manual {
190 s.complete_action();
191 }
192 }
193 Command::ResourceReply {
194 challenge_id,
195 scope,
196 allow,
197 } => {
198 s.resources.push((challenge_id, scope, allow));
199 }
200 Command::ConflictReply {
201 challenge_id,
202 choice,
203 apply_to_remaining,
204 } => {
205 s.requests.push((request.sequence, "conflict"));
206 s.conflict_replies
207 .push((challenge_id, choice, apply_to_remaining));
208 }
209 Command::Cancel => {
210 s.requests.push((request.sequence, "cancel"));
211 if !s.manual {
212 let consumed = s
213 .queue
214 .iter()
215 .filter(|e| matches!(e, HostEvent::Frame { .. }))
216 .count() as u64;
217 s.sequence -= consumed;
218 s.queue.clear();
219 s.frame(Event::CancelAck {
220 request_sequence: request.sequence,
221 status: CancelStatus::Requested,
222 });
223 s.finish(Outcome::Cancelled, Publication::None);
224 }
225 }
226 }
227 Ok(())
228 }
229 fn poll(&mut self) -> Option<HostEvent> {
230 let mut s = self.state.borrow_mut();
231 if s.pause {
232 s.pause = false;
233 return None;
234 }
235 s.pause = true;
236 s.queue.pop_front()
237 }
238}