Skip to content

Commit

Permalink
Use UserType rather than is_bot and is_oc_controlled_bot
Browse files Browse the repository at this point in the history
  • Loading branch information
hpeebles committed Jul 26, 2024
1 parent 8e5eda5 commit f16c7d2
Show file tree
Hide file tree
Showing 46 changed files with 284 additions and 198 deletions.
6 changes: 5 additions & 1 deletion backend/canisters/community/api/src/lifecycle/init.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use candid::{CandidType, Principal};
use serde::{Deserialize, Serialize};
use types::{AccessGate, BuildVersion, CanisterId, CommunityPermissions, Document, Milliseconds, Rules, SourceGroup, UserId};
use types::{
AccessGate, BuildVersion, CanisterId, CommunityPermissions, Document, Milliseconds, Rules, SourceGroup, UserId, UserType,
};

#[derive(CandidType, Serialize, Deserialize, Debug)]
pub struct Args {
Expand All @@ -14,6 +16,8 @@ pub struct Args {
pub primary_language: String,
pub created_by_principal: Principal,
pub created_by_user_id: UserId,
#[serde(default)]
pub created_by_user_type: UserType,
pub mark_active_duration: Milliseconds,
pub user_index_canister_id: CanisterId,
pub local_user_index_canister_id: CanisterId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use candid::{CandidType, Principal};
use serde::{Deserialize, Serialize};
use types::{
ChannelId, CommunityCanisterChannelSummary, CommunityCanisterCommunitySummary, GateCheckFailedReason, TimestampMillis,
UniquePersonProof, UserId, VerifiedCredentialGateArgs,
UniquePersonProof, UserId, UserType, VerifiedCredentialGateArgs,
};

#[derive(CandidType, Serialize, Deserialize, Debug)]
Expand All @@ -13,6 +13,8 @@ pub struct Args {
pub invite_code: Option<u64>,
pub is_platform_moderator: bool,
pub is_bot: bool,
#[serde(default)]
pub user_type: UserType,
pub diamond_membership_expires_at: Option<TimestampMillis>,
pub verified_credential_args: Option<VerifiedCredentialGateArgs>,
pub unique_person_proof: Option<UniquePersonProof>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use candid::{CandidType, Principal};
use serde::{Deserialize, Serialize};
use types::{
CommunityCanisterCommunitySummary, GateCheckFailedReason, TimestampMillis, UniquePersonProof, UserId,
CommunityCanisterCommunitySummary, GateCheckFailedReason, TimestampMillis, UniquePersonProof, UserId, UserType,
VerifiedCredentialGateArgs,
};

Expand All @@ -12,6 +12,8 @@ pub struct Args {
pub invite_code: Option<u64>,
pub is_platform_moderator: bool,
pub is_bot: bool,
#[serde(default)]
pub user_type: UserType,
pub diamond_membership_expires_at: Option<TimestampMillis>,
pub verified_credential_args: Option<VerifiedCredentialGateArgs>,
pub unique_person_proof: Option<UniquePersonProof>,
Expand Down
8 changes: 4 additions & 4 deletions backend/canisters/community/impl/src/jobs/import_groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::cell::Cell;
use std::collections::HashMap;
use std::time::Duration;
use tracing::{info, trace};
use types::{ChannelId, ChannelLatestMessageIndex, Chat, ChatId, Empty, UserId, UsersBlocked};
use types::{ChannelId, ChannelLatestMessageIndex, Chat, ChatId, Empty, UserId, UserType, UsersBlocked};
use utils::consts::OPENCHAT_BOT_USER_ID;

const PAGE_SIZE: u32 = 19 * 102 * 1024; // Roughly 1.9MB (1.9 * 1024 * 1024)
Expand Down Expand Up @@ -166,12 +166,12 @@ pub(crate) async fn process_channel_members(group_id: ChatId, channel_id: Channe

let (members_to_add_to_community, local_user_index_canister_id) = mutate_state(|state| {
let channel = state.data.channels.get(&channel_id).unwrap();
let mut to_add: HashMap<UserId, bool> = HashMap::new();
for (user_id, is_bot) in channel.chat.members.iter().map(|m| (m.user_id, m.is_bot)) {
let mut to_add: HashMap<UserId, UserType> = HashMap::new();
for (user_id, user_type) in channel.chat.members.iter().map(|m| (m.user_id, m.user_type)) {
if let Some(member) = state.data.members.get_by_user_id_mut(&user_id) {
member.channels.insert(channel_id);
} else {
to_add.insert(user_id, is_bot);
to_add.insert(user_id, user_type);
}
}

Expand Down
12 changes: 10 additions & 2 deletions backend/canisters/community/impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use std::time::Duration;
use types::{
AccessGate, Achievement, BuildVersion, CanisterId, ChatMetrics, CommunityCanisterCommunitySummary, CommunityMembership,
CommunityPermissions, CommunityRole, Cryptocurrency, Cycles, Document, Empty, FrozenGroupInfo, Milliseconds, Notification,
PaymentGate, Rules, TimestampMillis, Timestamped, UserId,
PaymentGate, Rules, TimestampMillis, Timestamped, UserId, UserType,
};
use types::{CommunityId, SNS_FEE_SHARE_PERCENT};
use user_canister::c2c_notify_achievement;
Expand Down Expand Up @@ -341,6 +341,7 @@ impl Data {
community_id: CommunityId,
created_by_principal: Principal,
created_by_user_id: UserId,
created_by_user_type: UserType,
is_public: bool,
name: String,
description: String,
Expand Down Expand Up @@ -370,13 +371,20 @@ impl Data {
let channels = Channels::new(
community_id,
created_by_user_id,
created_by_user_type,
default_channels,
default_channel_rules,
is_public,
rng,
now,
);
let members = CommunityMembers::new(created_by_principal, created_by_user_id, channels.public_channel_ids(), now);
let members = CommunityMembers::new(
created_by_principal,
created_by_user_id,
created_by_user_type,
channels.public_channel_ids(),
now,
);
let events = CommunityEvents::new(name.clone(), description.clone(), created_by_user_id, now);

Data {
Expand Down
1 change: 1 addition & 0 deletions backend/canisters/community/impl/src/lifecycle/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ fn init(args: Args) {
env.canister_id().into(),
args.created_by_principal,
args.created_by_user_id,
args.created_by_user_type,
args.is_public,
args.name,
args.description,
Expand Down
7 changes: 5 additions & 2 deletions backend/canisters/community/impl/src/model/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use std::collections::HashMap;
use types::{
ChannelId, ChannelMatch, CommunityCanisterChannelSummary, CommunityCanisterChannelSummaryUpdates, CommunityId,
GroupMembership, GroupMembershipUpdates, GroupPermissionRole, GroupPermissions, MultiUserChat, Rules, TimestampMillis,
Timestamped, UserId, MAX_THREADS_IN_SUMMARY,
Timestamped, UserId, UserType, MAX_THREADS_IN_SUMMARY,
};

use super::members::CommunityMembers;
Expand All @@ -31,6 +31,7 @@ impl Channels {
pub fn new(
community_id: CommunityId,
created_by: UserId,
created_by_user_type: UserType,
default_channels: Vec<String>,
default_channel_rules: Option<Rules>,
is_community_public: bool,
Expand All @@ -48,6 +49,7 @@ impl Channels {
community_id,
name,
created_by,
created_by_user_type,
default_channel_rules.clone(),
is_community_public,
rng.gen(),
Expand Down Expand Up @@ -182,6 +184,7 @@ impl Channel {
community_id: CommunityId,
name: String,
created_by: UserId,
created_by_user_type: UserType,
channel_rules: Option<Rules>,
is_community_public: bool,
anonymized_id: u128,
Expand All @@ -207,7 +210,7 @@ impl Channel {
permissions,
None,
None,
false,
created_by_user_type,
anonymized_id,
now,
),
Expand Down
15 changes: 11 additions & 4 deletions backend/canisters/community/impl/src/model/members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use rand::RngCore;
use serde::{Deserialize, Serialize};
use std::collections::hash_map::Entry::Vacant;
use std::collections::{HashMap, HashSet};
use types::{ChannelId, CommunityMember, CommunityPermissions, CommunityRole, TimestampMillis, Timestamped, UserId, Version};
use types::{
ChannelId, CommunityMember, CommunityPermissions, CommunityRole, TimestampMillis, Timestamped, UserId, UserType, Version,
};

const MAX_MEMBERS_PER_COMMUNITY: u32 = 100_000;

Expand All @@ -24,6 +26,7 @@ impl CommunityMembers {
pub fn new(
creator_principal: Principal,
creator_user_id: UserId,
creator_user_type: UserType,
public_channels: Vec<ChannelId>,
now: TimestampMillis,
) -> CommunityMembers {
Expand All @@ -35,7 +38,8 @@ impl CommunityMembers {
channels: public_channels.into_iter().collect(),
channels_removed: Vec::new(),
rules_accepted: Some(Timestamped::new(Version::zero(), now)),
is_bot: false,
is_bot: creator_user_type.is_bot(),
user_type: creator_user_type,
display_name: Timestamped::default(),
};

Expand All @@ -50,7 +54,7 @@ impl CommunityMembers {
}
}

pub fn add(&mut self, user_id: UserId, principal: Principal, is_bot: bool, now: TimestampMillis) -> AddResult {
pub fn add(&mut self, user_id: UserId, principal: Principal, user_type: UserType, now: TimestampMillis) -> AddResult {
if self.blocked.contains(&user_id) {
AddResult::Blocked
} else {
Expand All @@ -64,7 +68,8 @@ impl CommunityMembers {
channels: HashSet::new(),
channels_removed: Vec::new(),
rules_accepted: None,
is_bot,
is_bot: user_type.is_bot(),
user_type,
display_name: Timestamped::default(),
};
e.insert(member.clone());
Expand Down Expand Up @@ -342,6 +347,8 @@ pub struct CommunityMemberInternal {
pub channels_removed: Vec<Timestamped<ChannelId>>,
pub rules_accepted: Option<Timestamped<Version>>,
pub is_bot: bool,
#[serde(default)]
pub user_type: UserType,
display_name: Timestamped<Option<String>>,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::collections::HashMap;
use std::iter::zip;
use types::{
AccessGate, AddedToChannelNotification, CanisterId, ChannelId, EventIndex, MembersAdded, MessageIndex, Notification,
TimestampNanos, UserId,
TimestampNanos, UserId, UserType,
};

#[update]
Expand All @@ -22,7 +22,7 @@ async fn add_members_to_channel(args: Args) -> Response {
Err(response) => return response,
};

let mut users_to_add: Vec<UserId> = Vec::new();
let mut users_to_add: Vec<(UserId, UserType)> = Vec::new();
let mut users_failed_gate_check: Vec<UserFailedGateCheck> = Vec::new();
let mut users_failed_with_error: Vec<UserFailedError> = Vec::new();

Expand All @@ -31,7 +31,7 @@ async fn add_members_to_channel(args: Args) -> Response {
match local_user_index_canister_c2c_client::c2c_diamond_membership_expiry_dates(
prepare_result.local_user_index_canister_id,
&local_user_index_canister::c2c_diamond_membership_expiry_dates::Args {
user_ids: prepare_result.users_to_add.clone(),
user_ids: prepare_result.users_to_add.iter().map(|(u, _)| *u).collect(),
},
)
.await
Expand All @@ -48,7 +48,7 @@ async fn add_members_to_channel(args: Args) -> Response {
let futures: Vec<_> = prepare_result
.users_to_add
.iter()
.map(|user_id| {
.map(|(user_id, _)| {
check_if_passes_gate(
gate.clone(),
CheckGateArgs {
Expand All @@ -65,9 +65,9 @@ async fn add_members_to_channel(args: Args) -> Response {

let results = futures::future::join_all(futures).await;

for (user_id, result) in zip(prepare_result.users_to_add, results) {
for ((user_id, user_type), result) in zip(prepare_result.users_to_add, results) {
match result {
CheckIfPassesGateResult::Success => users_to_add.push(user_id),
CheckIfPassesGateResult::Success => users_to_add.push((user_id, user_type)),
CheckIfPassesGateResult::Failed(reason) => {
users_failed_gate_check.push(UserFailedGateCheck { user_id, reason })
}
Expand All @@ -89,20 +89,20 @@ async fn add_members_to_channel(args: Args) -> Response {
users_to_add,
prepare_result.users_already_in_channel,
users_failed_gate_check,
prepare_result.users_not_in_community,
users_failed_with_error,
prepare_result.is_bot,
state,
)
})
}

struct PrepareResult {
user_id: UserId,
users_to_add: Vec<UserId>,
users_to_add: Vec<(UserId, UserType)>,
users_already_in_channel: Vec<UserId>,
users_not_in_community: Vec<UserId>,
gate: Option<AccessGate>,
local_user_index_canister_id: CanisterId,
is_bot: bool,
member_display_name: Option<String>,
this_canister: CanisterId,
now_nanos: TimestampNanos,
Expand Down Expand Up @@ -132,19 +132,28 @@ fn prepare(args: &Args, state: &RuntimeState) -> Result<PrepareResult, Response>
return Err(NotAuthorized);
}

let (users_already_in_channel, users_to_add): (Vec<_>, Vec<_>) = args
.user_ids
.iter()
.copied()
.partition(|id| channel.chat.members.contains(id));
let mut users_to_add = Vec::new();
let mut users_already_in_channel = Vec::new();
let mut users_not_in_community = Vec::new();
for user_id in args.user_ids.iter() {
if let Some(member) = state.data.members.get_by_user_id(user_id) {
if !channel.chat.members.contains(user_id) {
users_to_add.push((*user_id, member.user_type));
} else {
users_already_in_channel.push(*user_id);
}
} else {
users_not_in_community.push(*user_id);
}
}

Ok(PrepareResult {
user_id,
users_to_add,
users_already_in_channel,
users_not_in_community,
gate: channel.chat.gate.as_ref().cloned(),
local_user_index_canister_id: state.data.local_user_index_canister_id,
is_bot: member.is_bot,
member_display_name: member.display_name().value.clone(),
this_canister: state.env.canister_id(),
now_nanos: state.env.now_nanos(),
Expand All @@ -166,11 +175,11 @@ fn commit(
added_by_name: String,
added_by_display_name: Option<String>,
channel_id: ChannelId,
users_to_add: Vec<UserId>,
users_to_add: Vec<(UserId, UserType)>,
mut users_already_in_channel: Vec<UserId>,
users_failed_gate_check: Vec<UserFailedGateCheck>,
_users_not_in_community: Vec<UserId>,
mut users_failed_with_error: Vec<UserFailedError>,
is_bot: bool,
state: &mut RuntimeState,
) -> Response {
if let Some(channel) = state.data.channels.get_mut(&channel_id) {
Expand All @@ -188,14 +197,14 @@ fn commit(
let mut users_added: Vec<UserId> = Vec::new();
let mut users_limit_reached: Vec<UserId> = Vec::new();

for user_id in users_to_add {
for (user_id, user_type) in users_to_add {
match channel.chat.members.add(
user_id,
now,
min_visible_event_index,
min_visible_message_index,
channel.chat.is_public.value,
is_bot,
user_type,
) {
AddResult::Success(_) => {
users_added.push(user_id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ async fn c2c_join_channel(args: Args) -> Response {
invite_code: args.invite_code,
is_platform_moderator: args.is_platform_moderator,
is_bot: args.is_bot,
user_type: args.user_type,
diamond_membership_expires_at: args.diamond_membership_expires_at,
verified_credential_args: args.verified_credential_args.clone(),
unique_person_proof: args.unique_person_proof.clone(),
Expand Down Expand Up @@ -241,7 +242,7 @@ pub(crate) fn join_channel_unchecked(
min_visible_event_index,
min_visible_message_index,
notifications_muted,
member.is_bot,
member.user_type,
);

match &result {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ pub(crate) fn join_community_impl(args: &Args, state: &mut RuntimeState) -> Resu
.push_event(CommunityEventInternal::UsersUnblocked(Box::new(event)), now);
}

match state.data.members.add(args.user_id, args.principal, args.is_bot, now) {
match state.data.members.add(args.user_id, args.principal, args.user_type, now) {
AddResult::Success(_) => {
let invitation = state.data.invited_users.remove(&args.user_id, now);

Expand Down
Loading

0 comments on commit f16c7d2

Please sign in to comment.