Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improves Ability to Debug Status #236

Merged
merged 1 commit into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions src/lib/alarms/access_token.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import {gStore} from '../storage/store';
import {StorageKey} from '../storage/keys';

interface AccessToken {
export interface AccessToken {
token: string;
steam_id?: string | null;
updated_at: number;
}

export async function getAccessToken(): Promise<string | null> {
export async function getAccessToken(): Promise<AccessToken> {
// Do we have a fresh local copy?
const tokenData = await gStore.getWithStorage<AccessToken>(chrome.storage.local, StorageKey.ACCESS_TOKEN);
if (tokenData?.token && tokenData.updated_at > Date.now() - 30 * 60 * 1000) {
// Token refreshed within the last 30 min, we can re-use
return tokenData.token;
return tokenData;
}

// Need to fetch a new one
Expand All @@ -23,25 +24,35 @@ export async function getAccessToken(): Promise<string | null> {

const webAPITokenMatch = /data-loyalty_webapi_token="&quot;([a-zA-Z0-9_.-]+)&quot;"/.exec(body);
if (!webAPITokenMatch || webAPITokenMatch.length === 0) {
console.error('failed to parse web api token');
return null;
throw new Error('failed to parse web api token');
}

const token = webAPITokenMatch[1];
const steamID = extractSteamID(body);

try {
await saveAccessToken(token);
await saveAccessToken(token, steamID);
} catch (e) {
console.error('failed ot save access token to storage', e);
}

return token;
return {token, steam_id: steamID, updated_at: Date.now()};
}

function extractSteamID(body: string): string | null {
const steamIDMatch = /g_steamID = "(\d+?)"/.exec(body);
if (!steamIDMatch || steamIDMatch.length === 0) {
return null;
}

return steamIDMatch[1];
}

export function saveAccessToken(token: string): Promise<void> {
export function saveAccessToken(token: string, steamID: string | null): Promise<void> {
// Explicitly use local storage to prevent issues with sync storage quota or connectivity issues
return gStore.setWithStorage(chrome.storage.local, StorageKey.ACCESS_TOKEN, {
token,
steam_id: steamID,
updated_at: Date.now(),
} as AccessToken);
}
Expand Down
43 changes: 40 additions & 3 deletions src/lib/alarms/csfloat_trade_pings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {pingTradeHistory} from './trade_history';
import {pingCancelTrades, pingSentTradeOffers} from './trade_offer';
import {HasPermissions} from '../bridge/handlers/has_permissions';
import {PingExtensionStatus} from '../bridge/handlers/ping_extension_status';
import {AccessToken, getAccessToken} from './access_token';

export const PING_CSFLOAT_TRADE_STATUS_ALARM_NAME = 'ping_csfloat_trade_status_alarm';

Expand Down Expand Up @@ -37,26 +38,62 @@ export async function pingTradeStatus() {
return;
}

if (pendingTrades.length === 0) {
// No active trades, return early
return;
let access: AccessToken | null = null;

try {
access = await getAccessToken();
} catch (e) {
console.error('failed to fetch access token', e);
}

let errors;

if (pendingTrades.length > 0) {
errors = await pingUpdates(pendingTrades);
}

// Ping status of ext + permissions
try {
await PingExtensionStatus.handleRequest(
{
access_token_steam_id: access?.steam_id,
history_error: errors?.history_error,
trade_offer_error: errors?.trade_offer_error,
},
{}
);
} catch (e) {
console.error('failed to ping extension status to csfloat', e);
}
}

interface UpdateErrors {
history_error?: string;
trade_offer_error?: string;
}

async function pingUpdates(pendingTrades: Trade[]): Promise<UpdateErrors> {
const errors: UpdateErrors = {};

try {
await pingTradeHistory(pendingTrades);
} catch (e) {
console.error('failed to ping trade history', e);
errors.history_error = (e as any).toString();
}

try {
await pingSentTradeOffers(pendingTrades);
} catch (e) {
console.error('failed to ping sent trade offer state', e);
errors.trade_offer_error = (e as any).toString();
}

try {
await pingCancelTrades(pendingTrades);
} catch (e) {
console.error('failed to ping cancel ping trade offers', e);
}

return errors;
}
4 changes: 2 additions & 2 deletions src/lib/alarms/trade_history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ interface TradeHistoryAPIResponse {
}

async function getTradeHistoryFromAPI(): Promise<TradeHistoryStatus[]> {
const accessToken = await getAccessToken();
const access = await getAccessToken();

// This only works if they have granted permission for https://api.steampowered.com
const resp = await fetch(
`https://api.steampowered.com/IEconService/GetTradeHistory/v1/?access_token=${accessToken}&max_trades=200`,
`https://api.steampowered.com/IEconService/GetTradeHistory/v1/?access_token=${access.token}&max_trades=200`,
{
credentials: 'include',
}
Expand Down
8 changes: 4 additions & 4 deletions src/lib/alarms/trade_offer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,10 @@ function offerStateMapper(e: TradeOffersAPIOffer): OfferStatus {
}

async function getSentTradeOffersFromAPI(): Promise<OfferStatus[]> {
const accessToken = await getAccessToken();
const access = await getAccessToken();

const resp = await fetch(
`https://api.steampowered.com/IEconService/GetTradeOffers/v1/?access_token=${accessToken}&get_sent_offers=true`,
`https://api.steampowered.com/IEconService/GetTradeOffers/v1/?access_token=${access.token}&get_sent_offers=true`,
{
credentials: 'include',
}
Expand All @@ -191,10 +191,10 @@ async function getSentTradeOffersFromAPI(): Promise<OfferStatus[]> {
}

async function getSentAndReceivedTradeOffersFromAPI(): Promise<{received: OfferStatus[]; sent: OfferStatus[]}> {
const accessToken = await getAccessToken();
const access = await getAccessToken();

const resp = await fetch(
`https://api.steampowered.com/IEconService/GetTradeOffers/v1/?access_token=${accessToken}&get_received_offers=true&get_sent_offers=true`,
`https://api.steampowered.com/IEconService/GetTradeOffers/v1/?access_token=${access.token}&get_received_offers=true&get_sent_offers=true`,
{
credentials: 'include',
}
Expand Down
9 changes: 8 additions & 1 deletion src/lib/bridge/handlers/ping_extension_status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {environment} from '../../../environment';
import {HasPermissions} from './has_permissions';
import {ExtensionVersion} from './extension_version';

export interface PingExtensionStatusRequest {}
export interface PingExtensionStatusRequest {
access_token_steam_id?: string | null;
history_error?: string | null;
trade_offer_error?: string | null;
}

export interface PingExtensionStatusResponse {}

Expand Down Expand Up @@ -39,6 +43,9 @@ export const PingExtensionStatus = new SimpleHandler<PingExtensionStatusRequest,
steam_community_permission: steamCommunityPermissions.granted,
steam_powered_permission: steamPoweredPermissions.granted,
version: versionResp.version,
access_token_steam_id: req.access_token_steam_id || '',
history_error: req.history_error || '',
trade_offer_error: req.trade_offer_error || '',
}),
});

Expand Down
Loading