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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
pub(crate) mod utils;
use crate::utils::get_arg;
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use quote::quote;
use syn::parse_macro_input;
use syn::spanned::Spanned;

/// Used to define a command
///
/// ```compile_fail
/// #[command(help = "Description")]
/// async fn hello_world(mut tx: mrsbfh::Sender, config: Config, sender: String, mut args: Vec<&str>) -> Result<(), Box<dyn std::error::Error>> where Config: mrsbfh::config::Loader + Clone {}
/// ```
#[proc_macro_attribute]
pub fn command(args: TokenStream, input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::ItemFn);

    let args = parse_macro_input!(args as syn::AttributeArgs);

    let help_const_name = syn::Ident::new(
        &format!(
            "{}_HELP",
            input.sig.ident.to_string().to_uppercase().replace("R#", "")
        ),
        input.sig.span(),
    );
    let help_description = match get_arg(
        input.span(),
        args,
        "help",
        "#[command(help = \"<description>\")]",
        1,
    ) {
        Ok(v) => syn::LitStr::new(&format!("* {}\n", v.value()), v.span()),
        Err(e) => return e,
    };

    let code = quote! {
        #input
        pub(crate) const #help_const_name: &str = #help_description;

    };
    code.into()
}

/// Used to generate the match case and help text
///
/// ```compile_fail
/// #[command_generate(bot_name = "botless", description = "Is it a bot or is it not?")]
/// enum Commands {
///     In,
///     Out
/// }
/// ```
///
/// Note: The defined enum will NOT be present at runtime. It gets replaced fully
#[proc_macro_attribute]
pub fn command_generate(args: TokenStream, input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as syn::ItemEnum);

    let args = parse_macro_input!(args as syn::AttributeArgs);

    let commands = input.variants.iter().map(|v| {
        let command_string = v.ident.to_string().to_lowercase();
        let command_short = {
            let chars: Vec<String> = v
                .ident
                .to_string()
                .to_case(Case::Snake)
                .split('_')
                .map(|x| x.chars().next().unwrap().to_string().to_lowercase())
                .collect();
            chars.join("")
        };
        let command = quote::format_ident!(
            "r#{}",
            syn::Ident::new(&v.ident.to_string().to_case(Case::Snake), v.span())
        );

        quote! {
            #command_string => {
                #command::#command(client, tx, config, sender, room_id, args).await
            },
            #command_short => {
                #command::#command(client, tx, config, sender, room_id, args).await
            },
        }
    });

    let help_parts = input.variants.iter().map(|v| {
        let command_string = v.ident.to_string().to_case(Case::Snake);
        let help_command =
            syn::Ident::new(&format!("{}_HELP", command_string.to_uppercase()), v.span());
        let command = quote::format_ident!(
            "r#{}",
            syn::Ident::new(&v.ident.to_string().to_case(Case::Snake), v.span())
        );

        quote! {
            #command::#help_command
        }
    });
    let mut help_format_string = String::from("{}");
    input.variants.iter().for_each(|_| {
        help_format_string = format!("{}{}", help_format_string, "{}");
    });

    let bot_name = match get_arg(
        input.span(),
        args.clone(),
        "bot_name",
        "#[command_generate(bot_name = \"<bot name>\", description = \"<bot description>\")]",
        2,
    ) {
        Ok(v) => v.value(),
        Err(e) => return e,
    };
    let description = match get_arg(
        input.span(),
        args,
        "description",
        "#[command_generate(bot_name = \"<bot name>\", description = \"<bot description>\")]",
        2,
    ) {
        Ok(v) => format!("{}\n\n", v.value()),
        Err(e) => return e,
    };

    let help_title = format!("# Help for the {} Bot\n\n", bot_name);
    let commands_title = "## Commands\n";
    let help_preamble = help_title + &description + commands_title;

    let code = quote! {

        async fn help(
            mut tx: mrsbfh::Sender,
        ) -> Result<(), Error> {
            let options = mrsbfh::pulldown_cmark::Options::empty();
            let help_markdown = format!(#help_format_string, #help_preamble, #(#help_parts,)*);
            let parser = mrsbfh::pulldown_cmark::Parser::new_ext(&help_markdown, options);
            let mut html = String::new();
            mrsbfh::pulldown_cmark::html::push_html(&mut html, parser);
            let owned_html = html.to_owned();

            mrsbfh::tokio::spawn(async move {
                let content = matrix_sdk::events::AnyMessageEventContent::RoomMessage(
                    matrix_sdk::events::room::message::MessageEventContent::notice_html(
                        &help_markdown,
                        owned_html,
                    ),
                );

                if let Err(e) = tx.send(content).await {
                    mrsbfh::tracing::error!("Error: {}",e);
                };
            });

            Ok(())
        }

        pub async fn match_command<'a>(cmd: &str, client: matrix_sdk::Client, config: Config<'a>, tx: mrsbfh::Sender, sender: String, room_id: matrix_sdk::identifiers::RoomId, args: Vec<&str>,) -> Result<(), Error> where Config<'a>: mrsbfh::config::Loader + Clone {
            match cmd {
                #(#commands)*
                "help" => {
                    help(tx).await
                },
                "h" => {
                    help(tx).await
                },
                _ => {Ok(())}
            }
        }

    };
    code.into()
}

#[proc_macro_derive(ConfigDerive)]
pub fn config_derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as syn::DeriveInput);
    let name = &ast.ident;

    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let expanded = quote! {
        impl #impl_generics mrsbfh::config::Loader for #name #ty_generics #where_clause {
            fn load<P: AsRef<std::path::Path> + std::fmt::Debug>(path: P) -> Result<Self, mrsbfh::errors::ConfigError> {
                let contents = std::fs::read_to_string(path)?;
                let config: Self = mrsbfh::serde_yaml::from_str(&contents)?;
                Ok(config)
            }
        }
    };

    TokenStream::from(expanded)
}

