Add GitHub integration

This commit is contained in:
raucao committed 2026-10-05 12:15:15 +02:00
1 parent 2ca2bfc5d6
commit 41bfb7ebbb
21 files changed
+1059 -49

No files matched your search

@@ -24,6 +24,10 @@ export default class SettingsIntegrationsAvatar extends Component {
return safeColor(this.siteIcon?.themeColor);
}
get iconUrlThemeColor() {
return safeColor(this.integration?.themeColor);
}
<template>
{{#if this.siteIcon}}
<span
@@ -40,6 +44,7 @@ export default class SettingsIntegrationsAvatar extends Component {
{{else if @integration.iconUrl}}
<span
class="icon-edge flex size-10 flex-none items-center justify-center overflow-hidden rounded-lg"
{{setStyle "background-color" this.iconUrlThemeColor}}
>
<img
src={{@integration.iconUrl}}
@@ -0,0 +1,222 @@
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import {
GITHUB_DEFAULT_URL,
GITHUB_ACCEPT,
authorizationHeader,
normalizeGithubUrl,
notificationsUrl,
} from '../../../config/github';
export default class SettingsIntegrationsGithubForm extends Component {
@service http;
@service notifications;
@service sites;
@service storage;
@tracked urlDraft = null;
@tracked token = '';
@tracked error = null;
@tracked submitting = false;
get integration() {
return this.args.props?.integration;
}
get isEdit() {
return this.args.props?.mode === 'edit';
}
get url() {
return this.urlDraft ?? this.integration?.url ?? GITHUB_DEFAULT_URL;
}
get defaultUrl() {
return GITHUB_DEFAULT_URL;
}
get title() {
return this.isEdit ? 'Edit GitHub' : 'Add GitHub Integration';
}
get submitLabel() {
return this.isEdit ? 'Save' : 'Connect';
}
@action
updateUrl(event) {
this.urlDraft = event.target.value;
this.error = null;
}
@action
updateToken(event) {
this.token = event.target.value;
this.error = null;
}
@action
async handleSubmit(event) {
event.preventDefault();
this.error = null;
const instanceUrl = normalizeGithubUrl(this.url);
if (!instanceUrl) {
this.error = 'Please enter a valid GitHub URL';
return;
}
// On edit a blank token keeps the stored one, so users can switch between
// github.com and an Enterprise host without re-entering the token.
const token = this.token.trim() || this.integration?.token;
if (!token) {
this.error = 'Please enter a personal access token';
return;
}
this.submitting = true;
try {
// The notifications endpoint is both a token check and a scope check:
// an unauthorized token fails with 401, a token without the
// notifications permission fails with 403.
await this.http.request(notificationsUrl(instanceUrl), {
headers: {
Authorization: authorizationHeader(token),
Accept: GITHUB_ACCEPT,
},
});
} catch (err) {
this.error = this.classifyError(err);
return;
} finally {
this.submitting = false;
}
// Only the credential fields are persisted; the edit row also carries
// display-only fields (avatar, labels) that must not be stored.
await this.storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: instanceUrl,
token,
createdAt: this.integration?.createdAt ?? Date.now(),
});
await this.sites.reload();
this.notifications.startPolling();
this.args.close?.();
}
classifyError(err) {
if (err?.status === 401) {
return 'Invalid personal access token';
}
if (err?.status === 403) {
return 'Use a classic token with the notifications scope';
}
if (err?.name === 'NetworkError') {
return 'Unable to reach GitHub. Check your connection.';
}
return 'Unable to verify your GitHub token';
}
<template>
<div class="p-6">
<h3
id="modal-title"
class="text-base font-semibold leading-6 text-gray-900"
>{{this.title}}</h3>
<div class="mt-2">
<p class="text-sm text-gray-500">
Connect GitHub to see your unread notification count on the dashboard.
</p>
</div>
<form {{on "submit" this.handleSubmit}} class="mt-5">
<div class="space-y-5">
<div>
<label
for="github-url"
class="block text-sm font-medium leading-6 text-gray-900"
>
Server URL
</label>
<div class="mt-2">
<input
type="text"
inputmode="url"
id="github-url"
name="url"
value={{this.url}}
{{on "input" this.updateUrl}}
placeholder={{this.defaultUrl}}
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Leave as-is unless you use GitHub Enterprise Server.
</p>
</div>
<div>
<label
for="github-token"
class="block text-sm font-medium leading-6 text-gray-900"
>
Personal access token
</label>
<div class="mt-2">
<input
type="password"
id="github-token"
name="token"
autocomplete="off"
value={{this.token}}
{{on "input" this.updateToken}}
placeholder={{if this.isEdit "Leave blank to keep current" ""}}
class="block w-full rounded-md border-0 px-3 py-2 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-indigo-600"
/>
</div>
<p class="mt-2 text-sm text-gray-500">
Use a
<a
href="https://github.com/settings/tokens/new"
target="_blank"
rel="noopener noreferrer"
class="text-indigo-600 hover:text-indigo-500"
>classic personal access token</a>
with the "notifications" scope.
</p>
</div>
{{#if this.error}}
<p class="text-sm text-red-600">{{this.error}}</p>
{{/if}}
</div>
<div class="mt-5 sm:mt-6 flex gap-3">
<button
type="submit"
disabled={{this.submitting}}
class="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:opacity-50"
>
{{this.submitLabel}}
</button>
<button
type="button"
{{on "click" @close}}
class="inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
>
Cancel
</button>
</div>
</form>
</div>
</template>
}
+75
View File
@@ -0,0 +1,75 @@
export const GITHUB_DEFAULT_URL = 'https://github.com';
// The bundled icon is an inverted, transparent GitHub mark (a white circle
// with the cat punched out), so it is rendered on a very dark grey backdrop.
export const GITHUB_ICON_URL = '/img/icons/github-inverted.png';
export const GITHUB_ICON_BACKGROUND = '#1f2937';
export const GITHUB_ACCEPT = 'application/vnd.github+json';
// Normalizes the user-supplied instance URL to a bare origin. GitHub.com and
// self-hosted GitHub Enterprise Server instances are both accepted.
export function normalizeGithubUrl(input) {
let value = (input ?? '').trim();
if (!value || /\s/.test(value)) {
return null;
}
if (!/^https?:\/\//i.test(value)) {
value = `https://${value}`;
}
try {
return new URL(value).origin;
} catch {
return null;
}
}
function isDotComHost(hostname) {
return hostname === 'github.com' || hostname === 'www.github.com';
}
export function isGithubDotCom(instanceUrl) {
const origin = normalizeGithubUrl(instanceUrl);
return origin ? isDotComHost(new URL(origin).hostname) : false;
}
// GitHub.com serves the REST API from a dedicated host; GitHub Enterprise
// Server exposes it under `/api/v3` on the instance itself.
export function apiBaseUrl(instanceUrl = GITHUB_DEFAULT_URL) {
const origin = normalizeGithubUrl(instanceUrl) ?? GITHUB_DEFAULT_URL;
const { hostname } = new URL(origin);
return isDotComHost(hostname) ? 'https://api.github.com' : `${origin}/api/v3`;
}
// The notifications endpoint returns unread threads only by default, so
// `per_page=1` lets us read the total from the Link header instead of
// downloading every notification.
export function notificationsUrl(instanceUrl) {
return `${apiBaseUrl(instanceUrl)}/notifications?per_page=1`;
}
export function authorizationHeader(token) {
return `Bearer ${token}`;
}
// GitHub paginates with RFC 5988 Link headers. With `per_page=1` the last page
// number equals the total unread count; when there is no Link header there is
// at most one page, so the fallback length is already exact.
export function unreadCountFromLink(linkHeader, fallback = 0) {
if (!linkHeader) {
return fallback;
}
const match = /[?&]page=(\d+)[^>]*>;\s*rel="last"/.exec(linkHeader);
if (!match) {
return fallback;
}
const count = Number.parseInt(match[1], 10);
return Number.isNaN(count) ? fallback : count;
}
+2
View File
@@ -1,11 +1,13 @@
import DiscourseForm from '../components/settings/integrations/discourse-form.gjs';
import BitcoinForm from '../components/settings/integrations/bitcoin-form.gjs';
import FeedbinForm from '../components/settings/integrations/feedbin-form.gjs';
import GithubForm from '../components/settings/integrations/github-form.gjs';
const FORMS = {
discourse: DiscourseForm,
bitcoin: BitcoinForm,
feedbin: FeedbinForm,
github: GithubForm,
};
export function formFor(type) {
+11 -9
View File
@@ -1,10 +1,12 @@
import { GITHUB_ICON_BACKGROUND, GITHUB_ICON_URL } from './github';
const PENCIL_ICON_PATH =
'm16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10';
const BITCOIN_ICON_PATH =
'M23.638 14.904c-1.602 6.43-8.113 10.34-14.542 8.736C2.67 22.05-1.244 15.525.362 9.105 1.962 2.67 8.475-1.243 14.9.358c6.43 1.605 10.342 8.115 8.738 14.546zm-6.35-4.613c.24-1.59-.974-2.45-2.64-3.03l.54-2.153-1.315-.328-.525 2.107c-.345-.087-.705-.167-1.064-.25l.526-2.127-1.32-.33-.54 2.165c-.285-.067-.565-.132-.84-.2l-.006-.02-1.815-.45-.35 1.407s.975.225.955.238c.535.136.63.486.615.766l-.862 3.454c-.04.1-.14.25-.365.195.01.014-.95-.237-.95-.237l-.656 1.51 1.72.43c.32.08.634.16.955.25l-.54 2.2 1.32.33.54-2.18c.36.1.71.19 1.05.28l-.53 2.16 1.31.33.54-2.2c2.28.43 3.99.26 4.71-1.8.58-1.65-.03-2.6-1.22-3.22.87-.2 1.53-.78 1.7-1.96z';
export const FEEDBIN_ICON_URL = '/img/feedbin.png';
export const FEEDBIN_ICON_URL = '/img/icons/feedbin.png';
// Metadata for every integration the app knows about. `hasSettings` controls
// whether the Manage screen exposes an edit affordance; `reconnectable` marks
@@ -47,15 +49,15 @@ export const INTEGRATIONS = [
reconnectable: false,
},
{
id: 'gitea',
label: 'Gitea',
description: 'Notifications from your Git hosting servers',
colorClass: 'bg-gray-300',
iconPath: PENCIL_ICON_PATH,
iconFill: false,
available: false,
id: 'github',
label: 'GitHub',
description: 'Unread notifications from GitHub',
colorClass: 'bg-gray-800',
iconUrl: GITHUB_ICON_URL,
themeColor: GITHUB_ICON_BACKGROUND,
available: true,
supportsMultiple: false,
hasSettings: false,
hasSettings: true,
reconnectable: false,
},
];
+5 -5
View File
@@ -1,4 +1,9 @@
export const SITE_GROUPS = [
{
id: 'code-forge',
label: 'Code Forges',
integrationTypes: ['github'],
},
{
id: 'discourse',
label: 'Discourse',
@@ -9,9 +14,4 @@ export const SITE_GROUPS = [
label: 'Feedbin',
integrationTypes: ['feedbin'],
},
{
id: 'code-forge',
label: 'Code Forges',
integrationTypes: ['github', 'gitea'],
},
];
+30
View File
@@ -59,6 +59,36 @@ const ADAPTERS = {
return this.sites.removeSource(instance.id);
},
},
github: {
instances() {
return this.sites.all
.filter((site) => site.type === 'github')
.map((site) => {
const state = this.notifications.stateFor(site);
const integration = this.sites.integrationFor(site.id);
return {
id: site.id,
type: 'github',
label: site.label,
icon: site.icon,
status: 'active',
// Passed through so the edit form can prefill the host and keep
// the stored token when the token field is left blank.
url: integration?.url,
token: integration?.token,
error: state.error,
errorType: state.errorType,
// GitHub uses a personal access token, so fixing a rejected
// credential happens through the Settings form.
canReconnect: false,
};
});
},
remove(instance) {
return this.sites.removeSource(instance.id);
},
},
bitcoin: {
instances() {
if (!this.bitcoin.enabled) {
+43 -9
View File
@@ -2,6 +2,12 @@ import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { HttpError } from './http';
import { authorizationHeader, unreadCountUrl } from '../config/feedbin';
import {
GITHUB_ACCEPT,
authorizationHeader as githubAuthorizationHeader,
notificationsUrl,
unreadCountFromLink,
} from '../config/github';
export const NOTIFICATIONS_DEFAULT_INTERVAL = 60000;
@@ -51,9 +57,30 @@ async function fetchFeedbinNotifications(integration, http) {
};
}
// GitHub's notifications endpoint returns unread threads only by default.
// Requesting a single thread lets us read the total from the Link header's
// `rel="last"` page instead of downloading every notification.
async function fetchGithubNotifications(integration, http) {
const response = await http.request(notificationsUrl(integration.url), {
headers: {
Authorization: githubAuthorizationHeader(integration.token),
Accept: GITHUB_ACCEPT,
},
});
const data = await response.json();
const fallback = Array.isArray(data) ? data.length : 0;
return {
unreadCount: unreadCountFromLink(response.headers.get('Link'), fallback),
notifications: [],
};
}
const ADAPTERS = {
discourse: fetchDiscourseNotifications,
feedbin: fetchFeedbinNotifications,
github: fetchGithubNotifications,
};
function defaultState(type) {
@@ -153,6 +180,7 @@ export default class NotificationsService extends Service {
classifyError(err, site) {
const isFeedbin = site?.type === 'feedbin';
const isGithub = site?.type === 'github';
if (err instanceof HttpError) {
if (err.errorType === 'not_logged_in') {
@@ -170,23 +198,29 @@ export default class NotificationsService extends Service {
if (err.status === 401 || err.status === 403) {
return {
errorType: 'unauthorized',
error: isFeedbin
? 'Update Feedbin credentials'
: 'Reconnect this forum',
error: isGithub
? 'Update GitHub token'
: isFeedbin
? 'Update Feedbin credentials'
: 'Reconnect this forum',
};
}
return {
errorType: 'http',
error: isFeedbin
? `Feedbin returned ${err.status}`
: `Forum returned ${err.status}`,
error: isGithub
? `GitHub returned ${err.status}`
: isFeedbin
? `Feedbin returned ${err.status}`
: `Forum returned ${err.status}`,
};
}
return {
errorType: 'unreachable',
error: isFeedbin
? 'Feedbin blocked — enable CORS or open feedbin.com'
: 'Notifications blocked — enable CORS on the forum or open it',
error: isGithub
? 'GitHub blocked — enable CORS or open the GitHub host'
: isFeedbin
? 'Feedbin blocked — enable CORS or open feedbin.com'
: 'Notifications blocked — enable CORS on the forum or open it',
};
}
+30
View File
@@ -3,6 +3,12 @@ import { tracked } from '@glimmer/tracking';
import { SITE_GROUPS } from '../config/sites';
import { FEEDBIN_ICON_URL } from '../config/integrations';
import { FEEDBIN_DEFAULT_URL } from '../config/feedbin';
import {
GITHUB_DEFAULT_URL,
GITHUB_ICON_BACKGROUND,
GITHUB_ICON_URL,
isGithubDotCom,
} from '../config/github';
import { normalizeOrigin } from './site-icons';
function labelForUrl(url) {
@@ -88,6 +94,30 @@ export default class SitesService extends Service {
};
}
// GitHub.com links straight to the notifications inbox and uses the
// bundled inverted mark on a dark grey backdrop. Enterprise hosts keep
// their URL so a favicon can be found.
if (integration.type === 'github') {
const dotCom = isGithubDotCom(integration.url);
const origin = normalizeOrigin(integration.url) ?? GITHUB_DEFAULT_URL;
return {
id: key,
type: 'github',
groupId: this.groupIdForType('github'),
label: dotCom ? 'GitHub' : labelForUrl(integration.url),
url: dotCom ? undefined : integration.url,
href: `${origin}/notifications`,
icon: dotCom
? {
dataUrl: GITHUB_ICON_URL,
maskable: true,
themeColor: GITHUB_ICON_BACKGROUND,
}
: undefined,
};
}
return {
id: key,
type: integration.type,
File renamed without changes.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

@@ -69,11 +69,16 @@ module(
assert.dom().containsText('Live BTC price on your dashboard');
assert.dom().containsText('Feedbin');
assert.dom().containsText('Unread count from your Feedbin RSS reader');
assert.dom().containsText('Gitea');
assert.dom().containsText('Notifications from your Git hosting servers');
assert.dom().containsText('GitHub');
assert.dom().containsText('Unread notifications from GitHub');
assert.dom('[data-add="feedbin"] img[src="/img/feedbin.png"]').exists();
assert.dom('[data-add="gitea"]').isDisabled();
assert
.dom('[data-add="feedbin"] img[src="/img/icons/feedbin.png"]')
.exists();
assert
.dom('[data-add="github"] img[src="/img/icons/github-inverted.png"]')
.exists();
assert.dom('[data-add="github"]').doesNotHaveAttribute('disabled');
});
test('clicking an integration opens its add form', async function (assert) {
@@ -39,16 +39,32 @@ module(
});
test('it renders a bundled image icon', async function (assert) {
this.integration = { iconUrl: '/img/feedbin.png' };
this.integration = { iconUrl: '/img/icons/feedbin.png' };
await render(
<template><Avatar @integration={{this.integration}} /></template>
);
assert.dom('img').hasAttribute('src', '/img/feedbin.png');
assert.dom('img').hasAttribute('src', '/img/icons/feedbin.png');
assert.dom('svg').doesNotExist();
});
test('it paints the backdrop behind a transparent bundled icon', async function (assert) {
this.integration = {
iconUrl: '/img/icons/github-inverted.png',
themeColor: '#1f2937',
};
await render(
<template><Avatar @integration={{this.integration}} /></template>
);
assert.dom('img').hasAttribute('src', '/img/icons/github-inverted.png');
assert
.dom('span')
.hasAttribute('style', /background-color:\s*rgb\(31, 41, 55\)/);
});
test('it falls back to the brand color and glyph', async function (assert) {
this.integration = {
colorClass: 'bg-indigo-500',
@@ -0,0 +1,268 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent } from '@ember/test-helpers';
import Github from 'dashtab/components/settings/integrations/github-form';
function registerServices(owner, overrides = {}) {
const http = overrides.http ?? { request: async () => ({}) };
const storage = overrides.storage ?? { set: async () => {} };
const sites = overrides.sites ?? { reload: async () => {} };
const notifications = overrides.notifications ?? { startPolling: () => {} };
owner.register('service:http', http, { instantiate: false });
owner.register('service:storage', storage, { instantiate: false });
owner.register('service:sites', sites, { instantiate: false });
owner.register('service:notifications', notifications, {
instantiate: false,
});
}
module(
'Integration | Component | settings/integrations/github-form',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the token form', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><Github @close={{noop}} /></template>);
assert.dom().containsText('Add GitHub Integration');
assert.dom('#github-url').exists().hasValue('https://github.com');
assert.dom('#github-token').exists();
assert.dom().containsText('classic personal access token');
assert
.dom('a[href="https://github.com/settings/tokens/new"]')
.exists()
.hasAttribute('target', '_blank');
assert.dom('form').exists();
});
test('submitting validates and stores the credentials', async function (assert) {
const requests = [];
const saved = [];
let reloaded = false;
let polling = false;
let closed = false;
registerServices(this.owner, {
http: {
request: async (url, options) => {
requests.push({ url, options });
return {};
},
},
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
sites: {
reload: async () => {
reloaded = true;
},
},
notifications: {
startPolling: () => {
polling = true;
},
},
});
const closeDialog = () => {
closed = true;
};
await render(<template><Github @close={{closeDialog}} /></template>);
await fillIn('#github-token', 'ghp_secret');
await triggerEvent('form', 'submit');
assert.strictEqual(requests.length, 1);
assert.strictEqual(
requests[0].url,
'https://api.github.com/notifications?per_page=1'
);
assert.strictEqual(
requests[0].options.headers['Authorization'],
'Bearer ghp_secret'
);
assert.strictEqual(
requests[0].options.headers['Accept'],
'application/vnd.github+json'
);
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].namespace, 'integrations');
assert.strictEqual(saved[0].key, 'github');
assert.strictEqual(saved[0].value.type, 'github');
assert.strictEqual(saved[0].value.status, 'active');
assert.strictEqual(saved[0].value.url, 'https://github.com');
assert.strictEqual(saved[0].value.token, 'ghp_secret');
assert.true(reloaded);
assert.true(polling);
assert.true(closed);
});
test('submitting an Enterprise URL derives the /api/v3 base', async function (assert) {
const requests = [];
const saved = [];
registerServices(this.owner, {
http: {
request: async (url, options) => {
requests.push({ url, options });
return {};
},
},
storage: {
set: async (namespace, key, value) => saved.push(value),
},
});
const noop = () => {};
await render(<template><Github @close={{noop}} /></template>);
await fillIn('#github-url', 'git.example.com');
await fillIn('#github-token', 'ghp_secret');
await triggerEvent('form', 'submit');
assert.strictEqual(
requests[0].url,
'https://git.example.com/api/v3/notifications?per_page=1'
);
assert.strictEqual(saved[0].url, 'https://git.example.com');
});
test('it rejects an invalid server URL', async function (assert) {
const requests = [];
registerServices(this.owner, {
http: {
request: async (...args) => requests.push(args),
},
});
const noop = () => {};
await render(<template><Github @close={{noop}} /></template>);
await fillIn('#github-url', 'not a valid url');
await fillIn('#github-token', 'ghp_secret');
await triggerEvent('form', 'submit');
assert.dom('#github-url').hasValue('not a valid url');
assert.dom().containsText('Please enter a valid GitHub URL');
assert.strictEqual(requests.length, 0);
});
test('it reports an invalid token without storing it', async function (assert) {
const saved = [];
let closed = false;
registerServices(this.owner, {
http: {
request: async () => {
throw { status: 401 };
},
},
storage: {
set: async (...args) => saved.push(args),
},
});
const closeDialog = () => {
closed = true;
};
await render(<template><Github @close={{closeDialog}} /></template>);
await fillIn('#github-token', 'bad');
await triggerEvent('form', 'submit');
assert.dom().containsText('Invalid personal access token');
assert.strictEqual(saved.length, 0);
assert.false(closed);
});
test('it reports a token missing the notifications scope', async function (assert) {
registerServices(this.owner, {
http: {
request: async () => {
throw { status: 403 };
},
},
});
const noop = () => {};
await render(<template><Github @close={{noop}} /></template>);
await fillIn('#github-token', 'no-scope');
await triggerEvent('form', 'submit');
assert
.dom()
.containsText('Use a classic token with the notifications scope');
});
test('it requires a token', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><Github @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a personal access token');
});
test('edit mode prefills the host and keeps the stored token when blank', async function (assert) {
const requests = [];
const saved = [];
registerServices(this.owner, {
http: {
request: async (url, options) => {
requests.push({ url, options });
return {};
},
},
storage: {
set: async (namespace, key, value) =>
saved.push({ namespace, key, value }),
},
});
this.props = {
mode: 'edit',
integration: {
url: 'https://git.example.com',
token: 'OLDT0KEN',
colorClass: 'bg-gray-900',
},
};
const noop = () => {};
await render(
<template><Github @props={{this.props}} @close={{noop}} /></template>
);
assert.dom().containsText('Edit GitHub');
assert.dom('#github-url').hasValue('https://git.example.com');
await triggerEvent('form', 'submit');
assert.strictEqual(requests.length, 1);
assert.strictEqual(
requests[0].url,
'https://git.example.com/api/v3/notifications?per_page=1'
);
assert.strictEqual(
requests[0].options.headers['Authorization'],
'Bearer OLDT0KEN'
);
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].value.url, 'https://git.example.com');
assert.strictEqual(saved[0].value.token, 'OLDT0KEN');
assert.strictEqual(saved[0].value.colorClass, undefined);
});
}
);
@@ -147,7 +147,7 @@ module(
assert.dom('[data-instance="discourse-abc"]').exists();
assert.dom('[data-instance="bitcoin"]').exists();
assert.dom('[data-integration="gitea"]').doesNotExist();
assert.dom('[data-integration="github"]').doesNotExist();
});
test('it lists integrations with settings above discourse sites', async function (assert) {
@@ -54,10 +54,10 @@ module('Integration | Component | site-links', function (hooks) {
label: 'Code Forges',
items: [
{
id: 'gitea-1',
type: 'gitea',
label: 'git.example.com',
href: 'https://git.example.com',
id: 'github',
type: 'github',
label: 'GitHub',
href: 'https://github.com/notifications',
unreadCount: 0,
},
],
+79
View File
@@ -0,0 +1,79 @@
import { module, test } from 'qunit';
import {
apiBaseUrl,
authorizationHeader,
isGithubDotCom,
normalizeGithubUrl,
notificationsUrl,
unreadCountFromLink,
} from 'dashtab/config/github';
module('Unit | Config | github', function () {
test('normalizeGithubUrl normalizes input and rejects junk', function (assert) {
assert.strictEqual(normalizeGithubUrl('github.com'), 'https://github.com');
assert.strictEqual(
normalizeGithubUrl('https://github.com/'),
'https://github.com'
);
assert.strictEqual(
normalizeGithubUrl('http://git.example.com'),
'http://git.example.com'
);
assert.strictEqual(normalizeGithubUrl(''), null);
assert.strictEqual(normalizeGithubUrl(' '), null);
assert.strictEqual(normalizeGithubUrl('not a valid url'), null);
});
test('isGithubDotCom recognizes github.com hosts', function (assert) {
assert.true(isGithubDotCom('https://github.com'));
assert.true(isGithubDotCom('https://www.github.com'));
assert.false(isGithubDotCom('https://git.example.com'));
assert.false(isGithubDotCom(''));
});
test('apiBaseUrl uses the dedicated host for github.com and /api/v3 otherwise', function (assert) {
assert.strictEqual(apiBaseUrl(), 'https://api.github.com');
assert.strictEqual(
apiBaseUrl('https://github.com'),
'https://api.github.com'
);
assert.strictEqual(
apiBaseUrl('https://git.example.com'),
'https://git.example.com/api/v3'
);
});
test('notificationsUrl requests a single unread thread', function (assert) {
assert.strictEqual(
notificationsUrl('https://github.com'),
'https://api.github.com/notifications?per_page=1'
);
assert.strictEqual(
notificationsUrl('https://git.example.com'),
'https://git.example.com/api/v3/notifications?per_page=1'
);
});
test('authorizationHeader uses a bearer token', function (assert) {
assert.strictEqual(authorizationHeader('ghp_x'), 'Bearer ghp_x');
});
test('unreadCountFromLink reads the last page and falls back otherwise', function (assert) {
assert.strictEqual(
unreadCountFromLink(
'<https://api.github.com/notifications?per_page=1&page=2>; rel="next", <https://api.github.com/notifications?per_page=1&page=7>; rel="last"',
0
),
7
);
assert.strictEqual(
unreadCountFromLink(
'<https://api.github.com/notifications?per_page=1&page=2>; rel="next"',
1
),
1
);
assert.strictEqual(unreadCountFromLink(null, 3), 3);
assert.strictEqual(unreadCountFromLink('garbage', 4), 4);
});
});
+36 -3
View File
@@ -75,7 +75,7 @@ module('Unit | Service | integrations', function (hooks) {
const service = this.owner.lookup('service:integrations');
const discourse = service.all.find((entry) => entry.id === 'discourse');
const bitcoinEntry = service.all.find((entry) => entry.id === 'bitcoin');
const gitea = service.all.find((entry) => entry.id === 'gitea');
const github = service.all.find((entry) => entry.id === 'github');
assert.true(discourse.supportsMultiple);
assert.false(discourse.hasSettings);
@@ -88,8 +88,11 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(bitcoinEntry.instances[0].interval, 60000);
assert.strictEqual(bitcoinEntry.instances[0].provider, 'binance');
assert.false(gitea.available);
assert.strictEqual(gitea.instances.length, 0);
assert.true(github.available);
assert.false(github.supportsMultiple);
assert.true(github.hasSettings);
assert.false(github.reconnectable);
assert.strictEqual(github.instances.length, 0);
});
test('rows is empty when nothing is connected', function (assert) {
@@ -205,4 +208,34 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(feedbin.instances[0].token, 'dG9rZW4=');
assert.false(feedbin.instances[0].canReconnect);
});
test('github adapter exposes the connected account without reconnect', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
{
id: 'github',
type: 'github',
label: 'GitHub',
href: 'https://github.com/notifications',
},
];
sites.records = {
github: { url: 'https://github.com', token: 'ghp_token' },
};
register(this.owner, { sites });
const service = this.owner.lookup('service:integrations');
const github = service.all.find((entry) => entry.id === 'github');
assert.false(github.supportsMultiple);
assert.true(github.hasSettings);
assert.false(github.reconnectable);
assert.strictEqual(github.instances.length, 1);
assert.strictEqual(github.instances[0].id, 'github');
assert.strictEqual(github.instances[0].label, 'GitHub');
assert.strictEqual(github.instances[0].url, 'https://github.com');
assert.strictEqual(github.instances[0].token, 'ghp_token');
assert.false(github.instances[0].canReconnect);
});
});
+175 -11
View File
@@ -36,7 +36,7 @@ module('Unit | Service | notifications', function (hooks) {
assert.strictEqual(pollable.status, 'loading');
assert.strictEqual(pollable.unreadCount, 0);
const plain = service.stateFor({ id: 'b', type: 'gitea' });
const plain = service.stateFor({ id: 'b', type: 'unknown' });
assert.strictEqual(plain.status, 'ready');
assert.strictEqual(plain.unreadCount, 0);
@@ -60,18 +60,15 @@ module('Unit | Service | notifications', function (hooks) {
service.stopPolling();
});
test('setup does not poll when only plain site links are connected', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-1', {
type: 'gitea',
status: 'active',
url: 'https://git.example.com',
});
test('isPollable is true only for integrations with an adapter', function (assert) {
const service = this.owner.lookup('service:notifications');
await service.ready;
assert.strictEqual(service.intervalId, null);
assert.true(service.isPollable({ type: 'discourse' }));
assert.true(service.isPollable({ type: 'feedbin' }));
assert.true(service.isPollable({ type: 'github' }));
assert.false(service.isPollable({ type: 'unknown' }));
service.stopPolling();
});
test('fetchSite normalizes a discourse response', async function (assert) {
@@ -268,6 +265,173 @@ module('Unit | Service | notifications', function (hooks) {
service.stopPolling();
});
test('fetchSite reads the GitHub unread count from the Link header', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://github.com',
token: 'ghp_token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
let requestedUrl;
let requestedHeaders;
globalThis.fetch = async (url, options) => {
requestedUrl = url;
requestedHeaders = options.headers;
return {
ok: true,
headers: {
get: (name) =>
name === 'Link'
? '<https://api.github.com/notifications?per_page=1&page=2>; rel="next", <https://api.github.com/notifications?per_page=1&page=7>; rel="last"'
: null,
},
json: async () => [],
};
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(
requestedUrl,
'https://api.github.com/notifications?per_page=1'
);
assert.strictEqual(requestedHeaders['Authorization'], 'Bearer ghp_token');
assert.strictEqual(
requestedHeaders['Accept'],
'application/vnd.github+json'
);
const state = service.stateFor(site);
assert.strictEqual(state.status, 'ready');
assert.strictEqual(state.unreadCount, 7);
assert.deepEqual(state.items, []);
service.stopPolling();
});
test('fetchSite derives the GitHub Enterprise API base from the host', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://git.example.com',
token: 'ghp_token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
let requestedUrl;
globalThis.fetch = async (url) => {
requestedUrl = url;
return { ok: true, headers: { get: () => null }, json: async () => [] };
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(
requestedUrl,
'https://git.example.com/api/v3/notifications?per_page=1'
);
service.stopPolling();
});
test('fetchSite treats a missing GitHub Link header as the returned length', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://github.com',
token: 'ghp_token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({
ok: true,
headers: { get: () => null },
json: async () => [{ id: '1', unread: true }],
});
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(service.stateFor(site).unreadCount, 1);
service.stopPolling();
});
test('fetchSite flags an invalid GitHub token', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://github.com',
token: 'stale',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({
ok: false,
status: 401,
json: async () => ({}),
});
const [site] = service.sites.all;
await service.fetchSite(site);
const state = service.stateFor(site);
assert.strictEqual(state.status, 'error');
assert.strictEqual(state.errorType, 'unauthorized');
assert.strictEqual(state.error, 'Update GitHub token');
service.stopPolling();
});
test('fetchSite flags a GitHub token missing the notifications scope', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://github.com',
token: 'no-scope',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({
ok: false,
status: 403,
json: async () => ({}),
});
const [site] = service.sites.all;
await service.fetchSite(site);
const state = service.stateFor(site);
assert.strictEqual(state.errorType, 'unauthorized');
assert.strictEqual(state.error, 'Update GitHub token');
service.stopPolling();
});
test('fetchSite marks an unreachable site when the request fails', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
+46 -1
View File
@@ -73,7 +73,7 @@ module('Unit | Service | sites', function (hooks) {
assert.strictEqual(item.groupId, 'feedbin');
assert.notOk(item.url);
assert.deepEqual(item.icon, {
dataUrl: '/img/feedbin.png',
dataUrl: '/img/icons/feedbin.png',
maskable: true,
});
@@ -99,6 +99,51 @@ module('Unit | Service | sites', function (hooks) {
assert.strictEqual(service.all[0].href, 'https://feedbin.example.com');
});
test('load builds the GitHub site with the bundled maskable icon', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://github.com',
token: 'ghp_token',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all.length, 1);
const [item] = service.all;
assert.strictEqual(item.label, 'GitHub');
assert.strictEqual(item.href, 'https://github.com/notifications');
assert.strictEqual(item.groupId, 'code-forge');
assert.notOk(item.url);
assert.deepEqual(item.icon, {
dataUrl: '/img/icons/github-inverted.png',
maskable: true,
themeColor: '#1f2937',
});
});
test('the GitHub site uses an Enterprise host and links to its notifications', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'github', {
type: 'github',
status: 'active',
url: 'https://git.example.com',
token: 'ghp_token',
});
const service = this.owner.lookup('service:sites');
await service.ready;
const [item] = service.all;
assert.strictEqual(item.label, 'git.example.com');
assert.strictEqual(item.href, 'https://git.example.com/notifications');
assert.strictEqual(item.url, 'https://git.example.com');
assert.notOk(item.icon);
});
test('integrationFor exposes the raw record for a site', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {