From f3d679da59a64711ef96042668b26dffd1e662d5 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sun, 29 Oct 2017 17:09:04 +0100 Subject: Add Database trait to be used by the Factoids plugin --- src/plugins/factoids/database.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/plugins/factoids/database.rs (limited to 'src/plugins/factoids/database.rs') diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs new file mode 100644 index 0000000..7a6f568 --- /dev/null +++ b/src/plugins/factoids/database.rs @@ -0,0 +1,18 @@ +use std::fmt; + +use std::collections::HashMap; + +pub trait Database: Send + Sync + fmt::Debug { + fn insert(&mut self, name: String, content: String) -> Option; + fn get(&self, name: &str) -> Option<&str>; +} + +impl Database for HashMap { + fn insert(&mut self, name: String, content: String) -> Option { + self.insert(name, content) + } + + fn get(&self, name: &str) -> Option<&str> { + self.get(name).map(String::as_str) + } +} -- cgit v1.2.3-70-g09d2 From 5928afc3bf83661cd3b11130a31a2d97ef135a9e Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 4 Nov 2017 22:46:39 +0100 Subject: Add MySql as a possible database for the Factoids plugin --- Cargo.lock | 67 ++++++++++++++++++++ Cargo.toml | 26 +++++++- migrations/.gitkeep | 0 .../2017-11-03-164322_create_factoids/down.sql | 1 + .../2017-11-03-164322_create_factoids/up.sql | 4 ++ src/lib.rs | 7 +++ src/plugins/factoids/database.rs | 72 +++++++++++++++++++--- src/plugins/factoids/mod.rs | 16 +++-- 8 files changed, 178 insertions(+), 15 deletions(-) create mode 100644 migrations/.gitkeep create mode 100644 migrations/2017-11-03-164322_create_factoids/down.sql create mode 100644 migrations/2017-11-03-164322_create_factoids/up.sql (limited to 'src/plugins/factoids/database.rs') diff --git a/Cargo.lock b/Cargo.lock index 3466ce6..91693d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -209,6 +209,55 @@ dependencies = [ "unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "derive-error-chain" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "diesel" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "mysqlclient-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "diesel_codegen" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel_infer_schema 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "diesel_infer_schema" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "dotenv" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "derive-error-chain 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "error-chain 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "dtoa" version = "0.4.2" @@ -302,6 +351,9 @@ name = "frippy" version = "0.3.1" dependencies = [ "clippy 0.0.177 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel_codegen 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "frippy_derive 0.1.0", "futures 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", "glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", @@ -624,6 +676,15 @@ dependencies = [ "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "mysqlclient-sys" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "pkg-config 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "vcpkg 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "native-tls" version = "0.1.4" @@ -1327,6 +1388,11 @@ dependencies = [ "checksum crypt32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e34988f7e069e0b2f3bfc064295161e489b2d4e04a2e4248fb94360cdf00b4ec" "checksum dbghelp-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "97590ba53bcb8ac28279161ca943a924d1fd4a8fb3fa63302591647c4fc5b850" "checksum debug_unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9a032eac705ca39214d169f83e3d3da290af06d8d1d344d1baad2fd002dca4b3" +"checksum derive-error-chain 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3c9ca9ade651388daad7c993f005d0d20c4f6fe78c1cdc93e95f161c6f5ede4a" +"checksum diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "304226fa7a3982b0405f6bb95dd9c10c3e2000709f194038a60ec2c277150951" +"checksum diesel_codegen 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18a42ca5c9b660add51d58bc5a50a87123380e1e458069c5504528a851ed7384" +"checksum diesel_infer_schema 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bf1957ff5cd3b04772e43c162c2f69c2aa918080ff9b020276792d236be8be52" +"checksum dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d6f0e2bb24d163428d8031d3ebd2d2bd903ad933205a97d0f18c7c1aade380f3" "checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab" "checksum either 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "740178ddf48b1a9e878e6d6509a1442a2d42fd2928aae8e7a6f8a36fb01981b3" "checksum encoding 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec" @@ -1373,6 +1439,7 @@ dependencies = [ "checksum mime_guess 2.0.0-alpha.3 (registry+https://github.com/rust-lang/crates.io-index)" = "013572795763289e14710c7b279461295f2673b2b338200c235082cd7ca9e495" "checksum mio 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0e8411968194c7b139e9105bc4ae7db0bae232af087147e72f0616ebf5fdb9cb" "checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" +"checksum mysqlclient-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "879ce08e38739c54d87b7f8332a476004fe2a095f40a142a36f889779d9942b7" "checksum native-tls 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "04b781c9134a954c84f0594b9ab3f5606abc516030388e8511887ef4c204a1e5" "checksum net2 0.2.31 (registry+https://github.com/rust-lang/crates.io-index)" = "3a80f842784ef6c9a958b68b7516bc7e35883c614004dd94959a4dca1b716c09" "checksum num 0.1.41 (registry+https://github.com/rust-lang/crates.io-index)" = "cc4083e14b542ea3eb9b5f33ff48bd373a92d78687e74f4cc0a30caeb754f0ca" diff --git a/Cargo.toml b/Cargo.toml index 87c9052..5ff779f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,9 @@ name = "frippy" path = "bin/main.rs" doc = false +[features] +mysql = ["diesel", "diesel_codegen", "dotenv"] + [dependencies] irc = "0.12.5" tokio-core = "0.1.10" @@ -34,6 +37,25 @@ serde_json = "1.0.3" glob = "0.2" frippy_derive = { path = "frippy_derive" } -unicode_names = { git = 'https://github.com/Jokler/unicode_names', branch = 'update-to-latest-unicode' } -clippy = {version = "*", optional = true} +[dependencies.unicode_names] +git = 'https://github.com/Jokler/unicode_names' +branch = 'update-to-latest-unicode' + +[dependencies.diesel] +version = "0.16.0" +optional = true +features = ["mysql"] + +[dependencies.diesel_codegen] +version = "0.16.0" +optional = true +features = ["mysql"] + +[dependencies.dotenv] +version = "0.10.1" +optional = true + +[dependencies.clippy] +version = "*" +optional = true \ No newline at end of file diff --git a/migrations/.gitkeep b/migrations/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/migrations/2017-11-03-164322_create_factoids/down.sql b/migrations/2017-11-03-164322_create_factoids/down.sql new file mode 100644 index 0000000..58c2110 --- /dev/null +++ b/migrations/2017-11-03-164322_create_factoids/down.sql @@ -0,0 +1 @@ +DROP TABLE factoids diff --git a/migrations/2017-11-03-164322_create_factoids/up.sql b/migrations/2017-11-03-164322_create_factoids/up.sql new file mode 100644 index 0000000..84e9f9d --- /dev/null +++ b/migrations/2017-11-03-164322_create_factoids/up.sql @@ -0,0 +1,4 @@ +CREATE TABLE factoids ( + name VARCHAR(32) PRIMARY KEY, + content VARCHAR(5000) NOT NULL +) diff --git a/src/lib.rs b/src/lib.rs index 5d15802..1f5514e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,13 @@ //! Frippy uses the [log](https://docs.rs/log) crate so you can log events //! which might be of interest. +#[cfg(feature = "mysql")] +#[macro_use] +extern crate diesel; +#[cfg(feature = "mysql")] +#[macro_use] +extern crate diesel_codegen; + #[macro_use] extern crate log; #[macro_use] diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 7a6f568..dbf136c 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -1,18 +1,74 @@ -use std::fmt; +#[cfg(feature = "mysql")] +extern crate dotenv; use std::collections::HashMap; -pub trait Database: Send + Sync + fmt::Debug { - fn insert(&mut self, name: String, content: String) -> Option; - fn get(&self, name: &str) -> Option<&str>; +#[cfg(feature = "mysql")] +use diesel::prelude::*; + +#[cfg(feature = "mysql")] +use diesel::mysql::MysqlConnection; + +pub trait Database: Send { + fn insert(&mut self, name: &str, content: &str) -> Option<()>; + fn get(&self, name: &str) -> Option; } impl Database for HashMap { - fn insert(&mut self, name: String, content: String) -> Option { - self.insert(name, content) + fn insert(&mut self, name: &str, content: &str) -> Option<()> { + self.insert(String::from(name), String::from(content)).map(|_| ()) + } + + fn get(&self, name: &str) -> Option { + self.get(name).cloned() + } +} + +#[cfg(feature = "mysql")] +#[derive(Queryable)] +struct Factoid { + pub name: String, + pub content: String, +} + +#[cfg(feature = "mysql")] +table! { + factoids (name) { + name -> Varchar, + content -> Varchar, + } +} + +#[cfg(feature = "mysql")] +#[derive(Insertable)] +#[table_name="factoids"] +struct NewFactoid<'a> { + pub name: &'a str, + pub content: &'a str, +} + + +#[cfg(feature = "mysql")] +impl Database for MysqlConnection { + fn insert(&mut self, name: &str, content: &str) -> Option<()> { + let factoid = NewFactoid { + name: name, + content: content, + }; + + ::diesel::insert(&factoid) + .into(factoids::table) + .execute(self) + .ok() + .map(|_| ()) } - fn get(&self, name: &str) -> Option<&str> { - self.get(name).map(String::as_str) + fn get(&self, name: &str) -> Option { + factoids::table + .filter(factoids::columns::name.eq(name)) + .limit(1) + .load::(self) + .ok() + .and_then(|v| v.first().map(|f| f.content.clone())) } } diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index a13bba6..5f9f99a 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -1,5 +1,6 @@ extern crate rlua; +use std::fmt; use self::rlua::prelude::*; use irc::client::prelude::*; use irc::error::Error as IrcError; @@ -8,11 +9,11 @@ use std::sync::Mutex; use plugin::*; mod database; -use self::database::*; +use self::database::Database; static LUA_SANDBOX: &'static str = include_str!("sandbox.lua"); -#[derive(PluginName, Debug)] +#[derive(PluginName)] pub struct Factoids { factoids: Mutex, } @@ -40,7 +41,7 @@ impl Factoids { let name = command.tokens.remove(0); try_lock!(self.factoids) - .insert(name, command.tokens.join(" ")); + .insert(&name, &command.tokens.join(" ")); server.send_notice(&command.source, "Successfully added") } @@ -63,7 +64,6 @@ impl Factoids { } fn exec(&self, server: &IrcServer, mut command: PluginCommand) -> Result<(), IrcError> { - if command.tokens.len() < 1 { self.invalid_command(server, &command) @@ -88,7 +88,7 @@ impl Factoids { } } } else { - String::from(factoid) + factoid }; server.send_privmsg(&command.target, &value) @@ -170,3 +170,9 @@ impl Plugin for Factoids { } } } + +impl fmt::Debug for Factoids { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Factoids {{ ... }}") + } +} -- cgit v1.2.3-70-g09d2 From 4b5693d3c6781a5ca4ef32f43f3994a65020c933 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 16 Dec 2017 18:13:02 +0100 Subject: Add more info to factoids and save old versions --- Cargo.lock | 78 +++++++++-- Cargo.toml | 19 ++- bin/main.rs | 30 ++++- migrations/.gitkeep | 0 .../2017-11-03-164322_create_factoids/up.sql | 8 +- src/lib.rs | 9 +- src/plugins/factoids/database.rs | 120 +++++++++++------ src/plugins/factoids/mod.rs | 146 +++++++++++++++++---- 8 files changed, 322 insertions(+), 88 deletions(-) delete mode 100644 migrations/.gitkeep (limited to 'src/plugins/factoids/database.rs') diff --git a/Cargo.lock b/Cargo.lock index 91693d5..936d8a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,32 +220,40 @@ dependencies = [ [[package]] name = "diesel" -version = "0.16.0" +version = "1.0.0-rc1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "chrono 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel_derives 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", "mysqlclient-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "diesel_codegen" -version = "0.16.0" +name = "diesel_derives" +version = "1.0.0-rc1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", - "diesel_infer_schema 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", - "dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "diesel_infer_schema" -version = "0.16.0" +version = "1.0.0-rc1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "infer_schema_macros 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "diesel_migrations" +version = "1.0.0-rc1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "migrations_internals 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", + "migrations_macros 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -350,9 +358,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "frippy" version = "0.3.1" dependencies = [ + "chrono 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "clippy 0.0.177 (registry+https://github.com/rust-lang/crates.io-index)", - "diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", - "diesel_codegen 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel_infer_schema 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", + "diesel_migrations 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", "dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "frippy_derive 0.1.0", "futures 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", @@ -502,6 +512,25 @@ name = "if_chain" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "infer_schema_internals" +version = "1.0.0-rc1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "diesel 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "infer_schema_macros" +version = "1.0.0-rc1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "infer_schema_internals 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "iovec" version = "0.1.1" @@ -628,6 +657,24 @@ dependencies = [ "libc 0.2.34 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "migrations_internals" +version = "1.0.0-rc1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "diesel 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "migrations_macros" +version = "1.0.0-rc1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "migrations_internals 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "mime" version = "0.3.5" @@ -1389,9 +1436,10 @@ dependencies = [ "checksum dbghelp-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "97590ba53bcb8ac28279161ca943a924d1fd4a8fb3fa63302591647c4fc5b850" "checksum debug_unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9a032eac705ca39214d169f83e3d3da290af06d8d1d344d1baad2fd002dca4b3" "checksum derive-error-chain 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3c9ca9ade651388daad7c993f005d0d20c4f6fe78c1cdc93e95f161c6f5ede4a" -"checksum diesel 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "304226fa7a3982b0405f6bb95dd9c10c3e2000709f194038a60ec2c277150951" -"checksum diesel_codegen 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18a42ca5c9b660add51d58bc5a50a87123380e1e458069c5504528a851ed7384" -"checksum diesel_infer_schema 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bf1957ff5cd3b04772e43c162c2f69c2aa918080ff9b020276792d236be8be52" +"checksum diesel 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "f6b9e512c7fbcc7240848252ff620ed5f0e996e25d5c694b2b535d27db7465c6" +"checksum diesel_derives 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "a631faea061a7b5ab85e842866da57dbc31cc5fe715397a5e5a5b0effd7146b9" +"checksum diesel_infer_schema 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "1cee2c5104f0258a4461c4c8694e870161cb974f4de8609fae3d496e26336590" +"checksum diesel_migrations 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "e1fd168d237ae0bd9e8bfdcb82ba87a4b72e4c1d9edd864242a67149c7f3c960" "checksum dotenv 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d6f0e2bb24d163428d8031d3ebd2d2bd903ad933205a97d0f18c7c1aade380f3" "checksum dtoa 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "09c3753c3db574d215cba4ea76018483895d7bff25a31b49ba45db21c48e50ab" "checksum either 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "740178ddf48b1a9e878e6d6509a1442a2d42fd2928aae8e7a6f8a36fb01981b3" @@ -1419,6 +1467,8 @@ dependencies = [ "checksum hyper-tls 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c81fa95203e2a6087242c38691a0210f23e9f3f8f944350bd676522132e2985" "checksum idna 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "014b298351066f1512874135335d62a789ffe78a9974f94b43ed5621951eaf7d" "checksum if_chain 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "61bb90bdd39e3af69b0172dfc6130f6cd6332bf040fbb9bdd4401d37adbd48b8" +"checksum infer_schema_internals 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "e2af8e23352c51aff14633500bfff361e9ea310375044b40dd8939e2defccd5c" +"checksum infer_schema_macros 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "aa05e92983b3f9af1e7508f7d4981452542d505640d1b328fe74f4466c82b953" "checksum iovec 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b6e8b9c2247fcf6c6a1151f1156932be5606c9fd6f55a2d7f9fc1cb29386b2f7" "checksum irc 0.12.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c5053c25509042e963baa67d0d648add9f72b7487784505a5d5a3054d136a615" "checksum itertools 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d3f2be4da1690a039e9ae5fd575f706a63ad5a2120f161b1d653c9da3930dd21" @@ -1435,6 +1485,8 @@ dependencies = [ "checksum markup5ever 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "ff834ac7123c6a37826747e5ca09db41fd7a83126792021c2e636ad174bb77d3" "checksum matches 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "100aabe6b8ff4e4a7e32c1c13523379802df0772b82466207ac25b013f193376" "checksum memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "796fba70e76612589ed2ce7f45282f5af869e0fdd7cc6199fa1aa1f1d591ba9d" +"checksum migrations_internals 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "c39531d07a48b5920d19310f9ba644667aac56edd933a6e7649893551756ad50" +"checksum migrations_macros 1.0.0-rc1 (registry+https://github.com/rust-lang/crates.io-index)" = "12d6c72b7dae5fb40009c6313ef5a2075aa25f479a8a51f6a487abef887a7a2c" "checksum mime 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e2e00e17be181010a91dbfefb01660b17311059dc8c7f48b9017677721e732bd" "checksum mime_guess 2.0.0-alpha.3 (registry+https://github.com/rust-lang/crates.io-index)" = "013572795763289e14710c7b279461295f2673b2b338200c235082cd7ca9e495" "checksum mio 0.6.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0e8411968194c7b139e9105bc4ae7db0bae232af087147e72f0616ebf5fdb9cb" diff --git a/Cargo.toml b/Cargo.toml index 5ff779f..5f535e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ path = "bin/main.rs" doc = false [features] -mysql = ["diesel", "diesel_codegen", "dotenv"] +mysql = ["diesel", "diesel_infer_schema", "diesel_migrations", "dotenv"] [dependencies] irc = "0.12.5" @@ -27,13 +27,14 @@ tokio-core = "0.1.10" futures = "0.1.16" log = "0.3.8" time = "0.1" -rlua = "0.9.2" +rlua = "0.9.3" reqwest = "0.8.0" select = "0.4.2" regex = "0.2.2" lazy_static = "0.2.9" serde = "1.0.15" serde_json = "1.0.3" +chrono = "0.4.0" glob = "0.2" frippy_derive = { path = "frippy_derive" } @@ -42,13 +43,19 @@ frippy_derive = { path = "frippy_derive" } git = 'https://github.com/Jokler/unicode_names' branch = 'update-to-latest-unicode' + [dependencies.diesel] -version = "0.16.0" +version = "1.0.0-beta1" +optional = true +features = ["mysql", "chrono"] + +[dependencies.diesel_infer_schema] +version = "1.0.0-beta1" optional = true features = ["mysql"] -[dependencies.diesel_codegen] -version = "0.16.0" +[dependencies.diesel_migrations] +version = "1.0.0-beta1" optional = true features = ["mysql"] @@ -58,4 +65,4 @@ optional = true [dependencies.clippy] version = "*" -optional = true \ No newline at end of file +optional = true diff --git a/bin/main.rs b/bin/main.rs index 1597a70..7869548 100644 --- a/bin/main.rs +++ b/bin/main.rs @@ -4,9 +4,16 @@ extern crate tokio_core; extern crate glob; extern crate futures; +#[cfg(feature = "mysql")] +#[macro_use] +extern crate diesel_migrations; +#[cfg(feature = "mysql")] +extern crate diesel; + #[macro_use] extern crate log; +#[cfg(not(feature = "mysql"))] use std::collections::HashMap; use log::{LogRecord, LogLevel, LogLevelFilter, LogMetadata}; @@ -18,6 +25,9 @@ use glob::glob; use frippy::plugins; use frippy::Config; +#[cfg(feature = "mysql")] +embed_migrations!(); + struct Logger; impl log::Log for Logger { @@ -44,7 +54,6 @@ impl log::Log for Logger { } fn main() { - let log_level = if cfg!(debug_assertions) { LogLevelFilter::Debug } else { @@ -87,7 +96,10 @@ fn main() { let mut disabled_plugins = None; if let &Some(ref options) = &config.options { if let Some(disabled) = options.get("disabled_plugins") { - disabled_plugins = Some(disabled.split(",").map(|p| p.trim()).collect::>()); + disabled_plugins = Some(disabled + .split(",") + .map(|p| p.trim()) + .collect::>()); } } @@ -97,8 +109,22 @@ fn main() { bot.add_plugin(plugins::Emoji::new()); bot.add_plugin(plugins::Currency::new()); bot.add_plugin(plugins::KeepNick::new()); + #[cfg(feature = "mysql")] + { + use diesel; + use diesel::Connection; + match diesel::mysql::MysqlConnection::establish("mysql://user:password@address/db") { + Ok(conn) => { + embedded_migrations::run(&conn).unwrap(); + bot.add_plugin(plugins::Factoids::new(conn)); + } + Err(e) => error!("Failed to connect to database: {}", e), + } + } + #[cfg(not(feature = "mysql"))] bot.add_plugin(plugins::Factoids::new(HashMap::new())); + if let Some(disabled_plugins) = disabled_plugins { for name in disabled_plugins { if let None = bot.remove_plugin(name) { diff --git a/migrations/.gitkeep b/migrations/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/migrations/2017-11-03-164322_create_factoids/up.sql b/migrations/2017-11-03-164322_create_factoids/up.sql index 84e9f9d..784a3f4 100644 --- a/migrations/2017-11-03-164322_create_factoids/up.sql +++ b/migrations/2017-11-03-164322_create_factoids/up.sql @@ -1,4 +1,8 @@ CREATE TABLE factoids ( - name VARCHAR(32) PRIMARY KEY, - content VARCHAR(5000) NOT NULL + name VARCHAR(32) NOT NULL, + idx INTEGER NOT NULL, + content TEXT NOT NULL, + author VARCHAR(32) NOT NULL, + created TIMESTAMP NOT NULL, + PRIMARY KEY (name, idx) ) diff --git a/src/lib.rs b/src/lib.rs index 1f5514e..4407e6a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,8 +35,10 @@ #[macro_use] extern crate diesel; #[cfg(feature = "mysql")] +extern crate diesel_infer_schema; +#[cfg(feature = "mysql")] #[macro_use] -extern crate diesel_codegen; +extern crate diesel_migrations; #[macro_use] extern crate log; @@ -48,12 +50,15 @@ extern crate frippy_derive; extern crate irc; extern crate futures; extern crate tokio_core; +extern crate regex; +extern crate chrono; +extern crate time; pub mod plugin; pub mod plugins; -use std::fmt; use std::collections::HashMap; +use std::fmt; use std::thread::spawn; use std::sync::Arc; diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index dbf136c..522c9d0 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -9,66 +9,112 @@ use diesel::prelude::*; #[cfg(feature = "mysql")] use diesel::mysql::MysqlConnection; +use chrono::NaiveDateTime; + +pub enum DbResponse { + Success, + Failed(&'static str), +} + +#[cfg_attr(feature = "mysql", derive(Queryable))] +#[derive(Clone, Debug)] +pub struct Factoid { + pub name: String, + pub idx: i32, + pub content: String, + pub author: String, + pub created: NaiveDateTime, +} + +#[cfg_attr(feature = "mysql", derive(Insertable))] +#[cfg_attr(feature = "mysql", table_name="factoids")] +pub struct NewFactoid<'a> { + pub name: &'a str, + pub idx: i32, + pub content: &'a str, + pub author: &'a str, + pub created: NaiveDateTime, +} + + pub trait Database: Send { - fn insert(&mut self, name: &str, content: &str) -> Option<()>; - fn get(&self, name: &str) -> Option; + fn insert(&mut self, factoid: &NewFactoid) -> DbResponse; + fn get(&self, name: &str, idx: i32) -> Option; + fn count(&self, name: &str) -> Result; } -impl Database for HashMap { - fn insert(&mut self, name: &str, content: &str) -> Option<()> { - self.insert(String::from(name), String::from(content)).map(|_| ()) +// HashMap +impl Database for HashMap<(String, i32), Factoid> { + fn insert(&mut self, factoid: &NewFactoid) -> DbResponse { + let factoid = Factoid { + name: String::from(factoid.name), + idx: factoid.idx, + content: factoid.content.to_string(), + author: factoid.author.to_string(), + created: factoid.created, + }; + + let name = String::from(factoid.name.clone()); + match self.insert((name, factoid.idx), factoid) { + None => DbResponse::Success, + Some(_) => DbResponse::Failed("Factoid was overwritten"), + } } - fn get(&self, name: &str) -> Option { - self.get(name).cloned() + fn get(&self, name: &str, idx: i32) -> Option { + self.get(&(String::from(name), idx)).map(|f| f.clone()) } -} -#[cfg(feature = "mysql")] -#[derive(Queryable)] -struct Factoid { - pub name: String, - pub content: String, + fn count(&self, name: &str) -> Result { + Ok(self.iter() + .filter(|&(&(ref n, _), _)| n == name) + .count() as i32) + } } +// MySql #[cfg(feature = "mysql")] table! { - factoids (name) { + factoids (name, idx) { name -> Varchar, - content -> Varchar, + idx -> Integer, + content -> Text, + author -> Varchar, + created -> Timestamp, } } -#[cfg(feature = "mysql")] -#[derive(Insertable)] -#[table_name="factoids"] -struct NewFactoid<'a> { - pub name: &'a str, - pub content: &'a str, -} - - #[cfg(feature = "mysql")] impl Database for MysqlConnection { - fn insert(&mut self, name: &str, content: &str) -> Option<()> { - let factoid = NewFactoid { - name: name, - content: content, - }; + fn insert(&mut self, factoid: &NewFactoid) -> DbResponse { + use diesel; - ::diesel::insert(&factoid) - .into(factoids::table) - .execute(self) - .ok() - .map(|_| ()) + match diesel::insert_into(factoids::table) + .values(factoid) + .execute(self) { + Ok(_) => DbResponse::Success, + Err(_) => DbResponse::Failed("Database error - possible duplicate"), + } } - fn get(&self, name: &str) -> Option { + fn get(&self, name: &str, idx: i32) -> Option { factoids::table - .filter(factoids::columns::name.eq(name)) + .find((name, idx)) .limit(1) .load::(self) .ok() - .and_then(|v| v.first().map(|f| f.content.clone())) + .and_then(|v| v.into_iter().next()) + } + + fn count(&self, name: &str) -> Result { + let count: Result = factoids::table + .filter(factoids::columns::name.eq(name)) + .count() + .first(self); + + match count { + Ok(c) => Ok(c as i32), + Err(_) => Err("Database Error"), + } } } diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index 5f9f99a..bb83700 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -1,15 +1,18 @@ extern crate rlua; use std::fmt; +use std::str::FromStr; +use std::sync::Mutex; use self::rlua::prelude::*; use irc::client::prelude::*; use irc::error::Error as IrcError; -use std::sync::Mutex; +use time; +use chrono::NaiveDateTime; use plugin::*; mod database; -use self::database::Database; +use self::database::{Database, DbResponse}; static LUA_SANDBOX: &'static str = include_str!("sandbox.lua"); @@ -33,50 +36,140 @@ impl Factoids { } fn add(&self, server: &IrcServer, command: &mut PluginCommand) -> Result<(), IrcError> { - if command.tokens.len() < 2 { return self.invalid_command(server, command); } let name = command.tokens.remove(0); - - try_lock!(self.factoids) - .insert(&name, &command.tokens.join(" ")); - - server.send_notice(&command.source, "Successfully added") + let content = command.tokens.join(" "); + let count = match try_lock!(self.factoids).count(&name) { + Ok(c) => c, + Err(e) => return server.send_notice(&command.source, e), + }; + + let tm = time::now().to_timespec(); + + let factoid = database::NewFactoid { + name: &name, + idx: count, + content: &content, + author: &command.source, + created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), + }; + + match try_lock!(self.factoids).insert(&factoid) { + DbResponse::Success => server.send_notice(&command.source, "Successfully added"), + DbResponse::Failed(e) => server.send_notice(&command.source, &e), + } } fn get(&self, server: &IrcServer, command: &PluginCommand) -> Result<(), IrcError> { - if command.tokens.len() < 1 { - self.invalid_command(server, command) + let (name, idx) = match command.tokens.len() { + 0 => return self.invalid_command(server, command), + 1 => { + let name = &command.tokens[0]; + let count = match try_lock!(self.factoids).count(name) { + Ok(c) => c, + Err(e) => return server.send_notice(&command.source, e), + }; + + if count < 1 { + return server.send_notice(&command.source, &format!("{} does not exist", name)); + } - } else { - let name = &command.tokens[0]; - let factoids = try_lock!(self.factoids); - let factoid = match factoids.get(name) { - Some(v) => v, - None => return self.invalid_command(server, command), - }; + (name, count - 1) + } + _ => { + let name = &command.tokens[0]; + let idx = match i32::from_str(&command.tokens[1]) { + Ok(i) => i, + Err(_) => return server.send_notice(&command.source, "Invalid index"), + }; + + (name, idx) + } + }; + + let factoid = match try_lock!(self.factoids).get(name, idx) { + Some(v) => v, + None => return server.send_notice(&command.source, &format!("{}~{} does not exist", name, idx)), + }; + + server.send_privmsg(&command.target, + &format!("{}: {}", factoid.name, factoid.content)) + } + + fn info(&self, server: &IrcServer, command: &PluginCommand) -> Result<(), IrcError> { + + match command.tokens.len() { + 0 => self.invalid_command(server, command), + 1 => { + let name = &command.tokens[0]; + let count = match try_lock!(self.factoids).count(name) { + Ok(c) => c, + Err(e) => return server.send_notice(&command.source, e), + }; + + match count { + 0 => server.send_notice(&command.source, &format!("{} does not exist", name)), + 1 => { + server.send_privmsg(&command.target, + &format!("There is 1 version of {}", name)) + } + _ => { + server.send_privmsg(&command.target, + &format!("There are {} versions of {}", count, name)) + } + } + } + _ => { + let name = &command.tokens[0]; + let idx = match i32::from_str(&command.tokens[1]) { + Ok(i) => i, + Err(_) => return server.send_notice(&command.source, "Invalid index"), + }; + + let factoid = match try_lock!(self.factoids).get(name, idx) { + Some(v) => v, + None => { + return server.send_notice(&command.source, + &format!("{}~{} does not exist", name, idx)) + } + }; + + server.send_privmsg(&command.target, + &format!("{}: Added by {} at {} UTC", + name, + factoid.author, + factoid.created)) + } - server.send_privmsg(&command.target, &format!("{}: {}", name, factoid)) } } - fn exec(&self, server: &IrcServer, mut command: PluginCommand) -> Result<(), IrcError> { + fn exec(&self, + server: &IrcServer, + mut command: PluginCommand, + error: bool) + -> Result<(), IrcError> { if command.tokens.len() < 1 { self.invalid_command(server, &command) } else { let name = command.tokens.remove(0); + let count = match try_lock!(self.factoids).count(&name) { + Ok(c) => c, + Err(e) => return server.send_notice(&command.source, e), + }; - let factoids = try_lock!(self.factoids); - let factoid = match factoids.get(&name) { - Some(v) => v, - None => return self.invalid_command(server, &command), + let factoid = match try_lock!(self.factoids).get(&name, count - 1) { + Some(v) => v.content, + None if error => return self.invalid_command(server, &command), + None => return Ok(()), }; - let value = if factoid.starts_with(">") { + let value = &if factoid.starts_with(">") { let factoid = String::from(&factoid[1..]); if factoid.starts_with(">") { @@ -149,7 +242,7 @@ impl Plugin for Factoids { tokens: t, }; - self.exec(server, c) + self.exec(server, c, false) } else { Ok(()) @@ -165,7 +258,8 @@ impl Plugin for Factoids { match sub_command.as_ref() { "add" => self.add(server, &mut command), "get" => self.get(server, &command), - "exec" => self.exec(server, command), + "info" => self.info(server, &command), + "exec" => self.exec(server, command, true), _ => self.invalid_command(server, &command), } } -- cgit v1.2.3-70-g09d2 From 5fdb7198bc73035cf5621ded8183000c3fcbbe29 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sun, 24 Dec 2017 02:00:00 +0100 Subject: Add 'remove' command to Factoids and make the Database trait public --- src/lib.rs | 5 ---- src/plugins/factoids/database.rs | 57 +++++++++++++++++++++++++++++----------- src/plugins/factoids/mod.rs | 20 +++++++++++++- src/plugins/mod.rs | 1 + 4 files changed, 61 insertions(+), 22 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/src/lib.rs b/src/lib.rs index 4407e6a..8b55dab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,11 +34,6 @@ #[cfg(feature = "mysql")] #[macro_use] extern crate diesel; -#[cfg(feature = "mysql")] -extern crate diesel_infer_schema; -#[cfg(feature = "mysql")] -#[macro_use] -extern crate diesel_migrations; #[macro_use] extern crate log; diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 522c9d0..1af586e 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -26,6 +26,8 @@ pub struct Factoid { pub created: NaiveDateTime, } +#[cfg(feature = "mysql")] +use self::mysql::factoids; #[cfg_attr(feature = "mysql", derive(Insertable))] #[cfg_attr(feature = "mysql", table_name="factoids")] pub struct NewFactoid<'a> { @@ -40,6 +42,7 @@ pub struct NewFactoid<'a> { pub trait Database: Send { fn insert(&mut self, factoid: &NewFactoid) -> DbResponse; fn get(&self, name: &str, idx: i32) -> Option; + fn delete(&mut self, name: &str, idx: i32) -> DbResponse; fn count(&self, name: &str) -> Result; } @@ -65,6 +68,13 @@ impl Database for HashMap<(String, i32), Factoid> { self.get(&(String::from(name), idx)).map(|f| f.clone()) } + fn delete(&mut self, name: &str, idx: i32) -> DbResponse { + match self.remove(&(String::from(name), idx)) { + Some(_) => DbResponse::Success, + None => DbResponse::Failed("Factoid not found"), + } + } + fn count(&self, name: &str) -> Result { Ok(self.iter() .filter(|&(&(ref n, _), _)| n == name) @@ -72,15 +82,18 @@ impl Database for HashMap<(String, i32), Factoid> { } } -// MySql +// Diesel automatically define the factoids module as public. +// For now this is how we keep it private. #[cfg(feature = "mysql")] -table! { - factoids (name, idx) { - name -> Varchar, - idx -> Integer, - content -> Text, - author -> Varchar, - created -> Timestamp, +mod mysql { + table! { + factoids (name, idx) { + name -> Varchar, + idx -> Integer, + content -> Text, + author -> Varchar, + created -> Timestamp, + } } } @@ -88,22 +101,34 @@ table! { impl Database for MysqlConnection { fn insert(&mut self, factoid: &NewFactoid) -> DbResponse { use diesel; - match diesel::insert_into(factoids::table) .values(factoid) .execute(self) { Ok(_) => DbResponse::Success, - Err(_) => DbResponse::Failed("Database error - possible duplicate"), + Err(e) => { + debug!("DB Insertion Error: {:?}", e); + DbResponse::Failed("Database error - possible duplicate") + } } } fn get(&self, name: &str, idx: i32) -> Option { - factoids::table - .find((name, idx)) - .limit(1) - .load::(self) - .ok() - .and_then(|v| v.into_iter().next()) + factoids::table.find((name, idx)).first(self).ok() + } + + fn delete(&mut self, name: &str, idx: i32) -> DbResponse { + use diesel; + use self::factoids::columns; + match diesel::delete(factoids::table + .filter(columns::name.eq(name)) + .filter(columns::idx.eq(idx))) + .execute(self) { + Ok(_) => DbResponse::Success, + Err(e) => { + debug!("DB Deletion Error: {:?}", e); + DbResponse::Failed("Failed to delete factoid") + } + } } fn count(&self, name: &str) -> Result { diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index bb83700..fcbbb79 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -11,7 +11,7 @@ use time; use chrono::NaiveDateTime; use plugin::*; -mod database; +pub mod database; use self::database::{Database, DbResponse}; static LUA_SANDBOX: &'static str = include_str!("sandbox.lua"); @@ -63,6 +63,23 @@ impl Factoids { } } + fn remove(&self, server: &IrcServer, command: &mut PluginCommand) -> Result<(), IrcError> { + if command.tokens.len() < 1 { + return self.invalid_command(server, command); + } + + let name = command.tokens.remove(0); + let count = match try_lock!(self.factoids).count(&name) { + Ok(c) => c, + Err(e) => return server.send_notice(&command.source, e), + }; + + match try_lock!(self.factoids).delete(&name, count - 1) { + DbResponse::Success => server.send_notice(&command.source, "Successfully removed"), + DbResponse::Failed(e) => server.send_notice(&command.source, &e), + } + } + fn get(&self, server: &IrcServer, command: &PluginCommand) -> Result<(), IrcError> { let (name, idx) = match command.tokens.len() { @@ -257,6 +274,7 @@ impl Plugin for Factoids { let sub_command = command.tokens.remove(0); match sub_command.as_ref() { "add" => self.add(server, &mut command), + "remove" => self.remove(server, &mut command), "get" => self.get(server, &command), "info" => self.info(server, &command), "exec" => self.exec(server, command, true), diff --git a/src/plugins/mod.rs b/src/plugins/mod.rs index f860d88..2e85932 100644 --- a/src/plugins/mod.rs +++ b/src/plugins/mod.rs @@ -11,4 +11,5 @@ pub use self::url::Url; pub use self::emoji::Emoji; pub use self::currency::Currency; pub use self::factoids::Factoids; +pub use self::factoids::database; pub use self::keepnick::KeepNick; -- cgit v1.2.3-70-g09d2 From 4a8e69f7f3069f8d059d0f88fba72e03712fd591 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sun, 24 Dec 2017 15:22:29 +0100 Subject: Log database errors and send a notice if no factoid was deleted --- src/plugins/factoids/database.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 1af586e..cb6f422 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -106,8 +106,8 @@ impl Database for MysqlConnection { .execute(self) { Ok(_) => DbResponse::Success, Err(e) => { - debug!("DB Insertion Error: {:?}", e); - DbResponse::Failed("Database error - possible duplicate") + error!("DB Insertion Error: {:?}", e); + DbResponse::Failed("Failed to add factoid") } } } @@ -123,9 +123,15 @@ impl Database for MysqlConnection { .filter(columns::name.eq(name)) .filter(columns::idx.eq(idx))) .execute(self) { - Ok(_) => DbResponse::Success, + Ok(v) => { + if v > 0 { + DbResponse::Success + } else { + DbResponse::Failed("Could not find any factoid with that name") + } + } Err(e) => { - debug!("DB Deletion Error: {:?}", e); + error!("DB Deletion Error: {:?}", e); DbResponse::Failed("Failed to delete factoid") } } -- cgit v1.2.3-70-g09d2 From 32e59aa3cc6567b909ab995a4e69beb12bdf0322 Mon Sep 17 00:00:00 2001 From: Jokler Date: Tue, 13 Feb 2018 21:37:58 +0100 Subject: Add download function & fromurl command --- bin/main.rs | 2 +- src/lib.rs | 1 + src/plugins/factoids/database.rs | 4 +-- src/plugins/factoids/mod.rs | 63 +++++++++++++++++++++++++++++----------- src/plugins/factoids/sandbox.lua | 1 + src/plugins/factoids/utils.rs | 13 +++++++++ src/plugins/url.rs | 61 ++------------------------------------ src/utils.rs | 59 +++++++++++++++++++++++++++++++++++++ 8 files changed, 125 insertions(+), 79 deletions(-) create mode 100644 src/plugins/factoids/utils.rs create mode 100644 src/utils.rs (limited to 'src/plugins/factoids/database.rs') diff --git a/bin/main.rs b/bin/main.rs index 9373afd..fd0b4ab 100644 --- a/bin/main.rs +++ b/bin/main.rs @@ -144,7 +144,7 @@ fn main() { if let Some(disabled_plugins) = disabled_plugins { for name in disabled_plugins { if let None = bot.remove_plugin(name) { - error!("{:?} was not found - could not disable", name); + error!("\"{}\" was not found - could not disable", name); } } } diff --git a/src/lib.rs b/src/lib.rs index 8b55dab..186d35c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,6 +51,7 @@ extern crate time; pub mod plugin; pub mod plugins; +pub mod utils; use std::collections::HashMap; use std::fmt; diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index cb6f422..b612d6f 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -106,7 +106,7 @@ impl Database for MysqlConnection { .execute(self) { Ok(_) => DbResponse::Success, Err(e) => { - error!("DB Insertion Error: {:?}", e); + error!("DB Insertion Error: \"{}\"", e); DbResponse::Failed("Failed to add factoid") } } @@ -131,7 +131,7 @@ impl Database for MysqlConnection { } } Err(e) => { - error!("DB Deletion Error: {:?}", e); + error!("DB Deletion Error: \"{}\"", e); DbResponse::Failed("Failed to delete factoid") } } diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index d67416f..f857f85 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -14,6 +14,9 @@ use plugin::*; pub mod database; use self::database::{Database, DbResponse}; +mod utils; +use self::utils::download; + static LUA_SANDBOX: &'static str = include_str!("sandbox.lua"); #[derive(PluginName)] @@ -35,6 +38,24 @@ impl Factoids { Factoids { factoids: Mutex::new(db) } } + fn create_factoid(&self, name: &str, content: &str, author: &str) -> Result<&str, &str> { + let count = try_lock!(self.factoids).count(&name)?; + let tm = time::now().to_timespec(); + + let factoid = database::NewFactoid { + name: name, + idx: count, + content: content, + author: author, + created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), + }; + + match try_lock!(self.factoids).insert(&factoid) { + DbResponse::Success => Ok("Successfully added"), + DbResponse::Failed(e) => Err(e), + } + } + fn add(&self, server: &IrcServer, command: &mut PluginCommand) -> Result<(), IrcError> { if command.tokens.len() < 2 { return self.invalid_command(server, command); @@ -42,24 +63,27 @@ impl Factoids { let name = command.tokens.remove(0); let content = command.tokens.join(" "); - let count = match try_lock!(self.factoids).count(&name) { - Ok(c) => c, - Err(e) => return server.send_notice(&command.source, e), - }; - let tm = time::now().to_timespec(); + match self.create_factoid(&name, &content, &command.source) { + Ok(v) => server.send_notice(&command.source, v), + Err(e) => server.send_notice(&command.source, e), + } + } - let factoid = database::NewFactoid { - name: &name, - idx: count, - content: &content, - author: &command.source, - created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), - }; + fn from_url(&self, server: &IrcServer, command: &mut PluginCommand) -> Result<(), IrcError> { + if command.tokens.len() < 2 { + return self.invalid_command(server, command); + } - match try_lock!(self.factoids).insert(&factoid) { - DbResponse::Success => server.send_notice(&command.source, "Successfully added"), - DbResponse::Failed(e) => server.send_notice(&command.source, &e), + let name = command.tokens.remove(0); + let url = &command.tokens[0]; + if let Some(content) = ::utils::download(1024, url) { + match self.create_factoid(&name, &content, &command.source) { + Ok(v) => server.send_notice(&command.source, v), + Err(e) => server.send_notice(&command.source, e), + } + } else { + server.send_notice(&command.source, "Failed to download.") } } @@ -110,7 +134,10 @@ impl Factoids { let factoid = match try_lock!(self.factoids).get(name, idx) { Some(v) => v, - None => return server.send_notice(&command.source, &format!("{}~{} does not exist", name, idx)), + None => { + return server.send_notice(&command.source, + &format!("{}~{} does not exist", name, idx)) + } }; server.send_privmsg(&command.target, @@ -194,7 +221,7 @@ impl Factoids { } else { match self.run_lua(&name, &factoid, &command) { Ok(v) => v, - Err(e) => format!("{}", e), + Err(e) => format!("\"{}\"", e), } } } else { @@ -222,6 +249,7 @@ impl Factoids { let globals = lua.globals(); globals.set("factoid", code)?; + globals.set("download", lua.create_function(download))?; globals.set("args", args)?; globals.set("input", command.tokens.join(" "))?; globals.set("user", command.source.clone())?; @@ -274,6 +302,7 @@ impl Plugin for Factoids { let sub_command = command.tokens.remove(0); match sub_command.as_ref() { "add" => self.add(server, &mut command), + "fromurl" => self.from_url(server, &mut command), "remove" => self.remove(server, &mut command), "get" => self.get(server, &command), "info" => self.info(server, &command), diff --git a/src/plugins/factoids/sandbox.lua b/src/plugins/factoids/sandbox.lua index 2fff150..282a903 100644 --- a/src/plugins/factoids/sandbox.lua +++ b/src/plugins/factoids/sandbox.lua @@ -18,6 +18,7 @@ local env = { print = send, input = input, user = user, channel = channel, + request = download, pairs = pairs, table = table, string = string, diff --git a/src/plugins/factoids/utils.rs b/src/plugins/factoids/utils.rs new file mode 100644 index 0000000..ad25eef --- /dev/null +++ b/src/plugins/factoids/utils.rs @@ -0,0 +1,13 @@ +extern crate reqwest; + +use utils; +use super::rlua::prelude::*; + +use self::LuaError::RuntimeError; + +pub fn download(_: &Lua, url: String) -> Result { + match utils::download(1024, &url) { + Some(v) => Ok(v), + None => Err(RuntimeError(format!("Failed to download {}", url))), + } +} diff --git a/src/plugins/url.rs b/src/plugins/url.rs index f6e06f3..6f4a68f 100644 --- a/src/plugins/url.rs +++ b/src/plugins/url.rs @@ -1,5 +1,4 @@ extern crate regex; -extern crate reqwest; extern crate select; use irc::client::prelude::*; @@ -7,15 +6,11 @@ use irc::error::Error as IrcError; use self::regex::Regex; -use std::str; -use std::io::{self, Read}; -use self::reqwest::Client; -use self::reqwest::header::Connection; - use self::select::document::Document; use self::select::predicate::Name; use plugin::*; +use utils; lazy_static! { static ref RE: Regex = Regex::new(r"(^|\s)(https?://\S+)").unwrap(); @@ -43,58 +38,6 @@ impl Url { } } - fn download(&self, url: &str) -> Option { - let response = Client::new() - .get(url) - .header(Connection::close()) - .send(); - - match response { - Ok(mut response) => { - let mut body = String::new(); - - // 500 kilobyte buffer - let mut buf = [0; 500 * 1000]; - let mut written = 0; - // Read until we reach EOF or max_kib KiB - loop { - let len = match response.read(&mut buf) { - Ok(0) => break, - Ok(len) => len, - Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, - Err(e) => { - debug!("Download from {:?} failed: {}", url, e); - return None; - } - }; - - let slice = match str::from_utf8(&buf[..len]) { - Ok(slice) => slice, - Err(e) => { - debug!("Failed to read bytes from {:?} as UTF8: {}", url, e); - return None; - } - }; - - body.push_str(slice); - written += len; - - // Check if the file is too large to download - if written > self.max_kib * 1024 { - debug!("Stopping download - File from {:?} is larger than {} KiB", url, self.max_kib); - return None; - } - - } - Some(body) // once told me - } - Err(e) => { - debug!("Bad response from {:?}: ({})", url, e); - return None; - } - } - } - fn url(&self, server: &IrcServer, message: &str, target: &str) -> Result<(), IrcError> { let url = match self.grep_url(message) { Some(url) => url, @@ -104,7 +47,7 @@ impl Url { }; - match self.download(&url) { + match utils::download(self.max_kib, &url) { Some(body) => { let doc = Document::from(body.as_ref()); diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..59a5a54 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,59 @@ +extern crate reqwest; + +use std::str; +use std::io::{self, Read}; + +use self::reqwest::Client; +use self::reqwest::header::Connection; + +pub fn download(max_kib: usize, url: &str) -> Option { + let response = Client::new() + .get(url) + .header(Connection::close()) + .send(); + + match response { + Ok(mut response) => { + let mut body = String::new(); + + // 500 kilobyte buffer + let mut buf = [0; 500 * 1000]; + let mut written = 0; + // Read until we reach EOF or max_kib KiB + loop { + let len = match response.read(&mut buf) { + Ok(0) => break, + Ok(len) => len, + Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, + Err(e) => { + debug!("Download from {:?} failed: {}", url, e); + return None; + } + }; + + let slice = match str::from_utf8(&buf[..len]) { + Ok(slice) => slice, + Err(e) => { + debug!("Failed to read bytes from {:?} as UTF8: {}", url, e); + return None; + } + }; + + body.push_str(slice); + written += len; + + // Check if the file is too large to download + if written > max_kib * 1024 { + debug!("Stopping download - File from {:?} is larger than {} KiB", url, max_kib); + return None; + } + + } + Some(body) + } + Err(e) => { + debug!("Bad response from {:?}: ({})", url, e); + return None; + } + } +} -- cgit v1.2.3-70-g09d2 From 5e309d4d58735e2ccc34542564265ace3cf1856e Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 24 Feb 2018 15:06:43 +0100 Subject: Log all database errors --- src/plugins/factoids/database.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index b612d6f..53efe6a 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -106,14 +106,20 @@ impl Database for MysqlConnection { .execute(self) { Ok(_) => DbResponse::Success, Err(e) => { - error!("DB Insertion Error: \"{}\"", e); + error!("DB Insertion Error: {}", e); DbResponse::Failed("Failed to add factoid") } } } fn get(&self, name: &str, idx: i32) -> Option { - factoids::table.find((name, idx)).first(self).ok() + match factoids::table.find((name, idx)).first(self) { + Ok(f) => Ok(f), + Err(e) => { + error!("DB Count Error: {}", e); + None + }, + } } fn delete(&mut self, name: &str, idx: i32) -> DbResponse { @@ -131,7 +137,7 @@ impl Database for MysqlConnection { } } Err(e) => { - error!("DB Deletion Error: \"{}\"", e); + error!("DB Deletion Error: {}", e); DbResponse::Failed("Failed to delete factoid") } } @@ -145,7 +151,10 @@ impl Database for MysqlConnection { match count { Ok(c) => Ok(c as i32), - Err(_) => Err("Database Error"), + Err(e) => { + error!("DB Count Error: {}", e); + Err("Database Error") + }, } } } -- cgit v1.2.3-70-g09d2 From 4e6c31fada410d6a156970a99c31760633d1b544 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 24 Feb 2018 15:10:54 +0100 Subject: Use correct return type --- src/plugins/factoids/database.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 53efe6a..cb5ef29 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -114,7 +114,7 @@ impl Database for MysqlConnection { fn get(&self, name: &str, idx: i32) -> Option { match factoids::table.find((name, idx)).first(self) { - Ok(f) => Ok(f), + Ok(f) => Some(f), Err(e) => { error!("DB Count Error: {}", e); None -- cgit v1.2.3-70-g09d2 From db0f14a163a087261db7360a90d6ac70fb92e884 Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 24 Feb 2018 17:18:09 +0100 Subject: Use r2d2 as a ConnectionPool for diesel --- Cargo.lock | 38 +++++++++++++++++++++++++++++++++ Cargo.toml | 17 ++++++++++++++- src/lib.rs | 4 ++++ src/main.rs | 19 +++++++++++------ src/plugins/factoids/database.rs | 46 ++++++++++++++++++++++++---------------- src/plugins/factoids/mod.rs | 20 ++++++++--------- 6 files changed, 109 insertions(+), 35 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/Cargo.lock b/Cargo.lock index e2a0350..d36e32e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,6 +11,11 @@ dependencies = [ "memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "antidote" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "backtrace" version = "0.3.5" @@ -391,6 +396,8 @@ dependencies = [ "irc 0.13.4 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "r2d2 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", + "r2d2-diesel 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "reqwest 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)", "rlua 0.12.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -927,6 +934,25 @@ name = "quote" version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "r2d2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "scheduled-thread-pool 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "r2d2-diesel" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "diesel 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "r2d2 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "rand" version = "0.3.22" @@ -1044,6 +1070,14 @@ dependencies = [ "winapi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "scheduled-thread-pool" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "scoped-tls" version = "0.1.0" @@ -1483,6 +1517,7 @@ dependencies = [ [metadata] "checksum adler32 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6cbd0b9af8587c72beadc9f72d35b9fbb070982c9e6203e46e93f10df25f8f45" "checksum aho-corasick 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d6531d44de723825aa81398a6415283229725a00fa30713812ab9323faa82fc4" +"checksum antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "34fde25430d87a9388dadbe6e34d7f72a462c8b43ac8d309b42b0a8505d7e2a5" "checksum backtrace 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ebbbf59b1c43eefa8c3ede390fcc36820b4999f7914104015be25025e0d62af2" "checksum backtrace-sys 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "44585761d6161b0f57afc49482ab6bd067e4edef48c12a152c237eb0203f7661" "checksum base64 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "229d032f1a99302697f10b27167ae6d03d49d032e6a8e2550e8d3fc13356d2b4" @@ -1588,6 +1623,8 @@ dependencies = [ "checksum pulldown-cmark 0.0.15 (registry+https://github.com/rust-lang/crates.io-index)" = "378e941dbd392c101f2cb88097fa4d7167bc421d4b88de3ff7dbee503bc3233b" "checksum quine-mc_cluskey 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "07589615d719a60c8dd8a4622e7946465dfef20d1a428f969e3443e7386d5f45" "checksum quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a" +"checksum r2d2 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f9078ca6a8a5568ed142083bb2f7dc9295b69d16f867ddcc9849e51b17d8db46" +"checksum r2d2-diesel 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9c29bad92da76d02bc2c020452ebc3a3fe6fa74cfab91e711c43116e4fb1a3" "checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" "checksum rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "eba5f8cb59cc50ed56be8880a5c7b496bfd9bd26394e176bc67884094145c2c5" "checksum redox_syscall 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "0d92eecebad22b767915e4d529f89f28ee96dbbf5a4810d2b844373f136417fd" @@ -1601,6 +1638,7 @@ dependencies = [ "checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" "checksum safemem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e27a8b19b835f7aea908818e871f5cc3a5a186550c30773be987e155e8163d8f" "checksum schannel 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "acece75e0f987c48863a6c792ec8b7d6c4177d4a027f8ccc72f849794f437016" +"checksum scheduled-thread-pool 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1a2ff3fc5223829be817806c6441279c676e454cc7da608faf03b0ccc09d3889" "checksum scoped-tls 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f417c22df063e9450888a7561788e9bd46d3bb3c1466435b4eccb903807f147d" "checksum security-framework 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "dfa44ee9c54ce5eecc9de7d5acbad112ee58755239381f687e564004ba4a2332" "checksum security-framework-sys 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "5421621e836278a0b139268f36eee0dc7e389b784dc3f79d8f11aabadf41bead" diff --git a/Cargo.toml b/Cargo.toml index bc49f61..7b7c6f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,14 @@ name = "frippy" doc = false [features] -mysql = ["diesel", "diesel_infer_schema", "diesel_migrations", "dotenv"] +mysql = [ + "diesel", + "diesel_infer_schema", + "diesel_migrations", + "dotenv", + "r2d2", + "r2d2-diesel" +] [dependencies] irc = "0.13.4" @@ -52,6 +59,14 @@ version = "1.1.0" optional = true features = ["mysql"] +[dependencies.r2d2] +version = "0.8.2" +optional = true + +[dependencies.r2d2-diesel] +version = "1.0.0" +optional = true + [dependencies.dotenv] version = "0.11.0" optional = true diff --git a/src/lib.rs b/src/lib.rs index bd2e302..aeead16 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,6 +32,10 @@ #[cfg(feature = "mysql")] #[macro_use] extern crate diesel; +#[cfg(feature = "mysql")] +extern crate r2d2; +#[cfg(feature = "mysql")] +extern crate r2d2_diesel; #[macro_use] extern crate frippy_derive; diff --git a/src/main.rs b/src/main.rs index cb4e384..6605693 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,10 @@ extern crate time; extern crate diesel_migrations; #[cfg(feature = "mysql")] extern crate diesel; +#[cfg(feature = "mysql")] +extern crate r2d2; +#[cfg(feature = "mysql")] +extern crate r2d2_diesel; #[macro_use] extern crate log; @@ -119,13 +123,16 @@ fn main() { #[cfg(feature = "mysql")] { if let Some(url) = mysql_url { - use diesel; - use diesel::Connection; - match diesel::mysql::MysqlConnection::establish(url) { - Ok(conn) => { - match embedded_migrations::run(&conn) { + use diesel::MysqlConnection; + use r2d2; + use r2d2_diesel::ConnectionManager; + + let manager = ConnectionManager::::new(url.clone()); + match r2d2::Pool::builder().build(manager) { + Ok(pool) => { + match embedded_migrations::run(&*pool.get().expect("Failed to get connection")) { Ok(_) => { - bot.add_plugin(plugins::Factoids::new(conn)); + bot.add_plugin(plugins::Factoids::new(pool)); info!("Connected to MySQL server") } Err(e) => { diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index cb5ef29..f003419 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -5,9 +5,12 @@ use std::collections::HashMap; #[cfg(feature = "mysql")] use diesel::prelude::*; - #[cfg(feature = "mysql")] use diesel::mysql::MysqlConnection; +#[cfg(feature = "mysql")] +use r2d2::Pool; +#[cfg(feature = "mysql")] +use r2d2_diesel::ConnectionManager; use chrono::NaiveDateTime; @@ -40,15 +43,15 @@ pub struct NewFactoid<'a> { pub trait Database: Send { - fn insert(&mut self, factoid: &NewFactoid) -> DbResponse; - fn get(&self, name: &str, idx: i32) -> Option; - fn delete(&mut self, name: &str, idx: i32) -> DbResponse; - fn count(&self, name: &str) -> Result; + fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse; + fn get_factoid(&self, name: &str, idx: i32) -> Option; + fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse; + fn count_factoids(&self, name: &str) -> Result; } // HashMap impl Database for HashMap<(String, i32), Factoid> { - fn insert(&mut self, factoid: &NewFactoid) -> DbResponse { + fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse { let factoid = Factoid { name: String::from(factoid.name), idx: factoid.idx, @@ -64,18 +67,18 @@ impl Database for HashMap<(String, i32), Factoid> { } } - fn get(&self, name: &str, idx: i32) -> Option { + fn get_factoid(&self, name: &str, idx: i32) -> Option { self.get(&(String::from(name), idx)).map(|f| f.clone()) } - fn delete(&mut self, name: &str, idx: i32) -> DbResponse { + fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse { match self.remove(&(String::from(name), idx)) { Some(_) => DbResponse::Success, None => DbResponse::Failed("Factoid not found"), } } - fn count(&self, name: &str) -> Result { + fn count_factoids(&self, name: &str) -> Result { Ok(self.iter() .filter(|&(&(ref n, _), _)| n == name) .count() as i32) @@ -98,12 +101,14 @@ mod mysql { } #[cfg(feature = "mysql")] -impl Database for MysqlConnection { - fn insert(&mut self, factoid: &NewFactoid) -> DbResponse { +impl Database for Pool> { + fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse { use diesel; + + let conn = &*self.get().expect("Failed to get connection"); match diesel::insert_into(factoids::table) .values(factoid) - .execute(self) { + .execute(conn) { Ok(_) => DbResponse::Success, Err(e) => { error!("DB Insertion Error: {}", e); @@ -112,8 +117,9 @@ impl Database for MysqlConnection { } } - fn get(&self, name: &str, idx: i32) -> Option { - match factoids::table.find((name, idx)).first(self) { + fn get_factoid(&self, name: &str, idx: i32) -> Option { + let conn = &*self.get().expect("Failed to get connection"); + match factoids::table.find((name, idx)).first(conn) { Ok(f) => Some(f), Err(e) => { error!("DB Count Error: {}", e); @@ -122,13 +128,15 @@ impl Database for MysqlConnection { } } - fn delete(&mut self, name: &str, idx: i32) -> DbResponse { + fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse { use diesel; use self::factoids::columns; + + let conn = &*self.get().expect("Failed to get connection"); match diesel::delete(factoids::table .filter(columns::name.eq(name)) .filter(columns::idx.eq(idx))) - .execute(self) { + .execute(conn) { Ok(v) => { if v > 0 { DbResponse::Success @@ -143,11 +151,13 @@ impl Database for MysqlConnection { } } - fn count(&self, name: &str) -> Result { + fn count_factoids(&self, name: &str) -> Result { + + let conn = &*self.get().expect("Failed to get connection"); let count: Result = factoids::table .filter(factoids::columns::name.eq(name)) .count() - .first(self); + .first(conn); match count { Ok(c) => Ok(c as i32), diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index 49ace10..b662d22 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -39,7 +39,7 @@ impl Factoids { } fn create_factoid(&self, name: &str, content: &str, author: &str) -> Result<&str, &str> { - let count = try_lock!(self.factoids).count(&name)?; + let count = try_lock!(self.factoids).count_factoids(&name)?; let tm = time::now().to_timespec(); let factoid = database::NewFactoid { @@ -50,7 +50,7 @@ impl Factoids { created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), }; - match try_lock!(self.factoids).insert(&factoid) { + match try_lock!(self.factoids).insert_factoid(&factoid) { DbResponse::Success => Ok("Successfully added"), DbResponse::Failed(e) => Err(e), } @@ -93,12 +93,12 @@ impl Factoids { } let name = command.tokens.remove(0); - let count = match try_lock!(self.factoids).count(&name) { + let count = match try_lock!(self.factoids).count_factoids(&name) { Ok(c) => c, Err(e) => return client.send_notice(&command.source, e), }; - match try_lock!(self.factoids).delete(&name, count - 1) { + match try_lock!(self.factoids).delete_factoid(&name, count - 1) { DbResponse::Success => client.send_notice(&command.source, "Successfully removed"), DbResponse::Failed(e) => client.send_notice(&command.source, &e), } @@ -110,7 +110,7 @@ impl Factoids { 0 => return self.invalid_command(client, command), 1 => { let name = &command.tokens[0]; - let count = match try_lock!(self.factoids).count(name) { + let count = match try_lock!(self.factoids).count_factoids(name) { Ok(c) => c, Err(e) => return client.send_notice(&command.source, e), }; @@ -132,7 +132,7 @@ impl Factoids { } }; - let factoid = match try_lock!(self.factoids).get(name, idx) { + let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { Some(v) => v, None => { return client.send_notice(&command.source, @@ -152,7 +152,7 @@ impl Factoids { 0 => self.invalid_command(client, command), 1 => { let name = &command.tokens[0]; - let count = match try_lock!(self.factoids).count(name) { + let count = match try_lock!(self.factoids).count_factoids(name) { Ok(c) => c, Err(e) => return client.send_notice(&command.source, e), }; @@ -176,7 +176,7 @@ impl Factoids { Err(_) => return client.send_notice(&command.source, "Invalid index"), }; - let factoid = match try_lock!(self.factoids).get(name, idx) { + let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { Some(v) => v, None => { return client.send_notice(&command.source, @@ -204,12 +204,12 @@ impl Factoids { } else { let name = command.tokens.remove(0); - let count = match try_lock!(self.factoids).count(&name) { + let count = match try_lock!(self.factoids).count_factoids(&name) { Ok(c) => c, Err(e) => return client.send_notice(&command.source, e), }; - let factoid = match try_lock!(self.factoids).get(&name, count - 1) { + let factoid = match try_lock!(self.factoids).get_factoid(&name, count - 1) { Some(v) => v.content, None if error => return self.invalid_command(client, &command), None => return Ok(()), -- cgit v1.2.3-70-g09d2 From ce2db228aac1c0114bcac30bb6c01212faca025a Mon Sep 17 00:00:00 2001 From: Jokler Date: Sat, 24 Feb 2018 20:13:32 +0100 Subject: Run rustfmt and clippy --- Cargo.lock | 6 +- src/lib.rs | 2 +- src/main.rs | 34 +++++------- src/plugin.rs | 2 +- src/plugins/emoji.rs | 2 +- src/plugins/factoids/database.rs | 31 +++++------ src/plugins/factoids/mod.rs | 117 ++++++++++++++++++++------------------- src/plugins/keepnick.rs | 2 +- src/plugins/tell.rs | 11 ++-- src/plugins/url.rs | 1 - src/utils.rs | 13 ++--- 11 files changed, 111 insertions(+), 110 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/Cargo.lock b/Cargo.lock index d36e32e..92cf4ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -721,7 +721,7 @@ dependencies = [ [[package]] name = "mime_guess" -version = "2.0.0-alpha.3" +version = "2.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "mime 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1024,7 +1024,7 @@ dependencies = [ "hyper-tls 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "libflate 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "mime_guess 2.0.0-alpha.3 (registry+https://github.com/rust-lang/crates.io-index)", + "mime_guess 2.0.0-alpha.4 (registry+https://github.com/rust-lang/crates.io-index)", "native-tls 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.27 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1599,7 +1599,7 @@ dependencies = [ "checksum migrations_internals 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bd916de6df9ac7e811e7e1ac28e0abfebe5205f3b29a7bda9ec8a41ee980a4eb" "checksum migrations_macros 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5a550cfd76f6cfdf15a7b541893d7c79b68277b0b309f12179211a373a56e617" "checksum mime 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e2e00e17be181010a91dbfefb01660b17311059dc8c7f48b9017677721e732bd" -"checksum mime_guess 2.0.0-alpha.3 (registry+https://github.com/rust-lang/crates.io-index)" = "013572795763289e14710c7b279461295f2673b2b338200c235082cd7ca9e495" +"checksum mime_guess 2.0.0-alpha.4 (registry+https://github.com/rust-lang/crates.io-index)" = "130ea3c9c1b65dba905ab5a4d9ac59234a9585c24d135f264e187fe7336febbd" "checksum mio 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "7da01a5e23070d92d99b1ecd1cd0af36447c6fd44b0fe283c2db199fa136724f" "checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" "checksum mysqlclient-sys 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "879ce08e38739c54d87b7f8332a476004fe2a095f40a142a36f889779d9942b7" diff --git a/src/lib.rs b/src/lib.rs index aeead16..cc6e921 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,8 +44,8 @@ extern crate lazy_static; #[macro_use] extern crate log; -extern crate irc; extern crate chrono; +extern crate irc; extern crate time; pub mod plugin; diff --git a/src/main.rs b/src/main.rs index 6605693..511fe09 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,12 +6,12 @@ extern crate glob; extern crate irc; extern crate time; +#[cfg(feature = "mysql")] +extern crate diesel; #[cfg(feature = "mysql")] #[macro_use] extern crate diesel_migrations; #[cfg(feature = "mysql")] -extern crate diesel; -#[cfg(feature = "mysql")] extern crate r2d2; #[cfg(feature = "mysql")] extern crate r2d2_diesel; @@ -103,10 +103,7 @@ fn main() { let mut mysql_url = None; if let Some(ref options) = config.options { if let Some(disabled) = options.get("disabled_plugins") { - disabled_plugins = Some(disabled - .split(",") - .map(|p| p.trim()) - .collect::>()); + disabled_plugins = Some(disabled.split(',').map(|p| p.trim()).collect::>()); } mysql_url = options.get("mysql_url"); @@ -129,18 +126,18 @@ fn main() { let manager = ConnectionManager::::new(url.clone()); match r2d2::Pool::builder().build(manager) { - Ok(pool) => { - match embedded_migrations::run(&*pool.get().expect("Failed to get connection")) { - Ok(_) => { - bot.add_plugin(plugins::Factoids::new(pool)); - info!("Connected to MySQL server") - } - Err(e) => { - bot.add_plugin(plugins::Factoids::new(HashMap::new())); - error!("Failed to run migrations: {}", e); - } + Ok(pool) => match embedded_migrations::run(&*pool.get() + .expect("Failed to get connection")) + { + Ok(_) => { + bot.add_plugin(plugins::Factoids::new(pool)); + info!("Connected to MySQL server") + } + Err(e) => { + bot.add_plugin(plugins::Factoids::new(HashMap::new())); + error!("Failed to run migrations: {}", e); } - } + }, Err(e) => error!("Failed to connect to database: {}", e), } } else { @@ -149,13 +146,12 @@ fn main() { } #[cfg(not(feature = "mysql"))] { - if let Some(_) = mysql_url { + if mysql_url.is_some() { error!("frippy was not built with the mysql feature") } bot.add_plugin(plugins::Factoids::new(HashMap::new())); } - if let Some(disabled_plugins) = disabled_plugins { for name in disabled_plugins { if bot.remove_plugin(name).is_none() { diff --git a/src/plugin.rs b/src/plugin.rs index a67d68f..f33fa80 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -11,7 +11,7 @@ pub enum ExecutionStatus { /// The [`Plugin`](trait.Plugin.html) does not need to do any more work on this [`Message`](../../irc/proto/message/struct.Message.html). Done, /// An error occured during the execution. - Err(IrcError), + Err(Box), /// The execution needs to be done by [`execute_threaded()`](trait.Plugin.html#tymethod.execute_threaded). RequiresThread, } diff --git a/src/plugins/emoji.rs b/src/plugins/emoji.rs index fcb04d1..a4276f4 100644 --- a/src/plugins/emoji.rs +++ b/src/plugins/emoji.rs @@ -100,7 +100,7 @@ impl Plugin for Emoji { .send_privmsg(message.response_target().unwrap(), &self.emoji(content)) { Ok(_) => ExecutionStatus::Done, - Err(e) => ExecutionStatus::Err(e), + Err(e) => ExecutionStatus::Err(Box::new(e)), }, _ => ExecutionStatus::Done, } diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index f003419..ccebfee 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -32,7 +32,7 @@ pub struct Factoid { #[cfg(feature = "mysql")] use self::mysql::factoids; #[cfg_attr(feature = "mysql", derive(Insertable))] -#[cfg_attr(feature = "mysql", table_name="factoids")] +#[cfg_attr(feature = "mysql", table_name = "factoids")] pub struct NewFactoid<'a> { pub name: &'a str, pub idx: i32, @@ -41,7 +41,6 @@ pub struct NewFactoid<'a> { pub created: NaiveDateTime, } - pub trait Database: Send { fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse; fn get_factoid(&self, name: &str, idx: i32) -> Option; @@ -60,7 +59,7 @@ impl Database for HashMap<(String, i32), Factoid> { created: factoid.created, }; - let name = String::from(factoid.name.clone()); + let name = factoid.name.clone(); match self.insert((name, factoid.idx), factoid) { None => DbResponse::Success, Some(_) => DbResponse::Failed("Factoid was overwritten"), @@ -68,7 +67,7 @@ impl Database for HashMap<(String, i32), Factoid> { } fn get_factoid(&self, name: &str, idx: i32) -> Option { - self.get(&(String::from(name), idx)).map(|f| f.clone()) + self.get(&(String::from(name), idx)).cloned() } fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse { @@ -79,9 +78,7 @@ impl Database for HashMap<(String, i32), Factoid> { } fn count_factoids(&self, name: &str) -> Result { - Ok(self.iter() - .filter(|&(&(ref n, _), _)| n == name) - .count() as i32) + Ok(self.iter().filter(|&(&(ref n, _), _)| n == name).count() as i32) } } @@ -107,8 +104,9 @@ impl Database for Pool> { let conn = &*self.get().expect("Failed to get connection"); match diesel::insert_into(factoids::table) - .values(factoid) - .execute(conn) { + .values(factoid) + .execute(conn) + { Ok(_) => DbResponse::Success, Err(e) => { error!("DB Insertion Error: {}", e); @@ -124,7 +122,7 @@ impl Database for Pool> { Err(e) => { error!("DB Count Error: {}", e); None - }, + } } } @@ -133,10 +131,12 @@ impl Database for Pool> { use self::factoids::columns; let conn = &*self.get().expect("Failed to get connection"); - match diesel::delete(factoids::table - .filter(columns::name.eq(name)) - .filter(columns::idx.eq(idx))) - .execute(conn) { + match diesel::delete( + factoids::table + .filter(columns::name.eq(name)) + .filter(columns::idx.eq(idx)), + ).execute(conn) + { Ok(v) => { if v > 0 { DbResponse::Success @@ -152,7 +152,6 @@ impl Database for Pool> { } fn count_factoids(&self, name: &str) -> Result { - let conn = &*self.get().expect("Failed to get connection"); let count: Result = factoids::table .filter(factoids::columns::name.eq(name)) @@ -164,7 +163,7 @@ impl Database for Pool> { Err(e) => { error!("DB Count Error: {}", e); Err("Database Error") - }, + } } } } diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index b662d22..c3d19b0 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -35,25 +35,27 @@ macro_rules! try_lock { impl Factoids { pub fn new(db: T) -> Factoids { - Factoids { factoids: Mutex::new(db) } + Factoids { + factoids: Mutex::new(db), + } } fn create_factoid(&self, name: &str, content: &str, author: &str) -> Result<&str, &str> { - let count = try_lock!(self.factoids).count_factoids(&name)?; - let tm = time::now().to_timespec(); - - let factoid = database::NewFactoid { - name: name, - idx: count, - content: content, - author: author, - created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), - }; + let count = try_lock!(self.factoids).count_factoids(name)?; + let tm = time::now().to_timespec(); + + let factoid = database::NewFactoid { + name: name, + idx: count, + content: content, + author: author, + created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), + }; - match try_lock!(self.factoids).insert_factoid(&factoid) { - DbResponse::Success => Ok("Successfully added"), - DbResponse::Failed(e) => Err(e), - } + match try_lock!(self.factoids).insert_factoid(&factoid) { + DbResponse::Success => Ok("Successfully added"), + DbResponse::Failed(e) => Err(e), + } } fn add(&self, client: &IrcClient, command: &mut PluginCommand) -> Result<(), IrcError> { @@ -70,7 +72,11 @@ impl Factoids { } } - fn from_url(&self, client: &IrcClient, command: &mut PluginCommand) -> Result<(), IrcError> { + fn save_from_url( + &self, + client: &IrcClient, + command: &mut PluginCommand, + ) -> Result<(), IrcError> { if command.tokens.len() < 2 { return self.invalid_command(client, command); } @@ -100,12 +106,11 @@ impl Factoids { match try_lock!(self.factoids).delete_factoid(&name, count - 1) { DbResponse::Success => client.send_notice(&command.source, "Successfully removed"), - DbResponse::Failed(e) => client.send_notice(&command.source, &e), + DbResponse::Failed(e) => client.send_notice(&command.source, e), } } fn get(&self, client: &IrcClient, command: &PluginCommand) -> Result<(), IrcError> { - let (name, idx) = match command.tokens.len() { 0 => return self.invalid_command(client, command), 1 => { @@ -135,19 +140,17 @@ impl Factoids { let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { Some(v) => v, None => { - return client.send_notice(&command.source, - &format!("{}~{} does not exist", name, idx)) + return client + .send_notice(&command.source, &format!("{}~{} does not exist", name, idx)) } }; let message = factoid.content.replace("\n", "|").replace("\r", ""); - client.send_privmsg(&command.target, - &format!("{}: {}", factoid.name, message)) + client.send_privmsg(&command.target, &format!("{}: {}", factoid.name, message)) } fn info(&self, client: &IrcClient, command: &PluginCommand) -> Result<(), IrcError> { - match command.tokens.len() { 0 => self.invalid_command(client, command), 1 => { @@ -159,14 +162,12 @@ impl Factoids { match count { 0 => client.send_notice(&command.source, &format!("{} does not exist", name)), - 1 => { - client.send_privmsg(&command.target, - &format!("There is 1 version of {}", name)) - } - _ => { - client.send_privmsg(&command.target, - &format!("There are {} versions of {}", count, name)) - } + 1 => client + .send_privmsg(&command.target, &format!("There is 1 version of {}", name)), + _ => client.send_privmsg( + &command.target, + &format!("There are {} versions of {}", count, name), + ), } } _ => { @@ -179,29 +180,32 @@ impl Factoids { let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { Some(v) => v, None => { - return client.send_notice(&command.source, - &format!("{}~{} does not exist", name, idx)) + return client.send_notice( + &command.source, + &format!("{}~{} does not exist", name, idx), + ) } }; - client.send_privmsg(&command.target, - &format!("{}: Added by {} at {} UTC", - name, - factoid.author, - factoid.created)) + client.send_privmsg( + &command.target, + &format!( + "{}: Added by {} at {} UTC", + name, factoid.author, factoid.created + ), + ) } - } } - fn exec(&self, - client: &IrcClient, - mut command: PluginCommand, - error: bool) - -> Result<(), IrcError> { + fn exec( + &self, + client: &IrcClient, + mut command: PluginCommand, + error: bool, + ) -> Result<(), IrcError> { if command.tokens.len() < 1 { self.invalid_command(client, &command) - } else { let name = command.tokens.remove(0); let count = match try_lock!(self.factoids).count_factoids(&name) { @@ -215,10 +219,10 @@ impl Factoids { None => return Ok(()), }; - let value = &if factoid.starts_with(">") { + let value = &if factoid.starts_with('>') { let factoid = String::from(&factoid[1..]); - if factoid.starts_with(">") { + if factoid.starts_with('>') { factoid } else { match self.run_lua(&name, &factoid, &command) { @@ -234,12 +238,12 @@ impl Factoids { } } - fn run_lua(&self, - name: &str, - code: &str, - command: &PluginCommand) - -> Result { - + fn run_lua( + &self, + name: &str, + code: &str, + command: &PluginCommand, + ) -> Result { let args = command .tokens .iter() @@ -295,7 +299,6 @@ impl Plugin for Factoids { }; self.exec(client, c, false) - } else { Ok(()) } @@ -309,7 +312,7 @@ impl Plugin for Factoids { let sub_command = command.tokens.remove(0); match sub_command.as_ref() { "add" => self.add(client, &mut command), - "fromurl" => self.from_url(client, &mut command), + "fromurl" => self.save_from_url(client, &mut command), "remove" => self.remove(client, &mut command), "get" => self.get(client, &command), "info" => self.info(client, &command), @@ -319,7 +322,9 @@ impl Plugin for Factoids { } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { - Err(String::from("Evaluation of commands is not implemented for Factoids at this time")) + Err(String::from( + "Evaluation of commands is not implemented for Factoids at this time", + )) } } diff --git a/src/plugins/keepnick.rs b/src/plugins/keepnick.rs index 73f4893..bdabd90 100644 --- a/src/plugins/keepnick.rs +++ b/src/plugins/keepnick.rs @@ -27,7 +27,7 @@ impl KeepNick { info!("Trying to switch nick from {} to {}", client_nick, cfg_nick); match client.send(Command::NICK(cfg_nick)) { Ok(_) => ExecutionStatus::Done, - Err(e) => ExecutionStatus::Err(e), + Err(e) => ExecutionStatus::Err(Box::new(e)), } } else { ExecutionStatus::Done diff --git a/src/plugins/tell.rs b/src/plugins/tell.rs index 34d7cf8..89d91f2 100644 --- a/src/plugins/tell.rs +++ b/src/plugins/tell.rs @@ -61,7 +61,9 @@ impl Tell { }; let mut tells = try_lock!(self.tells); - let tell_messages = tells.entry(receiver).or_insert(Vec::with_capacity(3)); + let tell_messages = tells + .entry(receiver) + .or_insert_with(|| Vec::with_capacity(3)); (*tell_messages).push(tell); Ok("Got it!") @@ -75,7 +77,7 @@ impl Tell { receiver, &format!("Tell from {}: {}", tell.sender, tell.message), ) { - return ExecutionStatus::Err(e); + return ExecutionStatus::Err(Box::new(e)); } debug!( "Sent {:?} from {:?} to {:?}", @@ -107,8 +109,9 @@ impl Tell { impl Plugin for Tell { fn execute(&self, client: &IrcClient, message: &Message) -> ExecutionStatus { match message.command { - Command::JOIN(_, _, _) => self.send_tell(client, message.source_nickname().unwrap()), - Command::PRIVMSG(_, _) => self.send_tell(client, message.source_nickname().unwrap()), + Command::JOIN(_, _, _) | Command::PRIVMSG(_, _) => { + self.send_tell(client, message.source_nickname().unwrap()) + } _ => ExecutionStatus::Done, } } diff --git a/src/plugins/url.rs b/src/plugins/url.rs index df4fdf2..52f92d8 100644 --- a/src/plugins/url.rs +++ b/src/plugins/url.rs @@ -44,7 +44,6 @@ impl Url { None => return Err("No Url was found."), }; - match utils::download(self.max_kib, &url) { Some(body) => { let doc = Document::from(body.as_ref()); diff --git a/src/utils.rs b/src/utils.rs index 59a5a54..0b965c8 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -7,10 +7,7 @@ use self::reqwest::Client; use self::reqwest::header::Connection; pub fn download(max_kib: usize, url: &str) -> Option { - let response = Client::new() - .get(url) - .header(Connection::close()) - .send(); + let response = Client::new().get(url).header(Connection::close()).send(); match response { Ok(mut response) => { @@ -44,16 +41,18 @@ pub fn download(max_kib: usize, url: &str) -> Option { // Check if the file is too large to download if written > max_kib * 1024 { - debug!("Stopping download - File from {:?} is larger than {} KiB", url, max_kib); + debug!( + "Stopping download - File from {:?} is larger than {} KiB", + url, max_kib + ); return None; } - } Some(body) } Err(e) => { debug!("Bad response from {:?}: ({})", url, e); - return None; + None } } } -- cgit v1.2.3-70-g09d2 From ac1afe4c7b0f62160f62b848d7f747cb7be74bbd Mon Sep 17 00:00:00 2001 From: Jokler Date: Sun, 25 Feb 2018 01:30:17 +0100 Subject: Return zero if count_factoids could not find the factoid --- src/plugins/factoids/database.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index ccebfee..386d3f7 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -152,14 +152,17 @@ impl Database for Pool> { } fn count_factoids(&self, name: &str) -> Result { + use diesel; + let conn = &*self.get().expect("Failed to get connection"); let count: Result = factoids::table .filter(factoids::columns::name.eq(name)) .count() - .first(conn); + .get_result(conn); match count { Ok(c) => Ok(c as i32), + Err(diesel::NotFound) => Ok(0), Err(e) => { error!("DB Count Error: {}", e); Err("Database Error") -- cgit v1.2.3-70-g09d2 From 92668ad4c53edcc1a317a16aa5ea30ca502f54ee Mon Sep 17 00:00:00 2001 From: Jokler Date: Sun, 25 Feb 2018 18:54:16 +0100 Subject: Add Mysql as a possible database to the Tell plugin --- migrations/2018-02-25-154922_create_tells/down.sql | 1 + migrations/2018-02-25-154922_create_tells/up.sql | 7 + src/main.rs | 10 +- src/plugins/factoids/database.rs | 15 ++- src/plugins/factoids/mod.rs | 2 +- src/plugins/tell.rs | 143 -------------------- src/plugins/tell/database.rs | 143 ++++++++++++++++++++ src/plugins/tell/mod.rs | 144 +++++++++++++++++++++ 8 files changed, 313 insertions(+), 152 deletions(-) create mode 100644 migrations/2018-02-25-154922_create_tells/down.sql create mode 100644 migrations/2018-02-25-154922_create_tells/up.sql delete mode 100644 src/plugins/tell.rs create mode 100644 src/plugins/tell/database.rs create mode 100644 src/plugins/tell/mod.rs (limited to 'src/plugins/factoids/database.rs') diff --git a/migrations/2018-02-25-154922_create_tells/down.sql b/migrations/2018-02-25-154922_create_tells/down.sql new file mode 100644 index 0000000..73c9b9b --- /dev/null +++ b/migrations/2018-02-25-154922_create_tells/down.sql @@ -0,0 +1 @@ +DROP TABLE tells diff --git a/migrations/2018-02-25-154922_create_tells/up.sql b/migrations/2018-02-25-154922_create_tells/up.sql new file mode 100644 index 0000000..9de037c --- /dev/null +++ b/migrations/2018-02-25-154922_create_tells/up.sql @@ -0,0 +1,7 @@ +CREATE TABLE tells ( + id SERIAL PRIMARY KEY, + sender VARCHAR(32) NOT NULL, + receiver VARCHAR(32) NOT NULL, + time TIMESTAMP NOT NULL, + message VARCHAR(512) NOT NULL +) diff --git a/src/main.rs b/src/main.rs index 511fe09..ec04d33 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,8 @@ extern crate r2d2_diesel; #[macro_use] extern crate log; +#[cfg(feature = "mysql")] +use std::sync::Arc; use std::collections::HashMap; use log::{Level, LevelFilter, Metadata, Record}; @@ -115,7 +117,6 @@ fn main() { bot.add_plugin(plugins::Emoji::new()); bot.add_plugin(plugins::Currency::new()); bot.add_plugin(plugins::KeepNick::new()); - bot.add_plugin(plugins::Tell::new()); #[cfg(feature = "mysql")] { @@ -130,11 +131,14 @@ fn main() { .expect("Failed to get connection")) { Ok(_) => { - bot.add_plugin(plugins::Factoids::new(pool)); + let pool = Arc::new(pool); + bot.add_plugin(plugins::Factoids::new(pool.clone())); + bot.add_plugin(plugins::Tell::new(pool.clone())); info!("Connected to MySQL server") } Err(e) => { bot.add_plugin(plugins::Factoids::new(HashMap::new())); + bot.add_plugin(plugins::Tell::new(HashMap::new())); error!("Failed to run migrations: {}", e); } }, @@ -142,6 +146,7 @@ fn main() { } } else { bot.add_plugin(plugins::Factoids::new(HashMap::new())); + bot.add_plugin(plugins::Tell::new(HashMap::new())); } } #[cfg(not(feature = "mysql"))] @@ -150,6 +155,7 @@ fn main() { error!("frippy was not built with the mysql feature") } bot.add_plugin(plugins::Factoids::new(HashMap::new())); + bot.add_plugin(plugins::Tell::new(HashMap::new())); } if let Some(disabled_plugins) = disabled_plugins { diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 386d3f7..88aa0fd 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -1,6 +1,8 @@ #[cfg(feature = "mysql")] extern crate dotenv; +#[cfg(feature = "mysql")] +use std::sync::Arc; use std::collections::HashMap; #[cfg(feature = "mysql")] @@ -29,8 +31,6 @@ pub struct Factoid { pub created: NaiveDateTime, } -#[cfg(feature = "mysql")] -use self::mysql::factoids; #[cfg_attr(feature = "mysql", derive(Insertable))] #[cfg_attr(feature = "mysql", table_name = "factoids")] pub struct NewFactoid<'a> { @@ -82,10 +82,10 @@ impl Database for HashMap<(String, i32), Factoid> { } } -// Diesel automatically define the factoids module as public. -// For now this is how we keep it private. +// Diesel automatically defines the factoids module as public. +// We create a schema module to keep it private. #[cfg(feature = "mysql")] -mod mysql { +mod schema { table! { factoids (name, idx) { name -> Varchar, @@ -98,7 +98,10 @@ mod mysql { } #[cfg(feature = "mysql")] -impl Database for Pool> { +use self::schema::factoids; + +#[cfg(feature = "mysql")] +impl Database for Arc>> { fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse { use diesel; diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index c3d19b0..d6abb1d 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -49,7 +49,7 @@ impl Factoids { idx: count, content: content, author: author, - created: NaiveDateTime::from_timestamp(tm.sec, tm.nsec as u32), + created: NaiveDateTime::from_timestamp(tm.sec, 0u32), }; match try_lock!(self.factoids).insert_factoid(&factoid) { diff --git a/src/plugins/tell.rs b/src/plugins/tell.rs deleted file mode 100644 index 89d91f2..0000000 --- a/src/plugins/tell.rs +++ /dev/null @@ -1,143 +0,0 @@ -use irc::client::prelude::*; -use irc::error::IrcError; - -use std::collections::HashMap; -use std::sync::Mutex; - -use plugin::*; - -macro_rules! try_lock { - ( $m:expr ) => { - match $m.lock() { - Ok(guard) => guard, - Err(poisoned) => poisoned.into_inner(), - } - } -} - -#[derive(PluginName, Default, Debug)] -pub struct Tell { - tells: Mutex>>, -} - -#[derive(Default, Debug)] -struct TellMessage { - sender: String, - // TODO Add time - message: String, -} - -impl Tell { - pub fn new() -> Tell { - Tell { - tells: Mutex::new(HashMap::new()), - } - } - - fn tell_command(&self, client: &IrcClient, command: &PluginCommand) -> Result<&str, String> { - if command.tokens.len() < 2 { - return Err(self.invalid_command(client)); - } - - let receiver = command.tokens[0].to_string(); - let sender = command.source.to_owned(); - - if receiver == sender { - return Err(String::from("That's your name!")); - } - - if command.source != command.target { - if let Some(users) = client.list_users(&command.target) { - if users.iter().any(|u| u.get_nickname() == receiver) { - return Err(format!("{} is in this channel.", receiver)); - } - } - } - - let message = command.tokens[1..].join(" "); - let tell = TellMessage { - sender: sender, - message: message, - }; - - let mut tells = try_lock!(self.tells); - let tell_messages = tells - .entry(receiver) - .or_insert_with(|| Vec::with_capacity(3)); - (*tell_messages).push(tell); - - Ok("Got it!") - } - - fn send_tell(&self, client: &IrcClient, receiver: &str) -> ExecutionStatus { - let mut tells = try_lock!(self.tells); - if let Some(tell_messages) = tells.get_mut(receiver) { - for tell in tell_messages { - if let Err(e) = client.send_notice( - receiver, - &format!("Tell from {}: {}", tell.sender, tell.message), - ) { - return ExecutionStatus::Err(Box::new(e)); - } - debug!( - "Sent {:?} from {:?} to {:?}", - tell.message, tell.sender, receiver - ); - } - } - tells.remove(receiver); - ExecutionStatus::Done - } - - fn invalid_command(&self, client: &IrcClient) -> String { - format!( - "Incorrect Command. \ - Send \"{} tell help\" for help.", - client.current_nickname() - ) - } - - fn help(&self, client: &IrcClient) -> String { - format!( - "usage: {} tell user message\r\n\ - example: {0} tell Foobar Hello!", - client.current_nickname() - ) - } -} - -impl Plugin for Tell { - fn execute(&self, client: &IrcClient, message: &Message) -> ExecutionStatus { - match message.command { - Command::JOIN(_, _, _) | Command::PRIVMSG(_, _) => { - self.send_tell(client, message.source_nickname().unwrap()) - } - _ => ExecutionStatus::Done, - } - } - - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { - panic!("Tell should not use threading") - } - - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - if command.tokens.is_empty() { - return client.send_notice(&command.source, &self.invalid_command(client)); - } - - match command.tokens[0].as_ref() { - "help" => client.send_notice(&command.source, &self.help(client)), - _ => match self.tell_command(client, &command) { - Ok(msg) => client.send_notice(&command.source, msg), - Err(msg) => client.send_notice(&command.source, &msg), - }, - } - } - - fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { - Err(String::from("This Plugin does not implement any commands.")) - } -} - -#[cfg(test)] -mod tests {} diff --git a/src/plugins/tell/database.rs b/src/plugins/tell/database.rs new file mode 100644 index 0000000..277847e --- /dev/null +++ b/src/plugins/tell/database.rs @@ -0,0 +1,143 @@ +#[cfg(feature = "mysql")] +extern crate dotenv; + +#[cfg(feature = "mysql")] +use std::sync::Arc; +use std::collections::HashMap; + +#[cfg(feature = "mysql")] +use diesel::prelude::*; +#[cfg(feature = "mysql")] +use diesel::mysql::MysqlConnection; +#[cfg(feature = "mysql")] +use r2d2::Pool; +#[cfg(feature = "mysql")] +use r2d2_diesel::ConnectionManager; + +use chrono::NaiveDateTime; + +pub enum DbResponse { + Success, + Failed(&'static str), +} + +#[cfg_attr(feature = "mysql", derive(Queryable))] +#[derive(PartialEq, Clone, Debug)] +pub struct TellMessage { + pub id: i64, + pub sender: String, + pub receiver: String, + pub time: NaiveDateTime, + pub message: String, +} + +#[cfg_attr(feature = "mysql", derive(Insertable))] +#[cfg_attr(feature = "mysql", table_name = "tells")] +pub struct NewTellMessage<'a> { + pub sender: &'a str, + pub receiver: &'a str, + pub time: NaiveDateTime, + pub message: &'a str, +} + +pub trait Database: Send { + fn insert_tell(&mut self, tell: &NewTellMessage) -> DbResponse; + fn get_tells(&self, receiver: &str) -> Option>; + fn delete_tells(&mut self, receiver: &str) -> DbResponse; +} + +// HashMap +impl Database for HashMap> { + fn insert_tell(&mut self, tell: &NewTellMessage) -> DbResponse { + let tell = TellMessage { + id: 0, + sender: tell.sender.to_string(), + receiver: tell.receiver.to_string(), + time: tell.time, + message: tell.message.to_string(), + }; + + let receiver = tell.receiver.clone(); + let tell_messages = self.entry(receiver) + .or_insert_with(|| Vec::with_capacity(3)); + (*tell_messages).push(tell); + + DbResponse::Success + } + + fn get_tells(&self, receiver: &str) -> Option> { + self.get(receiver).cloned() + } + + fn delete_tells(&mut self, receiver: &str) -> DbResponse { + match self.remove(receiver) { + Some(_) => DbResponse::Success, + None => DbResponse::Failed("Tells not found"), + } + } +} + +// Diesel automatically defines the tells module as public. +// We create a schema module to keep it private. +#[cfg(feature = "mysql")] +mod schema { + table! { + tells (id) { + id -> Bigint, + sender -> Varchar, + receiver -> Varchar, + time -> Timestamp, + message -> Varchar, + } + } +} + +#[cfg(feature = "mysql")] +use self::schema::tells; + +#[cfg(feature = "mysql")] +impl Database for Arc>> { + fn insert_tell(&mut self, tell: &NewTellMessage) -> DbResponse { + use diesel; + + let conn = &*self.get().expect("Failed to get connection"); + match diesel::insert_into(tells::table).values(tell).execute(conn) { + Ok(_) => DbResponse::Success, + Err(e) => { + error!("DB failed to insert tell: {}", e); + DbResponse::Failed("Failed to save Tell") + } + } + } + + fn get_tells(&self, receiver: &str) -> Option> { + use self::tells::columns; + + let conn = &*self.get().expect("Failed to get connection"); + match tells::table + .filter(columns::receiver.eq(receiver)) + .order(columns::time.asc()) + .load::(conn) + { + Ok(f) => Some(f), + Err(e) => { + error!("DB failed to get tells: {}", e); + None + } + } + } + + fn delete_tells(&mut self, receiver: &str) -> DbResponse { + use diesel; + use self::tells::columns; + + let conn = &*self.get().expect("Failed to get connection"); + match diesel::delete(tells::table.filter(columns::receiver.eq(receiver))).execute(conn) { + Ok(_) => DbResponse::Success, + Err(e) => { + error!("DB failed to delete tells: {}", e); + DbResponse::Failed("Failed to delete tells") + } + } + } +} diff --git a/src/plugins/tell/mod.rs b/src/plugins/tell/mod.rs new file mode 100644 index 0000000..1a1bef1 --- /dev/null +++ b/src/plugins/tell/mod.rs @@ -0,0 +1,144 @@ +use irc::client::prelude::*; +use irc::error::IrcError; + +use time; +use chrono::NaiveDateTime; +use std::sync::Mutex; + +use plugin::*; + +pub mod database; +use self::database::{Database, DbResponse}; + +macro_rules! try_lock { + ( $m:expr ) => { + match $m.lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + } + } +} + +#[derive(PluginName, Default)] +pub struct Tell { + tells: Mutex, +} + +impl Tell { + pub fn new(db: T) -> Tell { + Tell { + tells: Mutex::new(db), + } + } + + fn tell_command(&self, client: &IrcClient, command: &PluginCommand) -> Result<&str, String> { + if command.tokens.len() < 2 { + return Err(self.invalid_command(client)); + } + + let receiver = command.tokens[0].to_string(); + let sender = command.source.to_owned(); + + if receiver == sender { + return Err(String::from("That's your name!")); + } + + if command.source != command.target { + if let Some(users) = client.list_users(&command.target) { + if users.iter().any(|u| u.get_nickname() == receiver) { + return Err(format!("{} is in this channel.", receiver)); + } + } + } + + let tm = time::now().to_timespec(); + let message = command.tokens[1..].join(" "); + let tell = database::NewTellMessage { + sender: &sender, + receiver: &receiver, + time: NaiveDateTime::from_timestamp(tm.sec, 0u32), + message: &message, + }; + + match try_lock!(self.tells).insert_tell(&tell) { + DbResponse::Success => Ok("Got it!"), + DbResponse::Failed(e) => Err(e.to_string()), + } + } + + fn send_tell(&self, client: &IrcClient, receiver: &str) -> ExecutionStatus { + let mut tells = try_lock!(self.tells); + if let Some(tell_messages) = tells.get_tells(receiver) { + for tell in tell_messages { + if let Err(e) = client.send_notice( + receiver, + &format!("Tell from {}: {}", tell.sender, tell.message), + ) { + return ExecutionStatus::Err(Box::new(e)); + } + debug!( + "Sent {:?} from {:?} to {:?}", + tell.message, tell.sender, receiver + ); + } + } + tells.delete_tells(receiver); + ExecutionStatus::Done + } + + fn invalid_command(&self, client: &IrcClient) -> String { + format!( + "Incorrect Command. \ + Send \"{} tell help\" for help.", + client.current_nickname() + ) + } + + fn help(&self, client: &IrcClient) -> String { + format!( + "usage: {} tell user message\r\n\ + example: {0} tell Foobar Hello!", + client.current_nickname() + ) + } +} + +impl Plugin for Tell { + fn execute(&self, client: &IrcClient, message: &Message) -> ExecutionStatus { + match message.command { + Command::JOIN(_, _, _) | Command::PRIVMSG(_, _) => { + self.send_tell(client, message.source_nickname().unwrap()) + } + _ => ExecutionStatus::Done, + } + } + + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + panic!("Tell should not use threading") + } + + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { + if command.tokens.is_empty() { + return client.send_notice(&command.source, &self.invalid_command(client)); + } + + match command.tokens[0].as_ref() { + "help" => client.send_notice(&command.source, &self.help(client)), + _ => match self.tell_command(client, &command) { + Ok(msg) => client.send_notice(&command.source, msg), + Err(msg) => client.send_notice(&command.source, &msg), + }, + } + } + + fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { + Err(String::from("This Plugin does not implement any commands.")) + } +} + +use std::fmt; +impl fmt::Debug for Tell { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Tell {{ ... }}") + } +} -- cgit v1.2.3-70-g09d2 From 0b4131e8cf91ed10f24d3faed341034d518aea53 Mon Sep 17 00:00:00 2001 From: Jokler Date: Fri, 2 Mar 2018 22:11:21 +0100 Subject: Use Error & ErrorKind pair instead of simple enums Each plugin should define its own errors with a respective variant in the main ErrorKind of frippy. A new procedural macro was added to reduce the boilerplate required for new error system. It can be used by deriving "Error" and adding a name for the Error via the "error" attribute. So far non of the plugins except for Url and Factoids use their own errors yet. --- Cargo.lock | 40 ++++++++- frippy_derive/Cargo.toml | 5 +- frippy_derive/src/lib.rs | 86 +++++++++++++++++- src/error.rs | 114 +++++------------------- src/lib.rs | 56 ++++++------ src/main.rs | 51 ++++++----- src/plugin.rs | 21 +++-- src/plugins/currency.rs | 28 +++--- src/plugins/emoji.rs | 25 +++--- src/plugins/factoids/database.rs | 88 ++++++++---------- src/plugins/factoids/mod.rs | 187 +++++++++++++++++++++++---------------- src/plugins/factoids/utils.rs | 6 +- src/plugins/help.rs | 16 ++-- src/plugins/keepnick.rs | 29 +++--- src/plugins/mod.rs | 23 ++--- src/plugins/tell/mod.rs | 32 ++++--- src/plugins/url.rs | 63 ++++++++----- src/utils.rs | 34 ++++--- 18 files changed, 528 insertions(+), 376 deletions(-) (limited to 'src/plugins/factoids/database.rs') diff --git a/Cargo.lock b/Cargo.lock index dcbaad5..acb6f80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -414,8 +414,9 @@ dependencies = [ name = "frippy_derive" version = "0.1.0" dependencies = [ - "quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.12.13 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -925,6 +926,14 @@ name = "precomputed-hash" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "proc-macro2" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "pulldown-cmark" version = "0.0.15" @@ -949,6 +958,14 @@ name = "quote" version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "quote" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "r2d2" version = "0.8.2" @@ -1246,6 +1263,16 @@ dependencies = [ "unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "syn" +version = "0.12.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "synom" version = "0.11.3" @@ -1427,6 +1454,11 @@ name = "unicode-xid" version = "0.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "unicode_names" version = "0.1.7" @@ -1636,10 +1668,12 @@ dependencies = [ "checksum phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)" = "07e24b0ca9643bdecd0632f2b3da6b1b89bbb0030e0b992afc1113b23a7bc2f2" "checksum pkg-config 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "3a8b4c6b8165cd1a1cd4b9b120978131389f64bdaf456435caa41e630edba903" "checksum precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" +"checksum proc-macro2 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cd07deb3c6d1d9ff827999c7f9b04cdfd66b1b17ae508e14fe47b620f2282ae0" "checksum pulldown-cmark 0.0.15 (registry+https://github.com/rust-lang/crates.io-index)" = "378e941dbd392c101f2cb88097fa4d7167bc421d4b88de3ff7dbee503bc3233b" "checksum quick-error 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "eda5fe9b71976e62bc81b781206aaa076401769b2143379d3eb2118388babac4" "checksum quine-mc_cluskey 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "07589615d719a60c8dd8a4622e7946465dfef20d1a428f969e3443e7386d5f45" "checksum quote 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a" +"checksum quote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1eca14c727ad12702eb4b6bfb5a232287dcf8385cb8ca83a3eeaf6519c44c408" "checksum r2d2 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f9078ca6a8a5568ed142083bb2f7dc9295b69d16f867ddcc9849e51b17d8db46" "checksum r2d2-diesel 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eb9c29bad92da76d02bc2c020452ebc3a3fe6fa74cfab91e711c43116e4fb1a3" "checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" @@ -1675,6 +1709,7 @@ dependencies = [ "checksum string_cache_codegen 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "479cde50c3539481f33906a387f2bd17c8e87cb848c35b6021d41fb81ff9b4d7" "checksum string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1884d1bc09741d466d9b14e6d37ac89d6909cbcac41dd9ae982d4d063bbedfc" "checksum syn 0.11.11 (registry+https://github.com/rust-lang/crates.io-index)" = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad" +"checksum syn 0.12.13 (registry+https://github.com/rust-lang/crates.io-index)" = "517f6da31bc53bf080b9a77b29fbd0ff8da2f5a2ebd24c73c2238274a94ac7cb" "checksum synom 0.11.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6" "checksum synstructure 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3a761d12e6d8dcb4dcf952a7a89b475e3a9d69e4a69307e01a470977642914bd" "checksum take 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b157868d8ac1f56b64604539990685fa7611d8fa9e5476cf0c02cf34d32917c5" @@ -1695,6 +1730,7 @@ dependencies = [ "checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" "checksum unicode-normalization 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "51ccda9ef9efa3f7ef5d91e8f9b83bbe6955f9bf86aec89d5cce2c874625920f" "checksum unicode-xid 0.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unicode_names 0.1.7 (git+https://github.com/Jokler/unicode_names?branch=update-to-latest-unicode)" = "" "checksum unreachable 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1f2ae5ddb18e1c92664717616dd9549dde73f539f01bd7b77c2edb2446bdff91" "checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" diff --git a/frippy_derive/Cargo.toml b/frippy_derive/Cargo.toml index 937afba..b258f57 100644 --- a/frippy_derive/Cargo.toml +++ b/frippy_derive/Cargo.toml @@ -7,5 +7,6 @@ authors = ["Jokler "] proc-macro = true [dependencies] -syn = "0.11.11" -quote = "0.3.15" +syn = "0.12.13" +quote = "0.4.2" +failure = "0.1.1" diff --git a/frippy_derive/src/lib.rs b/frippy_derive/src/lib.rs index 2622f0b..efa349a 100644 --- a/frippy_derive/src/lib.rs +++ b/frippy_derive/src/lib.rs @@ -1,18 +1,20 @@ - //! Provides the plugin derive macro +#![recursion_limit="128"] extern crate proc_macro; extern crate syn; #[macro_use] extern crate quote; +extern crate failure; + use proc_macro::TokenStream; #[proc_macro_derive(PluginName)] pub fn derive_plugin(data: TokenStream) -> TokenStream { - let ast = syn::parse_derive_input(&data.to_string()).unwrap(); + let ast = syn::parse(data).unwrap(); let gen = expand_plugin(&ast); - gen.parse().unwrap() + gen.into() } fn expand_plugin(ast: &syn::DeriveInput) -> quote::Tokens { @@ -27,3 +29,81 @@ fn expand_plugin(ast: &syn::DeriveInput) -> quote::Tokens { } } } + +#[proc_macro_derive(Error, attributes(error))] +pub fn derive_error(data: TokenStream) -> TokenStream { + let ast = syn::parse(data).unwrap(); + let tokens = expand_error(&ast); + // panic!("{}", tokens.to_string()); + tokens.into() +} + +fn expand_error(ast: &syn::DeriveInput) -> quote::Tokens { + if let syn::Data::Enum(_) = ast.data { + } else { + panic!("Error should only be derived on ErrorKind enums"); + }; + + let mut name = None; + for attr in &ast.attrs { + if let Some(syn::Meta::NameValue(name_value)) = attr.interpret_meta() { + if "error" == name_value.ident.to_string() { + if let syn::Lit::Str(lit) = name_value.lit { + name = Some(lit.value()); + } + } + } + }; + + let struct_name = if let Some(name) = name { + syn::Ident::from(name) + } else { + panic!("Define the error attribute for all Error derives"); + }; + + let enum_name = &ast.ident; + + quote! { + #[derive(Debug)] + pub struct #struct_name { + inner: ::failure::Context<#enum_name>, + } + + impl #struct_name { + pub fn kind(&self) -> #enum_name { + *self.inner.get_context() + } + } + + impl From<#enum_name> for #struct_name { + fn from(kind: #enum_name) -> #struct_name { + #struct_name { + inner: ::failure::Context::new(kind), + } + } + } + + impl From<::failure::Context<#enum_name>> for #struct_name { + fn from(inner: ::failure::Context<#enum_name>) -> #struct_name { + #struct_name { inner: inner } + } + } + + impl ::failure::Fail for #struct_name { + fn cause(&self) -> Option<&::failure::Fail> { + self.inner.cause() + } + + fn backtrace(&self) -> Option<&::failure::Backtrace> { + self.inner.backtrace() + } + } + + impl ::std::fmt::Display for #struct_name { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + use std::fmt; + fmt::Display::fmt(&self.inner, f) + } + } + } +} diff --git a/src/error.rs b/src/error.rs index fa232be..36d5724 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,101 +1,31 @@ //! Errors for `frippy` crate using `failure`. -use std::io::Error as IoError; -use irc::error::IrcError; -use reqwest::Error as ReqwestError; -#[cfg(feature = "mysql")] -use r2d2::Error as R2d2Error; +use failure::Fail; -/// The main crate-wide error type. -#[derive(Debug, Fail)] -pub enum FrippyError { - /// A plugin error - #[fail(display = "A plugin error occured")] - Plugin(#[cause] PluginError), - - /// An IRC error - #[fail(display = "An IRC error occured")] - Irc(#[cause] IrcError), - - /// Missing config error - #[fail(display = "No config file was found")] - MissingConfig, - - /// A reqwest error - #[fail(display = "A reqwest error occured")] - Reqwest(#[cause] ReqwestError), - - /// An I/O error - #[fail(display = "An I/O error occured")] - Io(#[cause] IoError), - - /// An r2d2 error - #[cfg(feature = "mysql")] - #[fail(display = "An r2d2 error occured")] - R2d2(#[cause] R2d2Error), - - /// Reached download limit error - #[fail(display = "Reached download limit of {} KiB", limit)] - DownloadLimit { limit: usize }, +pub fn log_error(e: FrippyError) { + let text = e.causes() + .skip(1) + .fold(format!("{}", e), |acc, err| format!("{}: {}", acc, err)); + error!("{}", text); } -/// Errors related to plugins -#[derive(Debug, Fail)] -pub enum PluginError { - /// A Url error - #[fail(display = "A Url error occured")] - Url(#[cause] UrlError), - - /// A Factoids error - #[fail(display = "{}", error)] - Factoids { error: String }, -} - -/// A URL plugin error -#[derive(Debug, Fail)] -pub enum UrlError { - /// Missing URL error - #[fail(display = "No URL was found")] - MissingUrl, - - /// Missing title error - #[fail(display = "No title was found")] - MissingTitle, -} - -impl From for FrippyError { - fn from(e: UrlError) -> FrippyError { - FrippyError::Plugin(PluginError::Url(e)) - } -} - -impl From for FrippyError { - fn from(e: PluginError) -> FrippyError { - FrippyError::Plugin(e) - } -} - -impl From for FrippyError { - fn from(e: IrcError) -> FrippyError { - FrippyError::Irc(e) - } -} +/// The main crate-wide error type. +#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail, Error)] +#[error = "FrippyError"] +pub enum ErrorKind { + /// Connection error + #[fail(display = "A connection error occured")] + Connection, -impl From for FrippyError { - fn from(e: ReqwestError) -> FrippyError { - FrippyError::Reqwest(e) - } -} + /// A Url error + #[fail(display = "A Url error has occured")] + Url, -impl From for FrippyError { - fn from(e: IoError) -> FrippyError { - FrippyError::Io(e) - } -} + /// A Tell error + #[fail(display = "A Tell error has occured")] + Tell, -#[cfg(feature = "mysql")] -impl From for FrippyError { - fn from(e: R2d2Error) -> FrippyError { - FrippyError::R2d2(e) - } + /// A Factoids error + #[fail(display = "A Factoids error has occured")] + Factoids, } diff --git a/src/lib.rs b/src/lib.rs index 42b0089..8cf1e2f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -64,7 +64,8 @@ use std::sync::Arc; pub use irc::client::prelude::*; pub use irc::error::IrcError; -use error::FrippyError; +use error::*; +use failure::ResultExt; use plugin::*; @@ -150,11 +151,13 @@ impl Bot { pub fn connect(&self, reactor: &mut IrcReactor, config: &Config) -> Result<(), FrippyError> { info!("Plugins loaded: {}", self.plugins); - let client = reactor.prepare_client_and_connect(config)?; + let client = reactor + .prepare_client_and_connect(config) + .context(ErrorKind::Connection)?; info!("Connected to IRC server"); - client.identify()?; + client.identify().context(ErrorKind::Connection)?; info!("Identified"); // TODO Verify if we actually need to clone plugins twice @@ -169,25 +172,25 @@ impl Bot { } fn process_msg( - server: &IrcClient, + client: &IrcClient, mut plugins: ThreadedPlugins, message: Message, ) -> Result<(), IrcError> { // Log any channels we join if let Command::JOIN(ref channel, _, _) = message.command { - if message.source_nickname().unwrap() == server.current_nickname() { + if message.source_nickname().unwrap() == client.current_nickname() { info!("Joined {}", channel); } } // Check for possible command and save the result for later - let command = PluginCommand::from(&server.current_nickname().to_lowercase(), &message); + let command = PluginCommand::from(&client.current_nickname().to_lowercase(), &message); - plugins.execute_plugins(server, message); + plugins.execute_plugins(client, message); // If the message contained a command, handle it if let Some(command) = command { - if let Err(e) = plugins.handle_command(server, command) { + if let Err(e) = plugins.handle_command(client, command) { error!("Failed to handle command: {}", e); } } @@ -218,12 +221,12 @@ impl ThreadedPlugins { self.plugins.remove(&name.to_lowercase()).map(|_| ()) } - pub fn execute_plugins(&mut self, server: &IrcClient, message: Message) { + pub fn execute_plugins(&mut self, client: &IrcClient, message: Message) { let message = Arc::new(message); for (name, plugin) in self.plugins.clone() { // Send the message to the plugin if the plugin needs it - match plugin.execute(server, &message) { + match plugin.execute(client, &message) { ExecutionStatus::Done => (), ExecutionStatus::Err(e) => error!("Error in {} - {}", name, e), ExecutionStatus::RequiresThread => { @@ -233,15 +236,15 @@ impl ThreadedPlugins { message.to_string().replace("\r\n", "") ); - // Clone everything before the move - the server uses an Arc internally too + // Clone everything before the move - the client uses an Arc internally too let plugin = Arc::clone(&plugin); let message = Arc::clone(&message); - let server = server.clone(); + let client = client.clone(); // Execute the plugin in another thread spawn(move || { - if let Err(e) = plugin.execute_threaded(&server, &message) { - error!("Error in {} - {}", name, e); + if let Err(e) = plugin.execute_threaded(&client, &message) { + log_error(e); }; }); } @@ -251,12 +254,14 @@ impl ThreadedPlugins { pub fn handle_command( &mut self, - server: &IrcClient, + client: &IrcClient, mut command: PluginCommand, ) -> Result<(), FrippyError> { if !command.tokens.iter().any(|s| !s.is_empty()) { - let help = format!("Use \"{} help\" to get help", server.current_nickname()); - server.send_notice(&command.source, &help)?; + let help = format!("Use \"{} help\" to get help", client.current_nickname()); + client + .send_notice(&command.source, &help) + .context(ErrorKind::Connection)?; } // Check if the command is for this plugin @@ -266,12 +271,12 @@ impl ThreadedPlugins { debug!("Sending command \"{:?}\" to {}", command, name); - // Clone for the move - the server uses an Arc internally - let server = server.clone(); + // Clone for the move - the client uses an Arc internally + let client = client.clone(); let plugin = Arc::clone(plugin); spawn(move || { - if let Err(e) = plugin.command(&server, command) { - error!("Error in {} command - {}", name, e); + if let Err(e) = plugin.command(&client, command) { + log_error(e); }; }); @@ -280,11 +285,13 @@ impl ThreadedPlugins { let help = format!( "\"{} {}\" is not a command, \ try \"{0} help\" instead.", - server.current_nickname(), + client.current_nickname(), command.tokens[0] ); - Ok(server.send_notice(&command.source, &help)?) + Ok(client + .send_notice(&command.source, &help) + .context(ErrorKind::Connection)?) } } } @@ -298,6 +305,3 @@ impl fmt::Display for ThreadedPlugins { write!(f, "{}", plugin_names.join(", ")) } } - -#[cfg(test)] -mod tests {} diff --git a/src/main.rs b/src/main.rs index 3432e3e..b9a4b8f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,8 @@ extern crate r2d2; #[cfg(feature = "mysql")] extern crate r2d2_diesel; +#[macro_use] +extern crate failure; #[macro_use] extern crate log; @@ -27,9 +29,16 @@ use log::{Level, LevelFilter, Metadata, Record}; use irc::client::reactor::IrcReactor; use glob::glob; -use frippy::plugins; +pub use frippy::plugins::help::Help; +pub use frippy::plugins::url::Url; +pub use frippy::plugins::emoji::Emoji; +pub use frippy::plugins::tell::Tell; +pub use frippy::plugins::currency::Currency; +pub use frippy::plugins::keepnick::KeepNick; +pub use frippy::plugins::factoids::Factoids; + use frippy::Config; -use frippy::error::FrippyError; +use failure::Error; #[cfg(feature = "mysql")] embed_migrations!(); @@ -70,11 +79,14 @@ static LOGGER: Logger = Logger; fn main() { // Print any errors that caused frippy to shut down if let Err(e) = run() { - frippy::utils::log_error(e); + let text = e.causes() + .skip(1) + .fold(format!("{}", e), |acc, err| format!("{}: {}", acc, err)); + error!("{}", text); }; } -fn run() -> Result<(), FrippyError> { +fn run() -> Result<(), Error> { log::set_max_level(if cfg!(debug_assertions) { LevelFilter::Debug } else { @@ -100,7 +112,7 @@ fn run() -> Result<(), FrippyError> { // Without configs the bot would just idle if configs.is_empty() { - return Err(FrippyError::MissingConfig); + bail!("No config file was found"); } // Create an event loop to run the connections on. @@ -119,11 +131,11 @@ fn run() -> Result<(), FrippyError> { } let mut bot = frippy::Bot::new(); - bot.add_plugin(plugins::Help::new()); - bot.add_plugin(plugins::Url::new(1024)); - bot.add_plugin(plugins::Emoji::new()); - bot.add_plugin(plugins::Currency::new()); - bot.add_plugin(plugins::KeepNick::new()); + bot.add_plugin(Help::new()); + bot.add_plugin(Url::new(1024)); + bot.add_plugin(Emoji::new()); + bot.add_plugin(Currency::new()); + bot.add_plugin(KeepNick::new()); #[cfg(feature = "mysql")] { @@ -134,25 +146,24 @@ fn run() -> Result<(), FrippyError> { let manager = ConnectionManager::::new(url.clone()); match r2d2::Pool::builder().build(manager) { - Ok(pool) => match embedded_migrations::run(&*pool.get()?) - { + Ok(pool) => match embedded_migrations::run(&*pool.get()?) { Ok(_) => { let pool = Arc::new(pool); - bot.add_plugin(plugins::Factoids::new(pool.clone())); - bot.add_plugin(plugins::Tell::new(pool.clone())); + bot.add_plugin(Factoids::new(pool.clone())); + bot.add_plugin(Tell::new(pool.clone())); info!("Connected to MySQL server") } Err(e) => { - bot.add_plugin(plugins::Factoids::new(HashMap::new())); - bot.add_plugin(plugins::Tell::new(HashMap::new())); + bot.add_plugin(Factoids::new(HashMap::new())); + bot.add_plugin(Tell::new(HashMap::new())); error!("Failed to run migrations: {}", e); } }, Err(e) => error!("Failed to connect to database: {}", e), } } else { - bot.add_plugin(plugins::Factoids::new(HashMap::new())); - bot.add_plugin(plugins::Tell::new(HashMap::new())); + bot.add_plugin(Factoids::new(HashMap::new())); + bot.add_plugin(Tell::new(HashMap::new())); } } #[cfg(not(feature = "mysql"))] @@ -160,8 +171,8 @@ fn run() -> Result<(), FrippyError> { if mysql_url.is_some() { error!("frippy was not built with the mysql feature") } - bot.add_plugin(plugins::Factoids::new(HashMap::new())); - bot.add_plugin(plugins::Tell::new(HashMap::new())); + bot.add_plugin(Factoids::new(HashMap::new())); + bot.add_plugin(Tell::new(HashMap::new())); } if let Some(disabled_plugins) = disabled_plugins { diff --git a/src/plugin.rs b/src/plugin.rs index f33fa80..e57f072 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -2,16 +2,17 @@ use std::fmt; use irc::client::prelude::*; -use irc::error::IrcError; +use error::FrippyError; /// Describes if a [`Plugin`](trait.Plugin.html) is done working on a /// [`Message`](../../irc/proto/message/struct.Message.html) or if another thread is required. #[derive(Debug)] pub enum ExecutionStatus { - /// The [`Plugin`](trait.Plugin.html) does not need to do any more work on this [`Message`](../../irc/proto/message/struct.Message.html). + /// The [`Plugin`](trait.Plugin.html) does not need to do any more work on this + /// [`Message`](../../irc/proto/message/struct.Message.html). Done, /// An error occured during the execution. - Err(Box), + Err(FrippyError), /// The execution needs to be done by [`execute_threaded()`](trait.Plugin.html#tymethod.execute_threaded). RequiresThread, } @@ -19,15 +20,17 @@ pub enum ExecutionStatus { /// `Plugin` has to be implemented for any struct that should be usable /// as a `Plugin` in frippy. pub trait Plugin: PluginName + Send + Sync + fmt::Debug { - /// Handles messages which are not commands or returns [`RequiresThread`](enum.ExecutionStatus.html#variant.RequiresThread) + /// Handles messages which are not commands or returns + /// [`RequiresThread`](enum.ExecutionStatus.html#variant.RequiresThread) /// if [`execute_threaded()`](trait.Plugin.html#tymethod.execute_threaded) should be used instead. - fn execute(&self, server: &IrcClient, message: &Message) -> ExecutionStatus; + fn execute(&self, client: &IrcClient, message: &Message) -> ExecutionStatus; /// Handles messages which are not commands in a new thread. - fn execute_threaded(&self, server: &IrcClient, message: &Message) -> Result<(), IrcError>; + fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), FrippyError>; /// Handles any command directed at this plugin. - fn command(&self, server: &IrcClient, command: PluginCommand) -> Result<(), IrcError>; - /// Similar to [`command()`](trait.Plugin.html#tymethod.command) but return a String instead of sending messages directly to IRC. - fn evaluate(&self, server: &IrcClient, command: PluginCommand) -> Result; + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError>; + /// Similar to [`command()`](trait.Plugin.html#tymethod.command) but return a String instead of + /// sending messages directly to IRC. + fn evaluate(&self, client: &IrcClient, command: PluginCommand) -> Result; } /// `PluginName` is required by [`Plugin`](trait.Plugin.html). diff --git a/src/plugins/currency.rs b/src/plugins/currency.rs index 958c8e2..53a245c 100644 --- a/src/plugins/currency.rs +++ b/src/plugins/currency.rs @@ -6,7 +6,6 @@ use std::io::Read; use std::num::ParseFloatError; use irc::client::prelude::*; -use irc::error::IrcError; use self::reqwest::Client; use self::reqwest::header::Connection; @@ -14,6 +13,10 @@ use self::serde_json::Value; use plugin::*; +use error::FrippyError; +use error::ErrorKind as FrippyErrorKind; +use failure::ResultExt; + #[derive(PluginName, Default, Debug)] pub struct Currency; @@ -124,20 +127,28 @@ impl Plugin for Currency { ExecutionStatus::Done } - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> { panic!("Currency does not implement the execute function!") } - fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), IrcError> { + fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), FrippyError> { if command.tokens.is_empty() { - return client.send_notice(&command.source, &self.invalid_command(client)); + return Ok(client + .send_notice(&command.source, &self.invalid_command(client)) + .context(FrippyErrorKind::Connection)?); } match command.tokens[0].as_ref() { - "help" => client.send_notice(&command.source, &self.help(client)), + "help" => Ok(client + .send_notice(&command.source, &self.help(client)) + .context(FrippyErrorKind::Connection)?), _ => match self.convert(client, &mut command) { - Ok(msg) => client.send_privmsg(&command.target, &msg), - Err(msg) => client.send_notice(&command.source, &msg), + Ok(msg) => Ok(client + .send_privmsg(&command.target, &msg) + .context(FrippyErrorKind::Connection)?), + Err(msg) => Ok(client + .send_notice(&command.source, &msg) + .context(FrippyErrorKind::Connection)?), }, } } @@ -153,6 +164,3 @@ impl Plugin for Currency { } } } - -#[cfg(test)] -mod tests {} diff --git a/src/plugins/emoji.rs b/src/plugins/emoji.rs index a4276f4..f1d9376 100644 --- a/src/plugins/emoji.rs +++ b/src/plugins/emoji.rs @@ -3,10 +3,14 @@ extern crate unicode_names; use std::fmt; use irc::client::prelude::*; -use irc::error::IrcError; use plugin::*; +use error::FrippyError; +use error::ErrorKind as FrippyErrorKind; +use failure::Fail; +use failure::ResultExt; + struct EmojiHandle { symbol: char, count: i32, @@ -100,21 +104,23 @@ impl Plugin for Emoji { .send_privmsg(message.response_target().unwrap(), &self.emoji(content)) { Ok(_) => ExecutionStatus::Done, - Err(e) => ExecutionStatus::Err(Box::new(e)), + Err(e) => ExecutionStatus::Err(e.context(FrippyErrorKind::Connection).into()), }, _ => ExecutionStatus::Done, } } - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> { panic!("Emoji should not use threading") } - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice( - &command.source, - "This Plugin does not implement any commands.", - ) + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { + Ok(client + .send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) + .context(FrippyErrorKind::Connection)?) } fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result { @@ -126,6 +132,3 @@ impl Plugin for Emoji { } } } - -#[cfg(test)] -mod tests {} diff --git a/src/plugins/factoids/database.rs b/src/plugins/factoids/database.rs index 88aa0fd..b1fe8dd 100644 --- a/src/plugins/factoids/database.rs +++ b/src/plugins/factoids/database.rs @@ -13,13 +13,12 @@ use diesel::mysql::MysqlConnection; use r2d2::Pool; #[cfg(feature = "mysql")] use r2d2_diesel::ConnectionManager; +#[cfg(feature = "mysql")] +use failure::ResultExt; use chrono::NaiveDateTime; -pub enum DbResponse { - Success, - Failed(&'static str), -} +use super::error::*; #[cfg_attr(feature = "mysql", derive(Queryable))] #[derive(Clone, Debug)] @@ -42,15 +41,15 @@ pub struct NewFactoid<'a> { } pub trait Database: Send { - fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse; - fn get_factoid(&self, name: &str, idx: i32) -> Option; - fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse; - fn count_factoids(&self, name: &str) -> Result; + fn insert_factoid(&mut self, factoid: &NewFactoid) -> Result<(), FactoidsError>; + fn get_factoid(&self, name: &str, idx: i32) -> Result; + fn delete_factoid(&mut self, name: &str, idx: i32) -> Result<(), FactoidsError>; + fn count_factoids(&self, name: &str) -> Result; } // HashMap impl Database for HashMap<(String, i32), Factoid> { - fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse { + fn insert_factoid(&mut self, factoid: &NewFactoid) -> Result<(), FactoidsError> { let factoid = Factoid { name: String::from(factoid.name), idx: factoid.idx, @@ -61,23 +60,25 @@ impl Database for HashMap<(String, i32), Factoid> { let name = factoid.name.clone(); match self.insert((name, factoid.idx), factoid) { - None => DbResponse::Success, - Some(_) => DbResponse::Failed("Factoid was overwritten"), + None => Ok(()), + Some(_) => Err(ErrorKind::Duplicate)?, } } - fn get_factoid(&self, name: &str, idx: i32) -> Option { - self.get(&(String::from(name), idx)).cloned() + fn get_factoid(&self, name: &str, idx: i32) -> Result { + Ok(self.get(&(String::from(name), idx)) + .cloned() + .ok_or(ErrorKind::NotFound)?) } - fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse { + fn delete_factoid(&mut self, name: &str, idx: i32) -> Result<(), FactoidsError> { match self.remove(&(String::from(name), idx)) { - Some(_) => DbResponse::Success, - None => DbResponse::Failed("Factoid not found"), + Some(_) => Ok(()), + None => Err(ErrorKind::NotFound)?, } } - fn count_factoids(&self, name: &str) -> Result { + fn count_factoids(&self, name: &str) -> Result { Ok(self.iter().filter(|&(&(ref n, _), _)| n == name).count() as i32) } } @@ -102,38 +103,31 @@ use self::schema::factoids; #[cfg(feature = "mysql")] impl Database for Arc>> { - fn insert_factoid(&mut self, factoid: &NewFactoid) -> DbResponse { + fn insert_factoid(&mut self, factoid: &NewFactoid) -> Result<(), FactoidsError> { use diesel; - let conn = &*self.get().expect("Failed to get connection"); - match diesel::insert_into(factoids::table) + let conn = &*self.get().context(ErrorKind::NoConnection)?; + diesel::insert_into(factoids::table) .values(factoid) .execute(conn) - { - Ok(_) => DbResponse::Success, - Err(e) => { - error!("DB Insertion Error: {}", e); - DbResponse::Failed("Failed to add factoid") - } - } + .context(ErrorKind::MysqlError)?; + + Ok(()) } - fn get_factoid(&self, name: &str, idx: i32) -> Option { - let conn = &*self.get().expect("Failed to get connection"); - match factoids::table.find((name, idx)).first(conn) { - Ok(f) => Some(f), - Err(e) => { - error!("DB Count Error: {}", e); - None - } - } + fn get_factoid(&self, name: &str, idx: i32) -> Result { + let conn = &*self.get().context(ErrorKind::NoConnection)?; + Ok(factoids::table + .find((name, idx)) + .first(conn) + .context(ErrorKind::MysqlError)?) } - fn delete_factoid(&mut self, name: &str, idx: i32) -> DbResponse { + fn delete_factoid(&mut self, name: &str, idx: i32) -> Result<(), FactoidsError> { use diesel; use self::factoids::columns; - let conn = &*self.get().expect("Failed to get connection"); + let conn = &*self.get().context(ErrorKind::NoConnection)?; match diesel::delete( factoids::table .filter(columns::name.eq(name)) @@ -142,22 +136,19 @@ impl Database for Arc>> { { Ok(v) => { if v > 0 { - DbResponse::Success + Ok(()) } else { - DbResponse::Failed("Could not find any factoid with that name") + Err(ErrorKind::NotFound)? } } - Err(e) => { - error!("DB Deletion Error: {}", e); - DbResponse::Failed("Failed to delete factoid") - } + Err(e) => Err(e).context(ErrorKind::MysqlError)?, } } - fn count_factoids(&self, name: &str) -> Result { + fn count_factoids(&self, name: &str) -> Result { use diesel; - let conn = &*self.get().expect("Failed to get connection"); + let conn = &*self.get().context(ErrorKind::NoConnection)?; let count: Result = factoids::table .filter(factoids::columns::name.eq(name)) .count() @@ -166,10 +157,7 @@ impl Database for Arc>> { match count { Ok(c) => Ok(c as i32), Err(diesel::NotFound) => Ok(0), - Err(e) => { - error!("DB Count Error: {}", e); - Err("Database Error") - } + Err(e) => Err(e).context(ErrorKind::MysqlError)?, } } } diff --git a/src/plugins/factoids/mod.rs b/src/plugins/factoids/mod.rs index 806bb7e..2f3690f 100644 --- a/src/plugins/factoids/mod.rs +++ b/src/plugins/factoids/mod.rs @@ -5,21 +5,22 @@ use std::str::FromStr; use std::sync::Mutex; use self::rlua::prelude::*; use irc::client::prelude::*; -use irc::error::IrcError; -use error::FrippyError; -use error::PluginError; -use failure::Fail; use time; use chrono::NaiveDateTime; use plugin::*; pub mod database; -use self::database::{Database, DbResponse}; +use self::database::Database; mod utils; use self::utils::*; +use failure::ResultExt; +use error::ErrorKind as FrippyErrorKind; +use error::FrippyError; +use self::error::*; + static LUA_SANDBOX: &'static str = include_str!("sandbox.lua"); #[derive(PluginName)] @@ -43,8 +44,13 @@ impl Factoids { } } - fn create_factoid(&self, name: &str, content: &str, author: &str) -> Result<&str, FrippyError> { - let count = try_lock!(self.factoids).count_factoids(name).map_err(|e| PluginError::Factoids { error: e.to_owned() })?; + fn create_factoid( + &self, + name: &str, + content: &str, + author: &str, + ) -> Result<&str, FactoidsError> { + let count = try_lock!(self.factoids).count_factoids(name)?; let tm = time::now().to_timespec(); let factoid = database::NewFactoid { @@ -55,15 +61,14 @@ impl Factoids { created: NaiveDateTime::from_timestamp(tm.sec, 0u32), }; - match try_lock!(self.factoids).insert_factoid(&factoid) { - DbResponse::Success => Ok("Successfully added"), - DbResponse::Failed(e) => Err(PluginError::Factoids { error: e.to_owned() })?, - } + Ok(try_lock!(self.factoids) + .insert_factoid(&factoid) + .map(|()| "Successfully added!")?) } - fn add(&self, client: &IrcClient, command: &mut PluginCommand) -> Result<&str, FrippyError> { + fn add(&self, command: &mut PluginCommand) -> Result<&str, FactoidsError> { if command.tokens.len() < 2 { - return Ok(self.invalid_command(client, command).map(|()| "")?); + Err(ErrorKind::InvalidCommand)?; } let name = command.tokens.remove(0); @@ -72,45 +77,41 @@ impl Factoids { Ok(self.create_factoid(&name, &content, &command.source)?) } - fn add_from_url( - &self, - client: &IrcClient, - command: &mut PluginCommand, - ) -> Result<&str, FrippyError> { + fn add_from_url(&self, command: &mut PluginCommand) -> Result<&str, FactoidsError> { if command.tokens.len() < 2 { - return Ok(self.invalid_command(client, command).map(|()| "")?); + Err(ErrorKind::InvalidCommand)?; } let name = command.tokens.remove(0); let url = &command.tokens[0]; - let content = ::utils::download(url, Some(1024))?; + let content = ::utils::download(url, Some(1024)).context(ErrorKind::Download)?; Ok(self.create_factoid(&name, &content, &command.source)?) } - fn remove(&self, client: &IrcClient, command: &mut PluginCommand) -> Result<&str, FrippyError> { + fn remove(&self, command: &mut PluginCommand) -> Result<&str, FactoidsError> { if command.tokens.len() < 1 { - return Ok(self.invalid_command(client, command).map(|()| "")?); + Err(ErrorKind::InvalidCommand)?; } let name = command.tokens.remove(0); - let count = try_lock!(self.factoids).count_factoids(&name).map_err(|e| PluginError::Factoids { error: e.to_owned() } )?; + let count = try_lock!(self.factoids).count_factoids(&name)?; match try_lock!(self.factoids).delete_factoid(&name, count - 1) { - DbResponse::Success => Ok("Successfully removed"), - DbResponse::Failed(e) => Err(PluginError::Factoids { error: e.to_owned() })?, + Ok(()) => Ok("Successfully removed"), + Err(e) => Err(e)?, } } - fn get(&self, client: &IrcClient, command: &PluginCommand) -> Result { + fn get(&self, command: &PluginCommand) -> Result { let (name, idx) = match command.tokens.len() { - 0 => return Ok(self.invalid_command(client, command).map(|()| String::new())?), + 0 => Err(ErrorKind::InvalidCommand)?, 1 => { let name = &command.tokens[0]; - let count = try_lock!(self.factoids).count_factoids(name).map_err(|e| PluginError::Factoids { error: e.to_owned() } )?; + let count = try_lock!(self.factoids).count_factoids(name)?; if count < 1 { - Err(PluginError::Factoids { error: format!("{} does not exist", name) })?; + Err(ErrorKind::NotFound)?; } (name, count - 1) @@ -119,61 +120,55 @@ impl Factoids { let name = &command.tokens[0]; let idx = match i32::from_str(&command.tokens[1]) { Ok(i) => i, - Err(_) => Err(PluginError::Factoids { error: String::from("Invalid index") })?, + Err(_) => Err(ErrorKind::InvalidCommand)?, }; (name, idx) } }; - let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { - Some(v) => v, - None => Err(PluginError::Factoids { error: format!("{}~{} does not exist", name, idx) })?, - }; + let factoid = try_lock!(self.factoids) + .get_factoid(name, idx) + .context(ErrorKind::NotFound)?; let message = factoid.content.replace("\n", "|").replace("\r", ""); Ok(format!("{}: {}", factoid.name, message)) } - fn info(&self, client: &IrcClient, command: &PluginCommand) -> Result { + fn info(&self, command: &PluginCommand) -> Result { match command.tokens.len() { - 0 => Ok(self.invalid_command(client, command).map(|()| String::new())?), + 0 => Err(ErrorKind::InvalidCommand)?, 1 => { let name = &command.tokens[0]; - let count = try_lock!(self.factoids).count_factoids(name).map_err(|e| PluginError::Factoids { error: e.to_owned() } )?; + let count = try_lock!(self.factoids).count_factoids(name)?; Ok(match count { - 0 => Err(PluginError::Factoids { error: format!("{} does not exist", name) })?, + 0 => Err(ErrorKind::NotFound)?, 1 => format!("There is 1 version of {}", name), _ => format!("There are {} versions of {}", count, name), }) } _ => { let name = &command.tokens[0]; - let idx = i32::from_str(&command.tokens[1]).map_err(|_| PluginError::Factoids { error: String::from("Invalid index") })?; - - let factoid = match try_lock!(self.factoids).get_factoid(name, idx) { - Some(v) => v, - None => return Ok(format!("{}~{} does not exist", name, idx)), - }; + let idx = i32::from_str(&command.tokens[1]).context(ErrorKind::InvalidIndex)?; + let factoid = try_lock!(self.factoids).get_factoid(name, idx)?; - Ok(format!("{}: Added by {} at {} UTC", name, factoid.author, factoid.created)) + Ok(format!( + "{}: Added by {} at {} UTC", + name, factoid.author, factoid.created + )) } } } - fn exec( - &self, - client: &IrcClient, - mut command: PluginCommand, - ) -> Result { + fn exec(&self, mut command: PluginCommand) -> Result { if command.tokens.len() < 1 { - Ok(self.invalid_command(client, &command).map(|()| String::new())?) + Err(ErrorKind::InvalidIndex)? } else { let name = command.tokens.remove(0); - let count = try_lock!(self.factoids).count_factoids(&name).map_err(|e| PluginError::Factoids { error: e.to_owned() } )?; - let factoid = try_lock!(self.factoids).get_factoid(&name, count - 1).ok_or(PluginError::Factoids { error: format!("The factoid \"{}\" does not exist", name) })?; + let count = try_lock!(self.factoids).count_factoids(&name)?; + let factoid = try_lock!(self.factoids).get_factoid(&name, count - 1)?; let content = factoid.content; let value = if content.starts_with('>') { @@ -225,10 +220,6 @@ impl Factoids { Ok(output.join("|")) } - - fn invalid_command(&self, client: &IrcClient, command: &PluginCommand) -> Result<(), IrcError> { - client.send_notice(&command.source, "Invalid Command") - } } impl Plugin for Factoids { @@ -243,7 +234,7 @@ impl Plugin for Factoids { } } - fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), FrippyError> { if let Command::PRIVMSG(_, mut content) = message.command.clone() { content.remove(0); @@ -255,18 +246,22 @@ impl Plugin for Factoids { tokens: t, }; - match self.exec(client, c) { - Ok(f) => client.send_privmsg(&message.response_target().unwrap(), &f), - Err(_) => Ok(()), - } + Ok(match self.exec(c) { + Ok(f) => client + .send_privmsg(&message.response_target().unwrap(), &f) + .context(FrippyErrorKind::Connection)?, + Err(_) => (), + }) } else { Ok(()) } } - fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), IrcError> { + fn command(&self, client: &IrcClient, mut command: PluginCommand) -> Result<(), FrippyError> { if command.tokens.is_empty() { - return self.invalid_command(client, &command); + return Ok(client + .send_notice(&command.target, "Invalid command") + .context(FrippyErrorKind::Connection)?); } let target = command.target.clone(); @@ -274,19 +269,27 @@ impl Plugin for Factoids { let sub_command = command.tokens.remove(0); let result = match sub_command.as_ref() { - "add" => self.add(client, &mut command).map(|s| s.to_owned()), - "fromurl" => self.add_from_url(client, &mut command).map(|s| s.to_owned()), - "remove" => self.remove(client, &mut command).map(|s| s.to_owned()), - "get" => self.get(client, &command), - "info" => self.info(client, &command), - "exec" => self.exec(client, command), - _ => self.invalid_command(client, &command).map(|()| String::new()).map_err(|e| e.into()), + "add" => self.add(&mut command).map(|s| s.to_owned()), + "fromurl" => self.add_from_url(&mut command).map(|s| s.to_owned()), + "remove" => self.remove(&mut command).map(|s| s.to_owned()), + "get" => self.get(&command), + "info" => self.info(&command), + "exec" => self.exec(command), + _ => Err(ErrorKind::InvalidCommand.into()), }; Ok(match result { - Ok(v) => client.send_privmsg(&target, &v), - Err(e) => client.send_notice(&source, &e.cause().unwrap().to_string()), - }?) + Ok(v) => client + .send_privmsg(&target, &v) + .context(FrippyErrorKind::Connection)?, + Err(e) => { + let message = e.to_string(); + client + .send_notice(&source, &message) + .context(FrippyErrorKind::Connection)?; + Err(e).context(FrippyErrorKind::Factoids)? + } + }) } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { @@ -301,3 +304,39 @@ impl fmt::Debug for Factoids { write!(f, "Factoids {{ ... }}") } } + +pub mod error { + #[derive(Copy, Clone, Eq, PartialEq, Debug, Fail, Error)] + #[error = "FactoidsError"] + pub enum ErrorKind { + /// Invalid command error + #[fail(display = "Invalid Command")] + InvalidCommand, + + /// Invalid index error + #[fail(display = "Invalid index")] + InvalidIndex, + + /// Download error + #[fail(display = "Download failed")] + Download, + + /// Duplicate error + #[fail(display = "Entry already exists")] + Duplicate, + + /// Not found error + #[fail(display = "Factoid was not found")] + NotFound, + + /// MySQL error + #[cfg(feature = "mysql")] + #[fail(display = "Failed to execute MySQL Query")] + MysqlError, + + /// No connection error + #[cfg(feature = "mysql")] + #[fail(display = "No connection to the database")] + NoConnection, + } +} diff --git a/src/plugins/factoids/utils.rs b/src/plugins/factoids/utils.rs index 009b46b..70ac8a7 100644 --- a/src/plugins/factoids/utils.rs +++ b/src/plugins/factoids/utils.rs @@ -11,7 +11,11 @@ use self::LuaError::RuntimeError; pub fn download(_: &Lua, url: String) -> Result { match utils::download(&url, Some(1024)) { Ok(v) => Ok(v), - Err(e) => Err(RuntimeError(format!("Failed to download {} - {}", url, e.to_string()))), + Err(e) => Err(RuntimeError(format!( + "Failed to download {} - {}", + url, + e.to_string() + ))), } } diff --git a/src/plugins/help.rs b/src/plugins/help.rs index 4dd93d7..7e3658d 100644 --- a/src/plugins/help.rs +++ b/src/plugins/help.rs @@ -1,8 +1,11 @@ use irc::client::prelude::*; -use irc::error::IrcError; use plugin::*; +use error::FrippyError; +use error::ErrorKind as FrippyErrorKind; +use failure::ResultExt; + #[derive(PluginName, Default, Debug)] pub struct Help; @@ -17,18 +20,17 @@ impl Plugin for Help { ExecutionStatus::Done } - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> { panic!("Help should not use threading") } - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice(&command.source, "Help has not been added yet.") + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { + Ok(client + .send_notice(&command.source, "Help has not been added yet.") + .context(FrippyErrorKind::Connection)?) } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { Err(String::from("Help has not been added yet.")) } } - -#[cfg(test)] -mod tests {} diff --git a/src/plugins/keepnick.rs b/src/plugins/keepnick.rs index bdabd90..58ac167 100644 --- a/src/plugins/keepnick.rs +++ b/src/plugins/keepnick.rs @@ -1,8 +1,11 @@ use irc::client::prelude::*; -use irc::error::IrcError; use plugin::*; +use error::FrippyError; +use error::ErrorKind as FrippyErrorKind; +use failure::ResultExt; + #[derive(PluginName, Default, Debug)] pub struct KeepNick; @@ -25,9 +28,12 @@ impl KeepNick { if client_nick != cfg_nick { info!("Trying to switch nick from {} to {}", client_nick, cfg_nick); - match client.send(Command::NICK(cfg_nick)) { + match client + .send(Command::NICK(cfg_nick)) + .context(FrippyErrorKind::Connection) + { Ok(_) => ExecutionStatus::Done, - Err(e) => ExecutionStatus::Err(Box::new(e)), + Err(e) => ExecutionStatus::Err(e.into()), } } else { ExecutionStatus::Done @@ -45,21 +51,20 @@ impl Plugin for KeepNick { } } - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> { panic!("Tell should not use threading") } - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice( - &command.source, - "This Plugin does not implement any commands.", - ) + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { + Ok(client + .send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) + .context(FrippyErrorKind::Connection)?) } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { Err(String::from("This Plugin does not implement any commands.")) } } - -#[cfg(test)] -mod tests {} diff --git a/src/plugins/mod.rs b/src/plugins/mod.rs index 5b32efd..9a3ba2f 100644 --- a/src/plugins/mod.rs +++ b/src/plugins/mod.rs @@ -1,17 +1,8 @@ //! Collection of plugins included -mod help; -mod url; -mod emoji; -mod tell; -mod currency; -mod factoids; -mod keepnick; - -pub use self::help::Help; -pub use self::url::Url; -pub use self::emoji::Emoji; -pub use self::tell::Tell; -pub use self::currency::Currency; -pub use self::factoids::Factoids; -pub use self::factoids::database; -pub use self::keepnick::KeepNick; +pub mod help; +pub mod url; +pub mod emoji; +pub mod tell; +pub mod currency; +pub mod factoids; +pub mod keepnick; diff --git a/src/plugins/tell/mod.rs b/src/plugins/tell/mod.rs index 3a8feeb..7052b3e 100644 --- a/src/plugins/tell/mod.rs +++ b/src/plugins/tell/mod.rs @@ -1,5 +1,4 @@ use irc::client::prelude::*; -use irc::error::IrcError; use std::time::Duration; use std::sync::Mutex; @@ -10,6 +9,11 @@ use humantime::format_duration; use plugin::*; +use error::FrippyError; +use error::ErrorKind as FrippyErrorKind; +use failure::Fail; +use failure::ResultExt; + pub mod database; use self::database::{Database, DbResponse}; @@ -84,7 +88,7 @@ impl Tell { tell.sender, human_dur, tell.message ), ) { - return ExecutionStatus::Err(Box::new(e)); + return ExecutionStatus::Err(e.context(FrippyErrorKind::Connection).into()); } debug!( "Sent {:?} from {:?} to {:?}", @@ -123,22 +127,30 @@ impl Plugin for Tell { } } - fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), IrcError> { + fn execute_threaded(&self, _: &IrcClient, _: &Message) -> Result<(), FrippyError> { panic!("Tell should not use threading") } - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { if command.tokens.is_empty() { - return client.send_notice(&command.source, &self.invalid_command(client)); + return Ok(client + .send_notice(&command.source, &self.invalid_command(client)) + .context(FrippyErrorKind::Connection)?); } - match command.tokens[0].as_ref() { - "help" => client.send_notice(&command.source, &self.help(client)), + Ok(match command.tokens[0].as_ref() { + "help" => client + .send_notice(&command.source, &self.help(client)) + .context(FrippyErrorKind::Connection), _ => match self.tell_command(client, &command) { - Ok(msg) => client.send_notice(&command.source, msg), - Err(msg) => client.send_notice(&command.source, &msg), + Ok(msg) => client + .send_notice(&command.source, msg) + .context(FrippyErrorKind::Connection), + Err(msg) => client + .send_notice(&command.source, &msg) + .context(FrippyErrorKind::Connection), }, - } + }?) } fn evaluate(&self, _: &IrcClient, _: PluginCommand) -> Result { diff --git a/src/plugins/url.rs b/src/plugins/url.rs index 6f00466..fa4c6f4 100644 --- a/src/plugins/url.rs +++ b/src/plugins/url.rs @@ -2,7 +2,6 @@ extern crate regex; extern crate select; use irc::client::prelude::*; -use irc::error::IrcError; use self::regex::Regex; @@ -11,9 +10,12 @@ use self::select::predicate::Name; use plugin::*; use utils; + +use self::error::*; use error::FrippyError; -use error::UrlError; +use error::ErrorKind as FrippyErrorKind; use failure::Fail; +use failure::ResultExt; lazy_static! { static ref RE: Regex = Regex::new(r"(^|\s)(https?://\S+)").unwrap(); @@ -48,11 +50,11 @@ impl Url { Some(title_text) } - fn url(&self, text: &str) -> Result { - let url = self.grep_url(text).ok_or(UrlError::MissingUrl)?; - let body = utils::download(&url, Some(self.max_kib))?; + fn url(&self, text: &str) -> Result { + let url = self.grep_url(text).ok_or(ErrorKind::MissingUrl)?; + let body = utils::download(&url, Some(self.max_kib)).context(ErrorKind::Download)?; - Ok(self.get_title(&body).ok_or(UrlError::MissingTitle)?) + Ok(self.get_title(&body).ok_or(ErrorKind::MissingTitle)?) } } @@ -68,27 +70,48 @@ impl Plugin for Url { } } - fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), IrcError> { - match message.command { + fn execute_threaded(&self, client: &IrcClient, message: &Message) -> Result<(), FrippyError> { + Ok(match message.command { Command::PRIVMSG(_, ref content) => match self.url(content) { - Ok(title) => client.send_privmsg(message.response_target().unwrap(), &title), - Err(e) => Ok(utils::log_error(e)), + Ok(title) => client + .send_privmsg(message.response_target().unwrap(), &title) + .context(FrippyErrorKind::Connection)?, + Err(e) => Err(e).context(FrippyErrorKind::Url)?, }, - _ => Ok(()), - } + _ => (), + }) } - fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), IrcError> { - client.send_notice( - &command.source, - "This Plugin does not implement any commands.", - ) + fn command(&self, client: &IrcClient, command: PluginCommand) -> Result<(), FrippyError> { + Ok(client + .send_notice( + &command.source, + "This Plugin does not implement any commands.", + ) + .context(FrippyErrorKind::Connection)?) } fn evaluate(&self, _: &IrcClient, command: PluginCommand) -> Result { - self.url(&command.tokens[0]).map_err(|e| e.cause().unwrap().to_string()) + self.url(&command.tokens[0]) + .map_err(|e| e.cause().unwrap().to_string()) } } -#[cfg(test)] -mod tests {} +pub mod error { + /// A URL plugin error + #[derive(Copy, Clone, Eq, PartialEq, Debug, Fail, Error)] + #[error = "UrlError"] + pub enum ErrorKind { + /// A download error + #[fail(display = "A download error occured")] + Download, + + /// Missing URL error + #[fail(display = "No URL was found")] + MissingUrl, + + /// Missing title error + #[fail(display = "No title was found")] + MissingTitle, + } +} diff --git a/src/utils.rs b/src/utils.rs index cf91b37..06156be 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -4,15 +4,19 @@ use std::io::{self, Read}; use reqwest::Client; use reqwest::header::Connection; -use failure::Fail; -use error::FrippyError; +use failure::ResultExt; +use self::error::{DownloadError, ErrorKind}; /// Downloads the file and converts it to a String. /// Any invalid bytes are converted to a replacement character. /// /// The error indicated either a failed download or that the DownloadLimit was reached -pub fn download(url: &str, max_kib: Option) -> Result { - let mut response = Client::new().get(url).header(Connection::close()).send()?; +pub fn download(url: &str, max_kib: Option) -> Result { + let mut response = Client::new() + .get(url) + .header(Connection::close()) + .send() + .context(ErrorKind::Connection)?; // 100 kibibyte buffer let mut buf = [0; 100 * 1024]; @@ -25,7 +29,7 @@ pub fn download(url: &str, max_kib: Option) -> Result break, Ok(len) => len, Err(ref e) if e.kind() == io::ErrorKind::Interrupted => continue, - Err(e) => Err(e)?, + Err(e) => Err(e).context(ErrorKind::Read)?, }; bytes.extend_from_slice(&buf); @@ -34,7 +38,7 @@ pub fn download(url: &str, max_kib: Option) -> Result max_kib * 1024 { - Err(FrippyError::DownloadLimit { limit: max_kib })?; + Err(ErrorKind::DownloadLimit)?; } } } @@ -42,12 +46,20 @@ pub fn download(url: &str, max_kib: Option) -> Result