/// Used to generate code to autojoin when we get a invite for the bot
///
/// Requirements:
///
/// * Tokio
/// * Naming of arguments needs to be EXACTLY like in the example
/// * the async_trait macro needs to be BELOW the autojoin macro
///
/// ```compile_fail
/// #[mrsbfh::utils::autojoin]
/// #[async_trait]
/// impl EventEmitter for Bot {
///
/// async fn on_stripped_state_member(
///         &self,
///         room: SyncRoom,
///         room_member: &StrippedStateEvent<MemberEventContent>,
///         _: Option<MemberEventContent>,
///     ) {
///         // Your own logic. (Executed BEFORE the autojoin)
///     }
/// }
/// ```
///
#[proc_macro_attribute]
pub fn autojoin(_: TokenStream, input: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(input as syn::ItemImpl);
    let items = &mut input.items;

    for item in items {
        if let syn::ImplItem::Method(method) = item {
            if method.sig.ident == "on_stripped_state_member" {
                let original = method.block.clone();
                let new_block = syn::parse_quote! {
                    {
                        #original

                        // Autojoin logic
                        if room_member.state_key != self.client.user_id().await.unwrap() {
                            warn!("Got invite that isn't for us");
                            return;
                        }
                        if let matrix_sdk::room::Room::Invited(room) = room {
                            info!("Autojoining room {}", room.room_id());
                            let mut delay = 2;

                            while let Err(err) = room.accept_invitation().await {
                                // retry autojoin due to synapse sending invites, before the
                                // invited user can join for more information see
                                // https://github.com/matrix-org/synapse/issues/4345
                                error!(
                                    "Failed to join room {} ({:?}), retrying in {}s",
                                    room.room_id(),
                                    err,
                                    delay
                                );

                                tokio::time::sleep(tokio::time::Duration::from_secs(delay)).await;
                                delay *= 2;

                                if delay > 3600 {
                                    error!("Can't join room {} ({:?})", room.room_id(), err);
                                    break;
                                }
                            }
                            info!("Successfully joined room {}", room.room_id());
                        }
                    }
                };
                method.block = new_block;
            }
        }
    }

    TokenStream::from(quote! {#input})
}

/// Used to generate code to detect commands when we get a message for the bot
///
/// Requirements:
///
/// * Tokio
/// * Naming of arguments needs to be EXACTLY like in the example
/// * the async_trait macro needs to be BELOW the commands macro
/// * The match_command MUST be imported
///
/// ```compile_fail
/// use crate::commands::match_command;
///
/// #[mrsbfh::commands::commands]
/// #[async_trait]
/// impl EventEmitter for Bot {
///
/// async fn on_room_message(&self, room: SyncRoom, event: &SyncMessageEvent<MessageEventContent>) {
///         // Your own logic. (Executed BEFORE the commands matching)
///     }
/// }
/// ```
///
#[proc_macro_attribute]
pub fn commands(_: TokenStream, input: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(input as syn::ItemImpl);
    let items = &mut input.items;

    for item in items {
        if let syn::ImplItem::Method(method) = item {
            if method.sig.ident == "on_room_message" {
                let original = method.block.clone();
                let new_block = syn::parse_quote! {
                    {
                        #original

                        // Command matching logic
                        if let matrix_sdk::room::Room::Joined(room) = room {
                            let msg_body = if let matrix_sdk::events::SyncMessageEvent {
                                content: matrix_sdk::events::room::message::MessageEventContent {
                                    msgtype: matrix_sdk::events::room::message::MessageType::Text(matrix_sdk::events::room::message::TextMessageEventContent { body: msg_body, .. }),
                                    ..
                                },
                                ..
                            } = event
                            {
                                msg_body.clone()
                            } else {
                                String::new()
                            };
                            if msg_body.is_empty() {
                                return;
                            }

                            let sender = event.sender.clone().to_string();

                            let (tx, mut rx) = mpsc::channel(100);
                            let room_id = room.room_id().clone();

                            let cloned_config = self.config.clone();
                            let cloned_client = self.client.clone();
                            tokio::spawn(async move {
                                let whitespace_deduplicator_magic = regex::Regex::new(r"\s+").unwrap();
                                let command_matcher_magic = regex::Regex::new(r"!([\w-]+)").unwrap();
                                let normalized_body = whitespace_deduplicator_magic.replace_all(&msg_body, " ");
                                let mut split = msg_body.split_whitespace();

                                let command_raw = split.next().expect("This is not a command").to_lowercase();
                                let command = command_matcher_magic.captures(command_raw.as_str())
                                                                   .map_or(String::new(), |caps| {
                                                                        caps.get(1)
                                                                            .map_or(String::new(),
                                                                                    |m| String::from(m.as_str()))
                                                                   });
                                if !command.is_empty() {
                                   info!("Got command: {}", command);
                                }
                                // Make sure this is immutable
                                let args: Vec<&str> = split.collect();
                                if let Err(e) = match_command(
                                    command.as_str(),
                                    cloned_client.clone(),
                                    cloned_config.clone(),
                                    tx,
                                    sender,
                                    room_id,
                                    args,
                                )
                                .await
                                {
                                    error!("{}", e);
                                }

                            });

                            while let Some(v) = rx.recv().await {
                                if let Err(e) = room.send(v, None)
                                    .await
                                {
                                    error!("{}", e);
                                }
                            }
                        }
                    }
                };
                method.block = new_block;
            }
        }
    }

    TokenStream::from(quote! {#input})
}