Add Gitea integration

This commit is contained in:
raucao committed 2026-10-05 13:17:03 +02:00
1 parent b2e7d74b4f
commit 11be348a37
17 files changed
+1014 -19

No files matched your search

@@ -0,0 +1,231 @@
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 {
GITEA_ACCEPT,
applicationsUrl,
authorizationHeader,
integrationKey,
normalizeGiteaUrl,
notificationsCountUrl,
} from '../../../config/gitea';
export default class SettingsIntegrationsGiteaForm 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 ?? '';
}
get applicationsUrl() {
return applicationsUrl(this.url);
}
get title() {
return this.isEdit ? 'Edit Gitea' : 'Add Gitea 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 = normalizeGiteaUrl(this.url);
if (!instanceUrl) {
this.error = 'Please enter a valid Gitea URL';
return;
}
// On edit a blank token keeps the stored one, so users can update the host
// without re-entering the token.
const token = this.token.trim() || this.integration?.token;
if (!token) {
this.error = 'Please enter an access token';
return;
}
this.submitting = true;
try {
// The unread count endpoint doubles as a token and scope check: an
// invalid token fails with 401, a token without the read:notification
// permission fails with 403.
await this.http.request(notificationsCountUrl(instanceUrl), {
headers: {
Authorization: authorizationHeader(token),
Accept: GITEA_ACCEPT,
},
});
} catch (err) {
this.error = this.classifyError(err);
return;
} finally {
this.submitting = false;
}
// Key each instance by host so several Gitea instances can be connected.
// Editing keeps the existing key even if the host changes.
const key = this.integration?.id ?? integrationKey(instanceUrl);
// 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', key, {
type: 'gitea',
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 access token';
}
if (err?.status === 403) {
return 'Token is missing the read:notification scope';
}
if (err?.name === 'NetworkError') {
return 'Unable to reach Gitea. Check the URL and CORS.';
}
return 'Unable to verify your Gitea 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 a Gitea instance 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="gitea-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="gitea-url"
name="url"
value={{this.url}}
{{on "input" this.updateUrl}}
placeholder="gitea.example.com"
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">
The URL of your Gitea or Forgejo instance.
</p>
</div>
<div>
<label
for="gitea-token"
class="block text-sm font-medium leading-6 text-gray-900"
>
Access token
</label>
<div class="mt-2">
<input
type="password"
id="gitea-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">
Create a token with the "read:notification" scope in
{{#if this.applicationsUrl}}
<a
href={{this.applicationsUrl}}
target="_blank"
rel="noopener noreferrer"
class="text-indigo-600 hover:text-indigo-500"
>your instance's applications settings</a>.
{{else}}
your instance's applications settings.
{{/if}}
</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>
}
+7 -1
View File
@@ -19,6 +19,12 @@ export default class SiteLinksItemComponent extends Component {
return this.args.item?.status === 'error';
}
get link() {
return this.hasUnread && this.args.item?.notificationsHref
? this.args.item.notificationsHref
: this.args.item.href;
}
get icon() {
return this.args.item?.icon;
}
@@ -53,7 +59,7 @@ export default class SiteLinksItemComponent extends Component {
<template>
<a
href={{@item.href}}
href={{this.link}}
title={{this.tooltip}}
aria-label={{this.tooltip}}
data-status={{@item.status}}
+63
View File
@@ -0,0 +1,63 @@
export const GITEA_ICON_URL = '/img/icons/gitea.png';
// The bundled mark has white-based transparent edges, so it is rendered on a
// white backdrop to avoid fringing.
export const GITEA_ICON_BACKGROUND = '#ffffff';
export const GITEA_ACCEPT = 'application/json';
// Normalizes the user-supplied instance URL to a bare origin. Gitea is always
// self-hosted, so there is no default instance; installs under a subpath are
// not supported (the origin is all we keep).
export function normalizeGiteaUrl(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;
}
}
export function apiBaseUrl(instanceUrl) {
const origin = normalizeGiteaUrl(instanceUrl);
return origin ? `${origin}/api/v1` : null;
}
// Gitea exposes a dedicated unread count endpoint, so the badge costs a single
// small request instead of downloading the notification list.
export function notificationsCountUrl(instanceUrl) {
const base = apiBaseUrl(instanceUrl);
return base ? `${base}/notifications/new` : null;
}
// Where the user creates an access token for this instance.
export function applicationsUrl(instanceUrl) {
const origin = normalizeGiteaUrl(instanceUrl);
return origin ? `${origin}/user/settings/applications` : null;
}
// Gitea access tokens must be prefixed with the word "token".
export function authorizationHeader(token) {
return `token ${token}`;
}
export function unreadCountFromResponse(data) {
const count = data?.new;
return Number.isFinite(count) ? count : 0;
}
// Storage key for a connected instance, unique per host (including port) so
// several self-hosted Gitea instances can be connected side by side.
export function integrationKey(instanceUrl) {
const origin = normalizeGiteaUrl(instanceUrl);
return origin ? `gitea-${new URL(origin).host}` : null;
}
+2
View File
@@ -2,12 +2,14 @@ import DiscourseForm from '../components/settings/integrations/discourse-form.gj
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';
import GiteaForm from '../components/settings/integrations/gitea-form.gjs';
const FORMS = {
discourse: DiscourseForm,
bitcoin: BitcoinForm,
feedbin: FeedbinForm,
github: GithubForm,
gitea: GiteaForm,
};
export function formFor(type) {
+13
View File
@@ -1,4 +1,5 @@
import { GITHUB_ICON_BACKGROUND, GITHUB_ICON_URL } from './github';
import { GITEA_ICON_BACKGROUND, GITEA_ICON_URL } from './gitea';
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';
@@ -60,6 +61,18 @@ export const INTEGRATIONS = [
hasSettings: true,
reconnectable: false,
},
{
id: 'gitea',
label: 'Gitea',
description: 'Unread notifications from your Gitea instances',
colorClass: 'bg-[#609926]',
iconUrl: GITEA_ICON_URL,
themeColor: GITEA_ICON_BACKGROUND,
available: true,
supportsMultiple: true,
hasSettings: true,
reconnectable: false,
},
];
export function integrationFor(type) {
+1 -1
View File
@@ -2,7 +2,7 @@ export const SITE_GROUPS = [
{
id: 'code-forge',
label: 'Code Forges',
integrationTypes: ['github'],
integrationTypes: ['github', 'gitea'],
},
{
id: 'discourse',
+30
View File
@@ -89,6 +89,36 @@ const ADAPTERS = {
return this.sites.removeSource(instance.id);
},
},
gitea: {
instances() {
return this.sites.all
.filter((site) => site.type === 'gitea')
.map((site) => {
const state = this.notifications.stateFor(site);
const integration = this.sites.integrationFor(site.id);
return {
id: site.id,
type: 'gitea',
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,
// Gitea uses an 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) {
+45 -17
View File
@@ -9,6 +9,12 @@ import {
nextLink,
notificationsUrl,
} from '../config/github';
import {
GITEA_ACCEPT,
authorizationHeader as giteaAuthorizationHeader,
notificationsCountUrl,
unreadCountFromResponse,
} from '../config/gitea';
export const NOTIFICATIONS_DEFAULT_INTERVAL = 60000;
@@ -88,10 +94,43 @@ async function fetchGithubNotifications(integration, http) {
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: [],
};
}
const ADAPTERS = {
discourse: fetchDiscourseNotifications,
feedbin: fetchFeedbinNotifications,
github: fetchGithubNotifications,
gitea: fetchGiteaNotifications,
};
// 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' };
const UNAUTHORIZED_MESSAGES = {
github: 'Update GitHub token',
gitea: 'Update Gitea token',
feedbin: 'Update Feedbin credentials',
};
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',
};
function defaultState(type) {
@@ -190,8 +229,7 @@ export default class NotificationsService extends Service {
}
classifyError(err, site) {
const isFeedbin = site?.type === 'feedbin';
const isGithub = site?.type === 'github';
const type = site?.type;
if (err instanceof HttpError) {
if (err.errorType === 'not_logged_in') {
@@ -209,29 +247,19 @@ export default class NotificationsService extends Service {
if (err.status === 401 || err.status === 403) {
return {
errorType: 'unauthorized',
error: isGithub
? 'Update GitHub token'
: isFeedbin
? 'Update Feedbin credentials'
: 'Reconnect this forum',
error: UNAUTHORIZED_MESSAGES[type] ?? 'Reconnect this forum',
};
}
return {
errorType: 'http',
error: isGithub
? `GitHub returned ${err.status}`
: isFeedbin
? `Feedbin returned ${err.status}`
: `Forum returned ${err.status}`,
error: `${FORUM_LABELS[type] ?? 'Forum'} returned ${err.status}`,
};
}
return {
errorType: 'unreachable',
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',
error:
UNREACHABLE_MESSAGES[type] ??
'Notifications blocked — enable CORS on the forum or open it',
};
}
+22
View File
@@ -9,6 +9,7 @@ import {
GITHUB_ICON_URL,
isGithubDotCom,
} from '../config/github';
import { GITEA_ICON_BACKGROUND, GITEA_ICON_URL } from '../config/gitea';
import { normalizeOrigin } from './site-icons';
function labelForUrl(url) {
@@ -118,6 +119,27 @@ export default class SitesService extends Service {
};
}
// Gitea is always self-hosted. It uses the bundled mark on a white
// backdrop (leaving `url` unset so `resolveIcons` doesn't replace it),
// links to the root normally, and exposes a notifications link the tile
// can switch to when there are unread items.
if (integration.type === 'gitea') {
return {
id: key,
type: 'gitea',
groupId: this.groupIdForType('gitea'),
label: labelForUrl(integration.url),
url: undefined,
href: integration.url,
notificationsHref: `${integration.url}/notifications`,
icon: {
dataUrl: GITEA_ICON_URL,
maskable: true,
themeColor: GITEA_ICON_BACKGROUND,
},
};
}
return {
id: key,
type: integration.type,
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

@@ -71,6 +71,10 @@ module(
assert.dom().containsText('Unread count from your Feedbin RSS reader');
assert.dom().containsText('GitHub');
assert.dom().containsText('Unread notifications from GitHub');
assert.dom().containsText('Gitea');
assert
.dom()
.containsText('Unread notifications from your Gitea instances');
assert
.dom('[data-add="feedbin"] img[src="/img/icons/feedbin.png"]')
@@ -79,6 +83,8 @@ module(
.dom('[data-add="github"] img[src="/img/icons/github-inverted.png"]')
.exists();
assert.dom('[data-add="github"]').doesNotHaveAttribute('disabled');
assert.dom('[data-add="gitea"] img[src="/img/icons/gitea.png"]').exists();
assert.dom('[data-add="gitea"]').doesNotHaveAttribute('disabled');
});
test('clicking an integration opens its add form', async function (assert) {
@@ -0,0 +1,257 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'dashtab/tests/helpers';
import { render, fillIn, triggerEvent } from '@ember/test-helpers';
import Gitea from 'dashtab/components/settings/integrations/gitea-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/gitea-form',
function (hooks) {
setupRenderingTest(hooks);
test('it renders the token form without a default URL', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><Gitea @close={{noop}} /></template>);
assert.dom().containsText('Add Gitea Integration');
assert.dom('#gitea-url').exists().hasValue('');
assert.dom('#gitea-token').exists();
assert.dom('form').exists();
});
test('it links to the applications settings once a URL is entered', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><Gitea @close={{noop}} /></template>);
assert
.dom('a[href="https://git.example.com/user/settings/applications"]')
.doesNotExist();
await fillIn('#gitea-url', 'git.example.com');
assert
.dom('a[href="https://git.example.com/user/settings/applications"]')
.exists()
.hasAttribute('target', '_blank');
});
test('submitting validates and stores the credentials under a host key', 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><Gitea @close={{closeDialog}} /></template>);
await fillIn('#gitea-url', 'git.example.com');
await fillIn('#gitea-token', 'gta_secret');
await triggerEvent('form', 'submit');
assert.strictEqual(requests.length, 1);
assert.strictEqual(
requests[0].url,
'https://git.example.com/api/v1/notifications/new'
);
assert.strictEqual(
requests[0].options.headers['Authorization'],
'token gta_secret'
);
assert.strictEqual(
requests[0].options.headers['Accept'],
'application/json'
);
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].namespace, 'integrations');
assert.strictEqual(saved[0].key, 'gitea-git.example.com');
assert.strictEqual(saved[0].value.type, 'gitea');
assert.strictEqual(saved[0].value.status, 'active');
assert.strictEqual(saved[0].value.url, 'https://git.example.com');
assert.strictEqual(saved[0].value.token, 'gta_secret');
assert.true(reloaded);
assert.true(polling);
assert.true(closed);
});
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><Gitea @close={{noop}} /></template>);
await fillIn('#gitea-url', 'not a valid url');
await fillIn('#gitea-token', 'gta_secret');
await triggerEvent('form', 'submit');
assert.dom('#gitea-url').hasValue('not a valid url');
assert.dom().containsText('Please enter a valid Gitea 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><Gitea @close={{closeDialog}} /></template>);
await fillIn('#gitea-url', 'git.example.com');
await fillIn('#gitea-token', 'bad');
await triggerEvent('form', 'submit');
assert.dom().containsText('Invalid access token');
assert.strictEqual(saved.length, 0);
assert.false(closed);
});
test('it reports a token missing the notification scope', async function (assert) {
registerServices(this.owner, {
http: {
request: async () => {
throw { status: 403 };
},
},
});
const noop = () => {};
await render(<template><Gitea @close={{noop}} /></template>);
await fillIn('#gitea-url', 'git.example.com');
await fillIn('#gitea-token', 'no-scope');
await triggerEvent('form', 'submit');
assert.dom().containsText('Token is missing the read:notification scope');
});
test('it requires a server URL and token', async function (assert) {
registerServices(this.owner);
const noop = () => {};
await render(<template><Gitea @close={{noop}} /></template>);
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter a valid Gitea URL');
await fillIn('#gitea-url', 'git.example.com');
await triggerEvent('form', 'submit');
assert.dom().containsText('Please enter an access token');
});
test('edit mode prefills the host and keeps the stored token and key', 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: {
id: 'gitea-git.example.com',
url: 'https://git.example.com',
token: 'OLDT0KEN',
colorClass: 'bg-[#609926]',
},
};
const noop = () => {};
await render(
<template><Gitea @props={{this.props}} @close={{noop}} /></template>
);
assert.dom().containsText('Edit Gitea');
assert.dom('#gitea-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/v1/notifications/new'
);
assert.strictEqual(
requests[0].options.headers['Authorization'],
'token OLDT0KEN'
);
assert.strictEqual(saved.length, 1);
assert.strictEqual(saved[0].key, 'gitea-git.example.com');
assert.strictEqual(saved[0].value.url, 'https://git.example.com');
assert.strictEqual(saved[0].value.token, 'OLDT0KEN');
assert.strictEqual(saved[0].value.colorClass, undefined);
});
}
);
@@ -26,6 +26,40 @@ module('Integration | Component | site-links/item', function (hooks) {
assert.dom('[data-test-site-links-fallback]').hasText('F');
});
test('it links to the notifications page when there are unread items', async function (assert) {
this.set('item', {
id: 'gitea-git.example.com',
type: 'gitea',
label: 'git.example.com',
href: 'https://git.example.com',
notificationsHref: 'https://git.example.com/notifications',
status: 'ready',
unreadCount: 2,
});
await render(<template><SiteLinksItem @item={{this.item}} /></template>);
assert
.dom('a')
.hasAttribute('href', 'https://git.example.com/notifications');
});
test('it links to the site root when there are no unread items', async function (assert) {
this.set('item', {
id: 'gitea-git.example.com',
type: 'gitea',
label: 'git.example.com',
href: 'https://git.example.com',
notificationsHref: 'https://git.example.com/notifications',
status: 'ready',
unreadCount: 0,
});
await render(<template><SiteLinksItem @item={{this.item}} /></template>);
assert.dom('a').hasAttribute('href', 'https://git.example.com');
});
test('it renders the fetched site icon when one is available', async function (assert) {
this.set('item', {
id: 'discourse-abc',
+73
View File
@@ -0,0 +1,73 @@
import { module, test } from 'qunit';
import {
apiBaseUrl,
applicationsUrl,
authorizationHeader,
integrationKey,
normalizeGiteaUrl,
notificationsCountUrl,
unreadCountFromResponse,
} from 'dashtab/config/gitea';
module('Unit | Config | gitea', function () {
test('normalizeGiteaUrl normalizes input and rejects junk', function (assert) {
assert.strictEqual(
normalizeGiteaUrl('git.example.com'),
'https://git.example.com'
);
assert.strictEqual(
normalizeGiteaUrl('https://git.example.com/'),
'https://git.example.com'
);
assert.strictEqual(
normalizeGiteaUrl('http://gitea.example.com'),
'http://gitea.example.com'
);
assert.strictEqual(normalizeGiteaUrl(''), null);
assert.strictEqual(normalizeGiteaUrl(' '), null);
assert.strictEqual(normalizeGiteaUrl('not a valid url'), null);
});
test('apiBaseUrl appends the /api/v1 prefix', function (assert) {
assert.strictEqual(
apiBaseUrl('https://git.example.com'),
'https://git.example.com/api/v1'
);
assert.strictEqual(apiBaseUrl(''), null);
});
test('endpoint URLs build on the instance origin', function (assert) {
assert.strictEqual(
notificationsCountUrl('https://git.example.com'),
'https://git.example.com/api/v1/notifications/new'
);
assert.strictEqual(
applicationsUrl('https://git.example.com'),
'https://git.example.com/user/settings/applications'
);
assert.strictEqual(applicationsUrl(''), null);
});
test('authorizationHeader prefixes the token', function (assert) {
assert.strictEqual(authorizationHeader('abc123'), 'token abc123');
});
test('unreadCountFromResponse reads the new count', function (assert) {
assert.strictEqual(unreadCountFromResponse({ new: 4 }), 4);
assert.strictEqual(unreadCountFromResponse({ new: 0 }), 0);
assert.strictEqual(unreadCountFromResponse({}), 0);
assert.strictEqual(unreadCountFromResponse(null), 0);
});
test('integrationKey is unique per host', function (assert) {
assert.strictEqual(
integrationKey('https://git.example.com'),
'gitea-git.example.com'
);
assert.strictEqual(
integrationKey('https://git.example.com:3000'),
'gitea-git.example.com:3000'
);
assert.strictEqual(integrationKey(''), null);
});
});
+52
View File
@@ -76,6 +76,7 @@ module('Unit | Service | integrations', function (hooks) {
const discourse = service.all.find((entry) => entry.id === 'discourse');
const bitcoinEntry = service.all.find((entry) => entry.id === 'bitcoin');
const github = service.all.find((entry) => entry.id === 'github');
const gitea = service.all.find((entry) => entry.id === 'gitea');
assert.true(discourse.supportsMultiple);
assert.false(discourse.hasSettings);
@@ -93,6 +94,13 @@ module('Unit | Service | integrations', function (hooks) {
assert.true(github.hasSettings);
assert.false(github.reconnectable);
assert.strictEqual(github.instances.length, 0);
assert.true(gitea.available);
assert.true(gitea.supportsMultiple);
assert.true(gitea.hasSettings);
assert.false(gitea.reconnectable);
assert.strictEqual(gitea.themeColor, '#ffffff');
assert.strictEqual(gitea.instances.length, 0);
});
test('rows is empty when nothing is connected', function (assert) {
@@ -238,4 +246,48 @@ module('Unit | Service | integrations', function (hooks) {
assert.strictEqual(github.instances[0].token, 'ghp_token');
assert.false(github.instances[0].canReconnect);
});
test('gitea adapter exposes every connected instance without reconnect', async function (assert) {
const sites = new FakeSitesService();
sites.all = [
{
id: 'gitea-a.example.com',
type: 'gitea',
label: 'a.example.com',
href: 'https://a.example.com',
},
{
id: 'gitea-b.example.com',
type: 'gitea',
label: 'b.example.com',
href: 'https://b.example.com',
},
];
sites.records = {
'gitea-a.example.com': {
url: 'https://a.example.com',
token: 'token-a',
},
'gitea-b.example.com': {
url: 'https://b.example.com',
token: 'token-b',
},
};
register(this.owner, { sites });
const service = this.owner.lookup('service:integrations');
const gitea = service.all.find((entry) => entry.id === 'gitea');
assert.true(gitea.supportsMultiple);
assert.true(gitea.hasSettings);
assert.false(gitea.reconnectable);
assert.strictEqual(gitea.instances.length, 2);
assert.deepEqual(
gitea.instances.map((instance) => instance.id),
['gitea-a.example.com', 'gitea-b.example.com']
);
assert.strictEqual(gitea.instances[0].token, 'token-a');
assert.false(gitea.instances[0].canReconnect);
});
});
+122
View File
@@ -66,6 +66,7 @@ module('Unit | Service | notifications', function (hooks) {
assert.true(service.isPollable({ type: 'discourse' }));
assert.true(service.isPollable({ type: 'feedbin' }));
assert.true(service.isPollable({ type: 'github' }));
assert.true(service.isPollable({ type: 'gitea' }));
assert.false(service.isPollable({ type: 'unknown' }));
service.stopPolling();
@@ -456,6 +457,127 @@ module('Unit | Service | notifications', function (hooks) {
service.stopPolling();
});
test('fetchSite reads the Gitea unread count from the count endpoint', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-git.example.com', {
type: 'gitea',
status: 'active',
url: 'https://git.example.com',
token: 'gta_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, json: async () => ({ new: 5 }) };
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(
requestedUrl,
'https://git.example.com/api/v1/notifications/new'
);
assert.strictEqual(requestedHeaders['Authorization'], 'token gta_token');
assert.strictEqual(requestedHeaders['Accept'], 'application/json');
const state = service.stateFor(site);
assert.strictEqual(state.status, 'ready');
assert.strictEqual(state.unreadCount, 5);
assert.deepEqual(state.items, []);
service.stopPolling();
});
test('fetchSite treats a missing Gitea count as zero', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-git.example.com', {
type: 'gitea',
status: 'active',
url: 'https://git.example.com',
token: 'gta_token',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => ({ ok: true, json: async () => ({}) });
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(service.stateFor(site).unreadCount, 0);
service.stopPolling();
});
test('fetchSite flags an invalid Gitea token', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-git.example.com', {
type: 'gitea',
status: 'active',
url: 'https://git.example.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 Gitea token');
service.stopPolling();
});
test('fetchSite flags a Gitea token missing the notification scope', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-git.example.com', {
type: 'gitea',
status: 'active',
url: 'https://git.example.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 Gitea 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', {
+56
View File
@@ -144,6 +144,62 @@ module('Unit | Service | sites', function (hooks) {
assert.notOk(item.icon);
});
test('load builds a Gitea site keyed by host with a notifications link', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-git.example.com', {
type: 'gitea',
status: 'active',
url: 'https://git.example.com',
token: 'gta_token',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all.length, 1);
const [item] = service.all;
assert.strictEqual(item.id, 'gitea-git.example.com');
assert.strictEqual(item.label, 'git.example.com');
assert.strictEqual(item.groupId, 'code-forge');
assert.strictEqual(item.href, 'https://git.example.com');
assert.strictEqual(
item.notificationsHref,
'https://git.example.com/notifications'
);
assert.notOk(item.url);
assert.deepEqual(item.icon, {
dataUrl: '/img/icons/gitea.png',
maskable: true,
themeColor: '#ffffff',
});
});
test('load supports multiple Gitea instances', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'gitea-a.example.com', {
type: 'gitea',
status: 'active',
url: 'https://a.example.com',
token: 'a',
});
await storage.set('integrations', 'gitea-b.example.com', {
type: 'gitea',
status: 'active',
url: 'https://b.example.com',
token: 'b',
});
const service = this.owner.lookup('service:sites');
await service.ready;
assert.strictEqual(service.all.length, 2);
assert.deepEqual(
service.all.map((site) => site.id),
['gitea-a.example.com', 'gitea-b.example.com']
);
});
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', {