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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::Arc;

use tokio::sync::{broadcast, RwLockReadGuard};
use tokio::task::JoinHandle;

use ricq::structs::ImageInfo;
use ricq_core::msg::elem::GroupImage;
use ricq_core::msg::MessageChain;
use ricq_core::protocol::packet::Packet;
use ricq_core::RQResult;

use crate::client::decoder::Decoder;
use crate::protocol::protobuf::FirstViewMsg;
use crate::protocol::{protobuf, FirstView, FirstViewMessage, GuildSelfProfile};

pub mod builder;
pub mod decoder;
pub mod processor;

type GuildImageStoreResp = ricq_core::command::img_store::GroupImageStoreResp;

#[allow(dead_code)]
pub struct GuildClient {
    rq_client: Arc<ricq::Client>,
    listeners: HashMap<&'static str, broadcast::Receiver<Packet>>,
}

impl GuildClient {
    pub async fn new(rq_client: &Arc<ricq::Client>) -> Self {
        let rq_client = rq_client.clone();

        let listeners = HashMap::new();

        Self {
            rq_client,
            listeners,
        }
    }

    pub async fn engine(&self) -> Engine<'_> {
        Engine::from_rq(self.rq_client.engine.read().await)
    }

    pub async fn fetch_guild_first_view(&self) -> RQResult<Option<FirstView>> {
        let pkt = self.engine().await.build_sync_channel_first_view_packet();

        let cli = self.rq_client.clone();
        let first_view: JoinHandle<RQResult<FirstViewMsg>> = tokio::spawn(async move {
            static COMMAND: &str = "trpc.group_pro.synclogic.SyncLogic.PushFirstView";

            let mut rx = cli.listen_command(COMMAND).await;

            let r = rx.recv().await.unwrap();
            let mut first_view: FirstViewMsg = Decoder.decode_first_view_msg(r.body)?;

            for _ in 0..2 {
                let r = rx.recv().await.unwrap();
                let msg = Decoder.decode_first_view_msg(r.body)?;

                match msg {
                    FirstViewMsg {
                        push_flag,
                        channel_msgs,
                        get_msg_time,
                        ..
                    } if !channel_msgs.is_empty() => {
                        first_view.push_flag = push_flag;
                        first_view.channel_msgs = channel_msgs;
                        first_view.get_msg_time = get_msg_time;
                    }
                    FirstViewMsg {
                        direct_message_guild_nodes,
                        ..
                    } if !direct_message_guild_nodes.is_empty() => {
                        first_view.direct_message_guild_nodes = direct_message_guild_nodes;
                    }
                    _ => {}
                }
            }
            Ok(first_view)
        });

        let rsp = self.rq_client.send_and_wait(pkt).await?;

        let first_view_rsp = Decoder.decode_guild_first_view_response(rsp.body)?;

        let opt = match (first_view.await.unwrap()?, first_view_rsp) {
            (
                FirstViewMsg {
                    push_flag: Some(push_flag),
                    guild_nodes,
                    channel_msgs,
                    get_msg_time: Some(get_msg_time),
                    direct_message_guild_nodes,
                    ..
                },
                Some(response),
            ) => {
                let message = FirstViewMessage {
                    push_flag,
                    guild_nodes,
                    channel_msgs,
                    get_msg_time,
                    direct_message_guild_nodes,
                };

                Some(FirstView { response, message })
            }
            _ => None,
        };

        Ok(opt)
    }

    pub async fn fetch_guild_self_profile(
        &self,
        tiny_id: u64,
    ) -> RQResult<Option<GuildSelfProfile>> {
        let pkt = self.engine().await.build_get_user_profile_packet(tiny_id);
        let rsp = self.rq_client.send_and_wait(pkt).await?;
        let usr = Decoder.decode_guild_user_profile(rsp.body)?;

        let prof = match usr {
            Some(protobuf::GuildUserProfile {
                tiny_id: Some(tiny_id),
                nickname: Some(nickname),
                avatar_url: Some(avatar_url),
                ..
            }) => Some(GuildSelfProfile {
                tiny_id,
                nickname,
                avatar_url,
            }),
            _ => None,
        };

        Ok(prof)
    }

    pub async fn send_channel_message(
        &self,
        elems: MessageChain,
        guild_id: u64,
        channel_id: u64,
    ) -> RQResult<Packet> {
        let pkt = self.engine().await.build_send_channel_message_packet(
            elems.into(),
            guild_id,
            channel_id,
        );

        let ret = self.rq_client.send_and_wait(pkt).await?;

        Ok(ret) // todo: decode receipt
    }

    pub async fn upload_channel_image(
        &self,
        guild_id: u64,
        channel_id: u64,
        image: Vec<u8>,
    ) -> RQResult<GroupImage> {
        let image_store = self
            .get_guild_image_store(guild_id, channel_id, &image)
            .await?;
        match image_store {
            GuildImageStoreResp::Exist { .. } => {
                todo!("construct guild image")
            }
            GuildImageStoreResp::NotExist { .. } => {
                todo!("upload guild image")
            }
        }
    }

    pub async fn get_guild_image_store(
        &self,
        guild_id: u64,
        channel_id: u64,
        data: &[u8],
    ) -> RQResult<GuildImageStoreResp> {
        let image_info = ImageInfo::try_new(data)?;
        let req = self.engine().await.build_guild_image_store_packet(
            channel_id as _,
            guild_id,
            image_info.filename,
            image_info.md5,
            image_info.size as u64,
            image_info.width,
            image_info.height,
            image_info.image_type as u32,
        );
        let resp = self.rq_client.send_and_wait(req).await?;
        self.engine()
            .await
            .decode_group_image_store_response(resp.body)
    }
}

pub struct Engine<'a>(RwLockReadGuard<'a, ricq_core::Engine>);

impl<'a> Engine<'a> {
    fn from_rq(engine: RwLockReadGuard<'a, ricq_core::Engine>) -> Self {
        Self(engine)
    }
}

impl<'a> Deref for Engine<'a> {
    type Target = ricq_core::Engine;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}