aboutsummaryrefslogtreecommitdiff
path: root/src/model/utils.rs
Commit message (Collapse)AuthorAgeFilesLines
* Refactor imports/exports to use nested groups and better formattingacdenisSK2018-03-291-3/+5
|
* Implement or derive Serialize on all modelsZeyla Hellyer2018-01-011-0/+48
|
* Break up the model moduleZeyla Hellyer2017-12-161-1/+10
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The `model` module has historically been one giant module re-exporting all of the model types, which is somewhere around 100 types. This can be a lot to look at for a new user and somewhat overwhelming, especially with a large number of fine-grained imports from the module. The module is now neatly split up into submodules, mostly like it has been internally since the early versions of the library. The submodules are: - application - channel - error - event - gateway - guild - id - invite - misc - permissions - prelude - user - voice - webhook Each submodule contains types that are "owned" by the module. For example, the `guild` submodule contains, but not limited to, Emoji, AuditLogsEntry, Role, and Member. `channel` contains, but not limited to, Attachment, Embed, Message, and Reaction. Upgrade path: Instead of glob importing the models via `use serenity::model::*;`, instead glob import via the prelude: ```rust use serenity::model::prelude::*; ``` Instead of importing from the root model module: ```rust use serenity::model::{Guild, Message, OnlineStatus, Role, User}; ``` instead import from the submodules like so: ```rust use serenity::model::channel::Message; use serenity::model::guild::{Guild, Role}; use serenity::model::user::{OnlineStatus, User}; ```
* Merge branch 'branch-v0.4.5' into v0.5.0Zeyla Hellyer2017-12-091-2/+2
|\
| * Fix remaining deserializersZeyla Hellyer2017-12-091-2/+2
| | | | | | | | | | | | Following up on the recent commit to fix the snowflake types' deserializers, this commit fixes the rest of the library's usage of deserializers in the same manner.
* | Tune down repetition with a macroacdenisSK2017-11-301-56/+31
| |
* | Add Debug derives to more public typesthelearnerofcode2017-11-071-0/+2
| |
* | Whoops. Add a `FromStr` impl for `ReactionType`acdenisSK2017-11-041-1/+0
| |
* | Merge v0.4.3acdenisSK2017-11-041-1/+4
|\|
| * Rename `Guild::permissions_for`->`permissions_in`Zeyla Hellyer2017-10-301-1/+1
| | | | | | | | | | | | Rename `Guild::permissions_for` to `Guild::permissions_in`, deprecating `Guild::permissions_for` which is only an inline method to `permissions_in`.
* | Switch to parking_lot::{Mutex, RwLock}Zeyla Hellyer2017-10-101-10/+8
|/ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Switch to the `parking_lot` crate's implementations of `std::sync::Mutex` and `std::sync::RwLock`, which are more efficient. A writeup on why `parking_lot` is more efficient can be read here: <https://github.com/Amanieu/parking_lot> Upgrade path: Modify `mutex.lock().unwrap()` usage to `mutex.lock()` (not needing to unwrap or handle a result), and `rwlock.read().unwrap()`/`rwlock.write().unwrap()` usage to `rwlock.read()` and `rwlock.write()`. For example, modify: ```rust use serenity::CACHE; println!("{}", CACHE.read().unwrap().user.id); ``` to: ```rust use serenity::CACHE; println!("{}", CACHE.read().user.id); ```
* Apply rustfmtZeyla Hellyer2017-09-181-7/+5
|
* Fix compiles of a variety of feature combinationsZeyla Hellyer2017-09-181-2/+2
| | | | | This fixes compilation errors and warnings when compiling a mixture of non-default feature targets.
* Apply rustfmt + fix testsZeyla Hellyer2017-09-091-1/+2
|
* Implement categoriesacdenisSK2017-09-091-2/+4
|
* Add ability to play DCA and Opus files. (#148)Maiddog2017-08-271-7/+8
|
* Revamp `RwLock` usage in the libacdenisSK2017-08-241-8/+7
| | | | Also not quite sure if they goofed rustfmt or something, but its changes it did were a bit bizarre.
* Apply rustfmtZeyla Hellyer2017-08-181-5/+6
|
* rustfmtacdenisSK2017-07-271-32/+34
|
* Make Message::nonce a serde_json::ValueZeyla Hellyer2017-06-231-31/+0
| | | | | | | | | | | | | | | | | | Nonces can actually be almost anything - including booleans - so just use a Value to represent it since very few users will need it. This fixes errors like: ``` WARN:serenity::internal::ws_impl: (╯°□°)╯︵ ┻━┻ Error decoding: {"t":"MESSAGE_CREATE","s":12187872,"op":0,"d":{"type":0,"tts":false,"timestamp":"2017-06-01T01:00:00.000000+00:00","pinned":false,"nonce":"","mentions":[{"username":"redacted","id":"redacted","discriminator":"redacted","avatar":"redacted"}],"mention_roles":[],"mention_everyone":false,"id":"redacted","embeds":[],"edited_timestamp":null,"content":"redacted","channel_id":"redacted","author":{"username":"redacted","id":"redacted","discriminator":"redacted","bot":true,"avatar":"redacted"},"attachments":[]}} ERROR:serenity::client: Shard handler received err: Json(ErrorImpl { code: Message("Unknown i64 value: "), line: 0, column: 0 }) ``` and: ``` WARN:serenity::internal::ws_impl: (╯°□°)╯︵ ┻━┻ Error decoding: {"t":"MESSAGE_CREATE","s":1001192,"op":0,"d":{"type":0,"tts":false,"timestamp":"2017-06-01T01:01:01.000000+00:00","pinned":false,"nonce":true,"mentions":[],"mention_roles":[],"mention_everyone":false,"id":"redacted","embeds":[],"edited_timestamp":null,"content":"bork","channel_id":"redacted","author":{"username":"redacted","id":"redacted","discriminator":"redacted","bot":true,"avatar":"redacted"},"attachments":[]}} ERROR:serenity::client: Shard handler received err: Json(ErrorImpl { code: Message("invalid type: boolean `true`, expected identifier"), line: 0, column: 0 }) ```
* Fix negative nonces failing to deserializeZeyla Hellyer2017-06-101-0/+31
| | | | | | | | | | Negative message nonces caused deserialization errors, as serde would not deserialize integers into strings. To fix this, change `Message::nonce` into an `Option<Snowflake>` from an `Option<String>`. This new `Snowflake` is a wrapper around an `i64`. Use a new `I64Visitor` to deserialize i64s, u64s, and strs into the wanted i64.
* Restructure modulesZeyla Hellyer2017-05-221-5/+5
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Modules are now separated into a fashion where the library can be used for most use cases, without needing to compile the rest. The core of serenity, with no features enabled, contains only the struct (model) definitions, constants, and prelude. Models do not have most functions compiled in, as that is separated into the `model` feature. The `client` module has been split into 3 modules: `client`, `gateway`, and `http`. `http` contains functions to interact with the REST API. `gateway` contains the Shard to interact with the gateway, requiring `http` for retrieving the gateway URL. `client` requires both of the other features and acts as an abstracted interface over both the gateway and REST APIs, handling the event loop. The `builder` module has been separated from `utils`, and can now be optionally compiled in. It and the `http` feature are required by the `model` feature due to a large number of methods requiring access to them. `utils` now contains a number of utilities, such as the Colour struct, the `MessageBuilder`, and mention parsing functions. Each of the original `ext` modules are still featured, with `cache` not requiring any feature to be enabled, `framework` requiring the `client`, `model`, and `utils`, and `voice` requiring `gateway`. In total the features and their requirements are: - `builder`: none - `cache`: none - `client`: `gateway`, `http` - `framework`: `client`, `model`, `utils` - `gateway`: `http` - `http`: none - `model`: `builder`, `http` - `utils`: none - `voice`: `gateway` The default features are `builder`, `cache`, `client`, `framework`, `gateway`, `model`, `http`, and `utils`. To help with forwards compatibility, modules have been re-exported from their original locations.
* Fix permissions when sending to DMs or groupsalex2017-05-071-3/+12
| | | | | | | When performing an action on a DM Channel or Group, an arbitrary permission check would always fail, causing the action to error out with a lacking permissions error. To fix this, just assume the action will always succeed.
* Fix decoding for `CurrentUser.discriminator`Zeyla Hellyer2017-04-251-0/+37
| | | | | | Due to the serde 1.0 upgrade, integers are no longer automatically deserialized from Strings. To resolve this, create a visitor that performs the operation based on the input.
* Fix deserialization for IdsZeyla Hellyer2017-04-241-0/+39
| | | | | Attempt to deserialize from both a str and a u64 instead of the default derive impl.
* Update most dependency version requirementsZeyla Hellyer2017-04-231-9/+9
| | | | | | | | Update the dependencies `base64`, `bitflags`, `byteorder`, `serde`, `serde_derive`, and `serde_json`. These dependencies have been updated, with byteorder and serde** hitting v1.0.0, so they should be updated for the v0.2.0 serenity release.
* Deprecate methods prefixed with `get_`Zeyla Hellyer2017-04-191-5/+3
| | | | | | A lot of structs - such as `Guild` or `ChannelId` - have methods with prefixes of `get_`, which are generally discouraged. To fix this, deprecate them and remove them in v0.3.0.
* Switch to using serde for deserializationZeyla Hellyer2017-04-111-117/+48
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The current build system is rudimentary, incomplete, and rigid, offering little in the way of customizing decoding options. To solve this, switch to using serde-derive with custom Deserialization implementations. This allows very simple deserialization when special logic does not need to be applied, yet allows us to implement our own deserialization logic when required. The problem with the build system was that it built enums and structs from YAML files. This is not so good, because it requires creating a custom build system (which was rudimentary), creating "special struct configs" when logic needed to be ever so slightly extended (rigid), and if special logic needed to be applied, a custom deserialization method would have been needed to be made anyway (incomplete). To solve this, switch to serde-derive and implementing Deserialize ourselves where required. This reduces YAML definitions that might look like: ```yaml --- name: Group description: > A group channel, potentially including other users, separate from a [`Guild`]. [`Guild`]: struct.Guild.html fields: - name: channel_id description: The Id of the group channel. from: id type: ChannelId - name: icon description: The optional icon of the group channel. optional: true type: string - name: last_message_id description: The Id of the last message sent. optional: true type: MessageId - name: last_pin_timestamp description: Timestamp of the latest pinned message. optional: true type: string - name: name description: The name of the group channel. optional: true type: string - name: owner_id description: The Id of the group channel creator. type: UserId - name: recipients description: Group channel's members. custom: decode_users t: UserId, Arc<RwLock<User>> type: hashmap ``` to: ```rs /// A group channel - potentially including other [`User`]s - separate from a /// [`Guild`]. /// /// [`Guild`]: struct.Guild.html /// [`User`]: struct.User.html pub struct Group { /// The Id of the group channel. #[serde(rename="id")] pub channel_id: ChannelId, /// The optional icon of the group channel. pub icon: Option<String>, /// The Id of the last message sent. pub last_message_id: Option<MessageId>, /// Timestamp of the latest pinned message. pub last_pin_timestamp: Option<String>, /// The name of the group channel. pub name: Option<String>, /// The Id of the group owner. pub owner_id: UserId, /// A map of the group's recipients. #[serde(deserialize_with="deserialize_users")] pub recipients: HashMap<UserId, Arc<RwLock<User>>>, } ``` This is much simpler and does not have as much boilerplate. There should not be any backwards incompatible changes other than the old, public - yet undocumented (and hidden from documentation) - decode methods being removed. Due to the nature of this commit, field names may be incorrect, and will need to be corrected as deserialization errors are found.
* Remove selfbot supportZeyla Hellyer2017-04-051-100/+0
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | While selfbots have always been "roughly tolerated", lately they have been tolerated to less of a degree. The simple answer is to no longer support selfbots in any form. This is done for a few of reasons: 1) in anticipation of selfbots no longer being tolerated; 2) there are few reasons why one should make a selfbot in Rust and not a scripting language; 3) there are alternatives (i.e. discord-rs) that still support userbots. Selfbots are simply not a goal of the maintainer of serenity. Upgrade path: Don't use selfbots with serenity. Use discord-rs instead. The following has been removed: Enums: - `RelationshipType` Structs: - `FriendSourceFlags` - `ReadState` - `Relationship` - `SearchResult` - `SuggestionReason` - `Tutorial` - `UserConnection` - `UserGuildSettings` - `UserSettings` Removed the following fields: - `CurrentUser::mobile` - Ready::{ analytics_token, experiments, friend_suggestion_count, notes, read_state, relationships, tutorial, user_guild_settings, user_settings, } Removed the following methods: - `Client::login_user` Deprecated `Client::login_bot` in favour of `Client::login`. Removed `client::LoginType`. The following no longer take a `login_type` parameter: - `Context::new` - `Shard::new` `Shard::sync_guilds` has been removed. The `client::Error::{InvalidOperationAsBot, InvalidOperationAsUser}` variants have been removed. The following event handlers on `Client` have been removed: - `on_friend_suggestion_create` - `on_friend_suggestion_delete` - `on_relationship_add` - `on_relationship_remove` - `on_user_guild_settings_update` - `on_note_update` - `on_user_settings_update` The following `client::rest` functions have been removed: - `ack_message` - `edit_note` - `get_user_connections` - `search_channel_messages` - `search_guild_messages` The following `client::rest::ratelimiting::Route` variants have been removed: - `ChannelsIdMessagesSearch` - `GuildsIdMessagesSearch` - `UsersMeConnections` The following fields on `ext::cache::Cache` have been removed: - `guild_settings` - `relationships` - `settings` while the following methods have also been removed: - `update_with_relationship_add` - `update_with_relationship_remove` - `update_with_user_guild_settings_update` - `update_with_user_note_update` - `update_with_user_settings_update` The following methods have been removed across models: - `ChannelId::{ack, search}` - `Channel::{ack, search}` - `Group::{ack, search}` - `GuildChannel::{ack, search}` - `GuildId::{search, search_channels}` - `Guild::{search, search_channels}` - `Message::ack` - `PartialGuild::{search, search_channels}` - `PrivateChannel::{ack, search}` - `UserId::{delete_note, edit_note}` - `User::{delete_note, edit_note}` The following events in `model::events` have been removed: - `FriendSuggestionCreateEvent` - `FriendSuggestionDeleteEvent` - `MessageAckEvent` - `RelationshipAddEvent` - `RelationshipRemoveEvent` - `UserGuildSettingsUpdateEvent` - `UserNoteUpdateEvent` - `UserSettingsUpdateEvent` Consequently, the following variants on `model::event::Event` have been removed: - `FriendSuggestionCreate` - `FriendSuggestionDelete` - `MessageAdd` - `RelationshipAdd` - `RelationshipRemove` - `UserGuildSettingUpdate` - `UserNoteUpdate` - `UserSettingsUpdate` The `utils::builder::Search` search builder has been removed.
* Fix Member methods due to variant joined_at valuesZeyla Hellyer2017-03-201-16/+18
| | | | | | | | | | | | | | | Fix an issue where the library would check the Id of the guild that a member is in by checking the Member's ID and joined_at value with those of the members of guilds present in the cache. Performing this check would have the issue of where a joined_at for a member received over websocket would potentially have a varying value than that of the same member retrieved over REST. To fix this, attach the relevant guild's Id to the member on creation, where the Id is available. Fixes #68.
* Optimize cachingZeyla Hellyer2017-02-091-10/+11
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | Improve the cache by keeping track of new maps, making other maps have `Arc<RwLock>` values, optimizing already-existing methods, and take advantage of new, more efficient retrievals (e.g. simply keying a value from a map rather than iterating over vecs or maps and then itering over another vec). Keep track of two new maps in the cache: - **channels**: a map of all guild channels that exist, so that they can be efficiently found, and so a message's guild can be efficiently found - **users**: a map of all users that exist, so that it can be shared across all members and presences Other cache fields now have `Arc<RwLock>` values: - `groups` - `guilds` - `private_channels` `Cache::unavailable_guilds` is now a `HashSet<GuildId>` instead of a `Vec<GuildId>`. This should slightly optimize removals/insertions for large bots. `ext::cache::ChannelRef` has been removed as it became equivilant in functionality to `model::Channel`. Also, `model::Channel` now has all variant data encased in `Arc<RwLock>`s. E.g., `Channel::Group(Group)` is now `Channel::Group(Arc<RwLock<Group>>)`. Some model struct fields are now wrapped in an `Arc<RwLock>`. These are: - `Group::recipients`: `HashMap<UserId, User>` -> `HashMap<UserId, Arc<RwLock<User>>>` - `Guild::channels`: `HashMap<ChannelId, GuildChannel>` -> `HashMap<ChannelId, Arc<RwLock<GuildChannel>>>` - `Member::user`: `User` -> `Arc<RwLock<User>>` - `PrivateChannel::recipient`: `User` -> `Arc<RwLock<User>>` Some (cache-enabled) event handler signatures have changed to use `Arc<RwLock>`s: - `Client::on_call_delete` - `Client::on_call_update` - `Client::on_guild_delete` - `Client::on_guild_update` Many function signatures have changed: - `Cache::get_call` now returns a `Option<Arc<RwLock<Call>>>` instead of a `Option<&Call>` - `Cache::get_channel` now returns a `Option<Channel>` instead of a `Option<ChannelRef>`. This now also retrieves directly from the `Guild::channels` instead of iterating over guilds' for a guild channel - `Cache::get_guild` now returns a `Option<Arc<RwLock<Guild>>>` instead of a `Option<&Guild>` - `Cache::get_guild_channel` now returns a `Option<Arc<RwLock<GuildChannel>>>` instead of a `Option<&GuildChannel>` - `Cache::get_group` now returns a `Option<Arc<RwLock<Group>>>` instead of a `Option<&Group>` - `Cache::get_member` now returns a `Option<Member>` instead of a `Option<&Member>`, due to guilds being behind a lock themselves - `Cache::get_role` now returns a `Option<Role>` instead of a `Option<&Role>` for the above reason - `Cache::get_user` now returns a `Option<Arc<RwLock<User>>>` instead of a `Option<&User>` - `GuildId::find` now returns a `Option<Arc<RwLock<Guild>>>` instead of a `Option<Guild>` - `UserId::find` now returns a `Option<Arc<RwLock<User>>>` instead of a `Option<User>` - `Member::display_name` now returns a `Cow<String>` instead of a `&str` A new cache method has been added, `Cache::get_private_channel`, to retrieve a `PrivateChannel`. The `Display` formatter for `Channel` has been optimized to not clone.
* Properly drop on bindsAustin Hellyer2017-01-241-3/+3
| | | | | | | Instead of binding to `_why`, bind to `_`, dropping the value. This is pretty much just leftover from when the library was being rapidly developed before being released.
* Switch to a mostly-fully OOP approachAustin Hellyer2017-01-231-4/+4
| | | | | | The context is now strictly in relation to the context of the current channel related to the event, if any. See Context::say for a list of events that the context can be used for.
* Code style cleanupAustin Hellyer2017-01-081-5/+8
|
* Add guild and channel searchAustin Hellyer2016-12-291-0/+30
|
* Accept u64 shard countsAustin Hellyer2016-12-261-3/+3
|
* More config for CreateCommand, add various methodsIllia2016-12-101-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | | | Adds multiple configurations to the command builder, and adds methods to various structs. Context::get_current_user is a shortcut to retrieve the current user from the cache. Message::get_member retrieves the member object of the message, if sent in a guild. Message::is_private checks if the message was sent in a Group or PrivateChannel. User::member retrieves the user's member object in a guild by Id; Adds 6 configurations to the command builder: - dm_only: whether the command can only be used in direct messages; - guild_only: whether the command can only be used in guilds; - help_available: whether the command should be displayed in the help list; - max_args: specify the maximum number of arguments a command must be given; - min_args: specify the minimum number of arguments a command must be given; - required_permissions: the permissions a member must have to be able to use the command;
* Fix no-cache+method conditional compilesAustin Hellyer2016-12-101-3/+3
| | | | Additionally, flag imports behind feature flags to avoid unused imports.
* Change all try's into ?sacdenisSK2016-12-071-19/+19
| | | This breaks compatibility with < 1.13, but we didn't support that anyway.
* Clean up the codebaseAustin Hellyer2016-11-291-20/+1
|
* Optimize for cached, non-method compilesAustin Hellyer2016-11-281-7/+0
|
* Make Cache::get_channel return a referenceAustin Hellyer2016-11-261-2/+4
| | | | | | | Additionally, allow it to search the groups' and private channels' maps in the cache. As these are usually O(1) operations, it's cheap to allow, in comparison to the current unoptimized method of getting a guild's channel.
* Rename PublicChannel to GuildChannelAustin Hellyer2016-11-251-2/+2
|
* Allow compiling with only either cache or methodsAustin Hellyer2016-11-241-0/+7
| | | | | | | | | Some of the methods relied on the cache being present. Now, these methods only conditionally require the cache to be compiled and present. The cache was mainly used for checking if the current user had permission to perform operations.
* Change the CACHE to be an RwLockAustin Hellyer2016-11-221-1/+1
| | | | | | | | | | | | | | | | | | The global Cache used to be an Arc<Mutex>, however the issue is that it could only be opened for reading or writing once at a time. With an RwLock, multiple readers can access the Cache at once, while only one Writer may at once. This will allow users to be able to have multiple Readers open at once, which should ease some of the pains with working with the Cache. Upgrade path: Modify all uses of the CACHE from: `CACHE.lock().unwrap()` to `CACHE.read().unwrap()` if reading from the Cache (most use cases), or `CACHE.write().unwrap()` to write to it.
* Rename the State to CacheAustin Hellyer2016-11-221-7/+7
|
* Rename state methods from find_ to get_Austin Hellyer2016-11-191-2/+2
| | | | | | | | | | For consistency with the rest of the library, rename the methods prefixed with `find_` to `get_`. The past logic was that items are "found", as they may or may not exist. With get, the expectation is that it is _always_ there, i.e. over REST. However, this is inconsistent, and "get"ting over REST can fail for other reasons.
* Add state/framework/etc. conditional compile flagsAustin Hellyer2016-11-151-2/+6
| | | | | | | | | | | | | | | This adds conditional compilation for the following features, in addition to the voice conditional compilation flag: - extras (message builder) - framework - methods - state These 4 are enabled _by default_, while the `voice` feature flag is disabled. Disabling the state will allow incredibly low-memory bots.
* Add voice connection supportAustin Hellyer2016-11-141-1/+5
|
* Add internal moduleAustin Hellyer2016-11-141-1/+1
| | | | | Create a general `internal` module, and move `prelude_internal` to `internal::prelude`.