summaryrefslogtreecommitdiff
path: root/crates/imap/src/op/delete.rs
blob: 0d9ecec83bf634999a6bd5ee84c5de3dfc61f1a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::time::Instant;

use crate::{
    core::{Session, SessionData},
    spawn_op,
};
use common::listener::SessionStream;
use directory::Permission;
use imap_proto::{
    protocol::delete::Arguments, receiver::Request, Command, ResponseCode, StatusResponse,
};
use jmap::{changes::write::ChangeLog, mailbox::set::MailboxSet, services::state::StateManager};
use jmap_proto::types::{state::StateChange, type_state::DataType};
use store::write::log::ChangeLogBuilder;

use super::ImapContext;

impl<T: SessionStream> Session<T> {
    pub async fn handle_delete(&mut self, requests: Vec<Request<Command>>) -> trc::Result<()> {
        // Validate access
        self.assert_has_permission(Permission::ImapDelete)?;

        let data = self.state.session_data();
        let version = self.version;

        spawn_op!(data, {
            for request in requests {
                match request.parse_delete(version) {
                    Ok(argument) => match data.delete_folder(argument).await {
                        Ok(response) => {
                            data.write_bytes(response.into_bytes()).await?;
                        }
                        Err(error) => {
                            data.write_error(error).await?;
                        }
                    },
                    Err(response) => data.write_error(response).await?,
                }
            }

            Ok(())
        })
    }
}

impl<T: SessionStream> SessionData<T> {
    pub async fn delete_folder(&self, arguments: Arguments) -> trc::Result<StatusResponse> {
        let op_start = Instant::now();

        // Refresh mailboxes
        self.synchronize_mailboxes(false)
            .await
            .imap_ctx(&arguments.tag, trc::location!())?;

        // Validate mailbox
        let (account_id, mailbox_id) =
            if let Some(mailbox) = self.get_mailbox_by_name(&arguments.mailbox_name) {
                (mailbox.account_id, mailbox.mailbox_id)
            } else {
                return Err(trc::ImapEvent::Error
                    .into_err()
                    .details("Mailbox does not exist.")
                    .code(ResponseCode::TryCreate)
                    .id(arguments.tag));
            };

        // Delete message
        let access_token = self
            .get_access_token()
            .await
            .imap_ctx(&arguments.tag, trc::location!())?;
        let mut changelog = ChangeLogBuilder::new();
        let did_remove_emails = match self
            .server
            .mailbox_destroy(account_id, mailbox_id, &mut changelog, &access_token, true)
            .await
            .imap_ctx(&arguments.tag, trc::location!())?
        {
            Ok(did_remove_emails) => did_remove_emails,
            Err(err) => {
                return Err(trc::ImapEvent::Error
                    .into_err()
                    .details(err.description.unwrap_or("Delete failed".into()))
                    .code(ResponseCode::from(err.type_))
                    .id(arguments.tag));
            }
        };

        // Write changes
        let change_id = self
            .server
            .commit_changes(account_id, changelog)
            .await
            .imap_ctx(&arguments.tag, trc::location!())?;

        // Broadcast changes
        self.server
            .broadcast_state_change(if did_remove_emails {
                StateChange::new(account_id)
                    .with_change(DataType::Mailbox, change_id)
                    .with_change(DataType::Email, change_id)
                    .with_change(DataType::Thread, change_id)
            } else {
                StateChange::new(account_id).with_change(DataType::Mailbox, change_id)
            })
            .await;

        // Update mailbox cache
        for account in self.mailboxes.lock().iter_mut() {
            if account.account_id == account_id {
                account.mailbox_names.remove(&arguments.mailbox_name);
                account.mailbox_state.remove(&mailbox_id);
                break;
            }
        }

        trc::event!(
            Imap(trc::ImapEvent::DeleteMailbox),
            SpanId = self.session_id,
            MailboxName = arguments.mailbox_name,
            AccountId = account_id,
            MailboxId = mailbox_id,
            Elapsed = op_start.elapsed()
        );

        Ok(StatusResponse::ok("Mailbox deleted.").with_tag(arguments.tag))
    }
}