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
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::Context as _;
use async_graphql::{Context, Enum, InputObject, Object, ID};
use mas_storage::{
    compat::CompatSessionRepository,
    job::{JobRepositoryExt, SyncDevicesJob},
    RepositoryAccess,
};

use crate::graphql::{
    model::{CompatSession, NodeType},
    state::ContextExt,
};

#[derive(Default)]
pub struct CompatSessionMutations {
    _private: (),
}

/// The input of the `endCompatSession` mutation.
#[derive(InputObject)]
pub struct EndCompatSessionInput {
    /// The ID of the session to end.
    compat_session_id: ID,
}

/// The payload of the `endCompatSession` mutation.
pub enum EndCompatSessionPayload {
    NotFound,
    Ended(Box<mas_data_model::CompatSession>),
}

/// The status of the `endCompatSession` mutation.
#[derive(Enum, Copy, Clone, PartialEq, Eq, Debug)]
enum EndCompatSessionStatus {
    /// The session was ended.
    Ended,

    /// The session was not found.
    NotFound,
}

#[Object]
impl EndCompatSessionPayload {
    /// The status of the mutation.
    async fn status(&self) -> EndCompatSessionStatus {
        match self {
            Self::Ended(_) => EndCompatSessionStatus::Ended,
            Self::NotFound => EndCompatSessionStatus::NotFound,
        }
    }

    /// Returns the ended session.
    async fn compat_session(&self) -> Option<CompatSession> {
        match self {
            Self::Ended(session) => Some(CompatSession::new(*session.clone())),
            Self::NotFound => None,
        }
    }
}

#[Object]
impl CompatSessionMutations {
    async fn end_compat_session(
        &self,
        ctx: &Context<'_>,
        input: EndCompatSessionInput,
    ) -> Result<EndCompatSessionPayload, async_graphql::Error> {
        let state = ctx.state();
        let compat_session_id = NodeType::CompatSession.extract_ulid(&input.compat_session_id)?;
        let requester = ctx.requester();

        let mut repo = state.repository().await?;
        let clock = state.clock();

        let session = repo.compat_session().lookup(compat_session_id).await?;
        let Some(session) = session else {
            return Ok(EndCompatSessionPayload::NotFound);
        };

        if !requester.is_owner_or_admin(&session) {
            return Ok(EndCompatSessionPayload::NotFound);
        }

        let user = repo
            .user()
            .lookup(session.user_id)
            .await?
            .context("Could not load user")?;

        // Schedule a job to sync the devices of the user with the homeserver
        repo.job().schedule_job(SyncDevicesJob::new(&user)).await?;

        let session = repo.compat_session().finish(&clock, session).await?;

        repo.save().await?;

        Ok(EndCompatSessionPayload::Ended(Box::new(session)))
    }
}