Skip to content

Commit 555457b

Browse files
committed
Add api struct, progress on functions and such
1 parent 96b8422 commit 555457b

File tree

6 files changed

+117
-27
lines changed

6 files changed

+117
-27
lines changed

src/dev_commands.rs

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use crate::utils::agencies::Agency;
2+
use crate::utils::tracking;
13
use crate::{Context, Error};
24
use poise::CreateReply;
35
use serenity::builder::CreateEmbed;
@@ -34,11 +36,7 @@ pub async fn stop(ctx: Context<'_>) -> Result<(), Error> {
3436
ctx.msg.react(ctx, '👋').await?;
3537
}
3638
let author_name = ctx.author().name.clone();
37-
span!(
38-
Level::INFO,
39-
"{} is shutting down all shards",
40-
author_name
41-
);
39+
span!(Level::INFO, "{} is shutting down all shards", author_name);
4240
let shard_manager = ctx.framework().shard_manager().clone();
4341
shard_manager.shutdown_all().await;
4442
Ok(())
@@ -118,12 +116,25 @@ pub async fn addagency(_ctx: Context<'_>) -> Result<(), Error> {
118116
hide_in_help,
119117
subcommands("list")
120118
)]
121-
pub async fn track(_ctx: Context<'_>) -> Result<(), Error> {
119+
pub async fn track(
120+
ctx: Context<'_>,
121+
agency: String,
122+
line: String,
123+
station: String,
124+
) -> Result<(), Error> {
125+
// query database with passed in arguments
126+
122127
Ok(())
123128
}
124129

125130
/// Shows list of tracked lines or subway stations
126-
#[poise::command(prefix_command, track_edits, owners_only, hide_in_help)]
131+
#[poise::command(prefix_command, track_edits, owners_only, hide_in_help)] // TODO: Once done, add back slash command support
127132
pub async fn list(_ctx: Context<'_>) -> Result<(), Error> {
128133
Ok(())
129134
}
135+
136+
/// Gets the ETA of the next train at a specified station
137+
#[poise::command(prefix_command, track_edits, owners_only, hide_in_help)] // TODO: Once done, add back slash command support
138+
pub async fn eta(_ctx: Context<'_>) -> Result<(), Error> {
139+
Ok(())
140+
}

src/main.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use poise::serenity_prelude as serenity;
2-
use utils::tracking::Tracking;
32
use std::{sync::Arc, time::Duration};
43
use tracing::{span, Level};
54
use utils::database::Client;
5+
use utils::tracking::Tracking;
66
mod utils;
77
use crate::utils::config::get as get_config;
88
use crate::utils::config::Config;
@@ -20,7 +20,7 @@ type Context<'a> = poise::Context<'a, Data, Error>;
2020
pub struct Data {
2121
pub db: database::Client,
2222
pub config: Config,
23-
pub trackings: Vec<Tracking>
23+
pub trackings: Vec<Tracking>,
2424
}
2525

2626
async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
@@ -112,7 +112,7 @@ async fn main() {
112112
Ok(Data {
113113
db: Client::new().await.expect("Failed to connect to database"),
114114
config,
115-
trackings: Vec::new() // TODO replace
115+
trackings: Vec::new(), // TODO replace
116116
})
117117
})
118118
})

