Files
dashtab/app/services/notifications.js

366 lines
9.8 KiB
JavaScript

import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { HttpError, isCancellation } from './http';
import { authorizationHeader, unreadCountUrl } from '../config/feedbin';
import {
GITHUB_ACCEPT,
GITHUB_NOTIFICATIONS_MAX_PAGES,
authorizationHeader as githubAuthorizationHeader,
nextLink,
notificationsUrl,
} from '../config/github';
import {
GITEA_ACCEPT,
authorizationHeader as giteaAuthorizationHeader,
notificationsCountUrl,
unreadCountFromResponse,
} from '../config/gitea';
import {
HomeAssistantAuthError,
HomeAssistantConnectionError,
} from './home-assistant';
export const NOTIFICATIONS_DEFAULT_INTERVAL = 60000;
async function fetchDiscourseNotifications(integration, http) {
const data = await http.requestJson(`${integration.url}/notifications.json`, {
headers: {
'User-Api-Key': integration.apiKey,
'User-Api-Client-Id': integration.clientId,
},
});
const notifications = (data.notifications ?? []).map((notification) => ({
id: notification.id,
title:
notification.data?.topic_title ??
notification.data?.badge_name ??
'Notification',
read: Boolean(notification.read),
createdAt: notification.created_at,
topicId: notification.topic_id,
}));
return {
unreadCount: notifications.filter((notification) => !notification.read)
.length,
notifications,
};
}
// Feedbin's unread endpoint returns entry ids only, and potentially all of
// them. Requesting a single unread entry instead lets us read the total from
// the `X-Feedbin-Record-Count` response header, so the badge stays cheap.
async function fetchFeedbinNotifications(integration, http) {
const response = await http.request(unreadCountUrl(integration.url), {
headers: {
Authorization: authorizationHeader(integration.token),
Accept: 'application/json',
},
});
const header = response.headers.get('X-Feedbin-Record-Count');
const count = Number.parseInt(header ?? '0', 10);
return {
unreadCount: Number.isNaN(count) ? 0 : count,
notifications: [],
};
}
// GitHub's notifications endpoint returns unread threads only by default.
// GitHub no longer guarantees a `rel="last"` Link, so the count comes from
// walking the unread list via `rel="next"` and summing the threads. Most
// accounts fit in a single page.
async function fetchGithubNotifications(integration, http) {
const headers = {
Authorization: githubAuthorizationHeader(integration.token),
Accept: GITHUB_ACCEPT,
};
let url = notificationsUrl(integration.url);
let unreadCount = 0;
const seen = new Set();
while (url && !seen.has(url) && seen.size < GITHUB_NOTIFICATIONS_MAX_PAGES) {
seen.add(url);
const response = await http.request(url, { headers });
const data = await response.json();
if (Array.isArray(data)) {
unreadCount += data.filter((thread) => thread?.unread !== false).length;
}
url = nextLink(response.headers.get('Link'));
}
return { unreadCount, notifications: [] };
}
// Gitea exposes a dedicated unread count endpoint, so the badge costs a single
// small request rather than downloading the notification list.
async function fetchGiteaNotifications(integration, http) {
const data = await http.requestJson(notificationsCountUrl(integration.url), {
headers: {
Authorization: giteaAuthorizationHeader(integration.token),
Accept: GITEA_ACCEPT,
},
});
return {
unreadCount: unreadCountFromResponse(data),
notifications: [],
};
}
// Home Assistant exposes persistent notifications and repair issues over its
// WebSocket API, and pending updates as `update` entities. The `home-assistant`
// service does all of that over a short-lived socket and returns a summed
// count, so the adapter is a thin pass-through.
async function fetchHomeAssistantNotifications(
integration,
http,
homeAssistant
) {
const { unreadCount } = await homeAssistant.fetchSummary(integration);
return {
unreadCount,
notifications: [],
};
}
const ADAPTERS = {
discourse: fetchDiscourseNotifications,
feedbin: fetchFeedbinNotifications,
github: fetchGithubNotifications,
gitea: fetchGiteaNotifications,
homeassistant: fetchHomeAssistantNotifications,
};
// Per-integration wording for classified failures; anything not listed falls
// back to the generic forum wording.
const FORUM_LABELS = {
github: 'GitHub',
gitea: 'Gitea',
feedbin: 'Feedbin',
homeassistant: 'Home Assistant',
};
const UNAUTHORIZED_MESSAGES = {
github: 'Update GitHub token',
gitea: 'Update Gitea token',
feedbin: 'Update Feedbin credentials',
homeassistant: 'Update Home Assistant token',
};
const UNREACHABLE_MESSAGES = {
github: 'GitHub blocked — enable CORS or open the GitHub host',
gitea: 'Gitea blocked — enable CORS on the instance or open it',
feedbin: 'Feedbin blocked — enable CORS or open feedbin.com',
homeassistant: 'Home Assistant blocked — check the URL or open it',
};
function defaultState(type) {
return {
status: ADAPTERS[type] ? 'loading' : 'ready',
unreadCount: 0,
items: [],
};
}
// Polls connected sites for unread notifications and keeps the resulting state
// keyed by site id. Sites themselves (labels, links, icons, grouping) are owned
// by the `sites` service; this service only layers notification data on top.
export default class NotificationsService extends Service {
@service sites;
@service http;
@service homeAssistant;
@service pageLifecycle;
@tracked states = {};
intervalId = null;
fetching = false;
ready = null;
removeRestoreHandler = null;
constructor() {
super(...arguments);
this.ready = this.setup();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
async setup() {
await this.sites.ready;
if (this.sites.all.some((site) => this.isPollable(site))) {
this.startPolling();
}
}
// After a bfcache restore the pollers are stale and any request that was in
// flight when the tab was navigated away from can have left a site stuck in
// its error state. Clear those and fetch immediately instead of waiting for
// the next interval.
async handleRestore() {
const pollable = this.sites.all.filter((site) => this.isPollable(site));
if (pollable.length === 0) {
return;
}
for (const site of pollable) {
if (this.states[site.id]?.status === 'error') {
this.setState(site.id, {
status: 'loading',
error: null,
errorType: null,
});
}
}
await this.fetchAll();
}
isPollable(site) {
return Boolean(ADAPTERS[site.type]);
}
stateFor(site) {
return this.states[site.id] ?? defaultState(site.type);
}
setState(id, changes) {
const current = this.states[id] ?? {
status: 'loading',
unreadCount: 0,
items: [],
};
this.states = { ...this.states, [id]: { ...current, ...changes } };
}
async fetchAll() {
if (this.fetching) {
return;
}
this.fetching = true;
try {
await Promise.all(
this.sites.all
.filter((site) => this.isPollable(site))
.map((site) => this.fetchSite(site))
);
} finally {
this.fetching = false;
}
}
async fetchSite(site) {
const adapter = ADAPTERS[site.type];
if (!adapter) {
return;
}
try {
const result = await adapter(
this.sites.integrationFor(site.id),
this.http,
this.homeAssistant
);
this.setState(site.id, {
status: 'ready',
error: null,
errorType: null,
unreadCount: result.unreadCount,
items: result.notifications,
});
} catch (err) {
// A navigation or bfcache freeze cancels the request; that is not a
// failure and must not paint the tile as errored.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error(`Error fetching ${site.type} notifications:`, err);
this.setState(site.id, {
status: 'error',
...this.classifyError(err, site),
});
}
}
classifyError(err, site) {
const type = site?.type;
if (err instanceof HomeAssistantAuthError) {
return {
errorType: 'unauthorized',
error: UNAUTHORIZED_MESSAGES[type] ?? 'Update Home Assistant token',
};
}
if (err instanceof HomeAssistantConnectionError) {
return {
errorType: 'unreachable',
error: UNREACHABLE_MESSAGES[type] ?? err.message,
};
}
if (err instanceof HttpError) {
if (err.errorType === 'not_logged_in') {
return {
errorType: 'unauthorized',
error: 'No access token — reconnect this forum',
};
}
if (err.errorType === 'invalid_access') {
return {
errorType: 'unauthorized',
error: 'Access was rejected — reconnect this forum',
};
}
if (err.status === 401 || err.status === 403) {
return {
errorType: 'unauthorized',
error: UNAUTHORIZED_MESSAGES[type] ?? 'Reconnect this forum',
};
}
return {
errorType: 'http',
error: `${FORUM_LABELS[type] ?? 'Forum'} returned ${err.status}`,
};
}
return {
errorType: 'unreachable',
error:
UNREACHABLE_MESSAGES[type] ??
'Notifications blocked — enable CORS on the forum or open it',
};
}
startPolling() {
this.stopPolling();
this.fetchAll();
this.intervalId = setInterval(() => {
this.fetchAll();
}, NOTIFICATIONS_DEFAULT_INTERVAL);
}
stopPolling() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
}