psn_rs 0.1.0

Interact with PlayStation Network API in full Rust!
Documentation
use std::ops::Deref;

use crate::constants::TROPHIES_ENDPOINT_URL;
use crate::models::trophies::{TitleTrophies, TrophyTitle, TrophyTitles};
use crate::models::user::AccountID;
use crate::{PSNApiResult, PSNClient};

use super::pagination_params::PaginationParams;

impl PSNClient {
    /// Get all trophy titles associated with account identified by `account_id` parameter.
    pub async fn get_all_trophies_titles(
        &self,
        account_id: &AccountID,
    ) -> PSNApiResult<Vec<TrophyTitle>> {
        let mut trophies: Vec<TrophyTitle> = Vec::new();

        let mut pagination_params = PaginationParams::default();

        loop {
            let response = self
                .get_authenticated(
                    format!(
                        "{TROPHIES_ENDPOINT_URL}/users/{}/trophyTitles",
                        account_id.deref()
                    ),
                    None,
                    Some(pagination_params.to_params()),
                )
                .await?
                .error_for_status()?
                .json::<TrophyTitles>()
                .await?;

            log::trace!(
                "got response: next_offset={:?} - total_items_count={}",
                response.next_offset,
                response.total_item_count
            );

            trophies.extend(response.trophy_titles);

            match response.next_offset {
                Some(next_offset) => pagination_params.set_offset(next_offset),
                None => {
                    log::trace!("got all trophies, breaking");
                    break;
                }
            }
        }

        Ok(trophies)
    }

    /// Get all trophies earned for a specific title associated with account identified by `account_id` parameter.
    pub async fn get_trophies_earned_for_title(
        &self,
        account_id: &AccountID,
        title_id: &str,
        trophy_group_id: &str,
        ps5: bool,
    ) -> PSNApiResult<TitleTrophies> {
        let np_service_name = if ps5 { "trophy2" } else { "trophy" };
        let response = self
                .get_authenticated(
                    format!(
                        "{TROPHIES_ENDPOINT_URL}/users/{}/npCommunicationIds/{title_id}/trophyGroups/{trophy_group_id}/trophies?npServiceName={np_service_name}",
                        account_id.deref(),
                    ),
                    None,
                    Some(())
                )
                .await?
                .error_for_status()?
                .json::<TitleTrophies>()
                .await?;

        Ok(response)
    }
}