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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use async_channel::{Receiver, Sender};
use async_std::{prelude::StreamExt, task::spawn};
use futures::io::{AsyncBufReadExt, AsyncRead, BufReader};
use isahc::{http::Response, ResponseExt};
use std::{error::Error, fmt::Debug, io::Read, str::FromStr, sync::Arc};
use tracing::{error, info, trace, warn};
use twilight_cache_inmemory::{EventType, InMemoryCache};
use twilight_gateway::{cluster::Cluster, Event};
use twilight_http::Client as HttpClient;
use twilight_model::{
    gateway::{
        payload::update_status::UpdateStatusInfo,
        presence::{Activity, ActivityType, Status},
        Intents,
    },
    id::{ChannelId, GuildId, UserId},
};

use crate::{
    act::{Act, Stage},
    raccord,
};

pub struct Forward {
    pub cache: InMemoryCache,
    pub cluster: Cluster,
    pub http: HttpClient,
}

impl Forward {
    pub async fn init(
        token: String,
        target: Arc<raccord::Client>,
    ) -> Result<Self, Box<dyn Error + Send + Sync>> {
        let mut update_status = None;
        if let Ok(mut connecting_res) = target.get(raccord::Connecting)?.await {
            if connecting_res.status().is_success() {
                let content_type = connecting_res
                    .headers()
                    .get("content-type")
                    .and_then(|s| s.to_str().ok())
                    .and_then(|s| mime::Mime::from_str(s).ok())
                    .unwrap_or(mime::APPLICATION_OCTET_STREAM);

                if content_type == mime::APPLICATION_JSON {
                    let presence: raccord::Presence = connecting_res.json()?;

                    update_status = Some(UpdateStatusInfo {
                        afk: presence.afk.unwrap_or(true),
                        since: presence.since,
                        status: presence.status.unwrap_or(Status::Online),
                        activities: presence.activity.map(|activity| {
                            let (kind, name) = match activity {
                                raccord::Activity::Playing { name } => {
                                    (ActivityType::Playing, name)
                                }
                                raccord::Activity::Streaming { name } => {
                                    (ActivityType::Streaming, name)
                                }
                                raccord::Activity::Listening { name } => {
                                    (ActivityType::Listening, name)
                                }
                                raccord::Activity::Watching { name } => {
                                    (ActivityType::Watching, name)
                                }
                                raccord::Activity::Custom { name } => (ActivityType::Custom, name),
                            };

                            vec![Activity {
                                application_id: None,
                                assets: None,
                                created_at: None,
                                details: None,
                                emoji: None,
                                flags: None,
                                id: None,
                                instance: None,
                                party: None,
                                secrets: None,
                                state: None,
                                timestamps: None,
                                url: None,
                                kind,
                                name,
                            }]
                        }),
                    });
                }
            }
        }

        // TODO: env var control for intents (notably for privileged intents)
        let mut config = Cluster::builder(
            &token,
            Intents::DIRECT_MESSAGES | Intents::GUILD_MESSAGES | Intents::GUILD_MEMBERS,
        );

        if let Some(presence) = update_status {
            config = config.presence(presence);
        }

        let cluster = config.build().await?;

        let cluster_spawn = cluster.clone();
        spawn(async move {
            cluster_spawn.up().await;
        });

        let http = HttpClient::new(&token);

        let cache = InMemoryCache::builder()
            .event_types(
                EventType::MESSAGE_CREATE
                    | EventType::MESSAGE_DELETE
                    | EventType::MESSAGE_DELETE_BULK
                    | EventType::MESSAGE_UPDATE
                    | EventType::MEMBER_ADD
                    | EventType::MEMBER_CHUNK
                    | EventType::MEMBER_UPDATE
                    | EventType::MEMBER_REMOVE,
            )
            .build();

        Ok(Self {
            cache,
            cluster,
            http,
        })
    }

    pub async fn worker(
        self,
        target: Arc<raccord::Client>,
        ghosts: Receiver<(u64, Event)>,
        player: Sender<Stage>,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        let solids = self.cluster.events();
        let mut events = solids.merge(ghosts);

        while let Some((shard_id, event)) = events.next().await {
            spawn(handle_event(
                self.cache.clone(),
                target.clone(),
                shard_id,
                event,
                player.clone(),
            ));
        }

        Ok(())
    }
}

pub async fn handle_event(
    cache: InMemoryCache,
    target: Arc<raccord::Client>,
    shard_id: u64,
    event: Event,
    player: Sender<Stage>,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    cache.update(&event);

    match event {
        Event::MessageCreate(message) if message.guild_id.is_some() => {
            let msg = raccord::ServerMessage::from(&**message);
            let res = if let Some(command) = target.parse_command(&msg.content) {
                target.post(raccord::Command {
                    command,
                    message: msg,
                })
            } else {
                target.post(msg)
            }?
            .await?;
            handle_response(
                res,
                player,
                Some(message.guild_id.unwrap()),
                Some(message.channel_id),
                None,
            )
            .await?;
        }
        Event::MessageCreate(message) => {
            let msg = raccord::DirectMessage::from(&**message);
            let res = if let Some(command) = target.parse_command(&msg.content) {
                target.post(raccord::Command {
                    command,
                    message: msg,
                })
            } else {
                target.post(msg)
            }?
            .await?;
            handle_response(res, player, None, Some(message.channel_id), None).await?;
        }
        Event::MemberAdd(mem) => {
            let member = raccord::Member::from(&**mem);
            let res = target.post(raccord::ServerJoin(member))?.await?;
            handle_response(res, player, Some(mem.guild_id), None, None).await?;
        }
        Event::ShardConnected(_) => {
            info!("connected on shard {}", shard_id);
            let res = target.post(raccord::Connected { shard: shard_id })?.await?;
            handle_response(res, player, None, None, None).await?;
        }
        _ => {}
    }

    Ok(())
}

async fn handle_response<T: Debug + Read + AsyncRead + Unpin>(
    mut res: Response<T>,
    player: Sender<Stage>,
    from_server: Option<GuildId>,
    from_channel: Option<ChannelId>,
    _from_user: Option<UserId>,
) -> Result<(), Box<dyn Error + Send + Sync>> {
    let status = res.status();
    if status.is_informational() {
        warn!("unhandled information code {:?}", status);
    }

    if status == 204 || status == 404 {
        // no content, no action
        trace!("no action response: {:?}", status);
        return Ok(());
    }

    if status.is_redirection() {
        match status.into() {
            300 => warn!("TODO: multiple choice (http 300) is not designed yet"),
            301 | 302 | 303 | 307 | 308 => unreachable!("redirects should be handled by curl"),
            304 => error!("http 304 response caching not implemented"),
            305 | 306 => error!("proxy redirections (http 305 and 306) unsupported"),
            _ => error!("invalid 3xx code"),
        }

        return Ok(());
    }

    if status.is_client_error() || status.is_server_error() {
        error!(
            "error {:?} from target, TODO: more error handling here",
            status
        );
        return Ok(());
    }

    if !status.is_success() {
        error!("invalid response status: {:?}", status);
        return Ok(());
    }

    let content_type = res
        .headers()
        .get("content-type")
        .and_then(|s| s.to_str().ok())
        .and_then(|s| mime::Mime::from_str(s).ok())
        .unwrap_or(mime::APPLICATION_OCTET_STREAM);

    match (content_type.type_(), content_type.subtype()) {
        (mime::APPLICATION, mime::JSON) => {
            let default_server_id = res
                .headers()
                .get("accord-server-id")
                .and_then(|h| h.to_str().ok())
                .and_then(|s| u64::from_str(s).ok())
                .map(GuildId)
                .or(from_server);
            let default_channel_id = res
                .headers()
                .get("accord-channel-id")
                .and_then(|h| h.to_str().ok())
                .and_then(|s| u64::from_str(s).ok())
                .map(ChannelId)
                .or(from_channel);
            let has_content_length = res
                .headers()
                .get("content-length")
                .and_then(|s| s.to_str().ok())
                .and_then(|s| usize::from_str(s).ok())
                .unwrap_or(0)
                > 0;

            if has_content_length {
                info!("response has content-length, parsing single act");
                let act: Act = res.json()?;
                player
                    .send(Stage {
                        act,
                        default_server_id,
                        default_channel_id,
                    })
                    .await?;
            } else {
                info!("response has no content-length, streaming multiple acts");
                let mut lines = BufReader::new(res.into_body()).lines();
                loop {
                    if let Some(line) = lines.next().await {
                        let line = line?;
                        let act: Act = serde_json::from_str(line.trim())?;
                        player
                            .send(Stage {
                                act,
                                default_server_id,
                                default_channel_id,
                            })
                            .await?;
                    } else {
                        break;
                    }
                }
                info!("done streaming");
            }
        }
        (mime::TEXT, mime::PLAIN) => {
            let content = res.text()?;
            let header_channel = res
                .headers()
                .get("accord-channel-id")
                .and_then(|h| h.to_str().ok())
                .and_then(|s| u64::from_str(s).ok());

            player
                .send(Stage {
                    act: Act::CreateMessage {
                        content,
                        channel_id: header_channel,
                    },
                    default_server_id: from_server,
                    default_channel_id: from_channel,
                })
                .await?;
        }
        (t, s) => warn!("unhandled content-type {}/{}", t, s),
    }

    Ok(())
}