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
185
186
use std::io;

use tokio::io::{AsyncWrite, AsyncWriteExt};

pub(crate) const MAGIC: u8 = 0x07;
pub(crate) const TERMINATOR: u8 = 0x21;
pub(crate) const SEPARATOR: u8 = 0x20;

#[derive(Debug)]
pub(crate) enum Packet {
    SetNicknameRequest(Vec<u8>),
    SetNickname(Vec<u8>),
    ChangeNicknameRequest(Vec<u8>),
    ChangeNickname(Vec<u8>),
    UserListRequest,
    UserListResponse(Vec<Vec<u8>>),
    SendWord { sender: Vec<u8>, recipients: Vec<Vec<u8>>, word: Vec<u8> },
    DeliverWord { sender: Vec<u8>, word: Vec<u8> },
    SendInstructions { sender: Vec<u8>, recipients: Vec<Vec<u8>>, instructions: Vec<u8> },
    DeliverInstructions { sender: Vec<u8>, instructions: Vec<u8> },
    SendList { sender: Vec<u8>, recipients: Vec<Vec<u8>>, list: Vec<Vec<u8>> },
    DeliverList { sender: Vec<u8>, list: Vec<Vec<u8>> },
    SendImage { sender: Vec<u8>, recipients: Vec<Vec<u8>>, bytes: Vec<u8> },
    DeliverImage { sender: Vec<u8>, bytes: Vec<u8> },
    SendObject { sender: Vec<u8>, recipients: Vec<Vec<u8>>, bytes: Vec<u8> },
    DeliverObject { sender: Vec<u8>, bytes: Vec<u8> },
}

impl Packet {
    fn opcode(&self) -> Opcode {
        match self {
            Self::SetNicknameRequest(_) => Opcode::SetNicknameRequest,
            Self::SetNickname(_) => Opcode::SetNickname,
            Self::ChangeNicknameRequest(_) => Opcode::ChangeNicknameRequest,
            Self::ChangeNickname(_) => Opcode::ChangeNickname,
            Self::UserListRequest => Opcode::UserListRequest,
            Self::UserListResponse(_) => Opcode::UserListResponse,
            Self::SendWord { .. } => Opcode::SendWord,
            Self::DeliverWord { .. } => Opcode::DeliverWord,
            Self::SendInstructions { .. } => Opcode::SendInstructions,
            Self::DeliverInstructions { .. } => Opcode::DeliverInstructions,
            Self::SendList { .. } => Opcode::SendList,
            Self::DeliverList { .. } => Opcode::DeliverList,
            Self::SendImage { .. } => Opcode::SendImage,
            Self::DeliverImage { .. } => Opcode::DeliverImage,
            Self::SendObject { .. } => Opcode::SendObject,
            Self::DeliverObject { .. } => Opcode::DeliverObject,
        }
    }

    // TODO: Don't clone?
    fn users(&self) -> Vec<Vec<u8>> {
        match self {
            Self::SetNicknameRequest(_)
            | Self::SetNickname(_)
            | Self::ChangeNicknameRequest(_)
            | Self::ChangeNickname(_)
            | Self::UserListRequest => Vec::new(),
            Self::UserListResponse(users) => users.clone(),
            Self::SendWord { sender, recipients, .. }
            | Self::SendInstructions { sender, recipients, .. }
            | Self::SendList { sender, recipients, .. }
            | Self::SendImage { sender, recipients, .. }
            | Self::SendObject { sender, recipients, .. } => {
                let mut result = vec![sender.clone()];
                result.extend_from_slice(recipients);
                result
            },
            Self::DeliverWord { sender, .. }
            | Self::DeliverInstructions { sender, .. }
            | Self::DeliverList { sender, .. }
            | Self::DeliverImage { sender, .. }
            | Self::DeliverObject { sender, .. } => vec![sender.clone()],
        }
    }

