team-ljyzipelo

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