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
use bytes::Bytes;

use crate::{RQError, RQResult};

#[derive(PartialEq, derivative::Derivative, Eq)]
#[derivative(Default, Debug, Clone)]
pub enum PacketType {
    #[derivative(Default)]
    Simple,
    Login,
}

impl PacketType {
    pub fn value(&self) -> u32 {
        match self {
            PacketType::Login => 0x0A,
            PacketType::Simple => 0x0B,
        }
    }

    pub fn from_i32(v: i32) -> RQResult<Self> {
        match v {
            0x0A => Ok(Self::Login),
            0x0B => Ok(Self::Simple),
            _ => Err(RQError::InvalidPacketType),
        }
    }
}

#[derive(PartialEq, derivative::Derivative, Eq, Clone)]
#[derivative(Default, Debug)]
pub enum EncryptType {
    #[derivative(Default)]
    NoEncrypt,
    D2Key,
    EmptyKey,
}

impl EncryptType {
    pub fn value(&self) -> u32 {
        match self {
            EncryptType::NoEncrypt => 0x00,
            EncryptType::D2Key => 0x01,
            EncryptType::EmptyKey => 0x02,
        }
    }
    pub fn from_u8(v: u8) -> RQResult<Self> {
        match v {
            0x00 => Ok(Self::NoEncrypt),
            0x01 => Ok(Self::D2Key),
            0x02 => Ok(Self::EmptyKey),
            _ => Err(RQError::InvalidEncryptType),
        }
    }
}

#[derive(Default, Debug, Clone)]
pub struct Packet {
    pub packet_type: PacketType,
    pub encrypt_type: EncryptType,
    pub seq_id: i32,
    pub body: Bytes,
    pub command_name: String,
    pub uin: i64,
    pub message: String,
}

impl Packet {
    pub fn check_command_name(self, command_name: &str) -> RQResult<Self> {
        if self.command_name != command_name {
            Err(RQError::CommandNameMismatch(
                command_name.to_owned(),
                self.command_name,
            ))
        } else {
            Ok(self)
        }
    }
}