src/utils/api.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
use crate::serenity::{Command, User, UserId};
2+
use crate::utils::database::Client;
3+
use crate::Error;
4+
use sqlx::Row;
5+
6+
pub struct Api {
7+
client: Client,
8+
}
9+
10+
impl Api {
11+
pub fn new(client: Client) -> Self {
12+
Self { client }
13+
}
14+
15+
pub async fn build_url(&self, agency_id: i32) -> Result<String, Error> {
16+
let result = sqlx::query!(
17+
r#"SELECT api_url FROM agencies WHERE id = $1"#,
18+
agency_id
19+
)
20+
.fetch_one(&self.client.pool)
21+
.await?;
22+
let full_url = format!("https://{}", result.api_url);
23+
Ok(full_url)
24+
}
25+
26+
/// Checks the line cache for the line, if not then it will try to get it from the api
27+
pub async fn try_line(&self, agency_id: i32, line: String) -> Result<String, Error> {
28+
let line_id = sqlx::query!(r#"SELECT line_id FROM agency_line_cache WHERE agency_id = $1 AND LOWER(line_name) = LOWER($2)"#, agency_id, line.to_string()).fetch_one(&self.client.pool)
29+
.await?;
30+
let api_url = &self.build_url(agency_id);
31+
Ok(line_id.line_id) // TODO: This better work
32+
}
33+
34+
/// Attempts to get station data from the given agency, line and station name
35+
pub async fn try_station(
36+
&self,
37+
agency_id: i32,
38+
line: String,
39+
station: String,
40+
) -> Result<(), Error> {
41+
let line = self
42+
.try_line(agency_id, line)
43+
.await
44+
.expect("Could not find any matching lines");
45+
// TODO: api call to get station, return results
46+
Ok(())
47+
}
48+
}

src/utils/database.rs

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
use crate::get_secrets;
2-
use crate::serenity::{User, UserId, Command};
2+
use crate::serenity::{Command, User, UserId};
33
use crate::Error;
44
use sqlx::postgres::PgPool;
5+
use sqlx::types::chrono::{DateTime, Utc};
56
use tracing::{span, Level};
67

78
pub struct Client {
89
pub pool: PgPool,
910
}
1011

12+
pub struct DbPassenger {
13+
pub id: i64,
14+
pub created_at: Option<DateTime<Utc>> // This should not be optional but whatever i guess
15+
}
16+
1117
impl Client {
1218
pub async fn new() -> Result<Self, sqlx::Error> {
1319
let secrets = get_secrets();
@@ -27,7 +33,7 @@ impl Client {
2733
}
2834

2935
/// Adds a user, a.k.a 'Passenger' to the database
30-
pub async fn add_user(self: Self, user: User) -> Result<UserId, Error> {
36+
pub async fn add_user(&self, user: User) -> Result<UserId, Error> {
3137
sqlx::query!(
3238
r#"INSERT INTO users(id) VALUES ( $1 )"#,
3339
user.id.get() as i32
@@ -39,25 +45,50 @@ impl Client {
3945
}
4046

4147
/// Gets a user, a.k.a 'Passenger' from the database
42-
pub async fn get_user(self: Self, user: User) -> Result<UserId, Error> {
43-
sqlx::query!(r#"SELECT * FROM users WHERE id = $1"#, user.id.get() as i32)
48+
pub async fn get_user(&self, user: User) -> Result<DbPassenger, Error> {
49+
let result = sqlx::query_as!(DbPassenger, r#"SELECT * FROM users WHERE id = $1"#, user.id.get() as i32)
4450
.fetch_one(&self.pool)
4551
.await?;
4652

47-
Ok(user.id)
53+
Ok(result)
4854
}
4955

50-
pub async fn command_exists(&self, command: Command) -> Result<bool, Error>{
51-
sqlx::query!(r#"SELECT * FROM command_stats WHERE command_name = $1"#, command.name)
56+
/// Gets an Agency ID by checking short or long name
57+
pub async fn get_agency(&self, agency: String) -> Result<i32, Error> {
58+
let result = sqlx::query!(
59+
r#"SELECT id FROM agencies WHERE LOWER(short_name) = LOWER($1) OR LOWER(long_name) = LOWER($1)"#,
60+
agency
61+
)
5262
.fetch_one(&self.pool)
5363
.await?;
64+
Ok(result.id)
65+
}
66+
67+
pub async fn command_exists(&self, command: Command) -> Result<bool, Error> {
68+
sqlx::query!(
69+
r#"SELECT * FROM command_stats WHERE command_name = $1"#,
70+
command.name
71+
)
72+
.fetch_one(&self.pool)
73+
.await?;
5474
Ok(true)
5575
}
5676

5777
/// Adds an use to a specified command
5878
pub async fn update_command(&self, command: Command) -> Result<(), Error> {
59-
self.command_exists(command.clone()).await.expect(&format!("Command '{}' does not exist", command.name.to_string()));
79+
self.command_exists(command.clone()).await.expect(&format!(
80+
"Command '{}' does not exist",
81+
command.name.to_string()
82+
));
6083
sqlx::query!(r#"UPDATE command_stats SET command_count = (command_count + 1) WHERE command_name = $1"#, command.clone().name).execute(&self.pool).await?;
6184
Ok(())
6285
}
6386
}
87+
88+
impl Clone for Client {
89+
fn clone(&self) -> Self {
90+
Self {
91+
pool: self.pool.clone(),
92+
}
93+
}
94+
}

src/utils/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
pub mod agencies;
2+
pub mod api;
23
pub mod config;
34
pub mod database;
45
pub mod secrets;
5-
pub mod tracking;
6+
pub mod tracking;

src/utils/tracking.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
11
use crate::Error;
22
use sqlx::types::chrono::{DateTime, Utc};
33

4-
pub struct Tracking{
4+
pub struct Tracking {
55
pub id: i32,
66
pub owner_id: i64,
77
pub agency_id: i32,
88
pub line_id: i32,
99
pub stop_id: Option<i32>,
1010
pub started_at: DateTime<Utc>,
11-
pub updated_at: DateTime<Utc>
11+
pub updated_at: DateTime<Utc>,
1212
}
1313

14-
impl Tracking{
15-
fn new(){
14+
// With this, we will probably use tokio wakers
1615

17-
}
16+
impl Tracking {
17+
fn new() {}
1818

1919
/// Gets an update for this tracking, by making the necessary API calls and sending a
20-
fn get_update() -> Result<(), Error>{
21-
20+
fn get_update() -> Result<(), Error> {
2221
Ok(())
2322
}
24-
}
23+
}

0 commit comments

Comments
 (0)