use std::borrow::Cow;
use std::fmt;
use std::ops::{BitAnd, BitOr, BitOrAssign, Not};
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::error::ValidationError;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Perms(pub u64);
macro_rules! perm_bits {
($( $(#[$m:meta])* $name:ident = $bit:literal ),+ $(,)?) => {
impl Perms {
$( $(#[$m])* pub const $name: Perms = Perms(1 << $bit); )+
}
pub const REGISTRY: &[(u8, &str)] = &[ $( ($bit, stringify!($name)) ),+ ];
};
}
perm_bits! {
VIEW_CHANNEL = 0,
READ_MESSAGE_HISTORY = 1,
SEND_MESSAGES = 2,
SEND_IN_THREADS = 3,
CREATE_THREADS = 4,
EMBED_LINKS = 5,
ATTACH_FILES = 6,
ADD_REACTIONS = 7,
USE_EXTERNAL_EMOJI = 8,
MENTION_EVERYONE = 9,
MANAGE_MESSAGES = 10,
PIN_MESSAGES = 11,
MANAGE_THREADS = 12,
CREATE_POLLS = 13,
MANAGE_BOOKMARKS = 14,
BYPASS_SLOW_MODE = 15,
CONNECT = 16,
SPEAK = 17,
VIDEO = 18,
SCREEN_SHARE = 19,
MUTE_MEMBERS = 20,
DEAFEN_MEMBERS = 21,
MOVE_MEMBERS = 22,
RECORD_CALLS = 23,
MANAGE_CHANNELS = 32,
MANAGE_ROLES = 33,
MANAGE_SPACE = 34,
VIEW_AUDIT_LOG = 35,
MANAGE_EMOJI = 36,
ADD_MEMBERS = 37,
REMOVE_MEMBERS = 38,
TIMEOUT_MEMBERS = 39,
MANAGE_USER_GROUPS = 40,
CREATE_PUBLIC_CHANNELS = 41,
CREATE_PRIVATE_CHANNELS = 42,
ARCHIVE_CHANNELS = 43,
INVITE_GUESTS = 44,
BAN_MEMBERS = 47,
ADMINISTRATOR = 62,
}
const fn bits_range(lo: u32, hi: u32) -> u64 {
let mut v = 0u64;
let mut b = lo;
while b <= hi {
v |= 1 << b;
b += 1;
}
v
}
pub const DEFAULT_EVERYONE: Perms =
Perms(bits_range(0, 8) | 1 << 13 | bits_range(16, 19) | 1 << 37 | 1 << 41 | 1 << 42);
pub const CHANNEL_SCOPED: Perms = Perms(bits_range(0, 23));
pub const SPACE_SCOPED: Perms = Perms(bits_range(32, 44) | 1 << 47 | 1 << 62);
pub const ALL_DEFINED: Perms = Perms(CHANNEL_SCOPED.0 | SPACE_SCOPED.0);
pub const OVERWRITABLE: Perms = Perms(bits_range(0, 23) | 1 << 32 | 1 << 33);
pub const GUEST_MASK: Perms = Perms(bits_range(0, 9) | 1 << 11 | 1 << 13 | bits_range(16, 19));
pub const LINK_GUEST_MASK: Perms = Perms(1 << 0 | 1 << 2 | 1 << 7 | 1 << 16 | 1 << 17 | 1 << 18);
pub const LINK_GUEST_MASK_SCREEN: Perms = Perms(LINK_GUEST_MASK.0 | 1 << 19);
const _: () = assert!(LINK_GUEST_MASK_SCREEN.0 & !GUEST_MASK.0 == 0);
const _: () = assert!(LINK_GUEST_MASK.0 == 458_885 && LINK_GUEST_MASK_SCREEN.0 == 983_173);
pub const ASSISTANT_CEILING: Perms =
Perms(bits_range(0, 23) & !(1 << 10 | 1 << 12 | 1 << 14 | 1 << 20 | 1 << 21 | 1 << 22));
pub const SPACE_MANAGER: Perms = Perms(
bits_range(0, 22)
| 1 << 32
| 1 << 33
| 1 << 35
| 1 << 36
| 1 << 37
| 1 << 38
| 1 << 39
| 1 << 41
| 1 << 42
| 1 << 43,
);
pub const NO_SEND_CLEARS: Perms = Perms(1 << 5 | 1 << 6 | 1 << 9 | 1 << 13);
pub const ANNOUNCEMENT_EVERYONE_DENY: Perms = Perms::SEND_MESSAGES;
pub const ANNOUNCEMENT_EVERYONE_ALLOW: Perms = Perms::SEND_IN_THREADS;
pub const NONMEMBER_MASK: Perms = Perms(1 | 1 << 1 | 1 << 32 | 1 << 33 | 1 << 43);
pub const ARCHIVED_MASK: Perms = NONMEMBER_MASK;
pub const APP_GOVERNED_STRUCTURE: Perms = Perms(
1 << 32
| 1 << 33
| 1 << 34
| 1 << 36
| 1 << 37
| 1 << 38
| 1 << 40
| 1 << 41
| 1 << 42
| 1 << 43
| 1 << 44
| 1 << 62,
);
pub const APP_GOVERNED_MASK: Perms = Perms(ALL_DEFINED.0 & !APP_GOVERNED_STRUCTURE.0);
const _: () = assert!(APP_GOVERNED_STRUCTURE.0 == 4_611_720_614_388_957_184);
const _: () = assert!(APP_GOVERNED_MASK.0 == 141_321_620_684_799);
pub const SET_SLOW_MODE: Perms = Perms(1 << 48);
pub const REPORTED_ONLY: &[(u8, &str)] = &[(48, "SET_SLOW_MODE")];
const _: () = assert!(SET_SLOW_MODE.0 & ALL_DEFINED.0 == 0);
const _: () = assert!(SET_SLOW_MODE.0 == 281_474_976_710_656);
pub const READ_ONLY: Perms = Perms(1 | 1 << 1);
impl Perms {
pub const NONE: Perms = Perms(0);
pub const fn contains(self, other: Perms) -> bool {
self.0 & other.0 == other.0
}
pub fn names(self) -> Vec<&'static str> {
REGISTRY
.iter()
.filter(|(bit, _)| self.0 & (1 << bit) != 0)
.map(|(_, name)| *name)
.collect()
}
pub const fn undefined_bits(self) -> Perms {
Perms(self.0 & !ALL_DEFINED.0)
}
pub fn from_name(name: &str) -> Option<Perms> {
REGISTRY
.iter()
.find(|(_, n)| *n == name)
.map(|(bit, _)| Perms(1 << bit))
}
pub fn validate_request(self, field: &str) -> Result<(), ValidationError> {
let extra = self.undefined_bits();
if extra.0 != 0 {
return Err(ValidationError::invalid(
field,
format!("{field} sets undefined permission bits {}", extra.0),
));
}
Ok(())
}
pub fn validate_overwrite(self, field: &str) -> Result<(), ValidationError> {
let extra = self.0 & !OVERWRITABLE.0;
if extra != 0 {
return Err(ValidationError::invalid(
field,
format!("{field} sets bits {extra} that overwrites may not hold"),
));
}
Ok(())
}
}
impl BitOr for Perms {
type Output = Perms;
fn bitor(self, rhs: Perms) -> Perms {
Perms(self.0 | rhs.0)
}
}
impl BitOrAssign for Perms {
fn bitor_assign(&mut self, rhs: Perms) {
self.0 |= rhs.0;
}
}
impl BitAnd for Perms {
type Output = Perms;
fn bitand(self, rhs: Perms) -> Perms {
Perms(self.0 & rhs.0)
}
}
impl Not for Perms {
type Output = Perms;
fn not(self) -> Perms {
Perms(!self.0)
}
}
impl fmt::Display for Perms {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl Serialize for Perms {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Perms {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = Perms;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a permission bitfield as a decimal string")
}
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Perms, E> {
let b = s.as_bytes();
let canonical = !b.is_empty()
&& b.len() <= 20
&& b.iter().all(u8::is_ascii_digit)
&& (b[0] != b'0' || b.len() == 1);
if !canonical {
return Err(E::custom(format!(
"invalid perms {s:?}: expected a decimal u64 string"
)));
}
s.parse::<u64>()
.map(Perms)
.map_err(|e| E::custom(format!("invalid perms {s:?}: {e}")))
}
}
deserializer.deserialize_str(V)
}
}
impl JsonSchema for Perms {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
"Perms".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"pattern": "^(0|[1-9][0-9]{0,19})$",
"description": "A permission bitfield (u64) as a decimal string."
})
}
}