Skip to content

feat: implement reactions #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f41af73
feat: add reactions to the chat message model
Bloeckchengrafik Nov 20, 2024
002e44c
refactor: reactions use the serenity object as a store now
Bloeckchengrafik Nov 24, 2024
00a9c43
Merge branch 'main' into feat/reactions
Bloeckchengrafik Nov 24, 2024
330c075
feat: use both serenity and local state, load live reactions
Bloeckchengrafik Nov 28, 2024
e66d5c8
refactor: move out reaction list to own file
Bloeckchengrafik Nov 28, 2024
f05123e
feat: show reactions in the UI
Bloeckchengrafik Nov 28, 2024
4ce6ef0
feat: show reaction count in the UI
Bloeckchengrafik Nov 29, 2024
8265f2d
wip: handle reaction click
Bloeckchengrafik Dec 1, 2024
c274ac9
merge: main branch
Bloeckchengrafik Dec 1, 2024
d2cdcc5
Merge branch 'scopeclient-main' into feat/reactions
Bloeckchengrafik Dec 1, 2024
97f0cae
fix: cleanup merge (-shown reactions)
Bloeckchengrafik Dec 1, 2024
113d9c6
fix: show reactions again
Bloeckchengrafik Dec 2, 2024
e8b3cea
feat: update GPUI and refactor to make it happen
Bloeckchengrafik Jan 28, 2025
72b2529
feat: add / remove reactions
Bloeckchengrafik Jan 29, 2025
0ed0532
chore: cleanup
Bloeckchengrafik Jan 29, 2025
3a283fe
feat: show who reacted to a message
Bloeckchengrafik Jan 29, 2025
8674c51
chore: make clippy happy
Bloeckchengrafik Jan 29, 2025
bf4143a
feat: add ellipsis when more than 5 users reacted
Bloeckchengrafik Jan 29, 2025
f6f6ed8
chore: make clippy happy
Bloeckchengrafik Jan 29, 2025
9956f25
fix: error with deleting reactions
Bloeckchengrafik Jan 29, 2025
54239a1
feat: support twemoji
Bloeckchengrafik Feb 5, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,344 changes: 813 additions & 531 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ gpui = { git = "https://github.com/scopeclient/zed.git", branch = "feature/expor
] }
components = { package = "ui", git = "https://github.com/scopeclient/components", version = "0.1.0" }
reqwest_client = { git = "https://github.com/scopeclient/zed.git", branch = "feature/export-platform-window", version = "0.1.0" }
atomic_refcell = "0.1.13"
21 changes: 21 additions & 0 deletions assets/opensource-licenses/twemoji-assets
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Tim 'Piepmatz' Hesse

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
1 change: 1 addition & 0 deletions src/chat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ edition = "2021"
tokio = "1.41.1"
chrono.workspace = true
gpui.workspace = true
atomic_refcell.workspace = true
15 changes: 11 additions & 4 deletions src/chat/src/channel.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use std::{fmt::Debug, sync::Arc};

use tokio::sync::broadcast;

use tokio::sync::broadcast::Receiver;
use crate::reaction::ReactionEvent;
use crate::{async_list::AsyncList, message::Message};


