├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── example.rs └── src └── nntp.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "nntp" 4 | version = "0.0.5" 5 | authors = ["Matt McCoy "] 6 | repository = "https://github.com/mattnenterprise/rust-nntp" 7 | description = "NNTP client for Rust" 8 | readme = "README.md" 9 | license = "MIT OR Apache-2.0" 10 | 11 | [lib] 12 | name = "nntp" 13 | path = "src/nntp.rs" 14 | 15 | [[bin]] 16 | name = "example" 17 | path = "example.rs" 18 | -------------------------------------------------------------------------------- /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 {yyyy} {name of copyright owner} 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 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The rust-nntp Developers 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 all 11 | 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 THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | rust-nntp 2 | ================ 3 | NNTP Client for Rust 4 | 5 | 6 | [![Build Status](https://travis-ci.org/mattnenterprise/rust-imap.svg)](https://travis-ci.org/mattnenterprise/rust-imap) 7 | [![crates.io](http://meritbadge.herokuapp.com/nntp)](https://crates.io/crates/nntp) 8 | 9 | ### Usage 10 | ```rust 11 | extern crate nntp; 12 | 13 | use nntp::{Article, NNTPStream}; 14 | 15 | fn main() { 16 | let mut nntp_stream = match NNTPStream::connect(("nntp.aioe.org", 119)) { 17 | Ok(stream) => stream, 18 | Err(e) => panic!("{}", e) 19 | }; 20 | 21 | match nntp_stream.capabilities() { 22 | Ok(lines) => { 23 | for line in lines.iter() { 24 | print!("{}", line); 25 | } 26 | }, 27 | Err(e) => panic!(e) 28 | } 29 | 30 | match nntp_stream.list() { 31 | Ok(groups) => { 32 | for group in groups.iter() { 33 | println!("Name: {}, High: {}, Low: {}, Status: {}", group.name, group.high, group.low, group.status) 34 | } 35 | }, 36 | Err(e) => panic!(e) 37 | }; 38 | 39 | match nntp_stream.group("comp.sys.raspberry-pi") { 40 | Ok(_) => (), 41 | Err(e) => panic!(e) 42 | } 43 | 44 | match nntp_stream.article_by_number(6187) { 45 | Ok(Article{headers, body}) => { 46 | for (key, value) in headers.iter() { 47 | println!("{}: {}", key, value) 48 | } 49 | for line in body.iter() { 50 | print!("{}", line) 51 | } 52 | }, 53 | Err(e) => panic!(e) 54 | } 55 | 56 | match nntp_stream.article_by_id("") { 57 | Ok(Article{headers, body}) => { 58 | for (key, value) in headers.iter() { 59 | println!("{}: {}", key, value) 60 | } 61 | for line in body.iter() { 62 | print!("{}", line) 63 | } 64 | }, 65 | Err(e) => panic!(e) 66 | } 67 | 68 | let _ = nntp_stream.quit(); 69 | } 70 | ``` 71 | 72 | ### License 73 | 74 | MIT 75 | ## License 76 | 77 | Licensed under either of 78 | 79 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 80 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 81 | 82 | at your option. 83 | 84 | ### Contribution 85 | 86 | Unless you explicitly state otherwise, any contribution intentionally 87 | submitted for inclusion in the work by you, as defined in the Apache-2.0 88 | license, shall be dual licensed as above, without any additional terms or 89 | conditions. 90 | -------------------------------------------------------------------------------- /example.rs: -------------------------------------------------------------------------------- 1 | extern crate nntp; 2 | 3 | use nntp::{Article, NNTPStream}; 4 | 5 | fn main() { 6 | let mut nntp_stream = match NNTPStream::connect(("nntp.aioe.org", 119)) { 7 | Ok(stream) => stream, 8 | Err(e) => panic!("{}", e) 9 | }; 10 | 11 | match nntp_stream.capabilities() { 12 | Ok(lines) => { 13 | for line in lines.iter() { 14 | print!("{}", line); 15 | } 16 | }, 17 | Err(e) => panic!(e) 18 | } 19 | 20 | match nntp_stream.list() { 21 | Ok(groups) => { 22 | for group in groups.iter() { 23 | println!("Name: {}, High: {}, Low: {}, Status: {}", group.name, group.high, group.low, group.status) 24 | } 25 | }, 26 | Err(e) => panic!(e) 27 | }; 28 | 29 | match nntp_stream.group("comp.sys.raspberry-pi") { 30 | Ok(_) => (), 31 | Err(e) => panic!(e) 32 | } 33 | 34 | match nntp_stream.article_by_number(6187) { 35 | Ok(Article{headers, body}) => { 36 | for (key, value) in headers.iter() { 37 | println!("{}: {}", key, value) 38 | } 39 | for line in body.iter() { 40 | print!("{}", line) 41 | } 42 | }, 43 | Err(e) => panic!(e) 44 | } 45 | 46 | match nntp_stream.article_by_id("") { 47 | Ok(Article{headers, body}) => { 48 | for (key, value) in headers.iter() { 49 | println!("{}: {}", key, value) 50 | } 51 | for line in body.iter() { 52 | print!("{}", line) 53 | } 54 | }, 55 | Err(e) => panic!(e) 56 | } 57 | 58 | let _ = nntp_stream.quit(); 59 | } -------------------------------------------------------------------------------- /src/nntp.rs: -------------------------------------------------------------------------------- 1 | #![crate_name = "nntp"] 2 | #![crate_type = "lib"] 3 | 4 | //#![feature(collections)] 5 | 6 | use std::string::String; 7 | use std::io::{Read, Result, Error, ErrorKind, Write}; 8 | use std::net::TcpStream; 9 | use std::net::ToSocketAddrs; 10 | use std::vec::Vec; 11 | use std::collections::HashMap; 12 | use std::str::FromStr; 13 | 14 | /// Stream to be used for interfacing with a NNTP server. 15 | pub struct NNTPStream { 16 | stream: TcpStream, 17 | } 18 | 19 | pub struct Article { 20 | pub headers: HashMap, 21 | pub body: Vec 22 | } 23 | 24 | impl Article { 25 | pub fn new_article(lines: Vec) -> Article { 26 | let mut headers = HashMap::new(); 27 | let mut body = Vec::new(); 28 | let mut parsing_headers = true; 29 | 30 | for i in lines.iter() { 31 | if i == &format!("\r\n") { 32 | parsing_headers = false; 33 | continue; 34 | } 35 | if parsing_headers { 36 | let mut header = i.splitn(2, ':'); 37 | let chars_to_trim: &[char] = &['\r', '\n']; 38 | let key = format!("{}", header.nth(0).unwrap().trim_matches(chars_to_trim)); 39 | let value = format!("{}", header.nth(0).unwrap().trim_matches(chars_to_trim)); 40 | headers.insert(key, value); 41 | } else { 42 | body.push(i.clone()); 43 | } 44 | 45 | } 46 | Article {headers: headers, body: body} 47 | } 48 | } 49 | 50 | pub struct NewsGroup { 51 | pub name: String , 52 | pub high: isize, 53 | pub low: isize, 54 | pub status: String 55 | } 56 | 57 | impl NewsGroup { 58 | pub fn new_news_group(group: &str) -> NewsGroup { 59 | let chars_to_trim: &[char] = &['\r', '\n', ' ']; 60 | let trimmed_group = group.trim_matches(chars_to_trim); 61 | let split_group: Vec<&str> = trimmed_group.split(' ').collect(); 62 | NewsGroup{name: format!("{}", split_group[0]), high: FromStr::from_str(split_group[1]).unwrap(), low: FromStr::from_str(split_group[2]).unwrap(), status: format!("{}", split_group[3])} 63 | } 64 | } 65 | 66 | impl NNTPStream { 67 | 68 | /// Creates an NNTP Stream. 69 | pub fn connect(addr: A) -> Result { 70 | let tcp_stream = TcpStream::connect(addr)?; 71 | let mut socket = NNTPStream { stream: tcp_stream }; 72 | 73 | match socket.read_response(200) { 74 | Ok(_) => (), 75 | Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to read greeting response")) 76 | } 77 | 78 | Ok(socket) 79 | } 80 | 81 | /// The article indicated by the current article number in the currently selected newsgroup is selected. 82 | pub fn article(&mut self) -> Result
{ 83 | self.retrieve_article(&format!("ARTICLE\r\n")) 84 | } 85 | 86 | /// The article indicated by the article id is selected. 87 | pub fn article_by_id(&mut self, article_id: &str) -> Result
{ 88 | self.retrieve_article(&format!("ARTICLE {}\r\n", article_id)) 89 | } 90 | 91 | /// The article indicated by the article number in the currently selected newsgroup is selected. 92 | pub fn article_by_number(&mut self, article_number: isize) -> Result
{ 93 | self.retrieve_article(&format!("ARTICLE {}\r\n", article_number)) 94 | } 95 | 96 | fn retrieve_article(&mut self, article_command: &str) -> Result
{ 97 | match self.stream.write_fmt(format_args!("{}", article_command)) { 98 | Ok(_) => (), 99 | Err(_) => return Err(Error::new(ErrorKind::Other, "Failed to retreive atricle")) 100 | } 101 | 102 | match self.read_response(220) { 103 | Ok(_) => (), 104 | Err(e) => return Err(e) 105 | } 106 | 107 | match self.read_multiline_response() { 108 | Ok(lines) => { 109 | Ok(Article::new_article(lines)) 110 | } 111 | Err(e) => Err(e) 112 | } 113 | } 114 | 115 | /// Retrieves the body of the current article number in the currently selected newsgroup. 116 | pub fn body(&mut self) -> Result> { 117 | self.retrieve_body(&format!("BODY\r\n")) 118 | } 119 | 120 | /// Retrieves the body of the article id. 121 | pub fn body_by_id(&mut self, article_id: &str) -> Result> { 122 | self.retrieve_body(&format!("BODY {}\r\n", article_id)) 123 | } 124 | 125 | /// Retrieves the body of the article number in the currently selected newsgroup. 126 | pub fn body_by_number(&mut self, article_number: isize) -> Result> { 127 | self.retrieve_body(&format!("BODY {}\r\n", article_number)) 128 | } 129 | 130 | fn retrieve_body(&mut self, body_command: &str) -> Result> { 131 | match self.stream.write_fmt(format_args!("{}", body_command)) { 132 | Ok(_) => (), 133 | Err(e) => return Err(e) 134 | } 135 | 136 | match self.read_response(222) { 137 | Ok(_) => (), 138 | Err(e) => return Err(e) 139 | } 140 | 141 | self.read_multiline_response() 142 | } 143 | 144 | /// Gives the list of capabilities that the server has. 145 | pub fn capabilities(&mut self) -> Result> { 146 | let capabilities_command = format!("CAPABILITIES\r\n"); 147 | 148 | match self.stream.write_fmt(format_args!("{}", capabilities_command)) { 149 | Ok(_) => (), 150 | Err(e) => return Err(e) 151 | } 152 | 153 | match self.read_response(101) { 154 | Ok(_) => (), 155 | Err(e) => return Err(e) 156 | } 157 | 158 | self.read_multiline_response() 159 | } 160 | 161 | /// Retrieves the date as the server sees the date. 162 | pub fn date(&mut self) -> Result { 163 | let date_command = format!("DATE\r\n"); 164 | 165 | match self.stream.write_fmt(format_args!("{}", date_command)) { 166 | Ok(_) => (), 167 | Err(e) => return Err(e) 168 | } 169 | 170 | match self.read_response(111) { 171 | Ok((_, message)) => Ok(message), 172 | Err(e) => Err(e) 173 | } 174 | } 175 | 176 | /// Retrieves the headers of the current article number in the currently selected newsgroup. 177 | pub fn head(&mut self) -> Result> { 178 | self.retrieve_head(&format!("HEAD\r\n")) 179 | } 180 | 181 | /// Retrieves the headers of the article id. 182 | pub fn head_by_id(&mut self, article_id: &str) -> Result> { 183 | self.retrieve_head(&format!("HEAD {}\r\n", article_id)) 184 | } 185 | 186 | /// Retrieves the headers of the article number in the currently selected newsgroup. 187 | pub fn head_by_number(&mut self, article_number: isize) -> Result> { 188 | self.retrieve_head(&format!("HEAD {}\r\n", article_number)) 189 | } 190 | 191 | fn retrieve_head(&mut self, head_command: &str) -> Result> { 192 | match self.stream.write_fmt(format_args!("{}", head_command)) { 193 | Ok(_) => (), 194 | Err(e) => return Err(e) 195 | } 196 | 197 | match self.read_response(221) { 198 | Ok(_) => (), 199 | Err(e) => return Err(e) 200 | } 201 | 202 | self.read_multiline_response() 203 | } 204 | 205 | /// Moves the currently selected article number back one 206 | pub fn last(&mut self) -> Result { 207 | let last_command = format!("LAST\r\n"); 208 | 209 | match self.stream.write_fmt(format_args!("{}", last_command)) { 210 | Ok(_) => (), 211 | Err(e) => return Err(e) 212 | } 213 | 214 | match self.read_response(223) { 215 | Ok((_, message)) => Ok(message), 216 | Err(e) => Err(e) 217 | } 218 | } 219 | 220 | /// Lists all of the newgroups on the server. 221 | pub fn list(&mut self) -> Result> { 222 | let list_command = format!("LIST\r\n"); 223 | 224 | match self.stream.write_fmt(format_args!("{}", list_command)) { 225 | Ok(_) => (), 226 | Err(e) => return Err(e) 227 | } 228 | 229 | match self.read_response(215) { 230 | Ok(_) => (), 231 | Err(e) => return Err(e) 232 | } 233 | 234 | match self.read_multiline_response() { 235 | Ok(lines) => { 236 | let lines: Vec = lines.iter().map(|ref mut x| NewsGroup::new_news_group((*x))).collect(); 237 | return Ok(lines) 238 | }, 239 | Err(e) => Err(e) 240 | } 241 | } 242 | 243 | /// Selects a newsgroup 244 | pub fn group(&mut self, group: &str) -> Result<()> { 245 | let group_command = format!("GROUP {}\r\n", group); 246 | 247 | match self.stream.write_fmt(format_args!("{}", group_command)) { 248 | Ok(_) => (), 249 | Err(e) => return Err(e) 250 | } 251 | 252 | match self.read_response(211) { 253 | Ok(_) => Ok(()), 254 | Err(e) => Err(e) 255 | } 256 | } 257 | 258 | /// Show the help command given on the server. 259 | pub fn help(&mut self) -> Result> { 260 | let help_command = format!("HELP\r\n"); 261 | 262 | match self.stream.write_fmt(format_args!("{}", help_command)) { 263 | Ok(_) => (), 264 | Err(e) => return Err(e) 265 | } 266 | 267 | match self.read_response(100) { 268 | Ok(_) => (), 269 | Err(e) => return Err(e) 270 | } 271 | 272 | self.read_multiline_response() 273 | } 274 | 275 | /// Quits the current session. 276 | pub fn quit(&mut self) -> Result<()> { 277 | let quit_command = format!("QUIT\r\n"); 278 | match self.stream.write_fmt(format_args!("{}", quit_command)) { 279 | Ok(_) => (), 280 | Err(e) => return Err(e) 281 | } 282 | 283 | match self.read_response(205) { 284 | Ok(_) => Ok(()), 285 | Err(e) => Err(e) 286 | } 287 | } 288 | 289 | /// Retrieves a list of newsgroups since the date and time given. 290 | pub fn newgroups(&mut self, date: &str, time: &str, use_gmt: bool) -> Result> { 291 | let newgroups_command = match use_gmt { 292 | true => format!("NEWSGROUP {} {} GMT\r\n", date, time), 293 | false => format!("NEWSGROUP {} {}\r\n", date, time) 294 | }; 295 | 296 | match self.stream.write_fmt(format_args!("{}", newgroups_command)) { 297 | Ok(_) => (), 298 | Err(e) => return Err(e) 299 | } 300 | 301 | match self.read_response(231) { 302 | Ok(_) => (), 303 | Err(e) => return Err(e) 304 | } 305 | 306 | self.read_multiline_response() 307 | } 308 | 309 | /// Retrieves a list of new news since the date and time given. 310 | pub fn newnews(&mut self, wildmat: &str, date: &str, time: &str, use_gmt: bool) -> Result> { 311 | let newnews_command = match use_gmt { 312 | true => format!("NEWNEWS {} {} {} GMT\r\n", wildmat, date, time), 313 | false => format!("NEWNEWS {} {} {}\r\n", wildmat, date, time) 314 | }; 315 | 316 | match self.stream.write_fmt(format_args!("{}", newnews_command)) { 317 | Ok(_) => (), 318 | Err(e) => return Err(e) 319 | } 320 | 321 | match self.read_response(230) { 322 | Ok(_) => (), 323 | Err(e) => return Err(e) 324 | } 325 | 326 | self.read_multiline_response() 327 | } 328 | 329 | /// Moves the currently selected article number forward one 330 | pub fn next(&mut self) -> Result { 331 | let next_command = format!("NEXT\r\n"); 332 | match self.stream.write_fmt(format_args!("{}", next_command)) { 333 | Ok(_) => (), 334 | Err(e) => return Err(e) 335 | } 336 | 337 | match self.read_response(223) { 338 | Ok((_, message)) => Ok(message), 339 | Err(e) => Err(e) 340 | } 341 | } 342 | 343 | /// Posts a message to the NNTP server. 344 | pub fn post(&mut self, message: &str) -> Result<()> { 345 | if !self.is_valid_message(message) { 346 | return Err(Error::new(ErrorKind::Other, "Invalid message format. Message must end with \"\r\n.\r\n\"")); 347 | } 348 | 349 | let post_command = format!("POST\r\n"); 350 | 351 | match self.stream.write_fmt(format_args!("{}", post_command)) { 352 | Ok(_) => (), 353 | Err(e) => return Err(e) 354 | } 355 | 356 | match self.read_response(340) { 357 | Ok(_) => (), 358 | Err(e) => return Err(e) 359 | }; 360 | 361 | match self.stream.write_fmt(format_args!("{}", message)) { 362 | Ok(_) => (), 363 | Err(e) => return Err(e) 364 | } 365 | 366 | match self.read_response(240) { 367 | Ok(_) => Ok(()), 368 | Err(e) => Err(e) 369 | } 370 | } 371 | 372 | /// Gets information about the current article. 373 | pub fn stat(&mut self) -> Result { 374 | self.retrieve_stat(&format!("STAT\r\n")) 375 | } 376 | 377 | /// Gets the information about the article id. 378 | pub fn stat_by_id(&mut self, article_id: &str) -> Result { 379 | self.retrieve_stat(&format!("STAT {}\r\n", article_id)) 380 | } 381 | 382 | /// Gets the information about the article number. 383 | pub fn stat_by_number(&mut self, article_number: isize) -> Result { 384 | self.retrieve_stat(&format!("STAT {}\r\n", article_number)) 385 | } 386 | 387 | fn retrieve_stat(&mut self, stat_command: &str) -> Result { 388 | match self.stream.write_fmt(format_args!("{}", stat_command)) { 389 | Ok(_) => (), 390 | Err(_) => return Err(Error::new(ErrorKind::Other, "Write Error")) 391 | } 392 | 393 | match self.read_response(223) { 394 | Ok((_, message)) => Ok(message), 395 | Err(e) => Err(e) 396 | } 397 | } 398 | 399 | fn is_valid_message(&mut self, message: &str) -> bool { 400 | //Carriage return 401 | let cr = 0x0d; 402 | //Line Feed 403 | let lf = 0x0a; 404 | //Dot 405 | let dot = 0x2e; 406 | let message_string = message.to_string(); 407 | let message_bytes = message_string.as_bytes(); 408 | let length = message_string.len(); 409 | 410 | return length >= 5 && (message_bytes[length-1] == lf && message_bytes[length-2] == cr && 411 | message_bytes[length-3] == dot && message_bytes[length-4] == lf && message_bytes[length-5] == cr) 412 | } 413 | 414 | //Retrieve single line response 415 | fn read_response(&mut self, expected_code: isize) -> Result<(isize, String)> { 416 | //Carriage return 417 | let cr = 0x0d; 418 | //Line Feed 419 | let lf = 0x0a; 420 | let mut line_buffer: Vec = Vec::new(); 421 | 422 | while line_buffer.len() < 2 || (line_buffer[line_buffer.len()-1] != lf && line_buffer[line_buffer.len()-2] != cr) { 423 | let byte_buffer: &mut [u8] = &mut [0]; 424 | match self.stream.read(byte_buffer) { 425 | Ok(_) => {}, 426 | Err(_) => return Err(Error::new(ErrorKind::Other, "Error reading response")), 427 | } 428 | line_buffer.push(byte_buffer[0]); 429 | } 430 | 431 | let response = String::from_utf8(line_buffer).unwrap(); 432 | let chars_to_trim: &[char] = &['\r', '\n']; 433 | let trimmed_response = response.trim_matches(chars_to_trim); 434 | let trimmed_response_vec: Vec = trimmed_response.chars().collect(); 435 | if trimmed_response_vec.len() < 5 || trimmed_response_vec[3] != ' ' { 436 | return Err(Error::new(ErrorKind::Other, "Invalid response")); 437 | } 438 | 439 | let v: Vec<&str> = trimmed_response.splitn(2, ' ').collect(); 440 | let code: isize = FromStr::from_str(v[0]).unwrap(); 441 | let message = v[1]; 442 | if code != expected_code { 443 | return Err(Error::new(ErrorKind::Other, "Invalid response")) 444 | } 445 | Ok((code, message.to_string())) 446 | } 447 | 448 | fn read_multiline_response(&mut self) -> Result> { 449 | let mut response: Vec = Vec::new(); 450 | //Carriage return 451 | let cr = 0x0d; 452 | //Line Feed 453 | let lf = 0x0a; 454 | let mut line_buffer: Vec = Vec::new(); 455 | let mut complete = false; 456 | 457 | while !complete { 458 | while line_buffer.len() < 2 || (line_buffer[line_buffer.len()-1] != lf && line_buffer[line_buffer.len()-2] != cr) { 459 | let byte_buffer: &mut [u8] = &mut [0]; 460 | match self.stream.read(byte_buffer) { 461 | Ok(_) => {}, 462 | Err(_) => println!("Error Reading!"), 463 | } 464 | line_buffer.push(byte_buffer[0]); 465 | } 466 | 467 | match String::from_utf8(line_buffer.clone()) { 468 | Ok(res) => { 469 | if res == format!(".\r\n") { 470 | complete = true; 471 | } 472 | else { 473 | response.push(res.clone()); 474 | line_buffer = Vec::new(); 475 | } 476 | }, 477 | Err(_) => return Err(Error::new(ErrorKind::Other, "Error Reading")) 478 | } 479 | } 480 | Ok(response) 481 | } 482 | } 483 | --------------------------------------------------------------------------------