Initial commit: BRAT fork with Gitea support
Tatortreiniger / tatort-reinigen (release) Has been cancelled

This commit is contained in:
olivier committed 2026-05-24 18:35:09 -04:00
1 parent bd3153fd32
commit 8de00536fa
44 files changed
+5172 -3

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
import { themeDelete, themeSave, themesCheckAndUpdates } from "../features/themes";
import { detectProvider } from "../providers";
import type BratPlugin from "../main";
// This module is for API access for use in debugging console
export default class BratAPI {
plugin: BratPlugin;
constructor(plugin: BratPlugin) {
this.plugin = plugin;
}
console = (
logDescription: string,
...outputs: (string | number | boolean)[]
): void => {
console.log(`BRAT: ${logDescription}`, ...outputs);
};
themes = {
themeseCheckAndUpates: async (showInfo: boolean): Promise<void> => {
await themesCheckAndUpdates(this.plugin, showInfo);
},
themeInstallTheme: async (
cssRepository: string,
): Promise<void> => {
await themeSave(this.plugin, cssRepository, true);
},
themesDelete: (cssRepository: string): void => {
themeDelete(this.plugin, cssRepository);
},
/**
* Fetch a checksum of a theme CSS file from the repo.
* Works with GitHub and Gitea.
*/
getThemeChecksum: async (
repositoryPath: string,
betaVersion = false,
): Promise<string> => {
try {
const provider = detectProvider(repositoryPath);
const parsed = provider.parseUrl(repositoryPath);
const fileName = betaVersion ? "theme-beta.css" : "theme.css";
const css = await provider.getRawFile(parsed, fileName, "HEAD");
if (!css) return "0";
let sum = 0;
for (let i = 0; i < css.length; i++) sum += css.charCodeAt(i);
return sum.toString();
} catch {
return "0";
}
},
};
}
+102
View File
@@ -0,0 +1,102 @@
import { detectProvider } from "../providers";
import type { TokenInfo } from "../providers/PluginProvider";
export class TokenValidator {
private statusEl?: HTMLElement | null;
constructor(statusEl?: HTMLElement | null) {
this.statusEl = statusEl;
}
async validateToken(
token: string,
repository?: string,
): Promise<boolean> {
if (!token) {
this.updateStatus("No token provided", false);
return false;
}
try {
// If we have a repository, use its provider for validation
// Otherwise default to GitHub (generic token check)
const provider = repository ? detectProvider(repository) : detectProvider("github.com/test/test");
const parsed = repository ? provider.parseUrl(repository) : undefined;
const info: TokenInfo = await provider.validateToken(token, parsed);
if (info.valid) {
this.showValidInfo(info);
return true;
}
this.showError(info);
return false;
} catch (error) {
console.error("Token validation error:", error);
this.updateStatus("Failed to validate token", false);
return false;
}
}
private updateStatus(message: string, isValid: boolean): void {
if (!this.statusEl) return;
this.statusEl.empty();
this.statusEl.removeClass("valid", "invalid");
this.statusEl.addClass(isValid ? "valid" : "invalid");
this.statusEl.setText(message);
}
private showValidInfo(info: TokenInfo): void {
if (!this.statusEl) return;
this.statusEl.empty();
this.statusEl.removeClass("invalid");
this.statusEl.addClass("valid");
const details = this.statusEl.createDiv({ cls: "brat-token-details" });
details.createDiv({
text: "✓ Valid token",
cls: "brat-token-status valid",
});
if (info.details?.scopes) {
details.createDiv({
text: `Scopes: ${info.details.scopes}`,
cls: "brat-token-scopes",
});
}
if (info.details?.expires) {
const expires = new Date(info.details.expires);
const daysLeft = Math.ceil(
(expires.getTime() - Date.now()) / (1000 * 60 * 60 * 24),
);
if (daysLeft < 7) {
details.createDiv({
text: `⚠️ Token expires in ${daysLeft} days`,
cls: "brat-token-warning",
});
}
}
}
private showError(info: TokenInfo): void {
if (!this.statusEl) return;
this.statusEl.empty();
this.statusEl.removeClass("valid");
this.statusEl.addClass("invalid");
const details = this.statusEl.createDiv({ cls: "brat-token-error" });
details.createDiv({ text: `✗ ${info.message}` });
if (info.details?.validPrefixes) {
details.createDiv({
text: `Valid prefixes: ${info.details.validPrefixes}`,
});
}
if (info.details?.requiredScopes) {
details.createDiv({
text: `Required scopes: ${info.details.requiredScopes}`,
});
}
}
}
+16
View File
@@ -0,0 +1,16 @@
import { requestUrl } from "obsidian";
/**
* Tests if there is an internet connection
* @returns true if connected, false if no internet
*/
export async function isConnectedToInternet(): Promise<boolean> {
try {
const online = await requestUrl(
`https://obsidian.md/?${Math.random()}`,
);
return online.status >= 200 && online.status < 300;
} catch {
return false;
}
}
+38
View File
@@ -0,0 +1,38 @@
import type { TFile } from "obsidian";
import { moment, Platform } from "obsidian";
import { getDailyNoteSettings } from "obsidian-daily-notes-interface";
import type BratPlugin from "../main";
/**
* Logs events to a log file
*
* @param plugin - Plugin object
* @param textToLog - text to be saved to log file
* @param verboseLoggingOn - True if should only be logged if verbose logging is enabled
*
*/
export async function logger(
plugin: BratPlugin,
textToLog: string,
verboseLoggingOn = false,
): Promise<void> {
if (plugin.settings.debuggingMode) console.log(`BRAT: ${textToLog}`);
if (plugin.settings.loggingEnabled) {
if (!plugin.settings.loggingVerboseEnabled && verboseLoggingOn) return;
const fileName = `${plugin.settings.loggingPath}.md`;
const dateOutput = `[[${moment().format(getDailyNoteSettings().format).toString()}]] ${moment().format("HH:mm")}`;
const os = Platform.isDesktop
? (window.require("os") as { hostname: () => string })
: null;
const machineName = Platform.isDesktop ? os?.hostname() : "MOBILE";
const output = `${dateOutput} ${machineName} ${textToLog.replace("\n", " ")}\n`;
let file = plugin.app.vault.getAbstractFileByPath(fileName) as TFile;
if (!file) {
file = await plugin.app.vault.create(fileName, output);
} else {
await plugin.app.vault.append(file, output);
}
}
}
+32
View File
@@ -0,0 +1,32 @@
import { Notice, Platform } from "obsidian";
import type BratPlugin from "../main";
/**
* Displays a notice to the user
*
* @param plugin - Plugin object
* @param msg - Text to display to the user
* @param timeoutInSeconds - Number of seconds to show the Toast message
* @param contextMenuCallback - function to call if right mouse clicked
*/
export function toastMessage(
plugin: BratPlugin,
msg: string,
timeoutInSeconds = 10,
contextMenuCallback?: () => void,
): void {
if (!plugin.settings.notificationsEnabled) return;
const additionalInfo = contextMenuCallback
? Platform.isDesktop
? "(click=dismiss, right-click=Info)"
: "(click=dismiss)"
: "";
const newNotice: Notice = new Notice(
`BRAT\n${msg}\n${additionalInfo}`,
timeoutInSeconds * 1000,
);
if (contextMenuCallback)
newNotice.noticeEl.oncontextmenu = () => {
contextMenuCallback();
};
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Create a link to a repository, supporting both GitHub and Gitea.
* For bare `user/repo` format, creates a GitHub link.
* For full URLs (gitea), preserves the original URL.
*/
export function createRepoLink(
repoAddress: string,
optionalText?: string,
): DocumentFragment {
const newLink = new DocumentFragment();
const linkElement = document.createElement("a");
// Bare user/repo → GitHub link
if (/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(repoAddress)) {
linkElement.textContent = repoAddress;
linkElement.href = `https://github.com/${repoAddress}`;
} else {
// Full URL (Gitea or other) — use as-is
linkElement.textContent = repoAddress;
linkElement.href = repoAddress.startsWith("http")
? repoAddress
: `https://${repoAddress}`;
}
linkElement.target = "_blank";
newLink.appendChild(linkElement);
if (optionalText) {
newLink.appendChild(document.createTextNode(optionalText));
}
return newLink;
}
/**
* Creates a link from parts.
*/
export function createLink({
prependText,
url,
text,
appendText,
}: {
prependText?: string;
url: string;
text: string;
appendText?: string;
}): DocumentFragment {
const newLink = new DocumentFragment();
const linkElement = document.createElement("a");
linkElement.textContent = text;
linkElement.href = url;
if (prependText) {
newLink.appendChild(document.createTextNode(prependText));
}
newLink.appendChild(linkElement);
if (appendText) {
newLink.appendChild(document.createTextNode(appendText));
}
return newLink;
}
/**
* Legacy alias — kept for backward compat. Creates a GitHub link for bare repos,
* or a proper link for Gitea repos.
*/
export const createGitHubResourceLink = createRepoLink;