1use core::fmt;
47
48use alloc::string::{String, ToString};
49
50use imap_codec::{
51 CommandCodec,
52 fragmentizer::Fragmentizer,
53 imap_types::{
54 command::{Command, CommandBody},
55 core::TagGenerator,
56 mailbox::Mailbox,
57 response::{Code, StatusKind, Tagged},
58 sequence::SequenceSet,
59 },
60};
61use log::trace;
62use thiserror::Error;
63
64use crate::{
65 coroutine::*,
66 imap_try,
67 rfc3501::{
68 copy::{ImapCopyUid, uid_set_to_vec},
69 mailbox::encode_inplace,
70 },
71 send::*,
72};
73
74#[derive(Clone, Debug, Error)]
76pub enum ImapMessageMoveError {
77 #[error("IMAP MOVE failed: NO {0}")]
79 No(String),
80 #[error("IMAP MOVE failed: BAD {0}")]
82 Bad(String),
83 #[error("IMAP MOVE failed: BYE {0}")]
85 Bye(String),
86 #[error("IMAP MOVE failed: server did not return a tagged response")]
88 MissingTagged,
89 #[error("IMAP MOVE failed: {0}")]
91 Send(#[from] ImapSendError),
92}
93
94#[derive(Clone, Debug, Default, Eq, PartialEq)]
96pub struct ImapMessageMoveOptions {
97 pub uid: bool,
99}
100
101pub struct ImapMessageMove {
103 state: State,
104}
105
106impl ImapMessageMove {
107 pub fn new(
110 sequence_set: SequenceSet,
111 mut mailbox: Mailbox<'static>,
112 opts: ImapMessageMoveOptions,
113 ) -> Self {
114 encode_inplace(&mut mailbox);
115
116 let command = Command {
117 tag: TagGenerator::new().generate(),
118 body: CommandBody::Move {
119 sequence_set,
120 mailbox,
121 uid: opts.uid,
122 },
123 };
124
125 trace!("send IMAP command {command:?}");
126
127 let state = State::Send(ImapSend::new(CommandCodec::new(), command));
128
129 Self { state }
130 }
131}
132
133impl ImapCoroutine for ImapMessageMove {
134 type Yield = ImapYield;
135 type Return = Result<ImapCopyUid, ImapMessageMoveError>;
136
137 fn resume(
138 &mut self,
139 fragmentizer: &mut Fragmentizer,
140 arg: Option<&[u8]>,
141 ) -> ImapCoroutineState<Self::Yield, Self::Return> {
142 match &mut self.state {
143 State::Send(send) => {
144 let out = imap_try!(send, fragmentizer, arg);
145
146 if let Some(bye) = out.bye {
147 let err = ImapMessageMoveError::Bye(bye.text.to_string());
148 return ImapCoroutineState::Complete(Err(err));
149 }
150
151 let Some(Tagged { body, .. }) = out.tagged else {
152 let err = ImapMessageMoveError::MissingTagged;
153 return ImapCoroutineState::Complete(Err(err));
154 };
155
156 match body.kind {
157 StatusKind::Ok => {
158 let copyuid = if let Some(Code::CopyUid {
159 uid_validity,
160 source,
161 destination,
162 }) = body.code
163 {
164 Some((
165 uid_validity.get(),
166 uid_set_to_vec(source),
167 uid_set_to_vec(destination),
168 ))
169 } else {
170 None
171 };
172 ImapCoroutineState::Complete(Ok(copyuid))
173 }
174 StatusKind::No => {
175 let err = ImapMessageMoveError::No(body.text.to_string());
176 ImapCoroutineState::Complete(Err(err))
177 }
178 StatusKind::Bad => {
179 let err = ImapMessageMoveError::Bad(body.text.to_string());
180 ImapCoroutineState::Complete(Err(err))
181 }
182 }
183 }
184 }
185 }
186}
187
188enum State {
189 Send(ImapSend<CommandCodec>),
190}
191
192impl fmt::Display for State {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 match self {
195 Self::Send(_) => f.write_str("send move"),
196 }
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use core::str;
203
204 use alloc::{borrow::ToOwned, format, vec, vec::Vec};
205
206 use crate::rfc6851::r#move::*;
207
208 #[test]
209 fn success_with_copyuid_returns_uids() {
210 let mut mov = ImapMessageMove::new(
211 "1:3".try_into().expect("valid sequence set"),
212 "Archive".try_into().expect("valid mailbox"),
213 ImapMessageMoveOptions::default(),
214 );
215 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
216
217 let bytes = expect_wants_write(&mut mov, &mut frag, None);
218 let line = str::from_utf8(&bytes).expect("utf8 command");
219 let tag = first_word(line).to_owned();
220 assert!(line.contains("MOVE 1:3 Archive"));
221
222 expect_wants_read(&mut mov, &mut frag);
223
224 let reply = format!("{tag} OK [COPYUID 1700 1:3 10:12] MOVE completed\r\n");
225 let copyuid = expect_complete_ok(&mut mov, &mut frag, reply.as_bytes())
226 .expect("server returned COPYUID");
227 let (uid_validity, source, destination) = copyuid;
228 assert_eq!(1700, uid_validity);
229 assert_eq!(vec![1, 2, 3], source);
230 assert_eq!(vec![10, 11, 12], destination);
231 }
232
233 #[test]
234 fn uid_variant_sends_uid_move() {
235 let mut mov = ImapMessageMove::new(
236 "42".try_into().expect("valid sequence set"),
237 "Archive".try_into().expect("valid mailbox"),
238 ImapMessageMoveOptions { uid: true },
239 );
240 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
241
242 let bytes = expect_wants_write(&mut mov, &mut frag, None);
243 let line = str::from_utf8(&bytes).expect("utf8 command");
244 assert!(line.contains("UID MOVE 42 Archive"));
245 }
246
247 #[test]
248 fn tagged_no_returns_no_error() {
249 let mut mov = ImapMessageMove::new(
250 "1".try_into().expect("valid sequence set"),
251 "Archive".try_into().expect("valid mailbox"),
252 ImapMessageMoveOptions::default(),
253 );
254 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
255
256 let bytes = expect_wants_write(&mut mov, &mut frag, None);
257 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
258
259 expect_wants_read(&mut mov, &mut frag);
260
261 let reply = format!("{tag} NO destination mailbox does not exist\r\n");
262 let err = expect_complete_err(&mut mov, &mut frag, reply.as_bytes());
263 let ImapMessageMoveError::No(text) = err else {
264 panic!("expected ImapMessageMoveError::No, got {err:?}");
265 };
266 assert_eq!(text, "destination mailbox does not exist");
267 }
268
269 #[test]
270 fn bye_returns_bye_error() {
271 let mut mov = ImapMessageMove::new(
272 "1".try_into().expect("valid sequence set"),
273 "Archive".try_into().expect("valid mailbox"),
274 ImapMessageMoveOptions::default(),
275 );
276 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
277
278 let _ = expect_wants_write(&mut mov, &mut frag, None);
279 expect_wants_read(&mut mov, &mut frag);
280
281 let err = expect_complete_err(&mut mov, &mut frag, b"* BYE going down\r\n");
282 let ImapMessageMoveError::Bye(text) = err else {
283 panic!("expected ImapMessageMoveError::Bye, got {err:?}");
284 };
285 assert_eq!(text, "going down");
286 }
287
288 fn expect_wants_write(
289 cor: &mut ImapMessageMove,
290 frag: &mut Fragmentizer,
291 arg: Option<&[u8]>,
292 ) -> Vec<u8> {
293 match cor.resume(frag, arg) {
294 ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
295 state => panic!("expected WantsWrite, got {state:?}"),
296 }
297 }
298
299 fn expect_wants_read(cor: &mut ImapMessageMove, frag: &mut Fragmentizer) {
300 match cor.resume(frag, None) {
301 ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
302 state => panic!("expected WantsRead, got {state:?}"),
303 }
304 }
305
306 fn expect_complete_ok(
307 cor: &mut ImapMessageMove,
308 frag: &mut Fragmentizer,
309 reply: &[u8],
310 ) -> ImapCopyUid {
311 match cor.resume(frag, Some(reply)) {
312 ImapCoroutineState::Complete(Ok(value)) => value,
313 state => panic!("expected Complete(Ok), got {state:?}"),
314 }
315 }
316
317 fn expect_complete_err(
318 cor: &mut ImapMessageMove,
319 frag: &mut Fragmentizer,
320 reply: &[u8],
321 ) -> ImapMessageMoveError {
322 match cor.resume(frag, Some(reply)) {
323 ImapCoroutineState::Complete(Err(err)) => err,
324 state => panic!("expected Complete(Err), got {state:?}"),
325 }
326 }
327
328 fn first_word(line: &str) -> &str {
329 line.split_whitespace()
330 .next()
331 .expect("first whitespace-separated token")
332 }
333}