    fn to_bytes(self) -> Vec<u8> {
        let mut body = {
            let users = self.users();
            let mut content = Vec::new();
            content.push(self.opcode() as u8);
            content.extend_from_slice(users.len().to_string().as_bytes());
            content.push(TERMINATOR);
            for mut user in users {
                content.extend_from_slice(user.len().to_string().as_bytes());
                content.push(TERMINATOR);
                content.append(&mut user);
            }
            content.append(&mut match self {
                Packet::SetNicknameRequest(nickname)
                | Packet::SetNickname(nickname)
                | Packet::ChangeNicknameRequest(nickname)
                | Packet::ChangeNickname(nickname) => nickname,
                Packet::UserListRequest
                | Packet::UserListResponse(_) => Vec::new(),
                Packet::SendWord { word, .. }
                | Packet::DeliverWord { word, .. } => word,
                Packet::SendInstructions { instructions, .. }
                | Packet::DeliverInstructions { instructions, .. } => instructions,
                Packet::SendList { mut list, .. }
                | Packet::DeliverList { mut list, .. } => {
                    let mut content = Vec::new();
                    let mut list_iter = list.iter_mut().peekable();
                    while let Some(word) = list_iter.next() {
                        content.append(word);
                        if list_iter.peek().is_some() {
                            content.push(SEPARATOR);
                        }
                    }
                    content
                },
                Packet::SendImage { bytes, .. }
                | Packet::DeliverImage { bytes, .. }
                | Packet::SendObject { bytes, .. }
                | Packet::DeliverObject { bytes, .. } => bytes,
            });
            content
        };

        {
            let mut data = Vec::new();
            data.push(MAGIC);
            data.extend_from_slice(body.len().to_string().as_bytes());
            data.push(TERMINATOR);
            data.append(&mut body);
            data
        }
    }

    pub(crate) async fn async_write<W>(self, writer: &mut W) -> Result<(), io::Error>
        where W: AsyncWrite + Unpin
    {
        writer.write_all(&self.to_bytes()).await?;
        Ok(())
    }
}

#[derive(Debug)]
pub enum Error {
    InvalidOpcode,
}

pub(crate) enum Opcode {
    SetNicknameRequest = 0x61,
    SetNickname = 0x62,
    ChangeNicknameRequest = 0x58,
    ChangeNickname = 0x79,
    UserListRequest = 0x55,
    UserListResponse = 0x76,
    SendWord = 0x57,
    DeliverWord = 0x77,
    SendInstructions = 0x52,
    DeliverInstructions = 0x72,
    SendList = 0x4c,
    DeliverList = 0x6c,
    SendImage = 0x49,
    DeliverImage = 0x69,
    SendObject = 0x6f,
    DeliverObject = 0x4f,
}

impl TryFrom<u8> for Opcode {
    type Error = Error;

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            v if v == Self::SetNicknameRequest as u8 => Ok(Self::SetNicknameRequest),
            v if v == Self::SetNickname as u8 => Ok(Self::SetNickname),
            v if v == Self::ChangeNicknameRequest as u8 => Ok(Self::ChangeNicknameRequest),
            v if v == Self::ChangeNickname as u8 => Ok(Self::ChangeNickname),
            v if v == Self::UserListRequest as u8 => Ok(Self::UserListRequest),
            v if v == Self::UserListResponse as u8 => Ok(Self::UserListResponse),
            v if v == Self::SendWord as u8 => Ok(Self::SendWord),
            v if v == Self::DeliverWord as u8 => Ok(Self::DeliverWord),
            v if v == Self::SendInstructions as u8 => Ok(Self::SendInstructions),
            v if v == Self::DeliverInstructions as u8 => Ok(Self::DeliverInstructions),
            v if v == Self::SendList as u8 => Ok(Self::SendList),
            v if v == Self::DeliverList as u8 => Ok(Self::DeliverList),
            v if v == Self::SendImage as u8 => Ok(Self::SendImage),
            v if v == Self::DeliverImage as u8 => Ok(Self::DeliverImage),
            v if v == Self::SendObject as u8 => Ok(Self::SendObject),
            v if v == Self::DeliverObject as u8 => Ok(Self::DeliverObject),
            _ => Err(Error::InvalidOpcode),
        }
    }
}