Skip to content

Commit

Permalink
fix emoji search, remove user notification
Browse files Browse the repository at this point in the history
  • Loading branch information
avoonix committed Aug 6, 2024
1 parent 9605609 commit 07bd653
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 70 deletions.
8 changes: 0 additions & 8 deletions fuzzle/src/background_tasks/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,8 @@ pub async fn send_daily_report(
.reply_markup(Keyboard::daily_report(taggings)?)
.await?;

let new_users = database.get_users_added_24_hours().await?;
let new_sticker_sets = database.get_sticker_sets_added_24_hours().await?;

for new_user_id in new_users {
let new_user_id = UserId(new_user_id as u64);
bot.send_markdown(admin_id, Text::new_user(new_user_id))
.reply_markup(Keyboard::new_user(new_user_id))
.await?;
}

for (set_name, added_by_user_id) in new_sticker_sets {
let added_by_user_id = added_by_user_id.map(|user_id| UserId(user_id as u64));
bot.send_markdown(admin_id, Text::new_set(&set_name))
Expand Down
2 changes: 1 addition & 1 deletion fuzzle/src/database/queries/sticker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl Database {
sticker::sticker_set_id.eq(set_id),
sticker::telegram_file_identifier.eq(file_id),
sticker::sticker_file_id.eq(sticker_file_id),
sticker::emoji.eq(emoji.map(|e| e.to_string())),
sticker::emoji.eq(emoji.map(|e| e.to_string_without_variant())),
))
.on_conflict_do_nothing()
.execute(&mut self.pool.get()?)?;
Expand Down
9 changes: 0 additions & 9 deletions fuzzle/src/database/queries/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,4 @@ impl Database {
.execute(&mut self.pool.get()?)?;
Ok(())
}

#[tracing::instrument(skip(self), err(Debug))]
pub async fn get_users_added_24_hours(&self) -> Result<Vec<i64>, DatabaseError> {
let current_time = chrono::Utc::now().naive_utc(); // TODO: pass time as parameter?
Ok(user::table
.select(user::id)
.filter(user::created_at.ge(current_time - chrono::Duration::hours(24)))
.load(&mut self.pool.get()?)?)
}
}
2 changes: 1 addition & 1 deletion fuzzle/src/inline/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ impl Display for InlineQueryData {
}
InlineQueryData::SearchStickers { emoji, tags } => {
let tags = tags.join(" ");
let emoji = emoji.into_iter().map(|e| e.to_string()).join(" ");
let emoji = emoji.into_iter().map(|e| e.to_string_with_variant()).join(" ");
write!(f, "{emoji}")?;
if emoji.len() > 0 {
write!(f, " ")?;
Expand Down
9 changes: 4 additions & 5 deletions fuzzle/src/inline/inline_query_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ pub async fn query_stickers(

let emoji = emoji
.into_iter()
.map(|emoji| emoji.to_string())
.map(|emoji| emoji.to_string_without_variant())
.collect_vec();

let stickers = if query_empty {
Expand Down Expand Up @@ -928,14 +928,13 @@ async fn handle_most_used_emojis(
let thumbnail_url = Url::parse(&thumbnail_url)?;
Ok::<InlineQueryResult, BotError>(
InlineQueryResultArticle::new(
InlineQueryResultId::Emoji(emoji.to_string()).to_string(),
emoji.to_string(),
InlineQueryResultId::Emoji(emoji.clone()).to_string(),
emoji.to_string_with_variant(),
InputMessageContent::Text(InputMessageContentText::new(Markdown::escaped(
emoji.to_string(),
emoji.to_string_with_variant(),
))),
)
.description(Markdown::escaped(format!("used by {count} stickers")))
.reply_markup(Keyboard::emoji_article(emoji))
.thumb_url(thumbnail_url)
.thumb_width(THUMBNAIL_SIZE)
.thumb_height(THUMBNAIL_SIZE)
Expand Down
8 changes: 4 additions & 4 deletions fuzzle/src/inline/result_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ use nom::combinator::{eof, map};
use nom::sequence::{preceded, terminated};
use nom::{branch::alt, IResult};

use crate::util::{parse_emoji, set_name_literal, sticker_id_literal, tag_literal};
use crate::util::{parse_emoji, set_name_literal, sticker_id_literal, tag_literal, Emoji};

#[derive(Debug, PartialEq, Eq, Clone)]
pub(super) enum InlineQueryResultId {
Sticker(String),
Tag(String),
Set(String),
Emoji(String),
Emoji(Emoji),
Other(String),
}

Expand Down Expand Up @@ -42,7 +42,7 @@ fn parse_result(input: &str) -> IResult<&str, InlineQueryResultId> {
),
map(
preceded(tag("e:"), parse_emoji),
|emoji| InlineQueryResultId::Emoji(emoji.to_string()),
|emoji| InlineQueryResultId::Emoji(emoji),
),
map(
preceded(tag("o:"), alphanumeric1),
Expand All @@ -57,7 +57,7 @@ impl Display for InlineQueryResultId {
Self::Sticker(id) => write!(f, "s:{id}"),
Self::Tag(tag) => write!(f, "t:{tag}"),
Self::Set(set_id) => write!(f, "st:{set_id}"),
Self::Emoji(emoji) => write!(f, "e:{emoji}"),
Self::Emoji(emoji) => write!(f, "e:{}", emoji.to_string_without_variant()),
Self::Other(description) => write!(f, "o:{description}"),
}
}
Expand Down
9 changes: 2 additions & 7 deletions fuzzle/src/message/keyboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,11 +440,11 @@ impl Keyboard {
}

#[must_use]
pub fn emoji_article(emoji: Emoji) -> InlineKeyboardMarkup {
pub fn emoji_article(emoji: &Emoji) -> InlineKeyboardMarkup {
InlineKeyboardMarkup::new(vec![vec![
InlineKeyboardButton::switch_inline_query_current_chat(
format!("List stickers (ignores blacklist)"),
InlineQueryData::search_emoji(vec![], vec![emoji]),
InlineQueryData::search_emoji(vec![], vec![emoji.clone()]),
),
]])
}
Expand Down Expand Up @@ -592,11 +592,6 @@ impl Keyboard {
))
}

#[must_use]
pub fn new_user(user_id: UserId) -> InlineKeyboardMarkup {
InlineKeyboardMarkup::new([[user_button(user_id)]])
}

#[must_use]
pub fn merge(
sticker_id_a: &str,
Expand Down
39 changes: 34 additions & 5 deletions fuzzle/src/message/message_handler.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::{future::IntoFuture, time::Duration};

use itertools::Itertools;
use tracing::{info, Instrument};

use nom::combinator::eof;
use nom::combinator::map;
use nom::sequence::tuple;
use nom::{character::complete::multispace0, Finish};
use teloxide::{
dispatching::dialogue::GetChatId,
payloads::{SendMessageSetters, SendPhotoSetters},
Expand All @@ -13,6 +15,7 @@ use teloxide::{
},
utils::command::{BotCommands, ParseError},
};
use tracing::{info, Instrument};
use url::Url;

use crate::{
Expand All @@ -26,7 +29,7 @@ use crate::{
sticker::{fetch_sticker_file, import_individual_sticker_and_queue_set},
tags::suggest_tags,
text::{Markdown, Text},
util::{Emoji, Required},
util::{parse_emoji, Emoji, Required},
};

use super::{
Expand Down Expand Up @@ -115,13 +118,40 @@ async fn handle_sticker_sets(
Ok(())
}

fn emoji_search_command(input: &str) -> Option<Emoji> {
Finish::finish(map(
tuple((multispace0, parse_emoji, multispace0, eof)),
|(_, emoji, _, _)| emoji,
)(input))
.map(|(_, emoji)| emoji)
.ok()
}

async fn emoji_search_command_execute(
msg: &Message,
request_context: &RequestContext,
emoji: &Emoji,
) -> Result<(), BotError> {
request_context
.bot
.send_markdown(msg.chat.id, Markdown::escaped(format!("You sent a {} emoji", emoji.to_string_with_variant())))
.reply_markup(Keyboard::emoji_article(emoji))
.await?;
Ok(())
}

#[tracing::instrument(skip(request_context, msg))]
async fn handle_text_message(
text: &str,
request_context: RequestContext,
msg: Message,
) -> Result<(), BotError> {
let text = &fix_underline_command_separator(text);

if let Some(emoji) = emoji_search_command(text) {
return emoji_search_command_execute(&msg, &request_context, &emoji).await;
}

match RegularCommand::parse(text, &request_context.config.telegram_bot_username) {
Ok(command) => {
return command.execute(msg, request_context).await;
Expand Down Expand Up @@ -386,7 +416,7 @@ async fn handle_sticker_message(
.instrument(tracing::info_span!("telegram_bot_send_markdown"))
.await?;
}
DialogState::TagCreator (mut tag_creator) => {
DialogState::TagCreator(mut tag_creator) => {
let sticker = request_context
.database
.get_sticker_by_id(&sticker.file.unique_id)
Expand All @@ -398,7 +428,6 @@ async fn handle_sticker_message(
// .await?;
// let is_favorited = sticker_user.map_or(false, |su| su.is_favorite); // TODO: duplicated code


if !tag_creator.example_sticker_id.contains(&sticker.id) {
tag_creator.example_sticker_id.push(sticker.id.clone());
}
Expand Down
2 changes: 1 addition & 1 deletion fuzzle/src/tags/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn get_default_tag_manager(dir: PathBuf) -> anyhow::Result<Arc<TagMana
.add_default_tags()
.add_tags_from_csv(tags, 500, 1_000, true, true)
.add_default_aliases()
// .add_aliases_from_csv(aliases)
.add_aliases_from_csv(aliases)
.add_default_implications()
.add_implications_from_csv(implications)
.compute_transitive_implications()
Expand Down
32 changes: 16 additions & 16 deletions fuzzle/src/tags/tag_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,22 +229,22 @@ impl TagManager {
.any(|allowed_status| allowed_status == status)
}

// #[must_use]
//
// pub fn add_aliases_from_csv(mut self, csv: Vec<TagAliasCsv>) -> Self {
// let mut aliases = self.aliases.clone();
// for alias in csv {
// if !self.allowed_status(&alias.status) {
// continue;
// }
// if self.tags.get(&alias.consequent_name).is_some() {
// aliases.insert(alias.antecedent_name, alias.consequent_name);
// }
// }

// self.aliases = aliases;
// self
// }
#[must_use]

pub fn add_aliases_from_csv(mut self, csv: Vec<TagAliasCsv>) -> Self {
let mut aliases = self.aliases.clone();
for alias in csv {
if !self.allowed_status(&alias.status) {
continue;
}
if self.tags.get(&alias.consequent_name).is_some() {
aliases.insert(alias.antecedent_name, alias.consequent_name);
}
}

self.aliases = aliases;
self
}

#[must_use]

Expand Down
10 changes: 1 addition & 9 deletions fuzzle/src/text/texts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ If you search stickers by emojis instead of tags, the blacklist is not in effect
pub fn get_sticker_text(emoji: Option<Emoji>) -> Markdown {
Markdown::new(format!(
"UwU you sent a{}sticker :3",
escape(&emoji.map_or_else(|| " ".to_string(), |emoji| format!(" {emoji} ")))
escape(&emoji.map_or_else(|| " ".to_string(), |emoji| format!(" {} ", emoji.to_string_with_variant())))
))
}

Expand Down Expand Up @@ -290,14 +290,6 @@ Tags that will be removed:
))
}

#[must_use]
pub fn new_user(user_id: UserId) -> Markdown {
Markdown::new(format!(
"New user: {}",
format_user_id_as_markdown_link(user_id)
))
}

#[must_use]
pub fn untagged_set(set_name: &str, tags: &[String], count: usize) -> Markdown {
let tags = tags.into_iter().map(|t| escape(t)).join(", ");
Expand Down
12 changes: 8 additions & 4 deletions fuzzle/src/util/emoji.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,13 @@ impl Emoji {
}
}

impl Display for Emoji {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
impl Emoji {
pub fn to_string_without_variant(&self) -> String {
self.0.to_string()
}

pub fn to_string_with_variant(&self) -> String {
format!("{}\u{fe0f}", self.0)
}
}

Expand All @@ -33,7 +37,7 @@ pub fn parse_first_emoji(input: &str) -> (Option<Emoji>, &str) {
}) else {
return (None, input);
};
let emoji = Some(Emoji(emoji.as_str().to_string()));
let emoji = Some(Emoji::new_from_string_single(emoji.as_str()));
if let Some((second_index, _)) = graphemes.next() {
(emoji, &input[second_index..])
} else {
Expand Down

0 comments on commit 07bd653

Please sign in to comment.