├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── gitter.rs ├── lib.rs └── models.rs └── tests └── test.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | os: 4 | - linux 5 | - osx 6 | 7 | cache: cargo 8 | 9 | matrix: 10 | allow_failures: 11 | - rust: nightly 12 | 13 | rust: 14 | - stable 15 | - beta 16 | - nightly 17 | 18 | script: 19 | - cargo build --verbose 20 | - cargo test --verbose 21 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "gitter" 3 | version = "0.4.0" 4 | authors = ["shmutalov "] 5 | 6 | homepage = "https://github.com/shmutalov/gitter-rs" 7 | repository = "https://github.com/shmutalov/gitter-rs" 8 | 9 | description = "A library that provides Gitter API" 10 | readme = "README.md" 11 | license = "MIT/Apache-2.0" 12 | keywords = ["gitter", "api", "chat"] 13 | 14 | exclude = [".travis.yml"] 15 | 16 | [badges] 17 | travis-ci = { repository = "shmutalov/gitter-rs" } 18 | 19 | [dependencies] 20 | chrono = { version = "0.4", features = ["serde"] } 21 | serde = "1.0" 22 | serde_json = "1.0" 23 | serde_derive = "1.0" 24 | serde_urlencoded = "0.5" 25 | reqwest = "0.8.3" 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2017 Sherzod Mutalov 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Sherzod Mutalov 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gitter-rs 2 | 3 | [![license](https://img.shields.io/badge/license-MIT_or_Apache_2.0-blue.svg "License")](#license) 4 | [![](https://tokei.rs/b1/github/shmutalov/gitter-rs)](https://github.com/shmutalov/gitter-rs) 5 | [![](https://travis-ci.org/shmutalov/gitter-rs.svg?branch=master)](https://travis-ci.org/shmutalov/gitter-rs) 6 | [![gitter-rs on crates.io](https://img.shields.io/crates/v/gitter.svg)](https://crates.io/crates/gitter) 7 | [![Join the chat at https://gitter.im/gitter-rs/general](https://badges.gitter.im/gitter-rs/general.svg)](https://gitter.im/gitter-rs/general?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 8 | 9 | Gitter API in Rust 10 | 11 | [**`WIP`**](#roadmap) 12 | 13 | https://developer.gitter.im 14 | 15 | # Building 16 | ```sh 17 | cargo build 18 | ``` 19 | 20 | # Install 21 | 22 | ### Current version 23 | ```toml 24 | [dependencies] 25 | gitter = "0.4.0" 26 | ``` 27 | 28 | ### Development version 29 | ```toml 30 | [dependencies] 31 | gitter = { git = "https://github.com/shmutalov/gitter-rs" } 32 | ``` 33 | 34 | - [Initialize](#initialize) 35 | - [Users](#users) 36 | - [Rooms](#rooms) 37 | - [Messages](#messages) 38 | - [Documentation](http://docs.rs/gitter) 39 | - [Roadmap](#roadmap) 40 | - [License](#license) 41 | 42 | # Initialize 43 | 44 | ```rust 45 | extern crate gitter; 46 | use gitter::Gitter; 47 | 48 | ... 49 | 50 | let api = Gitter::new("YOUR_ACCESS_TOKEN").unwrap(); 51 | ``` 52 | 53 | _Following code snippets did not updated yet_ 54 | 55 | # Users 56 | 57 | - Get current user 58 | 59 | ```rust 60 | let user = api.get_user().unwrap(); 61 | ``` 62 | 63 | # Rooms 64 | 65 | 66 | ```rust 67 | // Get all rooms 68 | let rooms = api.get_rooms().unwrap(); 69 | 70 | // Get room by id 71 | let room = api.get_room("roomID").unwrap(); 72 | 73 | // Get rooms of some user 74 | let rooms = api.get_rooms("userID").unwrap(); 75 | 76 | // Join room 77 | let room = api.join_room("roomID", "userID").unwrap(); 78 | 79 | // Leave room 80 | let room = api.leave_room("roomID", "userID").unwrap(); 81 | 82 | // Get room id 83 | let room_id = api.get_room_id("room/uri").unwrap(); 84 | 85 | // Search gitter rooms 86 | let rooms = api.search_rooms("search/string").unwrap(); 87 | ``` 88 | 89 | # Messages 90 | 91 | ```rust 92 | // Get messages of room 93 | let messages = api.get_messages("roomID", None).unwrap(); 94 | 95 | // Get one message 96 | let message = api.get_message("roomID", "messageID").unwrap(); 97 | 98 | // Send message 99 | api.send_message("roomID", "free chat text").unwrap(); 100 | ``` 101 | 102 | # Roadmap 103 | 104 | This project is a work in progress. 105 | 106 | - [x] Implement base Rest API's and add some tests 107 | - [x] Test `send_message` method 108 | - [x] Implement all Rest API methods 109 | - [ ] Add support for Streaming API 110 | - [ ] Add support for Faye [_Optional_] 111 | - [ ] Add support for automated access token retreive via Github authentification 112 | - [ ] Cover with tests 113 | - [ ] Add examples 114 | 115 | # License 116 | 117 | `gitter-rs` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). 118 | 119 | See [`LICENSE-APACHE`](LICENSE-APACHE) and [`LICENSE-MIT`](LICENSE-MIT) for details. 120 | -------------------------------------------------------------------------------- /src/gitter.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::collections::HashMap; 3 | use reqwest::{Client, IntoUrl}; 4 | use reqwest::header::{Accept, Authorization, Bearer, ContentType, Headers}; 5 | use serde::{Deserialize, Serialize}; 6 | use serde_urlencoded; 7 | use std::time::Duration; 8 | 9 | use models::*; 10 | 11 | #[derive(Debug)] 12 | pub struct Gitter<'a> { 13 | token: Cow<'a, str>, 14 | api_base_url: Cow<'a, str>, 15 | client: Client, 16 | } 17 | 18 | const API_BASE_URL: &str = "https://api.gitter.im/v1"; 19 | 20 | #[derive(Debug)] 21 | pub enum ApiError { 22 | EmptyResponse, 23 | BadResponse(String), 24 | BadRequest(String), 25 | RoomNotFound, 26 | UserNotFound, 27 | Unknown(String), 28 | } 29 | 30 | type ApiResult = Result; 31 | 32 | impl<'a> Gitter<'a> { 33 | /// New initializes the Gitter API client 34 | pub fn new(token: S) -> ApiResult> 35 | where 36 | S: Into>, 37 | { 38 | match Client::builder().timeout(Duration::from_secs(40)).build() { 39 | Ok(client) => Ok(Gitter { 40 | token: token.into(), 41 | api_base_url: API_BASE_URL.into(), 42 | client, 43 | }), 44 | Err(e) => Err(ApiError::Unknown(e.to_string())), 45 | } 46 | } 47 | 48 | /// Returns the current user 49 | pub fn get_user(&self) -> ApiResult { 50 | let full_url = format!("{}/user", self.api_base_url); 51 | match self.get::<&str, Vec>(&full_url) { 52 | Ok(users) => { 53 | if !users.is_empty() { 54 | Ok(users[0].clone()) 55 | } else { 56 | Err(ApiError::UserNotFound) 57 | } 58 | } 59 | Err(e) => Err(e), 60 | } 61 | } 62 | 63 | /// Returns a list of Rooms the user is part of 64 | pub fn get_user_rooms(&self, user_id: S) -> ApiResult> 65 | where 66 | S: AsRef, 67 | { 68 | let full_url = format!("{}/user/{}/rooms", self.api_base_url, user_id.as_ref()); 69 | self.get(&full_url) 70 | } 71 | 72 | /// Receive user's unread items and mentions in the room 73 | pub fn get_unread_items(&self, user_id: U, room_id: R) -> ApiResult 74 | where 75 | U: AsRef, 76 | R: AsRef, 77 | { 78 | let full_url = format!("{}/user/{}/rooms/{}/unreadItems", self.api_base_url, user_id.as_ref(), room_id.as_ref()); 79 | self.get(&full_url) 80 | } 81 | 82 | /// Mark user's given room messages as read 83 | pub fn mark_messages_as_read( 84 | &self, 85 | user_id: U, 86 | room_id: R, 87 | message_ids: &[String], 88 | ) -> ApiResult<()> 89 | where 90 | U: AsRef, 91 | R: AsRef, 92 | { 93 | let full_url = format!("{}/user/{}/rooms/{}/unreadItems", self.api_base_url, user_id.as_ref(), room_id.as_ref()); 94 | let unread_items = UnreadItems::from_msg_ids(message_ids); 95 | self.post(&full_url, &unread_items) 96 | } 97 | 98 | /// Returns a list of rooms the current user is in 99 | pub fn get_rooms(&self) -> ApiResult> { 100 | let full_url = format!("{}/rooms", self.api_base_url); 101 | self.get(&full_url) 102 | } 103 | 104 | /// List of the user's GitHub Organizations and their respective Room if available. 105 | pub fn get_user_organizations(&self, user_id: S) -> ApiResult> 106 | where 107 | S: AsRef, 108 | { 109 | let full_url = format!("{}/user/{}/orgs", self.api_base_url, user_id.as_ref()); 110 | self.get(&full_url) 111 | } 112 | 113 | /// List of the user's GitHub Repositories and their respective Room if available. 114 | pub fn get_user_repositories(&self, user_id: S) -> ApiResult> 115 | where 116 | S: AsRef, 117 | { 118 | let full_url = format!("{}/user/{}/repos", self.api_base_url, user_id.as_ref()); 119 | self.get(&full_url) 120 | } 121 | 122 | /// List of Gitter channels nested under the current user. 123 | pub fn get_user_channels(&self, user_id: S) -> ApiResult> 124 | where 125 | S: AsRef, 126 | { 127 | let full_url = format!("{}/user/{}/channels", self.api_base_url, user_id.as_ref()); 128 | self.get(&full_url) 129 | } 130 | 131 | /// Returns the users in the room with the passed id 132 | pub fn get_users_in_room(&self, room_id: S) -> ApiResult> 133 | where 134 | S: AsRef, 135 | { 136 | let full_url = format!("{}/rooms/{}/users", self.api_base_url, room_id.as_ref()); 137 | self.get(&full_url) 138 | } 139 | 140 | /// Returns a room with the passed id 141 | pub fn get_room(&self, room_id: S) -> ApiResult 142 | where 143 | S: AsRef, 144 | { 145 | let full_url = format!("{}/rooms/{}", self.api_base_url, room_id.as_ref()); 146 | self.get(&full_url) 147 | } 148 | 149 | /// Returns a list of messages in a room. 150 | /// Pagination is optional. You can pass nil or specific pagination params. 151 | pub fn get_messages(&self, room_id: S, params: Option) -> ApiResult> 152 | where 153 | S: AsRef, 154 | { 155 | let mut full_url = format!("{}/rooms/{}/chatMessages", self.api_base_url, room_id.as_ref()); 156 | 157 | if let Some(p) = params { 158 | full_url.push_str("?"); 159 | full_url.push_str(&p.encode()); 160 | } 161 | 162 | self.get(&full_url) 163 | } 164 | 165 | /// Returns a message in a room. 166 | pub fn get_message(&self, room_id: R, message_id: M) -> ApiResult 167 | where 168 | R: AsRef, 169 | M: AsRef, 170 | { 171 | let full_url = format!("{}/rooms/{}/chatMessages/{}", self.api_base_url, room_id.as_ref(), message_id.as_ref()); 172 | self.get(&full_url) 173 | } 174 | 175 | /// Sends a message to a room 176 | pub fn send_message(&self, room_id: R, text: T) -> ApiResult 177 | where 178 | R: AsRef, 179 | T: AsRef, 180 | { 181 | let full_url = format!("{}/rooms/{}/chatMessages", self.api_base_url, room_id.as_ref()); 182 | let msg = OutMessage { 183 | text: text.as_ref() 184 | }; 185 | 186 | self.post(&full_url, &msg) 187 | } 188 | 189 | /// Update a message 190 | pub fn update_message(&self, room_id: R, msg_id: M, text: T) -> ApiResult<()> 191 | where 192 | R: AsRef, 193 | M: AsRef, 194 | T: AsRef, 195 | { 196 | let full_url = format!("{}/rooms/{}/chatMessages/{}", self.api_base_url, room_id.as_ref(), msg_id.as_ref()); 197 | let msg = OutMessage { 198 | text: text.as_ref() 199 | }; 200 | 201 | self.put(&full_url, &msg) 202 | } 203 | 204 | /// Joins a room 205 | pub fn join_room(&self, room_id: R, user_id: U) -> ApiResult 206 | where 207 | R: AsRef, 208 | U: AsRef, 209 | { 210 | let full_url = format!("{}/user/{}/rooms", self.api_base_url, user_id.as_ref()); 211 | let room = JoinRoom::from_id(room_id); 212 | 213 | self.post(&full_url, &room) 214 | } 215 | 216 | /// Join a room (uri method) 217 | pub fn join_room_by_uri(&self, uri: S) -> ApiResult 218 | where 219 | S: AsRef, 220 | { 221 | let full_url = format!("{}/rooms", self.api_base_url); 222 | let room = JoinRoom::from_uri(uri); 223 | 224 | self.post(&full_url, &room) 225 | } 226 | 227 | /// Update a room topic 228 | pub fn update_room_topic(&self, room_id: R, topic: T) -> ApiResult 229 | where 230 | R: AsRef, 231 | T: AsRef, 232 | { 233 | let full_url = format!("{}/rooms/{}", self.api_base_url, room_id.as_ref()); 234 | let room = UpdateRoom::from_topic(topic); 235 | 236 | self.post(&full_url, &room) 237 | } 238 | 239 | /// Update a room noindex (indexing in search engines) 240 | pub fn update_room_noindex(&self, room_id: S, noindex: bool) -> ApiResult 241 | where 242 | S: AsRef, 243 | { 244 | let full_url = format!("{}/rooms/{}", self.api_base_url, room_id.as_ref()); 245 | let room = UpdateRoom::from_noindex(noindex); 246 | 247 | self.post(&full_url, &room) 248 | } 249 | 250 | /// Update a room topic 251 | pub fn update_room_tags(&self, room_id: R, tags: T) -> ApiResult 252 | where 253 | R: AsRef, 254 | T: AsRef, 255 | { 256 | let full_url = format!("{}/rooms/{}", self.api_base_url, room_id.as_ref()); 257 | let room = UpdateRoom::from_tags(tags); 258 | 259 | self.post(&full_url, &room) 260 | } 261 | 262 | /// Removes a user from the room 263 | pub fn leave_room(&self, room_id: R, user_id: U) -> ApiResult<()> 264 | where 265 | R: AsRef, 266 | U: AsRef, 267 | { 268 | let full_url = format!("{}/rooms/{}/users/{}", self.api_base_url, room_id.as_ref(), user_id.as_ref()); 269 | 270 | self.delete(&full_url) 271 | } 272 | 273 | /// Delete a room 274 | pub fn delete_room(&self, room_id: S) -> ApiResult<()> 275 | where 276 | S: AsRef, 277 | { 278 | let full_url = format!("{}/rooms/{}", self.api_base_url, room_id.as_ref()); 279 | 280 | self.delete(&full_url) 281 | } 282 | 283 | /// Queries the Rooms resources of gitter API 284 | pub fn search_rooms(&self, room: S) -> ApiResult 285 | where 286 | S: AsRef, 287 | { 288 | let query = &[("q", room.as_ref())]; 289 | let full_url = format!("{}/rooms?{}", self.api_base_url, &serde_urlencoded::to_string(query).unwrap()); 290 | 291 | self.get(&full_url) 292 | } 293 | 294 | /// Returns the room ID of a given URI 295 | pub fn get_room_id(&self, uri: S) -> ApiResult 296 | where 297 | S: AsRef, 298 | { 299 | let uri = uri.as_ref(); 300 | self.search_rooms(uri.to_string())? 301 | .rooms 302 | .iter() 303 | .find(|r| r.uri.as_ref().map_or(false, |u| u == uri)) 304 | .map(|r| r.id.to_string()) 305 | .ok_or(ApiError::RoomNotFound) 306 | } 307 | 308 | /// Returns a list of groups the current user is in 309 | pub fn get_groups(&self) -> ApiResult> { 310 | let full_url = format!("{}/groups", self.api_base_url); 311 | 312 | self.get(&full_url) 313 | } 314 | 315 | /// List of rooms nested under the specified group. 316 | pub fn get_group_rooms(&self, group_id: S) -> ApiResult> 317 | where 318 | S: AsRef, 319 | { 320 | let full_url = format!("{}/groups/{}/rooms", self.api_base_url, group_id.as_ref()); 321 | 322 | self.get(&full_url) 323 | } 324 | 325 | /// create default headers 326 | fn default_headers(&self) -> Headers { 327 | let mut headers = Headers::new(); 328 | 329 | headers.set(ContentType::json()); 330 | headers.set(Accept::json()); 331 | headers.set(Authorization(Bearer { 332 | token: self.token.to_string(), 333 | })); 334 | 335 | headers 336 | } 337 | 338 | /// Returns raw data in bytes from specified url 339 | fn get(&self, url: S) -> ApiResult 340 | where 341 | S: IntoUrl, 342 | for<'de> T: Deserialize<'de>, 343 | { 344 | match self.client.get(url).headers(self.default_headers()).send() { 345 | Ok(mut response) => response 346 | .json::() 347 | .map_err(|e| ApiError::BadResponse(e.to_string())), 348 | Err(e) => Err(ApiError::BadRequest(e.to_string())), 349 | } 350 | } 351 | 352 | /// Posts raw body data to specified url and returns response raw data 353 | fn post(&self, url: S, body: B) -> ApiResult 354 | where 355 | S: IntoUrl, 356 | B: Serialize, 357 | for<'de> T: Deserialize<'de>, 358 | { 359 | match self.client 360 | .post(url) 361 | .headers(self.default_headers()) 362 | .json(&body) 363 | .send() 364 | { 365 | Ok(mut response) => response 366 | .json::() 367 | .map_err(|e| ApiError::BadResponse(e.to_string())), 368 | Err(e) => Err(ApiError::BadRequest(e.to_string())), 369 | } 370 | } 371 | 372 | /// Puts raw body data to specified url and returns response raw data 373 | fn put(&self, url: S, body: B) -> ApiResult 374 | where 375 | S: IntoUrl, 376 | B: Serialize, 377 | for<'de> T: Deserialize<'de>, 378 | { 379 | match self.client 380 | .put(url) 381 | .headers(self.default_headers()) 382 | .json(&body) 383 | .send() 384 | { 385 | Ok(mut response) => response 386 | .json::() 387 | .map_err(|e| ApiError::BadResponse(e.to_string())), 388 | Err(e) => Err(ApiError::BadRequest(e.to_string())), 389 | } 390 | } 391 | 392 | /// Deletes resource by specified url 393 | fn delete(&self, url: S) -> ApiResult 394 | where 395 | S: IntoUrl, 396 | for<'de> T: Deserialize<'de>, 397 | { 398 | match self.client 399 | .delete(url) 400 | .headers(self.default_headers()) 401 | .send() 402 | { 403 | Ok(mut response) => response 404 | .json::() 405 | .map_err(|e| ApiError::BadResponse(e.to_string())), 406 | Err(e) => Err(ApiError::BadRequest(e.to_string())), 407 | } 408 | } 409 | } 410 | 411 | /// Pagination params 412 | pub struct Pagination<'a> { 413 | /// Skip n messages 414 | pub skip: i32, 415 | 416 | /// Get messages before beforeId 417 | pub before_id: Option>, 418 | 419 | /// Get messages after afterId 420 | pub after_id: Option>, 421 | 422 | /// Maximum number of messages to return 423 | pub limit: i32, 424 | 425 | /// Search query 426 | #[allow(dead_code)] 427 | pub query: Option>, 428 | } 429 | 430 | impl<'a> Pagination<'a> { 431 | pub fn encode(self) -> String { 432 | let mut values = HashMap::new(); 433 | 434 | if let Some(after_id) = self.after_id { 435 | values.insert("afterId", after_id.to_string()); 436 | } 437 | 438 | if let Some(before_id) = self.before_id { 439 | values.insert("beforeId", before_id.to_string()); 440 | } 441 | 442 | if self.skip > 0 { 443 | values.insert("skip", self.skip.to_string()); 444 | } 445 | 446 | if self.limit > 0 { 447 | values.insert("limit", self.limit.to_string()); 448 | } 449 | 450 | serde_urlencoded::to_string(&values).unwrap() 451 | } 452 | } 453 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | extern crate serde_derive; 3 | 4 | extern crate serde; 5 | extern crate serde_json; 6 | extern crate serde_urlencoded; 7 | extern crate chrono; 8 | extern crate reqwest; 9 | 10 | pub mod models; 11 | pub mod gitter; 12 | 13 | pub use gitter::*; 14 | pub use models::*; 15 | -------------------------------------------------------------------------------- /src/models.rs: -------------------------------------------------------------------------------- 1 | use chrono::{DateTime, Utc}; 2 | 3 | #[derive(Deserialize, Debug)] 4 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 5 | pub enum GithubType { 6 | /// A room that represents a GitHub Organisation. 7 | Org, 8 | /// A room that represents a GitHub Repository. 9 | Repo, 10 | /// A one-to-one chat. 11 | #[serde(rename = "ONETOONE")] 12 | OneToOne, 13 | /// A Gitter channel nested under a GitHub Organisation. 14 | OrgChannel, 15 | /// A Gitter channel nested under a GitHub Repository. 16 | RepoChannel, 17 | /// A Gitter channel nested under a GitHub User. 18 | UserChannel, 19 | } 20 | 21 | /// A Room in Gitter can represent a GitHub Organization, a GitHub Repository, 22 | /// a Gitter Channel or a One-to-one conversation. 23 | /// In the case of the Organizations and Repositories, 24 | /// the access control policies are inherited from GitHub. 25 | #[derive(Deserialize, Debug)] 26 | pub struct Room { 27 | /// Room ID 28 | pub id: String, 29 | 30 | /// Room name 31 | pub name: String, 32 | 33 | /// Room topic. (default: GitHub repo description) 34 | pub topic: String, 35 | 36 | /// Room URI on Gitter 37 | pub uri: Option, 38 | 39 | /// Indicates if the room is a one-to-one chat 40 | #[serde(rename = "oneToOne")] 41 | pub one_to_one: bool, 42 | 43 | /// Count of users in the room 44 | #[serde(rename = "userCount")] 45 | pub user_count: i32, 46 | 47 | /// Number of unread messages for the current user 48 | #[serde(rename = "unreadItems")] 49 | pub unread_items: i32, 50 | 51 | /// Number of unread mentions for the current user 52 | pub mentions: i32, 53 | 54 | /// Last time the current user accessed the room in ISO format 55 | #[serde(rename = "lastAccessTime")] 56 | pub last_access_time: Option>, 57 | 58 | /// Indicates if the current user has disabled notifications 59 | pub lurk: bool, 60 | 61 | /// Path to the room on gitter 62 | pub url: String, 63 | 64 | /// Type of the room 65 | /// - ORG: A room that represents a GitHub Organization. 66 | /// - REPO: A room that represents a GitHub Repository. 67 | /// - ONETOONE: A one-to-one chat. 68 | /// - ORG_CHANNEL: A Gitter channel nested under a GitHub Organization. 69 | /// - REPO_CHANNEL A Gitter channel nested under a GitHub Repository. 70 | /// - USER_CHANNEL A Gitter channel nested under a GitHub User. 71 | #[serde(rename = "githubType")] 72 | pub github_type: GithubType, 73 | 74 | /// Tags that define the room 75 | pub tags: Option>, 76 | 77 | /// Determines, whether current user is room member or not 78 | #[serde(rename = "roomMember")] 79 | pub room_member: bool, 80 | 81 | /// Room version 82 | #[serde(rename = "v")] 83 | pub version: Option, 84 | } 85 | 86 | /// Join room request model 87 | #[derive(Serialize, Debug)] 88 | pub struct JoinRoom { 89 | /// Room ID to join 90 | #[serde(skip_serializing_if = "Option::is_none")] 91 | pub id: Option, 92 | #[serde(skip_serializing_if = "Option::is_none")] 93 | pub uri: Option, 94 | } 95 | 96 | impl JoinRoom { 97 | /// Create join room request from room ID 98 | pub fn from_id(id: S) -> JoinRoom 99 | where S: AsRef 100 | { 101 | JoinRoom { 102 | id: Some(id.as_ref().to_string()), 103 | uri: None, 104 | } 105 | } 106 | 107 | /// Create join room request from URI 108 | pub fn from_uri(uri: S) -> JoinRoom 109 | where S: AsRef 110 | { 111 | JoinRoom { 112 | id: None, 113 | uri: Some(uri.as_ref().to_string()), 114 | } 115 | } 116 | } 117 | 118 | #[derive(Serialize, Debug)] 119 | pub struct UpdateRoom { 120 | /// Room topic 121 | #[serde(skip_serializing_if = "Option::is_none")] 122 | pub topic: Option, 123 | 124 | /// Whether the room is indexed by search engines 125 | #[serde(skip_serializing_if = "Option::is_none")] 126 | pub noindex: Option, 127 | 128 | /// Tags that define the room 129 | #[serde(skip_serializing_if = "Option::is_none")] 130 | pub tags: Option 131 | } 132 | 133 | impl UpdateRoom { 134 | /// Create update room request only with topic parameter 135 | pub fn from_topic(topic: S) -> UpdateRoom 136 | where S: AsRef 137 | { 138 | UpdateRoom { 139 | topic: Some(topic.as_ref().to_string()), 140 | noindex: None, 141 | tags: None 142 | } 143 | } 144 | 145 | /// Create update room request only with noindex parameter 146 | pub fn from_noindex(noindex: bool) -> UpdateRoom { 147 | UpdateRoom { 148 | topic: None, 149 | noindex: Some(noindex), 150 | tags: None 151 | } 152 | } 153 | 154 | /// Create update room request only with tags parameter 155 | pub fn from_tags(tags: S) -> UpdateRoom 156 | where S: AsRef 157 | { 158 | UpdateRoom { 159 | topic: None, 160 | noindex: None, 161 | tags: Some(tags.as_ref().to_string()), 162 | } 163 | } 164 | } 165 | 166 | #[derive(Deserialize, Debug, Clone)] 167 | pub struct User { 168 | /// Gitter User ID 169 | pub id: String, 170 | 171 | /// Gitter/GitHub username 172 | pub username: String, 173 | 174 | /// Gitter/GitHub user real name 175 | #[serde(rename = "displayName")] 176 | pub display_name: String, 177 | 178 | /// Path to the user on Gitter 179 | pub url: String, 180 | 181 | /// User avatar URI 182 | #[serde(rename = "avatarUrl")] 183 | pub avatar_url: Option, 184 | 185 | /// User avatar URI (small) 186 | #[serde(rename = "avatarUrlSmall")] 187 | pub avatar_url_small: Option, 188 | 189 | /// User avatar URI (medium) 190 | #[serde(rename = "avatarUrlMedium")] 191 | pub avatar_url_medium: Option, 192 | 193 | /// Version 194 | #[serde(rename = "v")] 195 | pub version: Option, 196 | } 197 | 198 | #[derive(Deserialize, Debug)] 199 | pub struct Message { 200 | /// ID of the message 201 | pub id: String, 202 | 203 | /// Original message in plain-text/markdown 204 | pub text: String, 205 | 206 | /// HTML formatted message 207 | pub html: String, 208 | 209 | /// ISO formatted date of the message 210 | pub sent: DateTime, 211 | 212 | /// ISO formatted date of the message if edited 213 | #[serde(rename = "editedAt")] 214 | pub edited_at: Option>, 215 | 216 | /// User that sent the message 217 | #[serde(rename = "fromUser")] 218 | pub from: User, 219 | 220 | /// Boolean that indicates if the current user has read the message. 221 | pub unread: bool, 222 | 223 | /// Number of users that have read the message 224 | #[serde(rename = "readBy")] 225 | pub read_by: i32, 226 | 227 | /// List of URLs present in the message 228 | pub urls: Vec, 229 | 230 | /// List of @Mentions in the message 231 | pub mentions: Vec, 232 | 233 | /// List of #Issues referenced in the message 234 | pub issues: Vec, 235 | 236 | /// Version 237 | #[serde(rename = "v")] 238 | pub version: Option, 239 | } 240 | 241 | /// Send message request model 242 | #[derive(Serialize, Debug)] 243 | pub struct OutMessage<'a> { 244 | /// Original message in plain-text/markdown 245 | pub text: &'a str, 246 | } 247 | 248 | /// Mention holds data about mentioned user in the message 249 | #[derive(Deserialize, Debug)] 250 | pub struct Mention { 251 | /// User's username 252 | #[serde(rename = "screenName")] 253 | pub screen_name: String, 254 | 255 | /// Gitter User ID 256 | #[serde(rename = "userId")] 257 | pub user_id: String, 258 | 259 | /// Announcement 260 | pub announcement: Option, 261 | 262 | /// To all group 263 | pub group: Option, 264 | } 265 | 266 | /// Issue references issue in the message 267 | #[derive(Deserialize, Debug)] 268 | pub struct Issue { 269 | /// Issue number 270 | pub number: String, 271 | } 272 | 273 | /// URL presented in the message 274 | #[derive(Deserialize, Debug)] 275 | pub struct Url { 276 | /// URL 277 | pub url: String, 278 | } 279 | 280 | /// Search rooms result 281 | #[derive(Deserialize, Debug)] 282 | pub struct SearchResult { 283 | #[serde(rename = "results")] 284 | pub rooms: Vec, 285 | } 286 | 287 | #[derive(Deserialize, Debug)] 288 | pub struct Group { 289 | /// Group ID 290 | pub id: String, 291 | 292 | /// Group name. 293 | pub name: String, 294 | 295 | /// Group URI on Gitter. 296 | pub uri: String, 297 | 298 | /// Security descriptor. Describes the backing object we get permissions from. 299 | #[serde(rename = "backedBy")] 300 | pub backed_by: BackedBy, 301 | 302 | /// Base avatar URL (add s parameter to size) 303 | #[serde(rename = "avatarUrl")] 304 | pub avatar_url: String, 305 | } 306 | 307 | /// Security descriptor. Describes the backing object we get permissions from. 308 | #[derive(Deserialize, Debug)] 309 | pub struct BackedBy { 310 | #[serde(rename = "type")] 311 | pub group_type: Option, 312 | 313 | /// Represents how we find the backing object given the type 314 | #[serde(rename = "linkPath")] 315 | pub link_path: Option, 316 | } 317 | 318 | #[derive(Deserialize, Debug)] 319 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] 320 | pub enum GroupType { 321 | OneToOne, 322 | GhRepo, 323 | GhOrg, 324 | GhUser, 325 | } 326 | 327 | /// Unread messages and mentions 328 | #[derive(Serialize, Deserialize, Debug)] 329 | pub struct UnreadItems { 330 | /// Unread messages 331 | pub chat: Option>, 332 | 333 | /// Mentioned messaged 334 | #[serde(skip_serializing_if = "Option::is_none")] 335 | pub mention: Option>, 336 | } 337 | 338 | impl UnreadItems { 339 | pub fn from_msg_ids(msg_ids: &[String]) -> UnreadItems { 340 | UnreadItems { 341 | chat: Some(msg_ids.to_owned()), 342 | mention: None, 343 | } 344 | } 345 | } 346 | 347 | /// Github organization 348 | #[derive(Deserialize, Debug)] 349 | pub struct Organization { 350 | /// Organization ID 351 | pub id: u64, 352 | 353 | /// Organization name 354 | pub name: String, 355 | 356 | /// Organization avatar url 357 | #[serde(rename = "avatarUrl")] 358 | pub avatar_url: Option, 359 | 360 | /// Organization respective room 361 | pub room: Option, 362 | } 363 | 364 | /// Github repository info 365 | #[derive(Deserialize, Debug)] 366 | pub struct Repository { 367 | /// Repository ID 368 | pub id: u64, 369 | 370 | /// Repository name 371 | pub name: String, 372 | 373 | /// Repository URI 374 | pub uri: String, 375 | 376 | /// Determines whether repository is private or not 377 | pub private: bool, 378 | 379 | /// Repository respective room 380 | pub room: Option, 381 | } 382 | 383 | /// Gitter channel 384 | #[derive(Deserialize, Debug)] 385 | pub struct Channel { 386 | /// Channel ID 387 | pub id: String, 388 | 389 | /// Channel name 390 | pub name: String, 391 | 392 | /// Channel topic 393 | pub topic: String, 394 | 395 | /// Channel URI 396 | pub uri: Option, 397 | 398 | /// Is channel one-to-one 399 | #[serde(rename = "oneToOne")] 400 | pub one_to_one: bool, 401 | 402 | #[serde(rename = "unreadItems")] 403 | /// Unread items in channel 404 | pub unread_items: i32, 405 | 406 | /// Mentions in channel 407 | pub mentions: i32, 408 | 409 | /// Last access date and time 410 | #[serde(rename = "lastAccessTime")] 411 | pub last_access_time: Option>, 412 | 413 | pub lurk: bool, 414 | 415 | pub url: String, 416 | 417 | #[serde(rename = "githubType")] 418 | pub github_type: GithubType, 419 | 420 | pub security: String, 421 | } 422 | 423 | -------------------------------------------------------------------------------- /tests/test.rs: -------------------------------------------------------------------------------- 1 | extern crate gitter; 2 | extern crate serde; 3 | extern crate serde_json; 4 | 5 | use gitter::*; 6 | 7 | fn get_gitter_api<'a>() -> Gitter<'a> { 8 | let token = std::env::var("GITTER_BOT_TOKEN") 9 | .unwrap_or_else(|_| "GITTER_TOKEN_VALUE".into()); 10 | Gitter::new(token).unwrap() 11 | } 12 | 13 | #[test] 14 | fn deserialize_user() { 15 | let user_json_str = "[{ 16 | \"id\": \"53307734c3599d1de448e192\", 17 | \"username\": \"malditogeek\", 18 | \"displayName\": \"Mauro Pompilio\", 19 | \"url\": \"/malditogeek\", 20 | \"avatarUrlSmall\": \"https://avatars.githubusercontent.com/u/14751?\", 21 | \"avatarUrlMedium\": \"https://avatars.githubusercontent.com/u/14751?\" 22 | }]"; 23 | 24 | let user = serde_json::from_str::>(user_json_str).unwrap(); 25 | 26 | assert_eq!("53307734c3599d1de448e192", user[0].id); 27 | } 28 | 29 | #[test] 30 | fn serialize_out_message() { 31 | let out_msg = OutMessage { 32 | text: "test `message` from @shmutalov" 33 | }; 34 | let out_msg_expected = "{\"text\":\"test `message` from @shmutalov\"}"; 35 | let out_msg_json = serde_json::to_string(&out_msg).unwrap(); 36 | 37 | assert_eq!(&out_msg_expected, &out_msg_json); 38 | } 39 | 40 | #[test] 41 | fn api_get_user() { 42 | let api = get_gitter_api(); 43 | let user = api.get_user(); 44 | 45 | assert!(user.is_ok()); 46 | } 47 | 48 | #[test] 49 | fn api_get_user_rooms() { 50 | let api = get_gitter_api(); 51 | 52 | let user = api.get_user().unwrap(); 53 | let rooms = api.get_user_rooms(&user.id); 54 | 55 | assert!(rooms.is_ok()); 56 | } 57 | 58 | #[test] 59 | fn api_get_rooms() { 60 | let api = get_gitter_api(); 61 | let user = api.get_user().unwrap(); 62 | 63 | let rooms = api.get_rooms(); 64 | 65 | assert!(rooms.is_ok()); 66 | 67 | let user_rooms = api.get_user_rooms(&user.id); 68 | 69 | assert!(user_rooms.is_ok()); 70 | 71 | assert_eq!(rooms.unwrap().len(), user_rooms.unwrap().len()); 72 | } 73 | 74 | #[test] 75 | fn api_get_users_in_room() { 76 | let api = get_gitter_api(); 77 | 78 | let rooms = api.get_rooms().unwrap(); 79 | let users = api.get_users_in_room(&rooms[0].id); 80 | 81 | assert!(users.is_ok()); 82 | } 83 | 84 | #[test] 85 | fn api_get_room() { 86 | let api = get_gitter_api(); 87 | 88 | let rooms = api.get_rooms().unwrap(); 89 | let room = api.get_room(&rooms[0].id); 90 | 91 | assert!(room.is_ok()); 92 | } 93 | 94 | #[test] 95 | fn api_get_messages_without_pagination() { 96 | let api = get_gitter_api(); 97 | 98 | let rooms = api.get_rooms().unwrap(); 99 | let messages = api.get_messages(&rooms[0].id, None); 100 | 101 | assert!(messages.is_ok()); 102 | } 103 | 104 | #[test] 105 | fn api_get_messages_with_pagination() { 106 | let api = get_gitter_api(); 107 | 108 | let rooms = api.get_rooms().unwrap(); 109 | let pagination = Pagination { 110 | skip: 1, 111 | limit: 50, 112 | after_id: None, 113 | before_id: None, 114 | query: None, 115 | }; 116 | let messages = api.get_messages(&rooms[0].id, Some(pagination)); 117 | 118 | assert!(messages.is_ok()); 119 | } 120 | 121 | #[test] 122 | fn api_get_message() { 123 | let api = get_gitter_api(); 124 | 125 | let rooms = api.get_rooms().unwrap(); 126 | let messages = api.get_messages(&rooms[0].id, None).unwrap(); 127 | 128 | let message = api.get_message(&rooms[0].id, &messages[0].id); 129 | 130 | assert!(message.is_ok()); 131 | } 132 | 133 | #[test] 134 | fn api_get_room_id() { 135 | let api = get_gitter_api(); 136 | 137 | let rooms = api.get_rooms().unwrap(); 138 | let room = rooms.into_iter().find(|x| x.uri.is_some()).unwrap(); 139 | let room_id = api.get_room_id(room.uri.unwrap_or_else(|| "".to_owned())); 140 | 141 | assert!(room_id.is_ok()); 142 | } 143 | 144 | #[test] 145 | fn api_search_rooms() { 146 | let api = get_gitter_api(); 147 | 148 | let rooms = api.get_rooms().unwrap(); 149 | let room = rooms.into_iter().find(|x| x.uri.is_some()).unwrap(); 150 | let search_result = api.search_rooms(&room.name); 151 | 152 | assert!(search_result.is_ok()); 153 | assert!(!search_result.unwrap().rooms.is_empty()); 154 | } 155 | 156 | #[test] 157 | fn api_get_groups() { 158 | let api = get_gitter_api(); 159 | let groups = api.get_groups(); 160 | 161 | assert!(groups.is_ok()); 162 | } 163 | 164 | #[test] 165 | fn api_get_group_rooms() { 166 | let api = get_gitter_api(); 167 | let groups = api.get_groups().unwrap(); 168 | let rooms = api.get_group_rooms(&groups[0].id); 169 | 170 | assert!(rooms.is_ok()); 171 | } 172 | 173 | #[test] 174 | fn api_get_unread_items() { 175 | let api = get_gitter_api(); 176 | let user = api.get_user().unwrap(); 177 | let user_rooms = api.get_user_rooms(&user.id).unwrap(); 178 | 179 | let unread_items = api.get_unread_items(&user.id, &user_rooms[0].id); 180 | 181 | assert!(unread_items.is_ok()); 182 | } 183 | 184 | #[test] 185 | fn api_get_user_organizations() { 186 | let api = get_gitter_api(); 187 | let user = api.get_user().unwrap(); 188 | let user_orgs = api.get_user_organizations(&user.id); 189 | 190 | assert!(user_orgs.is_ok()); 191 | } 192 | 193 | #[test] 194 | fn api_get_user_repositories() { 195 | let api = get_gitter_api(); 196 | let user = api.get_user().unwrap(); 197 | let user_repos = api.get_user_repositories(&user.id); 198 | 199 | assert!(user_repos.is_ok()); 200 | } 201 | 202 | #[test] 203 | #[ignore] 204 | fn api_get_user_channels() { 205 | let api = get_gitter_api(); 206 | let user = api.get_user().unwrap(); 207 | let user_channels = api.get_user_channels(&user.id); 208 | 209 | assert!(user_channels.is_ok()); 210 | } 211 | 212 | #[test] 213 | fn api_send_message() { 214 | let api = get_gitter_api(); 215 | let room_id = api.get_room_id("gitter-rs/testing").unwrap(); 216 | 217 | let msg = "@shmutalov this is a `test` message.\n\n```rust\nfn main() {}```"; 218 | let result = api.send_message(&room_id, &msg).unwrap(); 219 | assert_eq!(&result.text, &msg); 220 | } 221 | --------------------------------------------------------------------------------