aboutsummaryrefslogtreecommitdiff
path: root/src/game.rs
diff options
context:
space:
mode:
authorNathan Perry <avaglir@gmail.com>2019-03-08 18:10:59 -0500
committerNathan Perry <avaglir@gmail.com>2019-03-08 18:10:59 -0500
commit108db50a7374a785f309e049b287e9b47532f566 (patch)
treed25be7765dcf79e259fd431a0bf3bc0979da0ce1 /src/game.rs
parent86025df1f6d814c98a14211ceb4da6cf6de915c7 (diff)
working version
Diffstat (limited to 'src/game.rs')
-rw-r--r--src/game.rs327
1 files changed, 94 insertions, 233 deletions
diff --git a/src/game.rs b/src/game.rs
index 200ef42..4fd7eca 100644
--- a/src/game.rs
+++ b/src/game.rs
@@ -1,5 +1,5 @@
use failure::err_msg;
-use oauth2::Config;
+use fnv::FnvHashMap;
use serenity::{
framework::standard::{
Args,
@@ -20,34 +20,11 @@ use crate::{
};
lazy_static! {
- static ref SHEETS_CLIENT_ID: String = must_env_lookup("SHEETS_CLIENT_ID");
- static ref SHEETS_SECRET: String = must_env_lookup("SHEETS_CLIENT_SECRET");
+ static ref SHEETS_API_KEY: String = must_env_lookup("SHEETS_API_KEY");
static ref SPREADSHEET_ID: String = must_env_lookup("SPREADSHEET_ID");
}
-#[cfg(debug_assertions)] const REDIRECT_URL: &'static str = "http://localhost:8080";
-#[cfg(not(debug_assertions))] const REDIRECT_URL: &'static str = "https://somali-derp.com/thulani_redirect";
-
pub fn register(s: StandardFramework) -> StandardFramework {
- use std::{
- thread,
- time::Duration,
- };
-
- thread::spawn(|| {
- thread::sleep(Duration::from_secs(10));
-
- loop {
- debug!("starting token maintenance");
- if let Err(e) = maintain_token() {
- error!("maintaining google access token: {}", e);
- }
- debug!("token maintenance complete");
-
- thread::sleep(Duration::from_secs(60 * 2));
- }
- });
-
s.command("game", |c| c
.known_as("gaem")
.desc("what game should we play?")
@@ -55,9 +32,32 @@ pub fn register(s: StandardFramework) -> StandardFramework {
)
}
-fn game(_ctx: &mut Context, msg: &Message, _args: Args) -> Result<()> {
- use std::collections::HashSet;
- use fnv::FnvHashMap;
+lazy_static! {
+ static ref USER_MAP: FnvHashMap<UserId, String> = {
+ use serde_json::Value;
+ use std::str;
+ let map_bytes = include_bytes!("../user_id_mapping.json");
+
+ let v: Value = serde_json::from_str(str::from_utf8(&map_bytes[..]).unwrap()).unwrap();
+ match v {
+ Value::Object(m) => {
+ m.iter()
+ .map(|(k, v)| match v {
+ Value::Number(n) => (UserId(n.as_u64().unwrap()), k.clone()),
+ _ => panic!("non-number in user id mapping"),
+ })
+ .collect()
+ },
+ _ => panic!("couldn't read user id mapping"),
+ }
+ };
+}
+
+fn game(_ctx: &mut Context, msg: &Message, mut args: Args) -> Result<()> {
+ use fnv::{
+ FnvHashMap,
+ FnvHashSet,
+ };
let guild = msg.channel_id.to_channel()?
.guild()
@@ -79,39 +79,20 @@ fn game(_ctx: &mut Context, msg: &Message, _args: Args) -> Result<()> {
.collect::<FnvHashMap<_, _>>();
let channel = pairs.get(&msg.author.id).unwrap_or(&*VOICE_CHANNEL_ID);
- let mut users = HashSet::new();
- pairs.iter().for_each(|(uid, cid)| {
- if cid == channel {
- users.insert(*uid);
- }
- });
-
-// if users.len() < 2 {
-// info!("too few users in voice chat to make game comparison");
-// send(msg.channel_id, "yer too lonely", msg.tts)?;
-// return Ok(());
-// }
-
- lazy_static! {
- static ref USER_MAP: FnvHashMap<UserId, String> = {
- use serde_json::Value;
- use std::str;
- let map_bytes = include_bytes!("../user_id_mapping.json");
+ let users = pairs
+ .iter()
+ .filter_map(|(uid, cid)| {
+ if cid == channel {
+ USER_MAP.get(uid).map(|s| s.to_lowercase())
+ } else { None }
+ })
+ .collect::<FnvHashSet<_>>();
- let v: Value = serde_json::from_str(str::from_utf8(&map_bytes[..]).unwrap()).unwrap();
- match v {
- Value::Object(m) => {
- m.iter()
- .map(|(k, v)| match v {
- Value::Number(n) => (UserId(n.as_u64().unwrap()), k.clone()),
- _ => panic!("non-number in user id mapping"),
- })
- .collect()
- },
- _ => panic!("couldn't read user id mapping"),
- }
- };
+ if users.len() < 2 {
+ info!("too few known users in voice chat to make game comparison");
+ send(msg.channel_id, "yer too lonely", msg.tts)?;
+ return Ok(());
}
use url::Url;
@@ -121,13 +102,11 @@ fn game(_ctx: &mut Context, msg: &Message, _args: Args) -> Result<()> {
u.query_pairs_mut()
.append_pair("ranges", "a1:p")
- .append_pair("valueRenderOption", "UNFORMATTED_VALUE")
- .append_pair("majorDimension", "COLUMNS");
-
- let oauth_token = get_oauth_token()?;
+ .append_pair("valueRenderOption", "FORMATTED_VALUE")
+ .append_pair("majorDimension", "COLUMNS")
+ .append_pair("key", &*SHEETS_API_KEY);
- let mut req = reqwest::Request::new(reqwest::Method::GET, u);
- req.headers_mut().insert("Authorization", reqwest::header::HeaderValue::from_str(&format!("Bearer {}", oauth_token))?);
+ let req = reqwest::Request::new(reqwest::Method::GET, u);
let client = reqwest::Client::new();
@@ -136,7 +115,7 @@ fn game(_ctx: &mut Context, msg: &Message, _args: Args) -> Result<()> {
#[derive(Deserialize)]
struct Resp {
#[serde(rename = "valueRanges")]
- value_ranges: Inner,
+ value_ranges: Vec<Inner>,
}
#[derive(Deserialize)]
@@ -144,187 +123,69 @@ fn game(_ctx: &mut Context, msg: &Message, _args: Args) -> Result<()> {
values: Vec<Vec<String>>,
}
- let data = resp.json::<Resp>()?.value_ranges.values;
-
- use itertools::Itertools;
- info!("data: {}", data.iter().map(|row| row.iter().join(" ")).join("\n"));
-
- Ok(())
-}
-
-lazy_static! {
- static ref CONFIG: Config = Config::new(
- SHEETS_CLIENT_ID.as_ref(),
- SHEETS_SECRET.as_ref(),
- "https://accounts.google.com/o/oauth2/v2/auth",
- "https://www.googleapis.com/oauth2/v4/token",
- )
- .add_scope("https://www.googleapis.com/auth/spreadsheets.readonly")
- .set_redirect_url(REDIRECT_URL);
-}
-
-fn get_oauth_token() -> Result<String> {
- use std::{
- net::TcpListener,
- };
-
- use url::Url;
- use chrono;
-
- use diesel::{
- NotFound,
- result::Error as DieselError,
- };
-
- use crate::db;
-
-
- lazy_static! {
- static ref AUTH_URL: Url = {
- let mut u = CONFIG.authorize_url();
- u.query_pairs_mut()
- .append_pair("access_type", "offline");
-
- u
- };
- }
-
- #[cfg(debug_assertions)]
- const PORT: u16 = 8080;
-
- #[cfg(not(debug_assertions))]
- const PORT: u16 = 8981;
+ let data = &resp.json::<Resp>()?.value_ranges[0].values;
- let conn = db::connection()?;
+ let user_indexes = (0..data.len())
+ .filter_map(|i| {
+ let user = data[i][0].to_lowercase();
- let token = db::GoogleOAuthToken::latest(&conn);
+ if users.contains(&user) {
+ Some((user, i))
+ } else { None }
+ })
+ .collect::<FnvHashMap<_, _>>();
- match token {
- Ok(t) => return Ok(t.token),
- Err(e) => {
- if let Some(NotFound) = e.downcast_ref::<DieselError>() {
- info!("no token found in database");
- } else {
- return Err(e);
- }
- }
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ enum GameStatus {
+ Installed,
+ NotInstalled,
+ NotOwned,
+ Unknown,
}
- eprintln!("please navigate to {} in your browser", AUTH_URL.as_str());
-
- let listener = TcpListener::bind(&format!("127.0.0.1:{}", PORT))?;
-
- const ATTEMPTS: usize = 10;
- let code = listener.incoming()
- .filter_map(|s| s.ok())
- .map(|mut stream| {
- use std::io::{
- BufReader,
- BufRead,
- Write,
- };
-
- let mut request_line = String::new();
-
- {
- let mut reader = BufReader::new(&stream);
- reader.read_line(&mut request_line).ok()?;
- }
-
- let url =
- Url::parse(&format!("http://localhost{}", request_line.split_whitespace().nth(1)?)).ok()?;
+ let user_games = user_indexes
+ .iter()
+ .map(|(user, col)| {
+ let empty_hash_set: FnvHashSet<_> = vec![].into_iter().collect();
- let code = url.query_pairs()
- .find(|(key, _)| key == "code")
- .map(|(_, code)| code.into_owned());
+ let mut game_map = vec! [
+ (GameStatus::Installed, empty_hash_set.clone()),
+ (GameStatus::NotInstalled, empty_hash_set.clone()),
+ (GameStatus::NotOwned, empty_hash_set.clone()),
+ (GameStatus::Unknown, empty_hash_set),
+ ]
+ .into_iter()
+ .collect::<FnvHashMap<_, _>>();
- let message = "all set";
- let resp = format!(
- "HTTP/1.1 20 OK\r\ncontent-length: {}\r\n\r\n{}",
- message.len(),
- message,
- );
+ (1..data[*col].len())
+ .for_each(|i| {
+ let status = &data[*col][i];
- stream.write_all(resp.as_bytes()).ok()?;
+ let game = &data[0][i];
+ if status.starts_with("y") {
+ game_map.get_mut(&GameStatus::Installed).unwrap().insert(game);
+ } else if status.starts_with("n/i") {
+ game_map.get_mut(&GameStatus::NotInstalled).unwrap().insert(game);
+ } else if status.starts_with("n") {
+ game_map.get_mut(&GameStatus::NotOwned).unwrap().insert(game);
+ } else {
+ game_map.get_mut(&GameStatus::Unknown).unwrap().insert(game);
+ }
+ });
- code
+ (user, game_map)
})
- .take(ATTEMPTS)
- .find(|x| !x.is_none());
-
- let code = match code {
- None => return Err(err_msg(format!("couldn't acquire oauth code from google after {} attempts", ATTEMPTS))),
- Some(c) => c.unwrap(),
- };
+ .collect::<FnvHashMap<_, _>>();
- let token = CONFIG.exchange_code(code)?;
+ let mut games_in_common = user_games.values().nth(0).unwrap()[&GameStatus::Installed].clone();
- if token.expires_in.is_none() || token.refresh_token.is_none() {
- return Err(err_msg("token expiration or refresh token was missing"));
+ for (_user, game_map) in user_games.iter() {
+ games_in_common = games_in_common.intersection(&game_map[&GameStatus::Installed]).cloned().collect();
}
- let now = chrono::Utc::now().naive_utc();
- let new_expiration = token.expires_in
- .map(|exp_sec| now + chrono::Duration::seconds(exp_sec.into()))
- .unwrap();
-
- let result = db::GoogleOAuthToken::create(&conn, token.access_token, token.refresh_token.unwrap(), new_expiration)?;
+ use itertools::Itertools;
+ let games_formatted = games_in_common.iter().join("\n");
- Ok(result.token)
+ send(msg.channel_id, &format!("games in common:\n{}", games_formatted), msg.tts)
}
-fn maintain_token() -> Result<()> {
- use diesel::{
- Connection,
- result::Error as DieselError,
- NotFound,
- };
-
- use chrono;
-
- use crate::db;
-
- let conn = db::connection()?;
-
- conn.transaction(|| {
- let latest_token = db::GoogleOAuthToken::latest(&conn);
- let latest_token = match latest_token {
- Ok(t) => t,
- Err(e) => {
- if let Some(NotFound) = e.downcast_ref::<DieselError>() {
- info!("maintaining google auth: no token to refresh found in database");
- return Ok(());
- }
-
- return Err(e);
- }
- };
-
- let now = chrono::Utc::now().naive_utc();
- let diff = latest_token.expiration - now;
-
- if diff > chrono::Duration::minutes(10) {
- info!("token has {} minutes remaining: not refreshing", diff.num_minutes());
- return Ok(());
- }
-
- let new_token = CONFIG.exchange_refresh_token(latest_token.refresh_token)?;
-
- if new_token.refresh_token.is_none() || new_token.expires_in.is_none() {
- return Err(err_msg("refreshed token missing refresh token or expiration"));
- }
-
- info!("received new token from google");
-
- let new_expiration = new_token.expires_in
- .map(|exp_sec| now + chrono::Duration::seconds(exp_sec.into()))
- .unwrap();
-
- db::GoogleOAuthToken::create(&conn,
- new_token.access_token,
- new_token.refresh_token.unwrap(),
- new_expiration)?;
-
- Ok(())
- })
-}