Files

216 lines
5.3 KiB
JavaScript

import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { isCancellation } from './http';
export const BITCOIN_DEFAULT_INTERVAL = 30000;
export const BITCOIN_INTERVAL_OPTIONS = [
{ value: 30000, label: 'Every 30 seconds' },
{ value: 60000, label: 'Every 60 seconds' },
{ value: 300000, label: 'Every 5 minutes' },
];
export const BITCOIN_DEFAULT_PROVIDER = 'coingecko';
export const BITCOIN_PROVIDERS = [
{
id: 'coingecko',
label: 'CoinGecko',
url: 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd&include_24hr_change=true',
parse(data) {
return {
price: Number.parseFloat(data.bitcoin.usd),
changePercent: Number.parseFloat(data.bitcoin.usd_24h_change),
};
},
},
{
id: 'binance',
label: 'Binance',
url: 'https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT',
parse(data) {
return {
price: Number.parseFloat(data.lastPrice),
changePercent: Number.parseFloat(data.priceChangePercent),
};
},
},
{
id: 'bitstamp',
label: 'Bitstamp',
url: 'https://cors.5apps.com/?uri=https://www.bitstamp.net/api/v2/ticker/btcusd/',
parse(data) {
return {
price: Number.parseFloat(data.last),
changePercent: Number.parseFloat(data.percent_change_24),
};
},
},
];
function providerFor(id) {
return BITCOIN_PROVIDERS.find((provider) => provider.id === id);
}
export default class BitcoinService extends Service {
@service storage;
@service http;
@service pageLifecycle;
removeRestoreHandler = null;
@tracked enabled = false;
@tracked interval = BITCOIN_DEFAULT_INTERVAL;
@tracked provider = BITCOIN_DEFAULT_PROVIDER;
@tracked price = null;
@tracked changePercent = null;
@tracked loading = false;
@tracked error = null;
intervalId = null;
fetching = false;
ready = null;
constructor() {
super(...arguments);
this.ready = this.load();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
// A bfcache restore may have cancelled the last price fetch, leaving a stale
// error behind. Fetch again immediately instead of waiting for the interval.
handleRestore() {
if (this.enabled) {
this.fetchPrice();
}
}
async load() {
try {
const integration = await this.storage.get('integrations', 'bitcoin');
if (integration?.status === 'active') {
this.enabled = true;
this.interval = integration.interval ?? BITCOIN_DEFAULT_INTERVAL;
// Records stored before providers existed used the Bitstamp source.
this.provider = integration.provider ?? 'bitstamp';
this.startPolling();
}
} catch (err) {
console.error('Error loading bitcoin integration:', err);
}
}
async enable(
interval = BITCOIN_DEFAULT_INTERVAL,
provider = BITCOIN_DEFAULT_PROVIDER
) {
await this.ready;
this.interval = interval;
this.provider = provider;
this.enabled = true;
await this.persist({ interval, provider });
this.startPolling();
}
async update(interval = this.interval, provider = this.provider) {
await this.ready;
this.interval = interval;
this.provider = provider;
this.enabled = true;
await this.persist({ interval, provider });
this.startPolling();
}
async persist({ interval, provider }) {
const existing = await this.storage.get('integrations', 'bitcoin');
await this.storage.set('integrations', 'bitcoin', {
...existing,
type: 'bitcoin',
status: 'active',
interval,
provider,
currency: existing?.currency ?? 'usd',
createdAt: existing?.createdAt ?? Date.now(),
});
}
async disable() {
await this.ready;
this.stopPolling();
this.enabled = false;
this.interval = BITCOIN_DEFAULT_INTERVAL;
this.provider = BITCOIN_DEFAULT_PROVIDER;
this.price = null;
this.changePercent = null;
this.error = null;
await this.storage.remove('integrations', 'bitcoin');
}
async fetchPrice() {
if (this.fetching) {
return;
}
const provider = providerFor(this.provider);
if (!provider) {
this.error = 'Unable to load the bitcoin price';
return;
}
this.fetching = true;
this.loading = true;
try {
const data = await this.http.requestJson(provider.url);
const { price, changePercent } = provider.parse(data);
this.price = price;
this.changePercent = changePercent;
this.error = null;
} catch (err) {
// A navigation or bfcache freeze cancels the request; keep the last
// known price and do not report a failure.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error('Error fetching bitcoin price:', err);
this.error = 'Unable to load the bitcoin price';
} finally {
this.fetching = false;
this.loading = false;
}
}
startPolling() {
this.stopPolling();
this.fetchPrice();
this.intervalId = setInterval(() => {
this.fetchPrice();
}, this.interval);
}
stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
}