Skip to content

Commit

Permalink
create sample from tab on rust side
Browse files Browse the repository at this point in the history
  • Loading branch information
shonya3 committed Aug 24, 2023
1 parent 87babe2 commit e301fec
Show file tree
Hide file tree
Showing 21 changed files with 18,457 additions and 548 deletions.
34 changes: 34 additions & 0 deletions divi/src/league.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ pub enum League {
SSFHCAncestor,
}

impl League {
pub fn is_trade(&self) -> bool {
match self {
League::Standard => true,
League::Hardcore => true,
League::SSFStandard => false,
League::SSFHardcore => false,
League::Ancestor => true,
League::HardcoreAncestor => true,
League::SSFAncestor => false,
League::SSFHCAncestor => false,
}
}
}

impl Default for League {
fn default() -> Self {
League::Ancestor
Expand Down Expand Up @@ -64,3 +79,22 @@ impl Default for TradeLeague {
TradeLeague::Ancestor
}
}

impl TryFrom<League> for TradeLeague {
type Error = &'static str;

fn try_from(value: League) -> Result<Self, Self::Error> {
let msg = "This league is not a trade league";

match value {
League::Standard => Ok(TradeLeague::Standard),
League::Hardcore => Ok(TradeLeague::Hardcore),
League::SSFStandard => Err(msg),
League::SSFHardcore => Err(msg),
League::Ancestor => Ok(TradeLeague::Ancestor),
League::HardcoreAncestor => Ok(TradeLeague::HardcoreAncestor),
League::SSFAncestor => Err(msg),
League::SSFHCAncestor => Err(msg),
}
}
}
2 changes: 1 addition & 1 deletion divi/src/sample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ pub enum SampleData {
#[cfg(test)]
mod tests {

use crate::{league::TradeLeague, IsCard};
use crate::IsCard;

use super::*;

Expand Down
87 changes: 68 additions & 19 deletions packages/app/src-tauri/lib/src/poe/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
pub mod auth;
pub mod error;
pub mod types;

use divi::league::League;
use divi::{
league::{League, TradeLeague},
prices::Prices,
sample::{DivinationCardsSample, SampleData},
};

use keyring::Entry;
use reqwest::Client;
use serde::Deserialize;
use serde_json::Value;
use tauri::{command, AppHandle};
use tauri::{command, AppHandle, State, Window};
use tokio::sync::Mutex;

use crate::{
error::Error,
event::{Event, ToastVariant},
js_result::JSResult,
prices::AppCardPrices,
};

use self::types::TabWithItems;

pub const API_URL: &'static str = "https://api.pathofexile.com";
const PROVIDER_LABEL: &'static str = "poe";
Expand All @@ -15,27 +31,54 @@ const AUTH_URL: &'static str = "https://www.pathofexile.com/oauth/authorize";
const TOKEN_URL: &'static str = "https://www.pathofexile.com/oauth/token";

#[command]
pub async fn stashes(league: League, app_handle: AppHandle) -> Value {
let val =
PoeProvider::stashes(league, app_handle.config().package.version.clone().unwrap()).await;
// dbg!(&val);
val
}

#[command]
pub async fn stash(
pub async fn sample_from_tab(
league: League,
stash_id: String,
substash_id: Option<String>,
app_handle: AppHandle,
) -> Value {
PoeProvider::stash(
league,
state: State<'_, Mutex<AppCardPrices>>,
window: Window,
) -> Result<JSResult<DivinationCardsSample>, ()> {
let tab = PoeProvider::tab_with_items(
&league,
stash_id,
substash_id,
app_handle.config().package.version.clone().unwrap(),
)
.await
.await;

let tab = match tab {
Ok(tab) => tab,
Err(err) => {
Event::Toast {
variant: ToastVariant::Danger,
message: format!("{}", err),
}
.emit(&window);
return Err(());
}
};

let prices = match TradeLeague::try_from(league) {
Ok(league) => {
let mut guard = state.lock().await;
guard.get_price(&league, &window).await
}
Err(_) => Prices::default(),
};

Ok(JSResult::from(DivinationCardsSample::create(
SampleData::from(tab),
Some(prices),
)))
}

#[command]
pub async fn stashes(league: League, app_handle: AppHandle) -> Value {
let val =
PoeProvider::stashes(league, app_handle.config().package.version.clone().unwrap()).await;
// dbg!(&val);
val
}

#[derive(Default)]
Expand All @@ -50,12 +93,12 @@ impl PoeProvider {
format!("{}_access_token", { PROVIDER_LABEL })
}

async fn stash(
league: League,
async fn tab_with_items(
league: &League,
stash_id: String,
substash_id: Option<String>,
version: String,
) -> Value {
) -> Result<TabWithItems, Error> {
let url = match substash_id {
Some(substash_id) => {
format!("{}/stash/{}/{}/{}", API_URL, league, stash_id, substash_id)
Expand Down Expand Up @@ -89,7 +132,13 @@ impl PoeProvider {
limit_account_header, limit_account_state_header
);

response.json::<Value>().await.unwrap()
#[derive(Deserialize)]
struct ResponseShape {
stash: TabWithItems,
}

let response_shape = response.json::<ResponseShape>().await?;
Ok(response_shape.stash)
}

async fn stashes(league: League, version: String) -> Value {
Expand Down
78 changes: 78 additions & 0 deletions packages/app/src-tauri/lib/src/poe/types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use divi::{
consts::{CARDS, LEGACY_CARDS},
sample::{CardNameAmount, SampleData},
IsCard,
};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum StashType {
PremiumStash,
CurrencyStash,
MapStash,
QuadStash,
FragmentStash,
EssenceStash,
Folder,
NormalStash,
DivinationCardStash,
#[serde(other)]
Other,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Item {
pub base_type: String,
pub stack_size: Option<i32>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TabNoItems {}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TabWithItems {
pub items: Vec<Item>,
#[serde(rename = "type")]
pub kind: Option<StashType>,
}

impl IsCard for Item {
fn is_card(&self) -> bool {
CARDS.contains(&self.base_type.as_str())
}

fn is_legacy_card(&self) -> bool {
LEGACY_CARDS.contains(&self.base_type.as_str())
}
}

impl From<TabWithItems> for SampleData {
fn from(tab: TabWithItems) -> Self {
let cards: Vec<CardNameAmount> = tab
.items
.into_iter()
.filter(|item| item.is_card())
.map(|item| CardNameAmount {
name: item.base_type,
amount: item.stack_size.unwrap_or_default(),
})
.collect();

SampleData::CardNameAmountList(cards)
}
}

#[cfg(test)]
mod tests {
use std::fs::read_to_string;

use super::TabWithItems;

#[test]
fn ser_stash() {
let json = read_to_string("stash.json").unwrap();
let stash: TabWithItems = serde_json::from_str(&json).unwrap();
dbg!(stash);
}
}
2 changes: 1 addition & 1 deletion packages/app/src-tauri/ser.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/app/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ async fn main() {
commands::open_url,
poe::auth::poe_auth,
poe::auth::poe_logout,
poe::stash,
poe::stashes,
poe::sample_from_tab
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
Loading

0 comments on commit e301fec

Please sign in to comment.