pub trait Channel: AsyncList<Content = Self::Message> + Send + Sync + Clone {
type Message: Message<Identifier = Self::Identifier>;
type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq;

fn get_receiver(&self) -> broadcast::Receiver<Self::Message>;
fn get_message_receiver(&self) -> broadcast::Receiver<Self::Message>;
fn get_reaction_receiver(&self) -> broadcast::Receiver<ReactionEvent<Self::Identifier>>;

fn send_message(&self, content: String, nonce: String) -> Self::Message;

Expand All @@ -23,8 +26,12 @@ impl<C: Channel> Channel for Arc<C> {
(**self).get_identifier()
}

fn get_receiver(&self) -> broadcast::Receiver<Self::Message> {
(**self).get_receiver()
fn get_message_receiver(&self) -> Receiver<Self::Message> {
(**self).get_message_receiver()
}

fn get_reaction_receiver(&self) -> Receiver<ReactionEvent<Self::Identifier>> {
(**self).get_reaction_receiver()
}

fn send_message(&self, content: String, nonce: String) -> Self::Message {
Expand Down
1 change: 1 addition & 0 deletions src/chat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod async_list;
pub mod channel;
pub mod client;
pub mod message;
pub mod reaction;
6 changes: 4 additions & 2 deletions src/chat/src/message.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
use std::fmt::Debug;

use chrono::{DateTime, Utc};
use gpui::{IntoElement, Render, View, WindowContext};
use gpui::{IntoElement, Render, Entity, App};

use crate::async_list::AsyncListItem;
use crate::reaction::ReactionList;

pub trait Message: Clone + AsyncListItem + Send {
type Identifier: Sized + Copy + Clone + Debug + Eq + PartialEq;
type Author: MessageAuthor<Identifier = <Self as Message>::Identifier>;
type Content: Render;

fn get_author(&self) -> Self::Author;
fn get_content(&self, cx: &mut WindowContext) -> View<Self::Content>;
fn get_content(&self, cx: &mut App) -> Entity<Self::Content>;
fn get_identifier(&self) -> Option<<Self as Message>::Identifier>;
fn get_nonce(&self) -> impl PartialEq;
fn should_group(&self, previous: &Self) -> bool;
fn get_timestamp(&self) -> Option<DateTime<Utc>>;
fn get_reactions(&mut self) -> Option<&mut impl ReactionList>;
}

#[derive(Debug, Clone, Copy)]
Expand Down
58 changes: 58 additions & 0 deletions src/chat/src/reaction.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use atomic_refcell::AtomicRefCell;
use gpui::{App, IntoElement, Rgba};
use std::fmt::{Debug, Formatter};
use std::sync::Arc;

pub type ReactionEvent<T> = (T, ReactionOperation);

#[derive(Copy, Clone, Debug)]
pub enum MessageReactionType {
Normal,
Burst,
}

#[derive(Clone, PartialEq)]
pub enum ReactionEmoji {
Simple(String),
Custom {
url: String,
animated: bool,
name: Option<String>,
id: u64,
},
}

impl Debug for ReactionEmoji {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ReactionEmoji::Simple(s) => write!(f, "{}", s),
ReactionEmoji::Custom { name, .. } => write!(f, ":{}:", name.clone().unwrap_or("<unknown>".to_string())),
}
}
}

pub trait MessageReaction: IntoElement {
fn get_count(&self, kind: Option<MessageReactionType>) -> u64;
fn get_self_reaction(&self) -> Option<MessageReactionType>;
fn get_emoji(&self) -> ReactionEmoji;
fn get_burst_colors(&self) -> Vec<Rgba>;
fn increment(&mut self, kind: MessageReactionType, user_is_self: bool, by: isize);
}

#[derive(Clone, Debug)]
pub enum ReactionOperation {
Add(ReactionEmoji, MessageReactionType),
AddSelf(ReactionEmoji, MessageReactionType),
Remove(ReactionEmoji),
RemoveSelf(ReactionEmoji),
RemoveAll,
RemoveEmoji(ReactionEmoji),
SetMembers(ReactionEmoji, Vec<String>),
}

pub trait ReactionList {
fn get_reactions(&self) -> &Arc<AtomicRefCell<Vec<impl MessageReaction>>>;
fn increment(&mut self, emoji: &ReactionEmoji, kind: MessageReactionType, user_is_self: bool, by: isize);
fn apply(&mut self, operation: ReactionOperation, app: &mut App);
fn get_content(&self, cx: &mut App) -> impl IntoElement;
}
9 changes: 8 additions & 1 deletion src/discord/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ name = "scope-backend-discord"
version = "0.1.0"
edition = "2021"

[features]
twemoji = ["twemoji-assets"]

[dependencies]
gpui.workspace = true
components.workspace = true
scope-chat = { version = "0.1.0", path = "../chat" }
serenity = { git = "https://github.com/scopeclient/serenity", version = "0.12" }
tokio = "1.41.1"
Expand All @@ -13,6 +17,9 @@ scope-backend-cache = { version = "0.1.0", path = "../cache" }
url = "2.5.3"
querystring = "1.1.0"
catty = "0.1.5"
atomic_refcell = "0.1.13"
atomic_refcell.workspace = true
rand = "0.8.5"
dashmap = "6.1.0"
log = "0.4.22"

twemoji-assets = { version = "1.3.0", optional = true }
30 changes: 19 additions & 11 deletions src/discord/src/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::{Arc, OnceLock};

use chrono::Utc;
use scope_backend_cache::async_list::{refcacheslice::Exists, AsyncListCache};
use scope_chat::reaction::ReactionEvent;
use scope_chat::{
async_list::{AsyncList, AsyncListIndex, AsyncListItem, AsyncListResult},
channel::Channel,
Expand All @@ -17,24 +18,26 @@ use crate::{

pub struct DiscordChannel {
channel: Arc<serenity::model::channel::Channel>,

receiver: broadcast::Receiver<DiscordMessage>,
message_receiver: broadcast::Receiver<DiscordMessage>,
reaction_receiver: broadcast::Receiver<ReactionEvent<Snowflake>>,
client: Arc<DiscordClient>,
cache: Arc<Mutex<AsyncListCache<DiscordMessage>>>,
blocker: Semaphore,
}

impl DiscordChannel {
pub(crate) async fn new(client: Arc<DiscordClient>, channel_id: ChannelId) -> Self {
let (sender, receiver) = broadcast::channel(10);

client.add_channel_message_sender(channel_id, sender).await;

let channel = Arc::new(channel_id.to_channel(client.discord()).await.unwrap());
let (message_sender, message_receiver) = broadcast::channel(10);
client.add_channel_message_sender(channel_id, message_sender).await;

let (reaction_sender, reaction_receiver) = broadcast::channel(10);
client.add_channel_reaction_sender(channel_id, reaction_sender).await;

DiscordChannel {
channel,
receiver,
message_receiver,
reaction_receiver,
client,
cache: Arc::new(Mutex::new(AsyncListCache::new())),
blocker: Semaphore::new(1),
Expand All @@ -46,8 +49,12 @@ impl Channel for DiscordChannel {
type Message = DiscordMessage;
type Identifier = Snowflake;

fn get_receiver(&self) -> broadcast::Receiver<Self::Message> {
self.receiver.resubscribe()
fn get_message_receiver(&self) -> broadcast::Receiver<Self::Message> {
self.message_receiver.resubscribe()
}

fn get_reaction_receiver(&self) -> broadcast::Receiver<ReactionEvent<Snowflake>> {
self.reaction_receiver.resubscribe()
}

fn send_message(&self, content: String, nonce: String) -> DiscordMessage {
Expand All @@ -69,7 +76,7 @@ impl Channel for DiscordChannel {
sent_time: Utc::now(),
list_item_id: Snowflake::random(),
},
content: OnceLock::new(),
content: Arc::new(OnceLock::new()),
}
}

Expand Down Expand Up @@ -255,7 +262,8 @@ impl Clone for DiscordChannel {
fn clone(&self) -> Self {
Self {
channel: self.channel.clone(),
receiver: self.receiver.resubscribe(),
message_receiver: self.message_receiver.resubscribe(),
reaction_receiver: self.reaction_receiver.resubscribe(),
client: self.client.clone(),
cache: self.cache.clone(),
blocker: Semaphore::new(1),
Expand Down
93 changes: 92 additions & 1 deletion src/discord/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ use std::{
sync::{Arc, OnceLock, Weak},
};

use crate::message::reaction::discord_reaction_to_emoji;
use atomic_refcell::AtomicRefCell;
use dashmap::DashMap;
use scope_chat::reaction::{MessageReactionType, ReactionEmoji, ReactionEvent, ReactionOperation};
use serenity::all::{EmojiId, Reaction, ReactionType};
use serenity::{
all::{
Cache, CacheHttp, ChannelId, Context, CreateMessage, EventHandler, GatewayIntents, GetMessages, GuildId, Http, Member, Message, MessageId,
Expand Down Expand Up @@ -37,6 +40,7 @@ impl CacheHttp for SerenityClient {
#[derive(Default)]
pub struct DiscordClient {
channel_message_event_handlers: RwLock<HashMap<ChannelId, Vec<broadcast::Sender<DiscordMessage>>>>,
channel_reaction_event_handlers: RwLock<HashMap<ChannelId, Vec<broadcast::Sender<ReactionEvent<Snowflake>>>>>,
client: OnceLock<SerenityClient>,
user: OnceLock<Arc<User>>,
channels: RwLock<HashMap<ChannelId, Arc<DiscordChannel>>>,
Expand All @@ -52,7 +56,6 @@ impl DiscordClient {
let client = Arc::new_cyclic(|weak| DiscordClient {
ready_notifier: AtomicRefCell::new(Some(sender)),
weak: weak.clone(),

..Default::default()
});

Expand Down Expand Up @@ -91,6 +94,10 @@ impl DiscordClient {
self.channel_message_event_handlers.write().await.entry(channel).or_default().push(sender);
}

pub async fn add_channel_reaction_sender(&self, channel: ChannelId, sender: broadcast::Sender<ReactionEvent<Snowflake>>) {
self.channel_reaction_event_handlers.write().await.entry(channel).or_default().push(sender);
}

pub async fn channel(self: Arc<Self>, channel_id: Snowflake) -> Arc<DiscordChannel> {
let channel_id = ChannelId::new(channel_id.0);

Expand Down Expand Up @@ -130,6 +137,49 @@ impl DiscordClient {
// FIXME: proper error handling
Some(channel_id.message(self.discord().http.clone(), message_id).await.unwrap())
}

async fn send_reaction_operation(&self, channel_id: ChannelId, message_id: MessageId, operation: ReactionOperation) {
if let Some(vec) = self.channel_reaction_event_handlers.read().await.get(&channel_id) {
for sender in vec {
let _ = sender.send((message_id.into(), operation.clone()));
}
}
}

fn emoji_to_serenity(emoji: &ReactionEmoji) -> ReactionType {
match emoji.clone() {
ReactionEmoji::Simple(c) => ReactionType::Unicode(c),
ReactionEmoji::Custom { name, animated, id, .. } => ReactionType::Custom {
id: EmojiId::new(id),
animated,
name,
},
}
}

pub async fn load_users_reacting_to(&self, channel_id: ChannelId, message_id: MessageId, emoji: ReactionEmoji) {
let reactions = channel_id.reaction_users(self.discord().http.clone(), message_id, Self::emoji_to_serenity(&emoji), Some(6), None).await;
if reactions.is_err() {return;}
let reactions = reactions.unwrap().iter().map(|user|user.name.clone()).collect();

self.send_reaction_operation(channel_id, message_id, ReactionOperation::SetMembers(emoji, reactions)).await;
}

pub async fn add_reaction(&self, channel_id: ChannelId, message_id: MessageId, emoji: ReactionEmoji) {
let reaction_type = Self::emoji_to_serenity(&emoji);
channel_id.create_reaction(self.discord().http.clone(), message_id, reaction_type).await.unwrap();

// Refresh reactions in UI
self.load_users_reacting_to(channel_id, message_id, emoji).await;
}

pub async fn remove_reaction(&self, channel_id: ChannelId, message_id: MessageId, emoji: ReactionEmoji) {
let reaction_type = Self::emoji_to_serenity(&emoji);
channel_id.delete_reaction(self.discord().http.clone(), message_id, None, reaction_type).await.unwrap();

// Refresh reactions in UI
self.load_users_reacting_to(channel_id, message_id, emoji).await;
}
}

#[async_trait]
Expand Down Expand Up @@ -163,4 +213,45 @@ impl EventHandler for DiscordClient {
}
}
}

async fn reaction_add(&self, _: Context, reaction: Reaction) {
let ty = if reaction.burst {
MessageReactionType::Burst
} else {
MessageReactionType::Normal
};

let emoji = discord_reaction_to_emoji(&reaction.emoji);
let me_id = self.user.get().expect("User not ready").id;

let operation = if reaction.member.is_none_or(|member| member.user.id == me_id) {
ReactionOperation::AddSelf(emoji, ty)
} else {
ReactionOperation::Add(emoji, ty)
};

self.send_reaction_operation(reaction.channel_id, reaction.message_id, operation).await;
}

async fn reaction_remove(&self, _: Context, reaction: Reaction) {
let emoji = discord_reaction_to_emoji(&reaction.emoji);
let me_id = self.user.get().expect("User not ready").id;

let operation = if reaction.member.is_none_or(|member| member.user.id == me_id) {
ReactionOperation::RemoveSelf(emoji)
} else {
ReactionOperation::Remove(emoji)
};

self.send_reaction_operation(reaction.channel_id, reaction.message_id, operation).await;
}

async fn reaction_remove_all(&self, _: Context, channel_id: ChannelId, removed_from_message_id: MessageId) {
self.send_reaction_operation(channel_id, removed_from_message_id, ReactionOperation::RemoveAll).await;
}

async fn reaction_remove_emoji(&self, _: Context, removed_reactions: Reaction) {
let emoji = discord_reaction_to_emoji(&removed_reactions.emoji);
self.send_reaction_operation(removed_reactions.channel_id, removed_reactions.message_id, ReactionOperation::RemoveEmoji(emoji)).await;
}
}
Loading