aboutsummaryrefslogtreecommitdiffstats
path: root/mumd/src/state/channel.rs
blob: f58ed159987e676715fff6f7e47d122c8be95bc5 (plain) (blame)
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
use crate::state::user::User;

use mumble_protocol::control::msgs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Channel {
    description: Option<String>,
    links: Vec<u32>,
    max_users: u32,
    name: String,
    parent: Option<u32>,
    position: i32,
}

impl Channel {
    pub fn new(mut msg: msgs::ChannelState) -> Self {
        Self {
            description: if msg.has_description() {
                Some(msg.take_description())
            } else {
                None
            },
            links: Vec::new(),
            max_users: msg.get_max_users(),
            name: msg.take_name(),
            parent: if msg.has_parent() {
                Some(msg.get_parent())
            } else {
                None
            },
            position: msg.get_position(),
        }
    }

    pub fn parse_channel_state(&mut self, mut msg: msgs::ChannelState) {
        if msg.has_description() {
            self.description = Some(msg.take_description());
        }
        self.links = msg.take_links();
        if msg.has_max_users() {
            self.max_users = msg.get_max_users();
        }
        if msg.has_name() {
            self.name = msg.take_name();
        }
        if msg.has_parent() {
            self.parent = Some(msg.get_parent());
        }
        if msg.has_position() {
            self.position = msg.get_position();
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn path(&self, channels: &HashMap<u32, Channel>) -> String {
        match &self.parent {
            Some(t) => format!("{}/{}", channels.get(t).unwrap().path(channels), self.name),
            None => self.name.clone(),
        }
    }
}

#[derive(Debug)]
struct ProtoTree<'a> {
    channel: Option<&'a Channel>,
    children: HashMap<u32, ProtoTree<'a>>,
    users: Vec<&'a User>,
}

impl<'a> ProtoTree<'a> {
    fn walk_and_add(
        &mut self,
        channel: &'a Channel,
        users: &HashMap<u32, Vec<&'a User>>,
        walk: &[u32],
    ) {
        match walk {
            [] => unreachable!("Walks should always have at least one element"),
            &[node] => {
                let pt = self.children.entry(node).or_insert(ProtoTree {
                    channel: None,
                    children: HashMap::new(),
                    users: Vec::new(),
                });
                pt.channel = Some(channel);
                pt.users = users.get(&node).cloned().unwrap_or_default();
            }
            longer => {
                self.children
                    .entry(longer[0])
                    .or_insert(ProtoTree {
                        channel: None,
                        children: HashMap::new(),
                        users: Vec::new(),
                    })
                    .walk_and_add(channel, users, &walk[1..]);
            }
        }
    }
}

impl<'a> From<&ProtoTree<'a>> for mumlib::state::Channel {
    fn from(tree: &ProtoTree<'a>) -> Self {
        let mut channel = mumlib::state::Channel::from(tree.channel.unwrap());
        let mut children = tree
            .children
            .iter()
            .map(|e| {
                (
                    e.1.channel.unwrap().position,
                    mumlib::state::Channel::from(e.1),
                )
            })
            .collect::<Vec<_>>();
        children.sort_by_key(|e| (e.0, e.1.name.clone()));
        channel.children = children.into_iter().map(|e| e.1).collect();
        channel.users = tree.users.iter().map(|e| (*e).into()).collect();
        channel
    }
}

pub fn into_channel(
    channels: &HashMap<u32, Channel>,
    users: &HashMap<u32, User>,
) -> mumlib::state::Channel {
    let mut walks = Vec::new();

    let mut channel_lookup = HashMap::new();

    for user in users.values() {
        channel_lookup
            .entry(user.channel())
            .or_insert_with(Vec::new)
            .push(user);
    }

    for (channel_id, channel) in channels {
        let mut walk = Vec::new();
        let mut current = *channel_id;
        while let Some(next) = channels.get(&current).unwrap().parent {
            walk.push(current);
            current = next;
        }
        walk.reverse();

        if !walk.is_empty() {
            walks.push((walk, channel));
        }
    }

    //root node is ignored because of how walk_and_add is implemented on ProtoTree
    let mut proto_tree = ProtoTree {
        channel: Some(channels.get(&0).unwrap()),
        children: HashMap::new(),
        users: channel_lookup
            .get(&0)
            .cloned()
            .unwrap_or_default(),
    };

    for (walk, channel) in walks {
        proto_tree.walk_and_add(channel, &channel_lookup, &walk);
    }

    (&proto_tree).into()
}

impl From<&Channel> for mumlib::state::Channel {
    fn from(channel: &Channel) -> Self {
        mumlib::state::Channel {
            description: channel.description.clone(),
            links: Vec::new(),
            max_users: channel.max_users,
            name: channel.name.clone(),
            children: Vec::new(),
            users: Vec::new(),
        }
    }
}