io_imap/rfc3501/
unsubscribe.rs1use core::fmt;
43
44use alloc::string::{String, ToString};
45
46use imap_codec::{
47 CommandCodec,
48 fragmentizer::Fragmentizer,
49 imap_types::{
50 command::{Command, CommandBody},
51 core::TagGenerator,
52 mailbox::Mailbox,
53 response::{StatusKind, Tagged},
54 },
55};
56use log::trace;
57use thiserror::Error;
58
59use crate::{coroutine::*, imap_try, rfc3501::mailbox::encode_inplace, send::*};
60
61#[derive(Clone, Debug, Error)]
63pub enum ImapMailboxUnsubscribeError {
64 #[error("IMAP UNSUBSCRIBE failed: NO {0}")]
65 No(String),
66 #[error("IMAP UNSUBSCRIBE failed: BAD {0}")]
67 Bad(String),
68 #[error("IMAP UNSUBSCRIBE failed: BYE {0}")]
69 Bye(String),
70
71 #[error("IMAP UNSUBSCRIBE failed: server did not return a tagged response")]
72 MissingTagged,
73
74 #[error("IMAP UNSUBSCRIBE failed: {0}")]
75 Send(#[from] SendImapCommandError),
76}
77
78pub struct ImapMailboxUnsubscribe {
80 state: State,
81}
82
83impl ImapMailboxUnsubscribe {
84 pub fn new(mut mailbox: Mailbox<'static>) -> Self {
85 encode_inplace(&mut mailbox);
86
87 let command = Command {
88 tag: TagGenerator::new().generate(),
89 body: CommandBody::Unsubscribe { mailbox },
90 };
91
92 trace!("send IMAP command {command:?}");
93
94 let state = State::Send(SendImapCommand::new(CommandCodec::new(), command));
95
96 Self { state }
97 }
98}
99
100impl ImapCoroutine for ImapMailboxUnsubscribe {
101 type Yield = ImapYield;
102 type Return = Result<(), ImapMailboxUnsubscribeError>;
103
104 fn resume(
105 &mut self,
106 fragmentizer: &mut Fragmentizer,
107 arg: Option<&[u8]>,
108 ) -> ImapCoroutineState<Self::Yield, Self::Return> {
109 loop {
110 trace!("unsubscribe: {}", self.state);
111
112 match &mut self.state {
113 State::Send(send) => {
114 let out = imap_try!(send, fragmentizer, arg);
115
116 if let Some(bye) = out.bye {
117 let err = ImapMailboxUnsubscribeError::Bye(bye.text.to_string());
118 return ImapCoroutineState::Complete(Err(err));
119 }
120
121 let Some(Tagged { body, .. }) = out.tagged else {
122 let err = ImapMailboxUnsubscribeError::MissingTagged;
123 return ImapCoroutineState::Complete(Err(err));
124 };
125
126 return match body.kind {
127 StatusKind::Ok => ImapCoroutineState::Complete(Ok(())),
128 StatusKind::No => {
129 let err = ImapMailboxUnsubscribeError::No(body.text.to_string());
130 ImapCoroutineState::Complete(Err(err))
131 }
132 StatusKind::Bad => {
133 let err = ImapMailboxUnsubscribeError::Bad(body.text.to_string());
134 ImapCoroutineState::Complete(Err(err))
135 }
136 };
137 }
138 }
139 }
140 }
141}
142
143enum State {
144 Send(SendImapCommand<CommandCodec>),
145}
146
147impl fmt::Display for State {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match self {
150 Self::Send(_) => f.write_str("send unsubscribe"),
151 }
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use core::str;
158
159 use alloc::{borrow::ToOwned, vec::Vec};
160
161 use super::*;
162
163 #[test]
164 fn success_returns_ok() {
165 let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
166 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
167
168 let bytes = expect_wants_write(&mut unsub, &mut frag, None);
169 let line = str::from_utf8(&bytes).expect("utf8 command");
170 let tag = first_word(line).to_owned();
171 assert!(line.contains("UNSUBSCRIBE Archive"));
172
173 expect_wants_read(&mut unsub, &mut frag);
174
175 let reply = format!("{tag} OK UNSUBSCRIBE completed\r\n");
176 expect_complete_ok(&mut unsub, &mut frag, reply.as_bytes());
177 }
178
179 #[test]
180 fn tagged_no_returns_no_error() {
181 let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
182 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
183
184 let bytes = expect_wants_write(&mut unsub, &mut frag, None);
185 let tag = first_word(str::from_utf8(&bytes).expect("utf8 command")).to_owned();
186
187 expect_wants_read(&mut unsub, &mut frag);
188
189 let reply = format!("{tag} NO not subscribed\r\n");
190 let err = expect_complete_err(&mut unsub, &mut frag, reply.as_bytes());
191 let ImapMailboxUnsubscribeError::No(text) = err else {
192 panic!("expected ImapMailboxUnsubscribeError::No, got {err:?}");
193 };
194 assert_eq!(text, "not subscribed");
195 }
196
197 #[test]
198 fn bye_returns_bye_error() {
199 let mut unsub = ImapMailboxUnsubscribe::new("Archive".try_into().expect("valid mailbox"));
200 let mut frag = Fragmentizer::new(50 * 1024 * 1024);
201
202 let _ = expect_wants_write(&mut unsub, &mut frag, None);
203 expect_wants_read(&mut unsub, &mut frag);
204
205 let err = expect_complete_err(&mut unsub, &mut frag, b"* BYE going down\r\n");
206 let ImapMailboxUnsubscribeError::Bye(text) = err else {
207 panic!("expected ImapMailboxUnsubscribeError::Bye, got {err:?}");
208 };
209 assert_eq!(text, "going down");
210 }
211
212 fn expect_wants_write(
215 cor: &mut ImapMailboxUnsubscribe,
216 frag: &mut Fragmentizer,
217 arg: Option<&[u8]>,
218 ) -> Vec<u8> {
219 match cor.resume(frag, arg) {
220 ImapCoroutineState::Yielded(ImapYield::WantsWrite(bytes)) => bytes,
221 state => panic!("expected WantsWrite, got {state:?}"),
222 }
223 }
224
225 fn expect_wants_read(cor: &mut ImapMailboxUnsubscribe, frag: &mut Fragmentizer) {
226 match cor.resume(frag, None) {
227 ImapCoroutineState::Yielded(ImapYield::WantsRead) => {}
228 state => panic!("expected WantsRead, got {state:?}"),
229 }
230 }
231
232 fn expect_complete_ok(cor: &mut ImapMailboxUnsubscribe, frag: &mut Fragmentizer, reply: &[u8]) {
233 match cor.resume(frag, Some(reply)) {
234 ImapCoroutineState::Complete(Ok(())) => {}
235 state => panic!("expected Complete(Ok), got {state:?}"),
236 }
237 }
238
239 fn expect_complete_err(
240 cor: &mut ImapMailboxUnsubscribe,
241 frag: &mut Fragmentizer,
242 reply: &[u8],
243 ) -> ImapMailboxUnsubscribeError {
244 match cor.resume(frag, Some(reply)) {
245 ImapCoroutineState::Complete(Err(err)) => err,
246 state => panic!("expected Complete(Err), got {state:?}"),
247 }
248 }
249
250 fn first_word(line: &str) -> &str {
251 line.split_whitespace()
252 .next()
253 .expect("first whitespace-separated token")
254 }
255}